Search code examples
pythondiscorddiscord.pybots

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?

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)