discord.py bot 只响应一个命令

时间:2021-01-02 17:31:53

标签: python error-handling discord bots discord.py

它只在给定时间显示其中一个命令。
如果我写 !hi!bye 它不会工作,但如果我写 !sing 它会输出 la la la
如果我在它之前切换字符,它会变成 !hi!sing 不起作用 但是 !bye 工作并说 Goodbye!

import os

client = discord.Client()

@client.event 
async def on_ready():
  print('We have logged in as {0.user}'
  .format(client))

@client.event
async def on_message(message):
  if message.author == client.user:
    return

  if message.content.startswith('!hi'):
    await message.channel.send('Hello!')

@client.event
async def on_message(message):
  if message.author == client.user:
    return

  if message.content.startswith('!bye'):
    await message.channel.send('Goodbye Friend!')

@client.event
async def on_message(message):
  if message.author == client.user:
    return

  if message.content.startswith('!sing'):
    await message.channel.send('la la la')

client.run(os.getenv('TOKEN'))```

4 个答案:

答案 0 :(得分:2)

只有一个事件,不要为每个命令都创建一个新的。

@client.event
async def on_message(message):
  if message.author == client.user:
    return
  elif message.content.startswith('!sing'):
    await message.channel.send('La La la.')
  elif message.content.startswith('!hi'):
    await message.channel.send('Hello!')

答案 1 :(得分:2)

您正在尝试使用多个事件,而是在一个事件中使用所有事件,如下所示:

@client.event
async def on_message(message):
  if message.author == client.user:
    return

  if message.content.startswith('!hi'):
    await message.channel.send('Hello!')
 
  elif message.content.startswith('!bye'):
    await message.channel.send('Goodbye Friend!')

  elif message.content.startswith('!sing'):
    await message.channel.send('la la la')

另外,请确保在其他事件中使用 elif 而不是 if。 应该这样做。

答案 2 :(得分:1)

不要重复 on_message 事件。只有一个并且将 if 语句放入这个事件中。

答案 3 :(得分:1)

这是使用 commands.Bot() 的完美示例:

from discord.ext import commands

bot = commands.Bot(command_prefix="!")

@bot.command()
async def hi(ctx):
    await ctx.send("Hello!")

@bot.command()
async def sing(ctx):
    await ctx.send("la la la!")

@bot.command()
async def bye(ctx):
    await ctx.send("Goodbye friend!")

Bot() 继承自 Client(),在处理命令时提供了更多功能!


参考:

相关问题