'How to make a bot stop a certain action and not close?
So here's my code.
# simple bot.
import random, discord, os, time, ctypes
from xmlrpc.client import MAXINT
from time import sleep
bot_token = "BOT TOKEN"
local_time = time.ctime(time.time())
randnum_bot = discord.Client()
@randnum_bot.event
async def on_ready():
guild_count = 0
print("""randomnum bot has started running.
Current time: """ + local_time)
for guild in randnum_bot.guilds:
guild_count += 1
print("randomnum bot is in " + str(guild.name))
@randnum_bot.event
async def on_message(message):
if(message.content == "!generatenum"):
random_time_interval = random.randint(0, 5)
random_times = random.randint(0, 100)
await message.channel.send(f"A random number will be generated every {random_time_interval} seconds for {random_times} times.")
for i in range(random.randint(0, 100)):
await message.channel.send(random.randint(0, MAXINT))
sleep(random_time_interval)
randnum_bot.run(bot_token)
Put simply, this Discord bot generates a random number for a random amount of times within a random interval of time.
But here's the thing: I want to make the bot cease all of its activities(and remain online) once a certain message is sent, for example a !stop
message.
I tried adding an elif
in the on_message
function, and I did it like this:
@randnum_bot.event
async def on_message(message):
if(message.content == "!generatenum"):
random_time_interval = random.randint(0, 5)
random_times = random.randint(0, 100)
await message.channel.send(f"A random number will be generated every {random_time_interval} seconds for {random_times} times.")
for i in range(random.randint(0, 100)):
await message.channel.send(random.randint(0, MAXINT))
sleep(random_time_interval)
elif(message.content == "!stop"):
await message.channel.send("Alright, see you next time!")
await randnum_bot.close()
Although it does make the bot stop once a message that contains !stop
is sent, it actually makes the bot go offline, which is really inconvenient. I also tried inserting await randnum_bot.run(bot_token)
after await randnum_bot.close()
, but that resulted in an error which was RuntimeError: Cannot close a running event loop
.
Is there a way to make a bot stop its activities, without actually making it go offline?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|