1
votes

I have a program that looks like this:

import things
import discord


def on_thing_happen (variable):
    get_info()
    do thing()
    # This is where I want to send a message in Discord

For reasons, the rest of my code cannot work in an async function.

Is there any way to do this? I cannot use an async def.

1
Does your use-case allow the use of a webhook? - derw
Possibly, but I've never used webhooks before, so I wouldn't know what I was doing. - T Mayer
Upon further inspection, no, a webhook wouldn't work. It needs to be a proper bot. - T Mayer
discord.py is a an async library, and while it is "sort of" possible to run a send event from a sync function it can cause some weird behavior. I'm not sure what blocking code you are trying to run, but it will likely be better to have a standard async function that runs your blocking function in an asyncio executor and you can use await send as normal - derw
How would it be "sort of possible"? - T Mayer

1 Answers

4
votes

Try this:

import things
import discord

client = discord.Client()

def on_thing_happen (variable):
    get_info()
    do thing()
    channel = client.get_channel(CHANNEL ID) #replace with channel id of text channel in discord
    client.loop.create_task(channel.send('Message'))

So instead of await channel.send('message') it is client.loop.create_task(channel.send('message')

I hope this works!