【问题标题】:Discord Bot Not Responding to Commands (Python)Discord Bot 不响应命令(Python)
【发布时间】:2021-02-17 21:23:40
【问题描述】:

我刚刚开始编写不和谐机器人。在尝试遵循在线说明和教程时,我的机器人不会响应命令。它对 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

【问题讨论】:

    标签: python command discord bots


    【解决方案1】:

    好的。首先,您在顶部需要的唯一导入语句是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() 函数。它在我这边工作得很好,所以我建议你在一个新文件中重新输入它,看看是否有效。

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

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

    【讨论】:

    • 非常感谢!我试过了,让它工作了。
    • 太棒了!很高兴我能帮助你!那你能把答案标记为正确吗?
    【解决方案2】:

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

    @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)
    

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

    【讨论】:

    • 非常感谢,也被卡住了。
    猜你喜欢
    • 2020-12-15
    • 2021-08-28
    • 2023-03-09
    • 2021-04-17
    • 2022-10-23
    • 1970-01-01
    • 2021-10-23
    相关资源
    最近更新 更多