Discord聊天机器人开发调用change_presence接口报错问题求助
Discord机器人运行异常修复方案
你遇到的两个报错都是discord.py版本迭代+aiohttp版本规范更新导致的API不兼容问题,具体修复方式如下:
1. change_presence参数类型错误修复
你使用的是v1.0+版本的discord.py,该版本已经移除了change_presence方法的game关键字参数,设置机器人状态需要传入activity参数,修正后的写法:
await self.change_presence(activity=discord.Game(name='chat with me!'))
注意:你现有代码里还有其他未触发的旧版API写法,运行到对应逻辑时也会报错,统一修正点如下:
- 原
message.server属性已更名为message.guild - 原
self.send_typing(channel)、self.send_message(channel, 内容)方法已移除,改为直接调用通道实例方法:await channel.trigger_typing()触发输入状态、await channel.send(内容)发送消息 - 新版discord.py需要手动开启消息意图才能读取消息内容,需要先去Discord开发者后台的机器人设置页打开
Message Content Intent开关,再在代码里声明对应意图
2. aiohttp会话创建弃用警告修复
aiohttp.ClientSession要求必须在异步执行上下文中创建,不能在全局同步代码块初始化。你可以在on_ready事件里初始化会话并挂载到机器人实例上,同时重写机器人的close方法,在程序退出时主动释放会话资源避免泄漏。
修正后可直接运行的完整代码
import asyncio import aiohttp import discord import re class FrostCleverbot(discord.Client): async def on_ready(self): # 异步初始化aiohttp会话,解决弃用警告 self.http_session = aiohttp.ClientSession() print(f'登录成功,机器人账号:{self.user}') # 修正状态设置参数 await self.change_presence(activity=discord.Game(name='chat with me!')) async def on_message(self, message): # 替换旧版server属性为guild if not message.author.bot and (not message.guild or self.user in message.mentions): # 替换旧版发送输入状态方法 await message.channel.trigger_typing() try: input_content = re.sub(f'<@!?{self.user.id}>', '', message.content).strip() params = { 'botid': 'f6d4afd83e34564d', 'custid': message.author.id, 'input': input_content or 'Hello' } # 使用异步初始化的会话发起请求 async with self.http_session.get('https://www.pandorabots.com/pandora/talk-xml', params=params) as resp: if resp.status == 200: text = await resp.text() text = text[text.find('<that>')+6:text.rfind('</that>')] text = text.replace('"','"').replace('<','<').replace('>','>').replace('&','&').replace('<br>',' ') # 替换旧版发消息方法 await message.channel.send(text) else: await message.channel.send("Uh oh, I didn't quite catch that!") except asyncio.TimeoutError: await message.channel.send("Uh oh, I think my head is on backwards!") async def close(self): # 退出前释放aiohttp会话资源 await self.http_session.close() await super().close() if __name__ == "__main__": print('正在启动机器人...') # 声明消息意图,适配新版discord.py要求 intents = discord.Intents.default() intents.message_content = True # 替换为你自己的机器人Token FrostCleverbot(intents=intents).run('你的机器人Token')
内容的提问来源于stack exchange,提问作者Jake
相关产品推荐
相关产品推荐

