Discord Bot已在线但无响应,$inspire命令失效求助
问题排查与修复方案
1. API地址拼写错误
你的get_quote函数里请求的ZenQuotes API地址存在拼写错误:
response = requests.get("https://zenquotes.io/api/ranom")
把ranom修正为正确的random即可:
response = requests.get("https://zenquotes.io/api/random")
2. Discord Intents权限缺失
Discord.py 2.0及以上版本中,Intents.default()默认不包含message_content权限,这会导致Bot无法读取消息内容,从而触发不了$inspire命令的判断逻辑。需要修改intents配置:
intents = discord.Intents.default() intents.message_content = True # 开启消息内容读取权限 client = discord.Client(intents=intents)
同时要在Discord开发者门户的Bot页面,找到「Privileged Gateway Intents」区域,手动开启Message Content Intent权限,否则代码设置无效。
3. 可选:添加异常处理避免崩溃
为防止API请求失败导致Bot崩溃,给get_quote函数补充异常处理:
def get_quote(): try: response = requests.get("https://zenquotes.io/api/random") response.raise_for_status() # 检查请求是否成功 json_data = json.loads(response.text) quote = f"{json_data[0]['q']} - {json_data[0]['a']}" return quote except Exception as e: print(f"获取名言失败: {e}") return "暂时无法获取励志名言,请稍后再试。"
修复后的完整代码
import discord import os import requests import json intents = discord.Intents.default() intents.message_content = True client = discord.Client(intents=intents) def get_quote(): try: response = requests.get("https://zenquotes.io/api/random") response.raise_for_status() json_data = json.loads(response.text) quote = f"{json_data[0]['q']} - {json_data[0]['a']}" return quote except Exception as e: print(f"获取名言失败: {e}") return "暂时无法获取励志名言,请稍后再试。" @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith('$inspire'): quote = get_quote() await message.channel.send(quote) client.run(os.environ['TOKEN'])
内容的提问来源于stack exchange,提问作者Omar Mustafa
相关产品推荐
相关产品推荐

