Skip to content

Instantly share code, notes, and snippets.

@ikr7 ikr7/vwatch.py
Created Jan 20, 2019

Embed
What would you like to do?
YouTube 実況ツイートするやつ
#!/usr/bin/env python3
import json
from urllib.request import Request, urlopen
from urllib.parse import urlparse, parse_qs
from twitter import Api
youtube_url = input('YouTube URL > ')
##############################
# Retrieve Video Information #
##############################
video_id = parse_qs(urlparse(youtube_url).query)['v'][0]
url = 'https://www.googleapis.com/youtube/v3/videos?id={id}&key={key}&part=snippet'.format(
id = video_id,
key = 'YouTube Data API v3 にアクセスできる Google の API キー'
)
with urlopen(url) as res:
data = json.loads(res.read().decode('UTF-8'))
title = data['items'][0]['snippet']['title']
description = data['items'][0]['snippet']['description']
channel_name = data['items'][0]['snippet']['channelTitle']
channel_link = 'https://www.youtube.com/channel/{}'.format(data['items'][0]['snippet']['channelId'])
print('Watching {title} by {channel_name}'.format(title = title, channel_name = channel_name))
md = '''
# [{title}]({youtube_url})
![thumbnail](https://i.ytimg.com/vi/{video_id}/hqdefault.jpg)
[{channel_name}]({channel_link})
{description}
## 実況
'''.format(
title = title,
youtube_url = youtube_url,
video_id = video_id,
channel_name = channel_name,
channel_link = channel_link,
description = description
)
api = Api(
consumer_key = 'Twitter API の Consumer Key',
consumer_secret = 'Twitter API の Consumer Secret',
access_token_key = 'Twitter API の Access Token',
access_token_secret = 'Twitter API の Access Token Secret'
)
#############
# Tweet URL #
#############
prev_tweet = api.PostUpdate('{title}~ https://youtu.be/{video_id} @YouTubeさんから'.format(title = title, video_id = video_id))
#########
# Watch #
#########
while True:
txt = input('Tweet > ')
if txt == 'quit':
break
prev_tweet = api.PostUpdate(txt, in_reply_to_status_id = prev_tweet.id)
md += '\n- {}'.format(txt)
###############
# Post to esa #
###############
esa_data = {
'post': {
'name': title.replace('/', '|'),
'body_md': md,
'wip': False,
'category': '/適当なカテゴリ'
}
}
esa_token = 'esaのアクセストークン'
req = Request(
url = 'https://api.esa.io/v1/teams/esa チーム ID/posts',
headers = {
'Authorization': 'Bearer {}'.format(esa_token),
'Content-Type': 'application/json'
},
method = 'POST',
data = json.dumps(esa_data).encode('UTF-8')
)
with urlopen(req) as res:
body = res.read()
esa_url = json.loads(body.decode('UTF-8'))['url']
print('Summerized: {}'.format(esa_url))
api.PostUpdate(esa_url, in_reply_to_status_id = prev_tweet.id)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.