Sync function #8227
Replies: 2 comments 5 replies
-
What issues are you experiencing? Any traceback and minimal reproducible code you can provide? |
Beta Was this translation helpful? Give feedback.
-
OverviewDiscord.py is an async library, meaning that what you're trying to achieve isn't going to yield a great solution. I'm going to show you two methods you can use and explain why both of them aren't great. Afterwards, I'm going to give you some questions to answer for yourself to you can hopefully find a solution that works for you. Async ApproachWe can use import asyncio
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='!', intents=discord.Intents.default())
bot.http.token = 'my_bot_token' # Used for Authentication
# asyncio.run will only work if there's no current event loop set. If there is though, you may want to look into
# asyncio.create_task.
channel: discord.TextChannel = asyncio.run(bot.fetch_channel(MY_CHANNEL_ID))
message: discord.Message = asyncio.run(channel.fetch_message(MY_MESSAGE_ID))
print(message.content) Using RequestsNothing limits you from using a 3rd party library like
import requests
BOT_TOKEN = 'my_bot_token' # Your bot's token, used for authentication
MY_CHANNEL_ID = 0 # The channel ID of the channel you want to fetch the message from.
MY_MESSAGE_ID = 0 # The message ID you want to fetch
url = f'https://discord.com/api/v10/channels/{MY_CHANNEL_ID}/messages/{MY_MESSAGE_ID}'
result = requests.get(
url,
headers={
'Authorization': f'Bot {BOT_TOKEN}',
'Content-Type': 'application/json',
},
)
print(result) Why are these bad?First ExampleThis is monkey patching the discord.py library to make an HTTP request from the library work. This also utilizes Second ExampleThis example, although better than the first, will still be unnecessary due to the nature of it. I personally can't think of a context in which you would need to use the Discord API without a Discord bot present - ignoring webhooks of course. Maybe you could elaborate? AlternativesI encourage you to think about why you need to fetch messages from the Discord API in a synchronous context. Could there be a better solution than Discord's API? Could you use a database to assist you and limit API calls? Have you done research for your use case to see if there's an alternative solution? It's a bit difficult for me to provide you an exact solution, as I have very little information. Feel free to elaborate on your situation and I can provide some more clarity for you if needed :) |
Beta Was this translation helpful? Give feedback.
-
Hello,
I have a question about the discord bot function, Can i create the sync function to get messagess from discord? Async function create some troubles on my app.
Beta Was this translation helpful? Give feedback.
All reactions