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

Python开发Discord机器人时判断用户ID是否在集合中报错如何解决

问题根因

  • 类型不匹配:message.author.id 输出为整数类型用户ID,你定义的authUser集合存储的是字符串格式ID,类型差异会导致in判断永远返回False
  • 语法冗余错误:if True :{print('rcvd'),}不符合Python语法规范,Python使用缩进而非大括号包裹代码块,该段为无用冗余代码,建议删除
  • 缺失意图配置:discord.py v2.0及以上版本默认关闭消息内容读取权限,需手动开启message_content意图才能正常识别消息指令

修复后可运行代码

import discord
import os

# 配置消息读取意图
intents = discord.Intents.default()
intents.message_content = True

client = discord.Client(intents=intents)
# 授权ID改为整数类型,替换为你实际的用户ID
authUser = {1234567890, 9876543210, 1122334455}

@client.event
async def on_message(message):
    # 跳过机器人自身消息避免循环触发
    if message.author == client.user:
        return
    
    if message.content.lower().startswith('.test'):
        print('rcvd test command')
        if message.author.id in authUser:
            print('authorized user access')
            embed1 = discord.Embed(title='Hello World!')
            await message.channel.send(embed=embed1)

client.run(os.getenv('TOKEN'))

配置注意事项

  • 替换authUser内的示例ID时,直接填写数字格式的用户ID,不需要加引号包裹
  • 需进入Discord开发者平台的机器人管理页,开启Message Content Intent权限,否则机器人无法读取消息内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 00:30:04