[英]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
事件。
通常,在使用commands.Bot
實現機器人時,您會使用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
偵聽器。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.