Discord 机器人不响应命令 (Python)

Discord Bot Not Responding to Commands (Python)

我刚刚开始编写 discord 机器人。在尝试按照在线说明和教程进行操作时,我的机器人不会响应命令。它对 on_message() 的响应非常好,但无论我尝试什么,它都不会响应命令。我确信这很简单,但我将不胜感激。

import discord
from discord.ext.commands import Bot
from discord.ext import commands

bot = commands.Bot(command_prefix='$')
TOKEN = '<token-here>'

@bot.event
async def on_ready():
    print(f'Bot connected as {bot.user}')
    
@bot.event
async def on_message(message):
    if message.content == 'test':
        await message.channel.send('Testing 1 2 3')
        
@bot.command(name='go')
async def dosomething(ctx):
    print("command called") #Tried putting this in help in debugging
    await message.channel.send("I did something")


        
bot.run(TOKEN)

Picture of me prompting the bot and the results

好的。首先,您需要在顶部的唯一导入语句是 from discord.ext import commands。其他两个不是必须的。

其次,我自己尝试修改您的代码,发现 on_message() 函数似乎会干扰命令,因此将其删除应该会有所帮助。

第三,当我复制我自己的一个工作机器人并慢慢更改所有代码直到它与你的相同时,我才发现这一点。出于某种原因 python 不喜欢我刚刚复制并粘贴您的代码。我以前从未见过这样的事情,所以老实说,除了您的代码是正确的并且只要您取消 on_message() 函数就应该可以工作之外,我真的不知道该说些什么。

这是我开始工作的最终代码:

from discord.ext import commands

bot = commands.Bot(command_prefix="$")
TOKEN = "<token-here>"


@bot.event
async def on_ready():
    print(f'Bot connected as {bot.user}')


@bot.command()
async def dosomething(ctx):
    await ctx.send("I did something")

bot.run(TOKEN)

如您所见,我对您的代码所做的唯一更改是删除了顶部的冗余导入,并删除了 on_message() 函数。它在我这边完美地工作,所以我建议你 re-type 在一个新文件中像这样输出,看看是否有效。

如果这对您不起作用,那么我的下一个猜测是您的 discord.py 安装有问题,因此您可以尝试卸载它然后重新安装它。

如果 none 有帮助请告诉我,我会看看是否可以帮助您找到其他可能导致问题的原因。

我一开始也犯了同样的错误

@bot.event
async def on_message(message):
    if message.content == 'test':
        await message.channel.send('Testing 1 2 3')

此函数覆盖 on_message 事件,因此它永远不会发送到 bot.command()

要修复它,您只需在 on_message 函数的末尾添加 await bot.process_commands(message):

async def on_message(message):
    if message.content == 'test':
        await message.channel.send('Testing 1 2 3')
    await bot.process_commands(message)

尚未测试,但应该可以解决您的问题。