Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Unable to send a message to Discord using discord.py

I’m trying to simply create a function that sends a discord message to a specific channel when the bot runs. I want to later call this function in a separate python script.
The code below seems to run fine, and the bot appears online – but it is fails to send the message:

import discord

client = discord.Client()
client.run("ABCDeFGHIjklMNOP.QrSTuV-HIjklMNOP") # the token

@client.event
async def on_ready():
    logs_channel = client.get_channel(12345689123456789) # the channel ID
    await logs_channel.send("Bot is up and running")
on_ready()

I’m sure I’m missing something basic but I cannot figure out what it is. I’ve tried a similar function in Node.js and it works fine however, I would prefer the bot to work in python. Discord.py is up to date, python is v3.10.
Any help would be greatly appreciated.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Client.run is a blocking call, meaning that events registered after you call it won’t actually be registered. Try calling Client.run after you register the event, as in:

import discord

client = discord.Client()

@client.event
async def on_ready():
    logs_channel = client.get_channel(12345689123456789) # the channel ID
    await logs_channel.send("Bot is up and running")

client.run("ABCDeFGHIjklMNOP.QrSTuV-HIjklMNOP") # the token

You also probably do not want to be manually calling an event handler. If you want to send a message by calling a function, you probably want to consider writing a separate function to the event handler.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading