ticketfrei/ticketfrei.py

84 lines
2.5 KiB
Python
Raw Normal View History

2017-06-17 16:15:13 +00:00
#!/usr/bin/env python3
import pytoml as toml
import mastodon
import os
2017-06-17 18:27:53 +00:00
import pickle
import re
2017-06-17 16:15:13 +00:00
import time
2017-06-17 17:37:33 +00:00
2017-06-17 18:27:53 +00:00
class RetootBot(object):
2017-06-17 17:37:33 +00:00
def __init__(self, config):
self.config = config
self.register()
self.login()
# load state
try:
with open('seen_toots.pickle', 'rb') as f:
self.seen_toots = pickle.load(f)
except IOError:
self.seen_toots = set()
def register(self):
self.client_id = os.path.join(
'appkeys',
2017-06-17 18:27:53 +00:00
self.config['mapp']['name'] +
'@' + self.config['muser']['server']
2017-06-17 17:37:33 +00:00
)
if not os.path.isfile(self.client_id):
mastodon.Mastodon.create_app(
2017-06-17 18:27:53 +00:00
self.config['mapp']['name'],
api_base_url=self.config['muser']['server'],
2017-06-17 17:37:33 +00:00
to_file=self.client_id
)
def login(self):
self.m = mastodon.Mastodon(
client_id=self.client_id,
2017-06-17 18:27:53 +00:00
api_base_url=self.config['muser']['server']
2017-06-17 17:37:33 +00:00
)
self.m.log_in(
2017-06-17 18:27:53 +00:00
self.config['muser']['email'],
self.config['muser']['password']
2017-06-17 17:37:33 +00:00
)
2017-06-17 18:27:53 +00:00
def retoot(self, toots=[]):
# toot external provided messages
for toot in toots:
self.m.toot(toot)
# boost mentions
retoots = []
2017-06-17 17:37:33 +00:00
for notification in self.m.notifications():
if (notification['type'] == 'mention'
and notification['status']['id'] not in self.seen_toots):
print('Boosting toot %d from %s: %s' % (
notification['status']['id'],
notification['status']['account']['acct'],
notification['status']['content']))
self.m.status_reblog(notification['status']['id'])
2017-06-17 18:27:53 +00:00
retoots.append(re.sub('<[^>]*>', '',
notification['status']['content']))
2017-06-17 17:37:33 +00:00
self.seen_toots.add(notification['status']['id'])
# save state
2017-06-17 18:27:53 +00:00
with open('seen_toots.pickle.part', 'xb') as f:
2017-06-17 17:37:33 +00:00
pickle.dump(self.seen_toots, f)
os.rename('seen_toots.pickle.part', 'seen_toots.pickle')
2017-06-17 18:27:53 +00:00
# return mentions for mirroring
return retoots
2017-06-17 17:37:33 +00:00
if __name__ == '__main__':
# read config in TOML format (https://github.com/toml-lang/toml#toml)
with open('ticketfrei.cfg') as configfile:
bot = RetootBot(toml.load(configfile))
while True:
bot.retoot()
time.sleep(1)