Last active
December 3, 2016 20:33
-
-
Save wodim/9f646c7d024b40d9118a31b3591860fd to your computer and use it in GitHub Desktop.
This file contains hidden or 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
from datetime import datetime | |
import os | |
import pickle | |
import sys | |
import markovify | |
import tweepy | |
CONFIG_KEYS = { | |
'aniruel': ('', '', '', ''), | |
'manolon': ('', '', '', ''), | |
'neus': ('', '', '', ''), | |
'toalla': ('', '', '', ''), | |
} | |
if len(sys.argv) != 3 or sys.argv[1] not in CONFIG_KEYS: | |
print('Usage: %s <twitter> <corpus>' % sys.argv[0]) | |
print('Available Twitter tokens: ' + ', '.join(list(CONFIG_KEYS))) | |
sys.exit(1) | |
_, config_key, corpus_filename = sys.argv | |
consumer_key, consumer_secret, access_token, access_token_secret = \ | |
CONFIG_KEYS[config_key] | |
model_filename = corpus_filename + '.pickle' | |
if os.path.exists(model_filename): | |
with open(model_filename, 'rb') as fp: | |
unpickled_model = pickle.load(fp) | |
text_model = markovify.Text.from_dict(unpickled_model) | |
else: | |
with open(corpus_filename) as fp: | |
text = fp.read() | |
if text.count('\n') > 2: | |
text_model = markovify.NewlineText(text, state_size=3) | |
else: | |
text_model = markovify.Text(text, state_size=3) | |
with open(model_filename, 'wb') as fp: | |
pickle.dump(text_model.to_dict(), fp) | |
auth = tweepy.OAuthHandler(consumer_key, consumer_secret) | |
auth.set_access_token(access_token, access_token_secret) | |
api = tweepy.API(auth) | |
while True: | |
sentence = text_model.make_short_sentence(140, tries=10000) | |
if sentence is None: | |
continue | |
try: | |
api.update_status(sentence) | |
except tweepy.error.TweepError as e: | |
if e.api_code == 187: # status is a duplicate | |
continue | |
else: # any other error | |
raise | |
else: | |
break | |
print('[%s] %s -> %s' % (datetime.now(), config_key, sentence)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment