在编写Discord Bot时,可能会遇到一个命令触发多次执行的情况,这通常是由于事件监听器被多次注册或者Bot的实例被意外地创建了多次。
bot.listen()
,每个监听器都会独立触发。@bot.command()
async def shutdown(ctx):
if ctx.author.id == YOUR_ID: # 确保只有特定用户可以关闭Bot
await ctx.send('Shutting down...')
await bot.close()
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
@bot.event
async def on_ready():
print(f'Logged in as {bot.user}')
@bot.command()
async def test(ctx):
print('Test command executed')
await ctx.send('Test')
@bot.command()
async def shutdown(ctx):
if ctx.author.id == YOUR_ID:
await ctx.send('Shutting down...')
await bot.close()
bot.run('YOUR_TOKEN')
确保替换YOUR_TOKEN
和YOUR_ID
为你的实际Discord Bot Token和用户ID。
通过以上方法,你可以避免命令的多次输出,并且可以安全地关闭或重启你的Bot。
领取专属 10元无门槛券
手把手带您无忧上云