2016-08-21 36 views
0

我目前正在編寫一個slack/youtube插件,將發佈的youtube鏈接添加到播放列表中。我認爲代碼是好的,但我剛剛開始,不知道它是oauth還是我。爲什麼我從YouTube API獲取404「視頻未找到」錯誤?

以下是錯誤:

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

您試圖添加到播放列表的視頻是否適用於所有人? – e666

+0

@ e666是的,我試過了多個ID,它返回相同的錯誤。 – SoNiKBooM

回答

0

找到它。這是代碼。我將所有輸出解析爲.lower(),因此視頻ID不正確。謝謝你們的幫助。

此外,credentials = run(flow, storage)已棄用。它應該是credentials = run_flow(flow, storage)

0

404錯誤意味着該網站或API無法找到。你會在API中遇到很多。不幸的是,我不能幫你進一步,因爲我沒有使用Python的Python,但只是檢查你的請求和發送