Discord.py机器人运行报deny_new相关TypeError排查求助
问题根因
该报错的核心原因是安装了已废弃多年的老旧discord.py 0.16.x版本,该版本完全不匹配Discord现行的官方API规范。当机器人拉取服务器频道的权限覆盖配置时,Discord返回的最新权限参数中包含旧版库从未定义的deny_new字段,旧代码解析参数时直接抛出TypeError: __new__() got an unexpected keyword argument 'deny_new',后续出现的“Task was destroyed but it is pending”是主报错引发的连锁资源回收异常,不属于独立故障。
落地修复步骤
- 彻底清理残留的旧版依赖,避免多版本包冲突:
执行命令:pip uninstall discord discord.py -y
操作中必须同时卸载discord和discord.py两个包——早年PyPI上存在同名非官方discord包,很多开发者误装后会和官方discord.py共存,持续触发兼容问题。 - 安装当前官方稳定版的discord.py库:
执行命令:pip install -U discord.py - 适配新版库的API改动,替换旧版本专属的方法调用:
旧代码里的client.send_message()是0.16版本的专属写法,新版已废弃,需改为频道对象直接调用的channel.send();同时必须匹配新版的意图(Intents)权限要求,否则机器人无法正常接收消息内容。适配后的可运行核心代码如下:import discord from discord.ext import commands TOKEN = '替换为你的机器人Token' # 初始化默认权限 intents = discord.Intents.default() intents.message_content = True # 开启消息内容读取权限,否则无法识别用户指令 client = commands.Bot(command_prefix=':', intents=intents) @client.event async def on_message(message): # 忽略机器人自身发送的消息 if message.author == client.user: return # 匹配help指令 if message.content.startswith(':help'): reply_text = '''Hello! I am Pytho Memer, a meme bot, at your service. You can make me get some nice memes for you.
You can use the following command for it::meme
This command will generate a meme for you.
Hope you will enjoy this. :)'''
await message.channel.send(reply_text)
@client.event
async def on_ready():
print('Logged in as')
print(client.user.name)
print(client.user.id)
print('------')
client.run(TOKEN)
- 配置校验:打开Discord开发者后台对应机器人的设置页,在“Privileged Gateway Intents”板块下打开`Message Content Intent`的开关,否则即使代码完全正确,机器人也读不到频道内的消息文本,出现触发指令无响应的问题。 内容的提问来源于stack exchange,提问作者Bhavyadeep Yadav
相关产品推荐
相关产品推荐

