Python开发的Discord bot调用timezonedb接口无法正常发消息如何解决
问题排查与修复方案
根因定位
get_time()函数的返回值为None:pprint.pprint()方法的作用是将内容打印到终端,本身没有有效返回值,你赋值给clock变量的内容实际是None,Discord 发送None时就会表现为空白消息。
修复代码
修正get_time函数返回逻辑
def get_time(): response = requests.get("http://api.timezonedb.com/v2.1/get-time-zone?key=W9BJQ3QMGG69&format=json&by=position&lat=37.9838&lng=23.7275") json_data = response.json() # 保留终端打印的逻辑 pprint.pprint(json_data) # 返回格式化后的JSON字符串用于发送Discord消息 return json.dumps(json_data, indent=2, ensure_ascii=False)
可选:新增异常捕获逻辑
避免接口请求超时、报错导致bot运行异常:
def get_time(): try: response = requests.get( "http://api.timezonedb.com/v2.1/get-time-zone?key=W9BJQ3QMGG69&format=json&by=position&lat=37.9838&lng=23.7275", timeout=10 ) response.raise_for_status() json_data = response.json() pprint.pprint(json_data) return json.dumps(json_data, indent=2, ensure_ascii=False) except Exception as e: return f"时间数据拉取失败:{str(e)}"
适配高版本discord.py的补充修改
如果你使用的是discord.py v2.0及以上版本,需要显式开启消息内容意图才能正常读取命令,修改client初始化代码:
intents = discord.Intents.default() intents.message_content = True client = discord.Client(intents=intents)
内容的提问来源于stack exchange,提问作者Adam Marx
相关产品推荐
相关产品推荐

