ticketfrei/active_bots/mastodonbot.py

74 lines
2.6 KiB
Python
Raw Permalink Normal View History

2018-03-28 15:36:35 +00:00
#!/usr/bin/env python3
from bot import Bot
import logging
2019-02-02 21:02:56 +00:00
from mastodon import Mastodon, MastodonServerError
2018-03-28 15:36:35 +00:00
import re
from report import Report
logger = logging.getLogger(__name__)
class MastodonBot(Bot):
def crawl(self, user):
"""
Crawl mentions from Mastodon.
:return: list of statuses
"""
mentions = []
try:
m = Mastodon(*user.get_masto_credentials())
except TypeError:
2018-09-13 15:33:33 +00:00
# logger.error("No Mastodon Credentials in database.", exc_info=True)
return mentions
2018-03-28 15:36:35 +00:00
try:
notifications = m.notifications()
2019-02-02 21:02:56 +00:00
except MastodonServerError:
logger.error("Unknown Mastodon API Error: 502")
2018-03-28 15:36:35 +00:00
return mentions
for status in notifications:
if (status['type'] == 'mention' and
2018-09-24 18:54:57 +00:00
not user.toot_is_seen(status['status']['uri'])):
2018-03-28 15:36:35 +00:00
# save state
2018-09-24 18:54:57 +00:00
user.toot_witness(status['status']['uri'])
2018-03-28 15:36:35 +00:00
# add mention to mentions
text = re.sub(r'<[^>]*>', '', status['status']['content'])
text = re.sub(
"(?<=^|(?<=[^a-zA-Z0-9-_.]))@([A-Za-z]+[A-Za-z0-9-_]+)",
"", text)
if status['status']['visibility'] == 'public':
mentions.append(Report(status['account']['acct'],
self,
text,
status['status']['id'],
status['status']['created_at']))
else:
mentions.append(Report(status['account']['acct'],
'mastodonPrivate',
text,
status['status']['id'],
status['status']['created_at']))
2018-03-28 15:36:35 +00:00
return mentions
def post(self, user, report):
try:
m = Mastodon(*user.get_masto_credentials())
except TypeError:
return # no mastodon account for this user.
2018-03-28 15:36:35 +00:00
if report.source == self:
try:
m.status_reblog(report.id)
except Exception:
logger.error('Error boosting: ' + report.id, exc_info=True)
2018-03-28 15:36:35 +00:00
else:
2018-04-15 09:42:34 +00:00
text = report.text
if len(text) > 500:
text = text[:500 - 4] + u' ...'
try:
2018-04-15 09:42:34 +00:00
m.toot(text)
except Exception:
2018-09-13 15:33:33 +00:00
logger.error('Error tooting: ' + user.get_city() + ': ' +
report.id, exc_info=True)