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

编译Discord Bot触发TypeError:intents参数类型错误的解决咨询

Discord Bot 运行报错修复指南

报错信息

C:\Users\User\Desktop\CommunityBot>communitybot.py
Traceback (most recent call last):
  File "C:\Users\User\Desktop\CommunityBot\communitybot.py", line 8, in <module>
    client = commands.Bot(command_prefix='!', intents= 8)
             ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\bot.py", line 171, in __init__
    super().__init__(intents=intents, **options)
  File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\ext\commands\core.py", line 1302, in __init__
    super().__init__(*args, **kwargs)
  File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 253, in __init__
    self._connection: ConnectionState = self._get_state(intents=intents, **options)
                                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 284, in _get_state
    return ConnectionState(dispatch=self.dispatch, handlers=self._handlers, hooks=self._hooks, http=self.http, **options)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\state.py", line 221, in __init__
    raise TypeError(f'intents parameter must be Intent not {type(intents)!r}')
TypeError: intents parameter must be Intent not <class 'int'>

核心问题原因

你给commands.Bot的intents参数传了整数8,但Discord.py要求必须传入**discord.Intents类型的对象**,不能直接传数值。另外代码里还存在其他几个会导致运行失败的问题,一并修复。

修复步骤

1. 修正Intents配置

  • 删除重复的client = discord.Client(...)定义,只保留commands.Bot的实例
  • 用discord.Intents对象替代整数,可按需开启权限(开发阶段可用discord.Intents.all(),上线建议精准开启)
  • 注意:成员相关的intents需要在Discord开发者后台的Bot页面开启「Server Members Intent」权限

2. 修复其他代码错误

  • 事件函数名错误:onReady改为on_ready(Discord.py事件名遵循小写加下划线规范)
  • 变量名错误:bot.get_guild改为client.get_guild,因为你的Bot实例名为client
  • 循环遍历错误:for member in guilds.member改为for member in guild.members
  • SQL注入风险:替换f-string拼接SQL的写法,改用参数化查询
  • INSERT字段不匹配:users表有6个字段,代码中需传入对应数量的值
  • 废弃方法替换:新版本Discord.py用guild.members替代fetch_members
  • 数据库连接优化:用上下文管理器管理连接,避免泄漏

完整修复代码

import discord
from discord.ext import commands
import sqlite3
from config import settings

# 配置Intents,按需开启所需权限
intents = discord.Intents.default()
intents.members = True  # 开启成员权限,需在开发者后台启用
intents.message_content = True  # 需处理消息内容时开启

# 创建Bot实例,仅保留这一个
client = commands.Bot(command_prefix='!', intents=intents)

# 初始化数据库
def init_db():
    with sqlite3.connect('server.db') as conn:
        cursor = conn.cursor()
        cursor.execute("""CREATE TABLE IF NOT EXISTS users(
            name TEXT,
            id INT,
            lvl INT,
            goals INT,
            assists INT,
            cleensheets INT
        )""")
        conn.commit()

@client.event
async def on_ready():
    init_db()
    print("Bot已成功连接")

    # 获取指定服务器成员
    guild = client.get_guild(696354089851813978)
    if guild:
        members = guild.members
        with sqlite3.connect('server.db') as conn:
            cursor = conn.cursor()
            for member in members:
                # 参数化查询避免SQL注入
                cursor.execute("SELECT id FROM users WHERE id = ?", (member.id,))
                if not cursor.fetchone():
                    # 插入完整6个字段的值
                    cursor.execute("INSERT INTO users VALUES (?, ?, ?, ?, ?, ?)",
                                  (str(member), member.id, 0, 0, 0, 0))
            conn.commit()

@client.event
async def on_member_join(member):
    with sqlite3.connect('server.db') as conn:
        cursor = conn.cursor()
        cursor.execute("SELECT id FROM users WHERE id = ?", (member.id,))
        if not cursor.fetchone():
            cursor.execute("INSERT INTO users VALUES (?, ?, ?, ?, ?, ?)",
                          (str(member), member.id, 0, 0, 0, 0))
            conn.commit()
            print(f"已添加新成员 {member} 到数据库")

@client.command(aliases=['pass'])
async def mypass(ctx, member: discord.Member = None):
    target_member = member or ctx.author
    with sqlite3.connect('server.db') as conn:
        cursor = conn.cursor()
        cursor.execute("SELECT lvl FROM users WHERE id = ?", (target_member.id,))
        result = cursor.fetchone()
        if result:
            lvl = result[0]
            embed = discord.Embed(description=f"用户 **{target_member}** 的等级是 **{lvl}**")
            await ctx.send(embed=embed)
        else:
            await ctx.send(f"用户 **{target_member}** 未在数据库中")

client.run(settings['TOKEN'])

额外注意事项

  • 确保在Discord开发者后台开启Server Members Intent和Message Content Intent(需处理消息时)
  • 上线时避免使用Intents.all(),仅开启Bot实际需要的权限,提升安全性
  • 始终用参数化查询处理数据库操作,避免SQL注入

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 06:15:33