如何对Twitch API返回的JSON变量使用If判断及排查代码无报错不运行问题
问题定位与修正方案
你遇到的「无报错但程序不生效」的核心原因
- 全局代码执行时序错配:你在Discord客户端完成登录、连上网关之前,就提前发了Twitch请求、准备获取Discord频道对象,这时候
client.get_channel(channelid)拿不到有效频道对象,后续发消息的操作全部空转 - 循环逻辑覆盖:MongoDB遍历循环结束后,全局变量
x、channelid只会保留查询结果的最后一条记录,前面所有配置的主播数据全部被覆盖,根本不会挨个校验直播状态 - 条件判断类型不匹配:Twitch API返回的
is_live是原生布尔值,不是字符串"True",哪怕你写了if finali == "True",这个判断永远不会命中 - 通知逻辑写死:原本应该轮询检查直播状态的逻辑,被写死成了程序启动后每隔60秒固定发一次通知,不管主播是否真的在直播,也不管直播有没有结束
修正后的可运行代码
把所有需要Discord连接完成后执行的逻辑,全部挪到后台任务里,加上每轮的状态检查、异常捕获,直接替换原来的代码即可:
import discord import requests import asyncio import pymongo # 初始化客户端与数据库连接 client = discord.Client() myclient = pymongo.MongoClient("mongodb url") mydb = mydb["Cluster0"] mycol = mydb["live"] # Twitch接口请求固定配置 TWITCH_HEADERS = { 'client-id': 'twitch client id', 'Authorization': 'twitch oauth token', } async def live_check_loop(): # 等Discord客户端完全连上网关 await client.wait_until_ready() # 持续轮询,直到机器人断开连接 while not client.is_closed(): # 每轮都重新拉取数据库里的最新配置,避免配置修改不生效 user_configs = mycol.find({"type": "user"}, {'_id': 0, 'twitch': 1, 'channelID': 1}) for config in user_configs: twitch_username = config.get('twitch') target_channel_id = config.get('channelID') # 跳过配置缺失的无效条目 if not twitch_username or not target_channel_id: continue # 带异常捕获发Twitch请求,避免单条配置出错拖垮整个轮询 try: resp = requests.get( url='https://api.twitch.tv/helix/search/channels', headers=TWITCH_HEADERS, params=(('query', twitch_username),), timeout=10 ) resp.raise_for_status() resp_data = resp.json() # 跳过搜索结果为空的情况 if not resp_data.get('data'): continue channel_info = resp_data['data'][0] # 正确的开播判断:因为is_live是布尔值,直接判断即可,不需要和字符串"True"比对 if channel_info['is_live']: live_title = channel_info['title'] # 替换缩略图的占位符参数,拿到可直接加载的图片地址 live_thumbnail = channel_info['thumbnail_url'].replace('{width}', '1280').replace('{height}', '720') target_channel = client.get_channel(int(target_channel_id)) if not target_channel: continue # 构造Embed并发送通知 notify_embed = discord.Embed( title=f"{twitch_username} 正在Twitch开播", description=live_title, url=f"https://twitch.tv/{twitch_username}", color=0x0C8BC2 ) notify_embed.set_image(url=live_thumbnail) await target_channel.send("@everyone") await target_channel.send(embed=notify_embed) except Exception as e: print(f"处理主播{twitch_username}的状态时出错:{str(e)}") # 每轮轮询间隔60秒 await asyncio.sleep(60) # 把轮询任务挂到事件循环上 client.loop.create_task(live_check_loop()) # 读取本地token启动机器人 discord_token = open("token.txt", "r").read().strip() client.run(discord_token)
关于你需要的If条件判断
按照Twitch API的返回结构,根本不需要写复杂的类型比对,直接判断布尔值即可:
# 正确写法 if channel_info['is_live']: # 执行开播通知逻辑 pass
内容的提问来源于stack exchange,提问作者Pois
相关产品推荐
相关产品推荐

