使用youtube API返回youtube livechat消息的Python脚本在一段时间后返回奇怪的KeyError和NoneType错误
我试图制作一个python脚本,通过命令行显示实时流聊天。我在问题中找到了用户的评论:10914284,我稍微修改了他的答案。这个程序运行了一段时间,但过了一段时间它会引发两种类型的错误。它可以显示livestream聊天一会儿,然后引发一个KeyError:使用youtube API返回youtube livechat消息的Python脚本在一段时间后返回奇怪的KeyError和NoneType错误,python,json,python-requests,youtube-api,keyerror,Python,Json,Python Requests,Youtube Api,Keyerror,我试图制作一个python脚本,通过命令行显示实时流聊天。我在问题中找到了用户的评论:10914284,我稍微修改了他的答案。这个程序运行了一段时间,但过了一段时间它会引发两种类型的错误。它可以显示livestream聊天一会儿,然后引发一个KeyError: Traceback (most recent call last): File "get_chat.py", line 58, in <module> print_message() File "get_cha
Traceback (most recent call last):
File "get_chat.py", line 58, in <module>
print_message()
File "get_chat.py", line 54, in print_message
for i in range(len(messages['items'])):
KeyError: 'items'
我有一些关于为什么会发生这种情况的假设。对于KeyError,当有200多条消息('maxResults':200
)时,可能会引发错误。我尝试将“maxResults”
值更改为类似2000的值,但仍然出现错误。
TypeError仅在您尝试多次运行脚本时出现,一段时间后,它会引发此错误。我想这可能是因为我在请求而消息重叠?不知怎的,它超出了范围?另一种可能是,我已经使用了当天所有的谷歌配额,API不会返回任何信息
任何帮助都将不胜感激。非常感谢。简单地说,我先检查一下钥匙
if __name__ == "__main__":
response = get_liveChatId()
items = response["items"]
for item in items:
if "liveChatId" in item['snippet']:
print(item['snippet']['liveChatId']) #Get the liveChatId
else:
pass
import requests
import json
API_KEY = 'YOUTUBE_API_KEY_HERE'
channelID = 'UC9pYOJPB5UYlMlGKKZWo-Bw' # Random youtube channel that is currently broadcasting a youtube livestream
params = {
'part': 'id',
'key': API_KEY,
'channelId': channelID,
'eventType': 'live',
'type': 'video',
'order': 'viewCount',
'fields': 'items(id(videoId))'
}
url = 'https://www.googleapis.com/youtube/v3/search'
r = requests.get(url, headers=None, params=params).json()
vID = r.get('items')[0].get('id').get('videoId')
#vID = r.get('items')[0]['id']['videoId'] returns same KeyError
params = {
'part': 'liveStreamingDetails,statistics,snippet',
'key': API_KEY,
'id': vID,
'fields': 'items(id,liveStreamingDetails(activeLiveChatId,concurrentViewers,actualStartTime),' + \
'snippet(channelId,channelTitle,description,liveBroadcastContent,publishedAt,thumbnails,title),statistics)'
}
url = 'https://www.googleapis.com/youtube/v3/videos'
r = requests.get(url, headers=None, params=params).json()
streamData = dict(r.get('items')[0])
chatID = streamData['liveStreamingDetails']['activeLiveChatId']
params = {
'part': 'snippet',
'key': API_KEY,
'liveChatId': chatID,
#'profileImageSize': 720,
'maxResults': 200
}
url = 'https://www.googleapis.com/youtube/v3/liveChat/messages'
def print_message():
while True:
messages = requests.get(url, headers=None, params=params).json()
for i in range(len(messages['items'])):
print(messages['items'][i]['snippet']['displayMessage'])
print_message()
if __name__ == "__main__":
response = get_liveChatId()
items = response["items"]
for item in items:
if "liveChatId" in item['snippet']:
print(item['snippet']['liveChatId']) #Get the liveChatId
else:
pass