Created
July 5, 2016 11:04
-
-
Save yue82/6378c832cbe0cc5eb44d7e1591e9de9e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
import os | |
import sys | |
import re | |
import json | |
import requests | |
from requests_oauthlib import OAuth1Session | |
def read_secrets(filename): | |
script_dir = os.path.abspath(os.path.dirname(__file__)) | |
secret_dir = '/'.join(script_dir.split('/')[:-1]) + '/secret' | |
secret_file = secret_dir + '/' + filename | |
secrets = {} | |
with open(secret_file, 'r') as fs: | |
for line in fs: | |
k, v = line.strip().split(' ') | |
secrets[k] = v | |
return secrets | |
def check_status(status_code): | |
if status_code == 200: | |
return True | |
func_name = sys._getframe(1).f_code.co_name | |
print 'Error({}): {}'.format(func_name, status_code) | |
exit(1) | |
def get_tltop_tweet(tw_secrets): | |
url = 'https://api.twitter.com/1.1/statuses/home_timeline.json' | |
twitter = OAuth1Session(tw_secrets['CK'], | |
tw_secrets['CS'], | |
tw_secrets['AT'], | |
tw_secrets['AS']) | |
params = {'count': 1, | |
'trim_user': True} | |
req = twitter.get(url, params=params) | |
check_status(req.status_code) | |
tltop_tw = json.loads(req.text)[0]['text'].strip() | |
return tltop_tw | |
def extract_main_text(tweet): | |
pattern = r'(@[a-zA-Z0-9_]+:?)|'\ | |
'(https?://[a-zA-Z0-9/.]+)|'\ | |
'(RT\ )|(#[\S]+)' | |
return re.sub(pattern, '', tweet).replace('\n', '').strip() | |
def get_bot_reply(tltop_tw, bot_secrets): | |
url = 'https://chatbot-api.userlocal.jp/api/chat' | |
params = {'key': bot_secrets['APIkey'], | |
'message': tltop_tw} | |
req = requests.get(url, params=params) | |
check_status(req.status_code) | |
bot_reply = json.loads(req.text)['result'] | |
return bot_reply | |
def post_tweet(tweet, tw_secrets): | |
url = 'https://api.twitter.com/1.1/statuses/update.json' | |
twitter = OAuth1Session(tw_secrets['CK'], | |
tw_secrets['CS'], | |
tw_secrets['AT'], | |
tw_secrets['AS']) | |
postmsg = {'status': tweet} | |
req = twitter.post(url, params=postmsg) | |
check_status(req.status_code) | |
if __name__ == '__main__': | |
tw_secrets = read_secrets('rubot_tw_secret') | |
bot_secrets = read_secrets('ul_aibot_secret') | |
tltop_tw = get_tltop_tweet(tw_secrets) | |
main_text = extract_main_text(tltop_tw) | |
bot_reply = get_bot_reply(main_text, bot_secrets) | |
max_tw_len = 140 | |
full_tweet = u'[bot]{} > "{}"'.format(bot_reply, main_text) | |
if len(full_tweet) > max_tw_len: | |
suffix = u'..."' | |
leave_len = max_tw_len - len(suffix) | |
full_tweet = full_tweet[:leave_len] + suffix | |
post_tweet(full_tweet, tw_secrets) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment