为什么我从YouTube API收到错误404“未找到视频”?

时间:2016-08-21 16:26:16

标签: python youtube-api python-3.5

我目前正在编写一个slack / youtube插件,用于将已发布的youtube链接添加到播放列表中。我认为代码还可以,但我刚刚开始,不知道是不是oauth还是我。

这是错误:

 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?')

2 个答案:

答案 0 :(得分:0)

404错误表示无法找到站点或API。你将会遇到很多关于API的问题。不幸的是我无法帮助你,因为我没有使用Python和API,只是检查你的请求和发送

答案 1 :(得分:0)

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

此外,credentials = run(flow, storage)已弃用。它应该是credentials = run_flow(flow, storage)