How to add a function to discord.py event loop?

前端 未结 3 1676
我在风中等你
我在风中等你 2021-02-16 00:01

I am using Python with discord.py. Documentation here

I\'ve got a bot that is running on a Discord server that links the server with a subr

3条回答
  •  伪装坚强ぢ
    2021-02-16 00:17

    You want your search_submissions() function to be async so other functions of your bot can still be invoked and your bot stays responsive. Define it to be def async and use aiohttp to send async HTTP requests to reddit -- what this does is send off the request, relinquish control to the event loop, and then take back control once the results have been transmitted back. If you use a standard HTTP library here instead then your whole bot will be blocked until the result comes back. This of course only makes sense if the task is mainly I/O-bound and less CPU-bound.

    Then call search_submissions() in on_message(message) -- but call it asynchronously using result = await search_submissions(). This will resume execution of on_message once the result of search_submissions is ready.

    If you truly want to do something else in the same context while waiting on search_submissions (which I think is unlikely), dispatch it as task = asyncio.create_task(search_submissions()). This will start the task immediately and allow you to do something else within the same function. Once you need the result you will have to result = await task.

    async def search_submissions():
        async with aiohttp.ClientSession() as session:
            async with session.get(some_reddit_url) as response:
                return await response.read()
    
    @client.event
    async def on_message(message):
        if message.content.startswith("reddit!hot"):
            result = await search_submissions()
            await message.channel.send(result)
    

提交回复
热议问题