Skip to content

Instantly share code, notes, and snippets.

@hapo31
Created March 19, 2021 12:52
Show Gist options
  • Save hapo31/380406f578d2be8475abfc7abf29d408 to your computer and use it in GitHub Desktop.
Save hapo31/380406f578d2be8475abfc7abf29d408 to your computer and use it in GitHub Desktop.
TwitterのURLを入れると動画ファイルを落としてくれるやつ.py
# -*- coding: utf-8 -*-
import os
import sys
import requests
import re
from pprint import pprint
import tweepy
# 公式クライアントのAPIキーなのでどうでもいいやつ
consumer_key = "IQKbtAYlXLripLGPWd0HUA"
consumer_secret = "GgDYlkSvaPxGxC4X8liwpUoqKwwr3lCADbz8A7ADU"
auth = tweepy.auth.AppAuthHandler(consumer_key, consumer_secret)
api = tweepy.API(auth)
def main():
url = ""
id = ""
loop = False
if len(sys.argv) <= 1:
loop = True
elif len(sys.argv) >= 3:
url = sys.argv[1:]
else:
url = sys.argv[1]
if loop:
while (True):
url = input("tweet url>")
getMedia(url)
elif type(url) is str:
getMedia(url)
else:
for u in url:
getMedia(u)
def getMedia(url):
match = re.search("https:\/\/twitter\.com\/([^\/]+)\/status\/(\d+)\??", url)
id = match.group(2)
tweet = api.get_status(id, tweet_mode="extended")
screen_name = tweet.author.screen_name
ent = None
if hasattr(tweet, "extended_entities"):
ent = tweet.extended_entities["media"][0]["video_info"]["variants"]
else:
print("Not available media data.")
exit(1)
media_url = ""
m3m8_url = ""
max_height = 0
max_height_url = ""
for i in ent:
if "content_type" in i:
if i["content_type"] == "video/mp4":
url = i["url"]
url_parts = url.split("/")
video_height = int(url_parts[-2].split("x")[1])
if video_height > max_height:
max_height = video_height
max_height_url = url
elif i["content_type"] == "application/x-mpegURL":
m3m8_url = i["url"]
media_url = max_height_url
if media_url or m3m8_url:
is_mp4 = len(media_url) != 0
target_url = media_url if is_mp4 else m3m8_url
print("find media:%s" % target_url)
r = requests.get(target_url)
if r.status_code == 200:
# id をファイル名にする
filename = "%s.mp4" % id
try:
os.mkdir("%s" % screen_name)
except:
pass
mode = "wb" if is_mp4 else "w"
with open("./%s/%s" % (screen_name, filename), mode) as f:
f.write(r.content)
print("*** file saved by %s ***" % filename)
else:
print("raised error. status:(%s)" % r.status_code)
print("done.")
else:
print("not found media...")
if __name__ == '__main__':
import traceback
exitCode = 0
try:
main()
except KeyboardInterrupt:
exit(0)
except Exception:
print(traceback.format_exc())
exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment