使用 youtube API 返回 youtube 实时聊天消息的 Python 脚本在一段时间后返回奇怪的 KeyError 和 NoneType 错误 [英] Python script returning youtube livechat messages with youtube API returns weird KeyError and NoneType errors after some time

查看:40
本文介绍了使用 youtube API 返回 youtube 实时聊天消息的 Python 脚本在一段时间后返回奇怪的 KeyError 和 NoneType 错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个通过命令行显示实时流聊天的 python 脚本.我在问题 Can无法从我不拥有的流中获得实时聊天,我稍微修改了他的回答.这个程序运行了一段时间,但过了一会儿它会引发两种类型的错误.它可以显示直播聊天一段时间,然后引发 KeyError:

I am trying to make a python script that displays a live stream chat through the command line. I found a comment by user:10914284 in the question Can't get live chat from stream I do not own and I modified his answer a little bit. This program works for a little bit, but then it raises two types of errors after a while. It can display the livestream chat for a little while then it raises a KeyError:

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'

奇怪的是,如果我尝试多次运行该程序,它会引发 TypeError,即使几分钟前脚本运行得很好.

Strangely, if I try to run the program multiple times it raises a TypeError, even though a couple of minutes ago the script ran just fine.

Traceback (most recent call last):
  File "get_chat.py", line 22, in <module>
    vID = r.get('items')[0]['id']['videoId']
TypeError: 'NoneType' object is not subscriptable

代码:

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()

我对这些可能发生的原因有一些假设.对于 KeyError,也许当有超过 200 条消息 ('maxResults': 200) 时,它会引发错误.我尝试将 ''maxResults' 值更改为 2000 之类的值,但错误仍然出现.TypeError 仅在您尝试多次运行脚本时出现,一段时间后,它会引发此错误.我认为这可能是因为我正在请求并且消息重叠?不知何故它超出了范围?另一种可能是我用完了当天所有的 google 配额,而 API 不会返回任何东西.

I have some hypotheses for why these might be happening. For the KeyError, maybe when there are more than 200 messages ('maxResults': 200) it raises the error. I tried changing the ''maxResults' value to something like 2000 but the error still appears. The TypeError only appears if you try to run the script multiple times, and after some time, it raises this error. I think this might be happening because I am requesting and the messages overlap? And somehow it is out of range? The other possibility is that I have used all my google quotas for the day and the API wont return me anything.

任何帮助将不胜感激.非常感谢.

Any help would be appreciated. Thank you very much.

推荐答案

那是因为你已经用完了所有的每日配额.

That is because you have spent all your daily quota.

这篇关于使用 youtube API 返回 youtube 实时聊天消息的 Python 脚本在一段时间后返回奇怪的 KeyError 和 NoneType 错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆