英文:
How do I close my Discord bot after it sends a message?
问题
def sendmessage(message):
@client.event
async def on_ready():
print(f'{client.user}已连接到Discord!')
CHANNEL_ID = (ID)
channel = client.get_channel(int(CHANNEL_ID))
await channel.send(message)
print("已发送")
client.run(TOKEN)
print("你好")
sendmessage("你好,世界!")
print("你好")
发送消息后,机器人保持活动状态,程序会冻结。为了方便,我已经包含了一个停止工作的示例程序:
print("你好")
sendmessage("你好,世界!")
print("你好")
第二个打印命令不会执行,因为机器人仍然处于活动状态。我该如何关闭机器人,使我的程序继续工作?
我尝试过在结尾处使用 bot.close()
,但它不起作用。
我尝试过使用 sys.exit(0)
,它会终止整个程序,而不仅仅是机器人。
我想要的是简化后的程序:
- 打印 '你好'
- 发送一个Discord消息
- 再次打印 '你好'
在第2步之后,它就卡住了。
英文:
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:
- Say 'Hi'
- Send a discord message
- Say 'Hi' again
It gets stuck after step 2.
答案1
得分: 1
程序陷入循环的原因是因为您在打印“sent”后没有关闭监听器。请尝试以下代码:
def sendmessage(message):
@client.event
async def on_ready():
print(f'{client.user} 已连接到 Discord!')
CHANNEL_ID = (ID)
channel = client.get_channel(int(CHANNEL_ID))
await channel.send(message)
print("已发送")
await client.close()
client.run(TOKEN)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论