twitools/transbot.py

70 lines
1.8 KiB
Python
Raw Permalink Normal View History

2017-02-28 10:03:20 +00:00
#!/usr/bin/env python3
import httptools, html.parser, tweepy, os, setuptools, google.cloud.translate, twitools, re
2017-02-28 11:01:35 +00:00
lang = setuptools.getListSetting("Translate", "lang")
ato = setuptools.getListSetting("Translate", "ato")
ase = setuptools.getListSetting("Translate", "ase")
2017-02-28 11:01:35 +00:00
if not (len(lang) == len(ato) and len(ato) == len(ase)):
raise setuptools.SetupException("Lists do not match in config.cfg.")
2017-02-28 11:01:35 +00:00
accounts = []
i = 0
2017-02-28 11:01:35 +00:00
while i < len(lang):
accounts += [[lang[i], ato[i], ase[i]]]
i += 1
origin = twitools.twoHelper().whoami()
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)
try:
with open(last_id_file, "r") as file:
savepoint = file.read()
except IOError:
savepoint = ""
2017-02-28 10:02:43 +00:00
print("No savepoint found. Trying to get as many results as possible.")
2017-02-28 11:01:35 +00:00
timeline = twitools.twoHelper().search(search, savepoint)
tw_counter = 0
er_counter = 0
translator = google.cloud.translate.Client()
for status in timeline:
2017-02-28 11:03:12 +00:00
text = html.parser.HTMLParser().unescape(status.text)
if text[0] == "@" or text[:4] == "RT @":
continue
for a in accounts:
2017-02-28 11:01:35 +00:00
two = twitools.twObject(ato=a[1], ase=a[2])
2017-03-13 22:36:04 +00:00
split = text.split()
intext = ""
for s in split:
if re.match(r'https?:\/\/[\S]*', s):
intext = " ".join([intext, httptools.shortURL(s)])
2017-03-13 22:36:04 +00:00
else:
intext = " ".join([intext, s])
2017-03-01 19:55:39 +00:00
tstring = translator.translate(intext, target_language=a[0])['translatedText'].replace("@", "@")
try:
two.tweet(html.parser.HTMLParser().unescape(tstring[:280]))
tw_counter += 1
2017-02-28 11:01:35 +00:00
except Exception as e:
2017-02-28 10:02:43 +00:00
print(e)
er_counter += 1
continue
with open(last_id_file, "w") as file:
file.write(str(status.id))
2017-02-28 10:02:43 +00:00
print("Finished. %d Tweets retweeted. %d errors occurred." % (tw_counter, er_counter))