首页 > 解决方案 > discord.py 消息被多次发送,每次增加 1

问题描述

真的很难用标题来形容。基本上我有一个名为#start 的函数,当在特定时间调用它时会发送一条关于不和谐的消息,要求我修改直到(再次)特定时间。但是当我回到不和谐状态时,事实证明消息已经发送了两次。所以然后我尝试执行 #start 命令,它发送了 3 次相同的消息。如果我再次输入#start,它会出现 4 次。这是我的代码:

if hour == 14:
   await bot.send_message(message.channel, "<@258621320898543616> Why don't you try some science revision now?")
   science = random.choice(sciences) 
   asyncio.sleep(0.5)
   await bot.send_message(message.channel, "<@258621320898543616> lemme see, how about " +science+"? Look over some of that")
   asyncio.sleep(1)
   await bot.send_message(message.channel, "you can take a break at 3:00")
while hour >= 14 and hour < 15:
   msg = await bot.wait_for_message(timeout=3, author=message.author)
   if msg:
      await bot.delete_message(msg)
   hour = int(time.strftime("%H"))

在我第四次输入 #start 之后,它会抛出一个错误说:

discord.errors.NotFound: NOT FOUND (status code: 404): Unknown Message

不确定代码有什么问题或如何阻止它发生。请帮忙?

标签: pythonbotsdiscorddiscord.py

解决方案


添加一个全局值,指示#start命令是否正在运行。

from discord.ext.commands import Bot

bot = Bot(command_prefix='#')
start_running = False

@bot.event
async def on_message(message):
    global start_running
    if message.content.startswith('#start'):
        if not start_running:                
            start_running = True
            # do stuff
            start_running = False

bot.run("token")

推荐阅读