Skip to content

Instantly share code, notes, and snippets.

@yavuzKomecoglu
Last active January 28, 2020 18:27
Show Gist options
  • Save yavuzKomecoglu/fe4606f4348fc17c090983863fa04c6f to your computer and use it in GitHub Desktop.
Save yavuzKomecoglu/fe4606f4348fc17c090983863fa04c6f to your computer and use it in GitHub Desktop.
youtube live broadcast control
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#Sample use: $ python3 test_youtube_live.py -c "UCryGec9PdUCLjpJW2mgCuLw"
# {'video_id': 'j78TwQCfEzc', 'video_link': 'https://www.youtube.com/watch?v=j78TwQCfEzc', 'published_at': '2019-11-14T03:13:53.000Z', 'title': 'Seeing 2020', 'isLive': True}
import argparse
import requests
import json
ap = argparse.ArgumentParser()
ap.add_argument("-c", "--channel_id", help="youtube channel id")
args = vars(ap.parse_args())
def checkYoutubeChannelIsLive(channel_id, google_api_key):
url_path = "https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={channelId}&type=video&eventType=live&key={apiKey}"
url = url_path.format(channelId = channel_id, apiKey = google_api_key)
#print(url)
r = requests.get(url=url)
#print(r.json())
channel_info = r.json()
channel_status = channel_info["pageInfo"]["totalResults"] > 0
video_id = channel_info["items"][0]["id"]["videoId"] if len(channel_info["items"]) > 0 else None
title = channel_info["items"][0]["snippet"]["title"] if len(channel_info["items"]) > 0 else None
published_at = channel_info["items"][0]["snippet"]["publishedAt"] if len(channel_info["items"]) > 0 else None
if channel_status and video_id is not None and title is not None and published_at is not None:
return {"isLive": True, "video_id": video_id, "video_link": "https://www.youtube.com/watch?v={}".format(video_id), "title": title, "published_at": published_at}
else:
return {"isLive": False}
if __name__ == '__main__':
#channel_id = "UCV6zcRug6Hqp1UX_FdyUeBg" #CNNTurk
channel_id = args["channel_id"]
google_api_key = "{GOOGLE_API_KEY}"
result = checkYoutubeChannelIsLive(channel_id, google_api_key)
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment