如何在我的Discord机器人发送消息后关闭它?

huangapple go评论71阅读模式
英文:

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),它会终止整个程序,而不仅仅是机器人。
我想要的是简化后的程序:

  1. 打印 '你好'
  2. 发送一个Discord消息
  3. 再次打印 '你好'

在第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:

  1. Say 'Hi'
  2. Send a discord message
  3. 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)

huangapple
  • 本文由 发表于 2023年3月31日 02:09:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/75891606.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定