8
votes

I'm developing a Discord bot in Python 3.6 using the discord.py library and I've had issues trying to send a message to a specific channel from the threads I create.

Basically, I have some threads monitoring websites and I'd like to call a function (that I'm passing to the threads) that sends a message to one specific channel when I notice a change on the website.

I initially tried calling client.send_message() directly without async/await but it didn't work at all, so I wrote the async/await function sending the message (tested it and it works) but again I had problems calling it from the threads, so I ended up passing the bot client to my threads and calling self.bot_client.loop.create_task(self.sendmsgfunction(msg)). That works, but it is incredibly slow (takes around 15 seconds to send the message, and it's probably not the correct way of doing it anyway) compared to the time it takes for the bot to answer a message with the usual @bot.event function.

I already tried creating an event loop with asyncio then calling the function, but again I ended up with an error.

Any ideas?

2
@AlexanderDmitriev would you mind providing an usage example? I can't figure out how to run the callback I scheduledJ. Doe
Did you get anywhere with this? I have a similar problem myself.Jachdich
@Jachdich I found out it's far easier to just use a webhook for that kind of thingsJ. Doe
You can always just send a direct request to the discord API, via a webhook for instance, there doesn't have to be a heavy async libary like discord.py in between.Buster

2 Answers

1
votes

You can use asyncio.run() to run an asynchronous function, like this:

import asyncio

async def async_func():
    print("Async function run!")

asyncio.run(async_func())
-7
votes

If you want to send a message to a specific channel, firstly you should get the channel object.

channel = discord.utils.get(ctx.guild.channels, id=channel_id_here)

Then you can just do

await channel.send()