twitools/transbot.py
2015-03-19 01:57:48 +01:00

82 lines
1.9 KiB
Python

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import HTMLParser, tweepy, os, translate
# [target_language,cons_key,cons_secret,access_token,access_secret]
accounts = [
]
origin = "Handle of original account (without @)"
search = "from:" + origin
last_id_filename = "last_id"
rt_bot_path = os.path.dirname(os.path.abspath(__file__))
last_id_file = os.path.join(rt_bot_path, last_id_filename)
auth = tweepy.OAuthHandler(accounts[0][1], accounts[0][2])
auth.set_access_token(accounts[0][3], accounts[0][4])
api = tweepy.API(auth)
try:
with open(last_id_file, "r") as file:
savepoint = file.read()
except IOError:
savepoint = ""
print "No savepoint found. Trying to get as many results as possible."
timelineIterator = tweepy.Cursor(api.search, q=search, since_id=savepoint).items()
timeline = []
for status in timelineIterator:
timeline.append(status)
timeline.reverse()
tw_counter = 0
er_counter = 0
for status in timeline:
print "(%(date)s) %(name)s: %(message)s\n" % \
{ "date" : status.created_at,
"name" : status.author.screen_name.encode('utf-8'),
"message" : status.text.encode('utf-8') }
text = HTMLParser.HTMLParser().unescape(status.text).encode('utf-8')
if text[0] == "@":
continue
for a in accounts:
auth = tweepy.OAuthHandler(a[1], a[2])
auth.set_access_token(a[3], a[4])
api = tweepy.API(auth)
tstring = ""
curstr = ""
for word in text.split(" "):
curstr += word
if word[-1] in "!?.":
tstring += translate.Translator(to_lang=a[0]).translate(curstr)) + " "
curstr = ""
if curstr != "":
tstring += translate.Translator(to_lang=a[0]).translate(curstr))
try:
api.update_status(tstring.encode('utf-8')[:140])
tw_counter += 1
except tweepy.error.TweepError, e:
print e
er_counter += 1
continue
with open(last_id_file, "w") as file:
file.write(str(status.id))
print "Finished. %d Tweets retweeted. %d errors occurred." % (tw_counter, er_counter)