Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active October 10, 2018 08:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komasaru/21e26138628ea0b6534a3bba08d1c5a6 to your computer and use it in GitHub Desktop.
Save komasaru/21e26138628ea0b6534a3bba08d1c5a6 to your computer and use it in GitHub Desktop.
Python script to tweet with medias by OAuth only.
#! /usr/local/bin/python3.6
"""
date name version
2017.11.10 mk-mode.com 1.00 新規作成
2018.08.05 mk-mode.com 1.01 画像ツイート機能を追加
Copyright(C) 2017-2018 mk-mode.com All Rights Reserved.
"""
from requests_oauthlib import OAuth1Session
import json
import sys
import traceback
import yaml
class Tweet:
""" Tweet class """
YML = "twitter.yml"
URL_UPD = "https://api.twitter.com/1.1/statuses/update.json"
URL_MEDIA = "https://upload.twitter.com/1.1/media/upload.json"
def __init__(self):
self.ac = sys.argv[1]
self.text = sys.argv[2].replace("\\n", "\n")
self.media_paths = sys.argv[3:] if len(sys.argv) > 3 else []
with open(self.YML) as f:
self.yml = yaml.load(f)
def exec(self):
""" Execution """
try:
if not(self.ac in self.yml):
print("'{}' could not be found!".format(self.ac))
sys.exit(0)
print("[{}]".format(self.ac, self.text))
status_code, res_json = self.__tweet()
if status_code == 200:
print("TWEET-ID:", res_json["id_str"])
else:
print("!ERROR! STATUS-CODE: ", status_code)
except Exception as e:
raise
def __tweet(self):
""" Tweet """
try:
oa = OAuth1Session(
self.yml[self.ac]["cons_key"],
self.yml[self.ac]["cons_sec"],
self.yml[self.ac]["accs_key"],
self.yml[self.ac]["accs_sec"]
)
if self.media_paths == []:
res = oa.post(self.URL_UPD, params = {"status": self.text})
else:
media_ids = []
for m in self.media_paths:
files = {"media" : open(m, 'rb')}
res_m = oa.post(self.URL_MEDIA, files = files)
if res_m.status_code != 200:
return [res_m.status_code, json.loads(res_m.text)]
media_ids.append(
json.loads(res_m.text)["media_id_string"]
)
res = oa.post(
self.URL_UPD,
params = {
"status": self.text,
"media_ids": ",".join(media_ids)
}
)
return [res.status_code, json.loads(res.text)]
except Exception as e:
raise
if __name__ == '__main__':
if len(sys.argv) < 3:
print("USAGE: ./tweet.py SCREEN-NAME TWEET-TEXT [MEDIA-PATH ...]")
sys.exit(0)
try:
Tweet().exec()
except Exception as e:
traceback.print_exc()
sys.exit(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment