Skip to content

Instantly share code, notes, and snippets.

@komasaru
Last active January 9, 2018 06:46
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/f9880d8a82cf3165d557f21084b355a0 to your computer and use it in GitHub Desktop.
Save komasaru/f9880d8a82cf3165d557f21084b355a0 to your computer and use it in GitHub Desktop.
Python script to tweet with OAuth only.
#! /usr/local/bin/python3.6
"""
Twitter tweet with OAuth only.
date name version
2017.11.10 mk-mode 1.00 Created.
Copyright(C) 2017 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"
def __init__(self):
self.ac = sys.argv[1]
self.text = sys.argv[2].replace("\\n", "\n")
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("[{}]\n{}".format(self.ac, self.text))
status_code, res_json = self.__tweet()
if status_code == 200:
print("(TWEET-ID: {})".format(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"]
)
res = oa.post(self.URL_UPD, params = {"status": self.text})
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")
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