twitools/transbot.py
2017-12-06 18:20:13 +01:00

70 lines
1.8 KiB
Python
Executable file
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
import httptools, html.parser, tweepy, os, setuptools, google.cloud.translate, twitools, re
lang = setuptools.getListSetting("Translate", "lang")
ato = setuptools.getListSetting("Translate", "ato")
ase = setuptools.getListSetting("Translate", "ase")
if not (len(lang) == len(ato) and len(ato) == len(ase)):
raise setuptools.SetupException("Lists do not match in config.cfg.")
accounts = []
i = 0
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 = ""
print("No savepoint found. Trying to get as many results as possible.")
timeline = twitools.twoHelper().search(search, savepoint)
tw_counter = 0
er_counter = 0
translator = google.cloud.translate.Client()
for status in timeline:
text = html.parser.HTMLParser().unescape(status.text)
if text[0] == "@" or text[:4] == "RT @":
continue
for a in accounts:
two = twitools.twObject(ato=a[1], ase=a[2])
split = text.split()
intext = ""
for s in split:
if re.match(r'https?:\/\/[\S]*', s):
intext = " ".join([intext, httptools.shortURL(s)])
else:
intext = " ".join([intext, s])
tstring = translator.translate(intext, target_language=a[0])['translatedText'].replace("@", "@")
try:
two.tweet(html.parser.HTMLParser().unescape(tstring[:280]))
tw_counter += 1
except Exception as 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))