为什么我会收到来自 YouTube API 的错误 404 "Video not found"?



我目前正在编写一个slack/youtube插件来添加发布的youtube链接到播放列表。我认为代码是可以的,但我只是刚开始,不知道它是否对我有用。

错误如下:

 Traceback (most recent call last):
  File "slackapi.py", line 124, in <module>
    add_video_to_playlist(youtube,vidID)
  File "slackapi.py", line 88, in add_video_to_playlist
    'videoId': vidID
  File "/usr/local/lib/python3.5/dist-packages/oauth2client/util.py", line 137, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/local/lib/python3.5/dist-packages/googleapiclient/http.py", line 838, in execute
    raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 404 when requesting https://www.googleapis.com/youtube/v3/playlistItems?alt=json&part=snippet returned "Video not found."

代码如下:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import httplib2
import os
import sys
import time
import urllib
import re
from slackclient import SlackClient
# yt cmds below
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow
from urllib.parse import urlparse, parse_qs
# starterbot's ID as an environment variable
BOT_ID = os.environ.get('BOT_ID')

# constants
AT_BOT = '<@' + BOT_ID + '>'
EXAMPLE_COMMAND = 'do'
# youtube constants
plID = 'PL7KBspcfHWhvOPW-merPTB5vIT1KMK6dS'
CLIENT_SECRETS_FILE = 'client_secrets.json'
YT_COMMAND = 'youtube.'
YOUTUBE_SCOPE = "https://www.googleapis.com/auth/youtube"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
# This variable defines a message to display if the CLIENT_SECRETS_FILE is
# missing.
MISSING_CLIENT_SECRETS_MESSAGE = 
    """ WARNING: Please configure OAuth 2.0
To make this sample run you will need to populate the client_secrets.json file
found at:
   %s
with information from the Developers Console
https://console.developers.google.com/
For more information about the client_secrets.json file format, please visit:
https://developers.google.com/api-client-library/python/guide/aaa_client_secrets
""" 
    % os.path.abspath(os.path.join(os.path.dirname(__file__),
                      CLIENT_SECRETS_FILE))
# This OAuth 2.0 access scope allows for full read/write access to the
# authenticated user's account.
def get_authenticated_service():
        flow = flow_from_clientsecrets(CLIENT_SECRETS_FILE, scope=YOUTUBE_SCOPE,
        message=MISSING_CLIENT_SECRETS_MESSAGE)
        storage = Storage("%s-oauth2.json" % sys.argv[0])
        credentials = storage.get()
        if credentials is None or credentials.invalid:
            credentials = run(flow, storage)
        return build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,
            http=credentials.authorize(httplib2.Http()))

# instantiate Slack client
slack_client = SlackClient(os.environ.get('SLACK_BOT_TOKEN'))

def add_video_to_playlist(youtube,vidID):
      add_video_request=youtube.playlistItems().insert(
      part="snippet",
      body={
            'snippet': {
              'playlistId': plID,
              'resourceId': {
                      'kind': 'youtube#video',
                  'videoId': vidID
                }
            #'position': 0
            }
    }
).execute()

def parse_slack_output(slack_rtm_output):
    output_list = slack_rtm_output
    if output_list and len(output_list) > 0:
        for output in output_list:
            if output and 'text' in output and YT_COMMAND in output['text']:
                # return youtube link
                return output['text'].lower(), 
                       output['channel']
    return None, None

if __name__ == '__main__':
    READ_WEBSOCKET_DELAY = 1  # 1 second delay between reading from firehose
    if slack_client.rtm_connect():
        print ('StarterBot connected and running!')
        while True:
            (command, channel) = 
                parse_slack_output(slack_client.rtm_read())
            if command and channel:
                youtube = get_authenticated_service()
                command = command.split('|', 1)[0]
                pattern = r'(?:https?://)?(?:[0-9A-Z-]+.)?(?:youtube|youtu|youtube-nocookie).(?:com|be)/(?:watch?v=|watch?.+&v=|embed/|v/|.+?v=)?([^&=n%?]{11})'
                vidID = re.findall(pattern, command)
                response = "Your video ID is " + ' '.join(vidID)
                slack_client.api_call("chat.postMessage", channel=channel, text=response, as_user=True)
                add_video_to_playlist(youtube,vidID)
#handle_command(command, channel)
            time.sleep(READ_WEBSOCKET_DELAY)
    else:
        print ('Connection failed. Invalid Slack token or bot ID?')

404错误表示无法找到站点或API。您将在api中经常遇到这种情况。不幸的是,我不能进一步帮助你,因为我没有使用Python api,但只是检查你的请求和发送

找到了。这是代码。我将所有输出解析为。lower(),因此视频id不正确。谢谢你们的帮助。

也不推荐使用credentials = run(flow, storage)。应该是credentials = run_flow(flow, storage)

相关内容

  • 没有找到相关文章

最新更新