diff --git a/README.md b/README.md index 3abdc94..7877042 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,13 @@ # twiki -This tool is meant to be run regularily and tweets recent changes made to a MediaWiki. +Cross-posts recent changes made to a MediaWiki. +This tool started as "twitter only" news updater but is now a cross-poster. -It can be seen in action at [@chaosdorf_wiki](https://twitter.com/chaosdorf_wiki). +It can be seen in action at: +* Twitter https://twitter.com/chaosdorf_wiki +* Mastodon https://botsin.space/web/@chaosdorf_wiki +* Matrix https://app.element.io/#/room/#chaosdorf-activities:cybre.space +* Discord ## requirements @@ -10,7 +15,7 @@ twiki needs a few things to work: * Python 3 * a MediaWiki to monitor (it needs no account or key, though) - * a Twitter account to post from (with credentials) + * at least one supported social media account to post from (with credentials) * a few Python libraries ## installation diff --git a/config.py b/config.py index 95a313e..697b8e5 100644 --- a/config.py +++ b/config.py @@ -14,22 +14,26 @@ IGNORE_MINOR_CHANGES = False IGNORE_BOTS = False +TWITTER_ACTIVE = False TWITTER_DRY_RUN = False TWITTER_API_KEY = '' TWITTER_API_SECRET = '' TWITTER_TOKEN = '' TWITTER_TOKEN_SECRET = '' +MATRIX_ACTIVE = True MATRIX_DRY_RUN = False MATRIX_USER_NAME = '' # @chaosdorf_wiki:matrix.org MATRIX_PASSWORD = '' MATRIX_SERVER = '' # https://matrix-client.matrix.org MATRIX_ROOM_ID = '' # !aqsASgGGPgMEVHeMdW:cybre.space +MASTODON_ACTIVE = True MASTODON_DRY_RUN = False MASTODON_ACCESS_TOKEN = '' MASTODON_API_BASE_URL = '' # https://botsin.space +DISCORD_ACTIVE = True DISCORD_DRY_RUN = False DISCORD_APP_ID = '' DISCORD_TOKEN = '' diff --git a/container/.env b/container/env similarity index 100% rename from container/.env rename to container/env diff --git a/docker-compose.yml b/docker-compose.yml index 714c27a..63ebda8 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -9,8 +9,8 @@ services: #environment: # - "INTERVAL=10" env_file: - - container/.env + - container/env volumes: - .:/app # do not make the .env available within the container - - ./container/dummy/.gitkeep:/app/container/.env + - ./container/dummy/.gitkeep:/app/container/env diff --git a/helper.py b/helper.py index 33e2fe3..0899d64 100644 --- a/helper.py +++ b/helper.py @@ -5,7 +5,21 @@ def any_dry_run(): - return config.TWITTER_DRY_RUN or config.MATRIX_DRY_RUN or config.MASTODON_DRY_RUN + dry_run_count = 0 + + if config.TWITTER_ACTIVE and config.TWITTER_DRY_RUN: + dry_run_count += 1 + + if config.MATRIX_ACTIVE and config.MATRIX_DRY_RUN: + dry_run_count += 1 + + if config.MASTODON_ACTIVE and config.MASTODON_DRY_RUN: + dry_run_count += 1 + + if config.DISCORD_ACTIVE and config.DISCORD_DRY_RUN: + dry_run_count += 1 + + return dry_run_count > 0 def data_valid(data_list): diff --git a/messager.py b/messager.py index a638c6a..aba983f 100644 --- a/messager.py +++ b/messager.py @@ -1,13 +1,14 @@ #!/usr/bin/env python3 import logging + +from requests import ReadTimeout from twython import Twython from clients.MatrixClient import MatrixClient from clients.DiscordClient import DiscordClient from mastodon import Mastodon import config import helper -from readwiki import WikiChange -import readwiki +from readwiki import ReadWiki import CanMessage log = logging.getLogger(__name__) @@ -86,24 +87,29 @@ def run(last_revid): """ log.debug("last rev id: %s", last_revid) - twitter_bot = get_bot_twitter() - matrix_bot = get_bot_matrix() - mastodon_bot = get_bot_mastodon() - discord_bot = get_bot_discord() + twitter_bot = get_bot_twitter() if config.TWITTER_ACTIVE else None + matrix_bot = get_bot_matrix() if config.MATRIX_ACTIVE else None + mastodon_bot = get_bot_mastodon() if config.MASTODON_ACTIVE else None + discord_bot = get_bot_discord() if config.DISCORD_ACTIVE else None changes = list() changes_overflow = False new_messages_count = 0 - for change in readwiki.get_changes(): - if change.revId <= last_revid: - break - new_messages_count += 1 - changes.append(change) + try: + read_wiki = ReadWiki() + for change in read_wiki.get_changes(): + if change.revId <= last_revid: + break + + new_messages_count += 1 + changes.append(change) - if new_messages_count >= config.MAX_ENTRIES: - changes_overflow = True - break + if new_messages_count >= config.MAX_ENTRIES: + changes_overflow = True + break + except ReadTimeout as ex: + log.debug("Read TimeOut: %s", ex) log.debug("got the following changes: %s", changes) @@ -114,7 +120,7 @@ def run(last_revid): missing_message = \ "Limit of {} changes reached. Please see https://{}{}Special:RecentChanges for more information."\ .format(config.MAX_ENTRIES, config.WIKI_SITE, config.WIKI_VIEW_PATH) - missing_link = WikiChange() + missing_link = ReadWiki.WikiChange() missing_link.revId = changes[-1].revId missing_link.set_message(missing_message) @@ -202,7 +208,7 @@ def send_discord(_discord, message): log.info("finished, got %s as the latest revid", highest_ref_id) if helper.any_dry_run(): - log.info("DRY_RUN, don't save revid") + log.warning("DRY_RUN, don't save %s revid", highest_ref_id) else: can_message.set_last_revid(highest_ref_id) can_message.save() diff --git a/readwiki.py b/readwiki.py index 466cbcc..4c042d4 100755 --- a/readwiki.py +++ b/readwiki.py @@ -1,139 +1,160 @@ #!/usr/bin/env python3 from mwclient import Site +from requests import ReadTimeout + import config import logging log = logging.getLogger(__name__) -site = Site(config.WIKI_SITE, path=config.WIKI_API_PATH) - - -class WikiChange: - def __init__(self): - self.hasData = False - self.revision = None - self.change = None - self.revId = -1 - self.message = '' - - def set_data(self, _revision, _change): - self.hasData = True - self.revision = _revision - self.change = _change - self.revId = self.change["revid"] - - def set_message(self, _message): - self.message = _message - - def can_be_send(self): - """ - various checks to see if the change might be spam or other unwanted stuff - """ - - # show_params.append("!log") does not work? re-patch - if self.change["type"] == "log": - log.debug('exclude log') - return False - - if not self.hasData: - log.debug('HAS NO DATA') - return False - - return True - - def get_message(self): - if self.message != '': - return self.message - - if not self.hasData: - raise Exception('NO MESSAGE AND NO DATA TO PROCESS!') - if self.change["type"] == "new": - # new pages have no diff, just link to the revision - link = "https://{}{}?oldid={}".format( - config.WIKI_SITE, - config.WIKI_VIEW_PATH, - self.change["revid"], +class ReadWiki: + + class WikiChange: + + def __init__(self): + self.hasData = False + self.revision = None + self.change = None + self.revId = -1 + self.message = '' + + def set_data(self, _revision, _change): + self.hasData = True + self.revision = _revision + self.change = _change + self.revId = self.change["revid"] + + def set_message(self, _message): + self.message = _message + + def can_be_send(self): + """ + various checks to see if the change might be spam or other unwanted stuff + """ + + # show_params.append("!log") does not work? re-patch + if self.change["type"] == "log": + log.debug('exclude log') + return False + + if not self.hasData: + log.debug('HAS NO DATA') + return False + + return True + + def get_message(self): + if self.message != '': + return self.message + + if not self.hasData: + raise Exception('NO MESSAGE AND NO DATA TO PROCESS!') + + if self.change["type"] == "new": + # new pages have no diff, just link to the revision + link = "https://{}{}?oldid={}".format( + config.WIKI_SITE, + config.WIKI_VIEW_PATH, + self.change["revid"], + ) + else: + link = "https://{}{}?type=revision&diff=next&oldid={}".format( + config.WIKI_SITE, + config.WIKI_VIEW_PATH, + self.change["old_revid"], + ) + _message = "{} - {} by {}".format( + self.revision["pagetitle"], link, self.revision["user"] ) - else: - link = "https://{}{}?type=revision&diff=next&oldid={}".format( - config.WIKI_SITE, - config.WIKI_VIEW_PATH, - self.change["old_revid"], - ) - _message = "{} - {} by {}".format( - self.revision["pagetitle"], link, self.revision["user"] - ) - if self.revision["comment"] != "": - _message += " - {}".format(self.revision["comment"]) - - if len(_message) > 279: - _message = _message[:275] + '...' - - self.revId = self.change["revid"] - - self.message = _message - return self.message + if self.revision["comment"] != "": + _message += " - {}".format(self.revision["comment"]) + if len(_message) > 279: + _message = _message[:275] + '...' -def get_filter(): - show_params = list() - # WARNING:mwclient.client:Unrecognized value for parameter "rcshow": !log - #show_params.append("!log") + self.revId = self.change["revid"] - if config.IGNORE_MINOR_CHANGES: - show_params.append("!minor") - if config.IGNORE_BOTS: - show_params.append("!bot") - return '|'.join(show_params) + self.message = _message + return self.message -def get_changes(): - """ Iterates over the recent changes made to the wiki. """ - # maybe support more complex queries? - show = get_filter() - counter_ignored = 0 - counter_blacklist = 0 - counter_revision = 0 - total_changes = 0 - for change in site.recentchanges(show=show): - total_changes += 1 - log.debug("got a change %s", change) - change_obj = WikiChange() + def __init__(self): + self.site = None try: - revisions = site.revisions([change["revid"]]) - if not revisions: - counter_revision += 1 - continue - - revision = revisions[0] - - if revision["user"] in config.USER_NAME_BLACK_LIST: - counter_blacklist += 1 - continue - - change_obj.set_data(revision, change) - - if not change_obj.can_be_send(): - log.debug('was ignored %s', change_obj.revId) - counter_ignored += 1 - continue - - except IndexError as exc: - log.error('recentchanges index ERROR: %s', "{}: {}".format(type(exc).__name__, exc)) - change_obj.set_message("{}: {}".format(type(exc).__name__, exc)) - - yield change_obj - - log.debug( - 'changes | ignored: %s | blacklisted: %s | no revision: %s | of total %s / %s', - counter_ignored, counter_blacklist, counter_revision, - (counter_ignored + counter_blacklist + counter_revision), - total_changes - ) + self.site = Site(config.WIKI_SITE, path=config.WIKI_API_PATH) + except ReadTimeout as ex: + log.debug("ReadWiki Read TimeOut: %s", ex) + + # all other exceptions may fly + #except Exception as ex: + # log.error('ReadWiki.Site could not be initialized: {}'.format(ex)) + + def get_filter(self): + show_params = list() + # WARNING:mwclient.client:Unrecognized value for parameter "rcshow": !log + #show_params.append("!log") + + if config.IGNORE_MINOR_CHANGES: + show_params.append("!minor") + if config.IGNORE_BOTS: + show_params.append("!bot") + return '|'.join(show_params) + + + def get_changes(self): + """ Iterates over the recent changes made to the wiki. """ + + if not self.site: + return + + # maybe support more complex queries? + show = self.get_filter() + counter_ignored = 0 + counter_blacklist = 0 + counter_revision = 0 + total_changes = 0 + + for change in self.site.recentchanges(show=show): + total_changes += 1 + log.debug("got a change %s", change) + change_obj = ReadWiki.WikiChange() + + try: + revisions = self.site.revisions([change["revid"]]) + if not revisions: + counter_revision += 1 + continue + + revision = revisions[0] + + if revision["user"] in config.USER_NAME_BLACK_LIST: + counter_blacklist += 1 + continue + + change_obj.set_data(revision, change) + + if not change_obj.can_be_send(): + log.debug('was ignored %s', change_obj.revId) + counter_ignored += 1 + continue + + except IndexError as exc: + log.error('recentchanges index ERROR: %s', "{}: {}".format(type(exc).__name__, exc)) + change_obj.set_message("{}: {}".format(type(exc).__name__, exc)) + + yield change_obj + + log.debug( + 'changes | ignored: %s | blacklisted: %s | no revision: %s | of total %s / %s', + counter_ignored, counter_blacklist, counter_revision, + (counter_ignored + counter_blacklist + counter_revision), + total_changes + ) if __name__ == '__main__': - for wikiChange in get_changes(): + readWiki = ReadWiki() + for wikiChange in readWiki.get_changes(): print(wikiChange.get_message())