未使用'on_message'的重新定义是什么意思

What does redefinition of unused 'on_message' mean

我在 Discord 上制作的这个机器人只是一个刽子手游戏。我已经能够完成机器人的最基本部分,现在我正在尝试添加第二个命令。但是第 24 行出现错误,提示“从第 13 行重新定义未使用的 'on_message'”。

第二个命令应该在一个人发送“$start”后打印一些东西。但是,当我这样做时它不起作用。

这是我当前的代码:

import discord 
import random 
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("$help"):
    await message.channel.send("To start your game, type '$start'")


client.run(os.getenv("TOKEN"))

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

  if message.content.startswith("$start"):
    await message.channel.send("You will have to guess a month. Have fun :) (The first letter will be always capital)")

这就是问题所在:

@client.event
async def on_message(message): #this is line 24
  if message.author == client.user:
    return

  if message.content.startswith("$start"): 
    await message.channel.send("You will have to guess a month. Have fun :) (The first letter will be always capital)")

 

问题:
您重新定义了 on_message 函数。这意味着,有 2 个同名函数 on_message.

解决方法: 由于您一直在使用一些 if 语句来决定在哪个命令上执行哪个函数,因此您可以将所有 if 语句组合到一个函数中,因此您的代码如下所示:

import discord 
import random 
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("$help"):
    await message.channel.send("To start your game, type '$start'") 

  if message.content.startswith("$start"):
    await message.channel.send("You will have to guess a month. Have fun :) (The first letter will be always capital)")

client.run(os.getenv("TOKEN"))

错误说明了它的字面意思:您正在为同一个 Client.

重新定义 on_message 事件

通常,在使用命令实现机器人时,您会使用来自 discord.ext 分支的 commands.Bot 客户端,而不是本机 Client

所以这段代码:

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

  if message.content.startswith("$help"):
    await message.channel.send("To start your game, type '$start'")

将替换为:

client = commands.Bot("$")
@client.command()
async def help(ctx):
  if ctx.author == client.user:
     return
  await message.channel.send("To start your game, type '$start'")

不过仅供参考,您可以通过 Bot.listen() 装饰器在您的代码中有多个 on_message 侦听器。