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

How do I close my Discord bot after it sends a message?

I am using a bot to send a message in between a program, utilising it as a function.

def sendmessage(message):
    @client.event
    async def on_ready():
        print(f'{client.user} has connected to Discord!')
        CHANNEL_ID = (ID)
        channel = client.get_channel(int(CHANNEL_ID))
        await channel.send(message)
        print("sent")
    client.run(TOKEN)

After it sends a message, the bot stays active and the program freezes.
For ease, I have included an example of a program that stops working:

print("Hi")
sendmessage("Hello world!")
print("Hi")

The second print command doesn’t go through as the bot is still active.
How do I shut down the bot so my program keeps on working?

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

I’ve tried using bot.close() at the end, and it doesn’t work.
I’ve tried using sys.exit(0), and it terminates the entire program, not only the bot.
What I want is for the simplified program to:

  1. Say ‘Hi’
  2. Send a discord message
  3. Say ‘Hi’ again

It gets stuck after step 2.

>Solution :

the reason your program gets stuck in a loop is because you didn’t close the listener after printing "sent". Try this code:

def sendmessage(message):
    @client.event
    async def on_ready():
        print(f'{client.user} has connected to Discord!')
        CHANNEL_ID = (ID)
        channel = client.get_channel(int(CHANNEL_ID))
        await channel.send(message)
        print("sent")
        await client.close()
    client.run(TOKEN)
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