Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending messages from synchronous thread in a Python Discord bot

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?

like image 441
J. Doe Avatar asked Feb 28 '19 15:02

J. Doe


People also ask

How do I send a message from a discord bot in Python?

# Bot class DiscordBot: def __init__(self, TOKEN: str): # create / run bot def send_msg(self, channel_id: int, message: str): # send message to the channel # Some other Script my_notifier = DiscordBot("TOKEN") my_notifier. send_msg(12345, "Hello!")

Can discord bots join threads?

Once updated, Bots will also be able to moderate the content within a Thread just like they do Channels. Some of the most popular bots, such as ProBot and Arcane, are already prepared to moderate within Threads, along with the discord. js and discord.py libraries.

How do you send a message on Webhooks discord Python?

You just need a webhook URL and just do a POST request on that URL and the message will be sent to discord. Webhooks can also be used if your bot has to send messages to a channel a lot.

How do I use Python in discord chat?

Start by going to Repl.it. Create a new Repl and choose "Python" as the language. To use the discord.py library, just write import discord at the top of main.py . Repl.it will automatically install this dependency when you press the "run" button.


1 Answers

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())
like image 156
CircuitSacul Avatar answered Sep 20 '22 20:09

CircuitSacul