@client.event 和@client.command

@client.event and @client.command

所以我一直在使用 discord.py 编写一个机器人,我发现了一个我似乎无法修复的错误。 首先,我有这样的东西:

@client.command()
async def ping(ctx):
  await ctx.send("Pong!")

然后我在这里添加了一个完整的部分:

@client.event
async def on_message(message):
# print(message)
  if message.content.startswith('$random'):
      if len(message.content) == 7:
        await message.channel.send("**You need to provide a valid number range. Examples: *$random 7 69 | $random 69 (automatically sets the first number as 1)***")
      else:
        if message.content.split(" ",1)[1] == "help":
          await message.channel.send("**You need to provide a valid number range. Examples: *$random 7 69 | $random 69 (automatically sets the first number as 1)***")
        try:
          if message.content.split(" ",2)[2] != "":
            number1 = int(message.content.split(" ",2)[1])
            number2 = int(message.content.split(" ",2)[2])
            number2send = str(random.randint(number1,number2))

            await message.channel.send("Your random number is: **" + number2send + "**")
            return
        except:
          try:
            if message.content.split(" ",1)[1] != "":
              number = int(message.content.split(" ",1)[1])
              number2send = str(random.randint(1,number))

              await message.channel.send("Your random number is: **" + number2send + "**")
              return
          except:
            await message.channel.send("**You need to provide a valid number range. Examples: *$random 7 69 | $random 69 (automatically sets the first number as 1)***")
            return
    
  if message.content.startswith('$timein'):
    if len(message.content) == 7:
        await message.channel.send("**You need to provide a valid country***")
    else:
      try:
        lad = message.split(" ",1)[1]
        print("Location address:", lad)
        location = geolocator.geocode(lad)
  
        print("Latitude and Longitude of the said address:")
        print((location.latitude, location.longitude))
          
        # pass the Latitude and Longitude
        # into a timezone_at
        # and it return timezone
        obj = TimezoneFinder()
          
        # returns 'Europe/Berlin'
        result = obj.timezone_at(lng=location.longitude, lat=location.latitude)
        print("Time Zone : ", result)
      except:
        return  

并且像第一部分和 $timein 命令一样的任何命令都不再起作用,而它们都可以自己运行,我不知道为什么。 我觉得错误是由

的差异引起的

@client.command

@client.event

所以这可能是导致问题的原因。 无论如何,对于帮助我解决这些问题的好心人,在此先感谢!

由于 on_message,您的命令无效。发生的事情是您正在覆盖默认值 on_message 而默认值 on_message 是处理命令的那个。您可以通过在 on_message.

末尾添加 bot.process_commands(message) 行来修复它

Discord.py 在 F.A.Q 中涵盖了这个问题,阅读更多内容 here

另外,附注。请不要自己处理命令,Discord.py 的命令扩展有很多您可能没有发现的功能。请学习更多关于命令的知识,它将减轻您的工作量,并且更容易开发您梦想中的机器人。