You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py开发报错:'NoneType' object has no attribute 'id'求助

解决Discord.py调用bot.process_commands()触发'NoneType' object has no attribute 'id'错误

问题原因

你同时创建了discord.Client和commands.Bot两个客户端实例,但仅启动了client,bot实例从未完成登录初始化,导致bot.user为None。调用bot.process_commands(message)时,内部逻辑需要对比消息作者ID和机器人自身ID,自然会触发AttributeError。

另外,commands.Bot是discord.Client的子类,完全具备处理消息事件和命令的能力,不需要同时维护两个客户端实例。

修正方案

改用单一commands.Bot实例处理所有逻辑,同时实现前缀为$、返回用户输入参数的命令:

import os
import discord
from discord.ext import commands
from dotenv import load_dotenv

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
intents = discord.Intents.default()
intents.message_content = True
activity = discord.Activity(name='null, dying, trying to fix me', type=discord.ActivityType.watching)

# 仅初始化Bot实例,前缀设为$
bot = commands.Bot(intents=intents, command_prefix='$', activity=activity)

@bot.event
async def on_ready():
    print(f'{bot.user.name} has connected to Discord!')
    channel = bot.get_channel(956302622170701946)
    await channel.send(f'connected successfully as {bot.user.name}#{bot.user.discriminator}')

@bot.event
async def on_message(message):
    # 先排除机器人自身消息,避免循环
    if message.author == bot.user:
        return
    
    # 处理自定义消息逻辑
    if message.content.startswith('hello'):
        await message.channel.send("hello stopid")
    elif message.content.startswith('die'):
        await message.channel.send('ok :sob: i ded now')
        await bot.close()
    
    # 最后调用命令处理,确保自定义逻辑不阻塞命令
    await bot.process_commands(message)

# 基础命令示例
@bot.command()
async def a(ctx):
    await ctx.send("a")

# 带参数的命令,返回用户输入的参数
@bot.command()
async def echo(ctx, *, args):
    await ctx.send(f'你输入的参数是:{args}')

bot.run(TOKEN)

关键修改点

  • 移除多余的discord.Client实例,统一使用commands.Bot
  • 将命令前缀改为$,匹配需求
  • 调整on_message逻辑顺序:先过滤自身消息,处理自定义逻辑,最后调用process_commands
  • 添加echo命令示例,接收任意参数并返回给用户

内容的提问来源于stack exchange,提问作者null

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 10:30:53