命令不在discord.py 2.0中运行 - 没有错误,但在discord.py 1.7.3中运行

Mat*_*ial 4 python discord discord.py

我试图了解从 Discord.py 版本 1.7.3 迁移到 2.0 的工作原理。特别是,这是我正在使用的测试代码:

from discord.ext import commands

with open('token.txt', 'r') as f:
    TOKEN = f.read()

bot = commands.Bot(command_prefix='$', help_command=None)

@bot.event
async def on_ready():
    print('bot is ready')

@bot.command()
async def test1(ctx):
    print('test command')

bot.run(TOKEN)
Run Code Online (Sandbox Code Playgroud)

在discord.py 1.7.3中,机器人打印“机器人已准备好”,我可以执行命令$test1

在discord.py 2.0中,机器人打印“机器人已准备就绪”,但我无法执行该命令,并且当我尝试执行该命令时控制台中没有任何错误消息。

为什么会发生这种情况?如何在我的机器人中恢复版本 1.7.3 的行为?

小智 14

将意图与discord.py一起使用

  1. 启用意图

    Help_Image_Intents_Message_Content


  1. 将您的意图添加到机器人中

    现在让我们添加message_content Intent。

    import discord
    from discord.ext import commands
    
    intents = discord.Intents.default()
    intents.message_content = True
    
    bot = commands.Bot(command_prefix='$', intents=intents, help_command=None)
    
    Run Code Online (Sandbox Code Playgroud)

  1. 把它放在一起

    代码现在应该如下所示。

    import discord
    from discord.ext import commands
    
    with open('token.txt', 'r') as f: TOKEN = f.read()
    
    # Intents declaration
    intents = discord.Intents.default()
    intents.message_content = True
    
    bot = commands.Bot(command_prefix='$', intents=intents, help_command=None)
    
    @bot.event
    async def on_ready():
        print('bot is ready')
    
    # Make sure you have set the name parameter here
    @bot.command(name='test1', aliases=['t1'])
    async def test1(ctx):
        print('test command')
    
    bot.run(TOKEN)
    
    Run Code Online (Sandbox Code Playgroud)