Discord.py机器人对所有消息回复相同内容的问题求助
Discord.py机器人对所有用户消息返回相同内容的排查与修复
问题根源分析
结合你提供的代码,导致所有用户消息返回相同内容的核心问题集中在以下几点:
- API请求URL为空:
generate_response函数中url = '',直接导致HTTP请求失败,触发异常后所有请求都会使用默认的"No response"作为响应。 - 历史记录清空操作无效:两处
message_history[key].clear缺少括号,没有实际执行清空操作,错误的对话历史会被重复使用,引发统一的错误响应。 - 异常处理逻辑缺失细节:API请求失败时没有针对性的错误提示,所有异常都会返回相同的默认文本,且缺乏错误日志辅助排查问题。
修复步骤
补全API请求URL
将generate_response中的空URL替换为你实际使用的GPT接口地址,例如OpenAI官方接口:url = "https://api.openai.com/v1/chat/completions"同时根据接口要求补充授权信息到请求头,比如添加:
headers = { 'Content-Type': 'application/json', 'Authorization': f'Bearer {os.environ["OPENAI_API_KEY"]}' }修复历史记录清空调用
将on_message中两处message_history[key].clear修改为带括号的方法调用,确保实际执行清空:if response == "No valid response available.": message_history[key].clear() # 添加上括号执行清空操作 except Exception as e: print(f"生成响应时出错: {str(e)}") # 添加错误日志便于排查 message_history[key].clear() # 添加上括号执行清空操作优化异常处理与响应逻辑
为不同错误场景设置差异化提示,避免所有情况返回相同内容:try: response = await generate_response(history) if response == "No valid response available.": message_history[key].clear() response = "我没获取到有效内容,我们重新聊吧?" except Exception as e: print(f"API请求出错: {str(e)}") message_history[key].clear() response = "抱歉,我现在有点卡壳,稍后再试呀~"验证API响应结构
检查当前API返回的JSON格式是否与代码解析逻辑匹配。如果接口返回结构变更(比如第三方代理接口的字段不同),需要调整generate_response中的解析代码:# 示例:如果API返回的是data.response字段而非choices结构 response_message = completion.get("data", {}).get("response", "No valid response available.")
额外优化建议
- 在
generate_response中添加HTTP响应状态码检查,快速定位请求是否成功:async with session.post(url, headers=headers, json=data) as response: if response.status != 200: print(f"API请求失败,状态码: {response.status}") raise Exception(f"HTTP Error {response.status}") completion = json.loads(await response.text()) - 定期清理
message_history中长时间未活跃用户的记录,避免内存占用过高。
内容的提问来源于stack exchange,提问作者Samir
相关产品推荐
相关产品推荐

