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

Discord.py机器人运行报错:初始化缺少必填参数'intents'

解决Discord机器人初始化缺少intents参数的错误

错误原因

Discord.py 2.0及以上版本强制要求创建commands.Bot实例时必须传入intents参数,这是Discord API的权限控制机制,用来限定机器人可以接收的事件类型,旧版本无参数初始化的写法已不再支持。

解决步骤

  • 先定义intents对象,可先启用默认intents满足基础功能:
    intents = discord.Intents.default()
    
    若要处理命令、读取消息内容,需额外开启消息内容权限:
    intents.message_content = True
    
  • 修改commands.Bot初始化代码,传入intents参数:
    bot = commands.Bot(command_prefix='?', intents=intents)
    
  • 删除代码中多余的client = discord.Client(),因为commands.Bot是discord.Client的子类,已包含客户端核心功能,无需重复创建。

修改后的完整代码

import os
import discord
from discord.ext import commands
from replit import db
TOKEN = os.environ['TOKEN']

# 初始化intents
intents = discord.Intents.default()
intents.message_content = True  # 开启消息内容权限,处理命令必须

bot = commands.Bot(command_prefix='?', intents=intents)

@bot.command()
async def start(ctx):
    await ctx.send("Welcome " + ctx.message.author.mention)
    await ctx.send("Do ?commands to see all the commands")
    # 注意:author.id是整数,需转为字符串作为字典键
    db["money-" + str(ctx.message.author.id)] = "0"
    db["xp-" + str(ctx.message.author.id)] = "0"
    db["started-" + str(ctx.message.author.id)] = "1"

@bot.command()
async def commands(ctx):
    # 用get方法避免未初始化用户的KeyError
    started = db.get("started-" + str(ctx.message.author.id), "0")
    if started == "1":
      await ctx.send("--------------------")
      await ctx.send("Command list")
      await ctx.send("--------------------")
      await ctx.send("?start")
      await ctx.send("Initializes your account")
      await ctx.send("?commands")
      await ctx.send("Opens this menu")
      await ctx.send("--------------------")
    else:
      await ctx.send("You haven't run ?start yet!")
      
bot.run(TOKEN)

额外注意事项

  • 若需要机器人获取成员列表、服务器信息等权限,需在Discord开发者门户的机器人设置页面开启对应的Privileged Gateway Intents,并在代码中启用对应intents选项。
  • 代码中还优化了两处细节:将原echo命令改为更贴合逻辑的start,以及处理用户ID转字符串(字典键不能为整数)、用db.get避免未初始化用户的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 23:25:19