From 81e59e5f3bcf3b053b6dcaf67e499105f920a25f Mon Sep 17 00:00:00 2001 From: bison-- Date: Sat, 19 Nov 2022 10:23:58 +0100 Subject: [PATCH 1/7] added discord support --- clients/DiscordClient.py | 21 +++++++++++ MatrixClient.py => clients/MatrixClient.py | 0 clients/__init__.py | 0 config.py | 5 +++ helper.py | 10 +++++ messager.py | 43 ++++++++++++++++++---- requirements.txt | 1 + 7 files changed, 72 insertions(+), 8 deletions(-) create mode 100644 clients/DiscordClient.py rename MatrixClient.py => clients/MatrixClient.py (100%) create mode 100644 clients/__init__.py diff --git a/clients/DiscordClient.py b/clients/DiscordClient.py new file mode 100644 index 0000000..e6fa604 --- /dev/null +++ b/clients/DiscordClient.py @@ -0,0 +1,21 @@ +import config +import logging +import requests + +log = logging.getLogger(__name__) + + +class DiscordClient: + def __init__(self): + self.URL = 'https://discord.com/api/v9/channels/{}/messages'.format(config.DISCORD_CHANNEL_ID) + + def send_message(self, message): + header = { + 'authorization': 'Bot ' + config.DISCORD_TOKEN, + } + + payload = { + 'content': message, + } + + requests.post(self.URL, data=payload, headers=header) diff --git a/MatrixClient.py b/clients/MatrixClient.py similarity index 100% rename from MatrixClient.py rename to clients/MatrixClient.py diff --git a/clients/__init__.py b/clients/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/config.py b/config.py index 4b55f3e..95a313e 100644 --- a/config.py +++ b/config.py @@ -30,6 +30,11 @@ MASTODON_ACCESS_TOKEN = '' MASTODON_API_BASE_URL = '' # https://botsin.space +DISCORD_DRY_RUN = False +DISCORD_APP_ID = '' +DISCORD_TOKEN = '' +DISCORD_CHANNEL_ID = '' + USER_NAME_BLACK_LIST = set() diff --git a/helper.py b/helper.py index 96b4565..33e2fe3 100644 --- a/helper.py +++ b/helper.py @@ -45,3 +45,13 @@ def can_matrix(): ] return data_valid(required_config_data) + + +def can_discord(): + required_config_data = [ + config.DISCORD_APP_ID, + config.DISCORD_TOKEN, + config.DISCORD_CHANNEL_ID, + ] + + return data_valid(required_config_data) diff --git a/messager.py b/messager.py index cae1ec5..a638c6a 100644 --- a/messager.py +++ b/messager.py @@ -1,7 +1,8 @@ #!/usr/bin/env python3 import logging from twython import Twython -from MatrixClient import MatrixClient +from clients.MatrixClient import MatrixClient +from clients.DiscordClient import DiscordClient from mastodon import Mastodon import config import helper @@ -69,9 +70,18 @@ def get_bot_mastodon() -> Mastodon() or None: return mastodon_bot +def get_bot_discord() -> DiscordClient() or None: + if not helper.can_discord(): + return None + + log.debug("initialise discord client") + + return DiscordClient() + + def run(last_revid): """ - Tweets less than 'max_changes' changes newer than 'last_revid'. + Sends messages less than 'max_changes' changes newer than 'last_revid'. Returns the new 'last_revid'. """ log.debug("last rev id: %s", last_revid) @@ -79,6 +89,7 @@ def run(last_revid): twitter_bot = get_bot_twitter() matrix_bot = get_bot_matrix() mastodon_bot = get_bot_mastodon() + discord_bot = get_bot_discord() changes = list() changes_overflow = False @@ -111,9 +122,10 @@ def run(last_revid): for change in changes: message = change.get_message() - tweet(twitter_bot, message) - toot(mastodon_bot, message) - matrix(matrix_bot, message) + send_tweet(twitter_bot, message) + send_toot(mastodon_bot, message) + send_matrix(matrix_bot, message) + send_discord(discord_bot, message) if not changes: log.debug("no changes, rev id: %s", last_revid) @@ -123,7 +135,7 @@ def run(last_revid): return changes[-1].revId -def tweet(twitter, message): +def send_tweet(twitter, message): if twitter is None: return @@ -138,7 +150,7 @@ def tweet(twitter, message): log.warning('TWITTER DRY RUN!') -def toot(_mastodon, message): +def send_toot(_mastodon, message): if _mastodon is None: return @@ -153,7 +165,7 @@ def toot(_mastodon, message): log.warning('MASTODON DRY RUN!') -def matrix(_matrix, message): +def send_matrix(_matrix, message): if _matrix is None: return @@ -168,6 +180,21 @@ def matrix(_matrix, message): log.warning('MATRIX DRY RUN!') +def send_discord(_discord, message): + if _discord is None: + return + + logging.debug("Send discord: %s", message) + + if not config.DISCORD_DRY_RUN: + try: + _discord.send_message(message) + except Exception as ex: + log.error('DISCORD SEND ERROR: ' + str(ex)) + else: + log.warning('DISCORD DRY RUN!') + + if __name__ == '__main__': can_message = CanMessage.CanMessage() diff --git a/requirements.txt b/requirements.txt index e3da9cd..96baf84 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,3 +2,4 @@ mwclient twython matrix-nio Mastodon.py +requests From 2fb661d14805299663d5ff1ac93829935a77f6c1 Mon Sep 17 00:00:00 2001 From: bison-- Date: Sat, 19 Nov 2022 10:40:11 +0100 Subject: [PATCH 2/7] changed description / features --- README.md | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) 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 From 65ea416ecf60d3b1274ed9752c862569eac80f9e Mon Sep 17 00:00:00 2001 From: bison-- Date: Sat, 20 Jan 2024 16:32:58 +0100 Subject: [PATCH 3/7] allow services to be completely deactivated, deactivate twittler by default --- config.py | 4 ++++ messager.py | 8 ++++---- 2 files changed, 8 insertions(+), 4 deletions(-) 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/messager.py b/messager.py index a638c6a..66b4c14 100644 --- a/messager.py +++ b/messager.py @@ -86,10 +86,10 @@ 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 From d9ed1f93ba80af81f92c17b3efb99cb01099a05b Mon Sep 17 00:00:00 2001 From: bison-- Date: Sat, 20 Jan 2024 16:47:57 +0100 Subject: [PATCH 4/7] fix dryrun bug --- helper.py | 16 +++++++++++++++- messager.py | 2 +- 2 files changed, 16 insertions(+), 2 deletions(-) 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 66b4c14..79a10ea 100644 --- a/messager.py +++ b/messager.py @@ -202,7 +202,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() From 5e10b4b5698e3c0123979dee0f8e173ac9bf2b99 Mon Sep 17 00:00:00 2001 From: bison-- Date: Wed, 24 Apr 2024 05:22:56 +0200 Subject: [PATCH 5/7] rename .env to env because some security scanner ring alarm, because an .env file in the repo for fcks sake why is all of this so stupid -.- --- container/{.env => env} | 0 docker-compose.yml | 4 ++-- 2 files changed, 2 insertions(+), 2 deletions(-) rename container/{.env => env} (100%) 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 From 43c4c520071dc1e0563b1ec62e40981503b3e8fa Mon Sep 17 00:00:00 2001 From: bison-- Date: Fri, 9 May 2025 11:43:38 +0200 Subject: [PATCH 6/7] stop read timeouts from emailing errors --- messager.py | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/messager.py b/messager.py index 79a10ea..0d7144c 100644 --- a/messager.py +++ b/messager.py @@ -1,5 +1,7 @@ #!/usr/bin/env python3 import logging + +from requests import ReadTimeout from twython import Twython from clients.MatrixClient import MatrixClient from clients.DiscordClient import DiscordClient @@ -94,16 +96,20 @@ def run(last_revid): 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) - if new_messages_count >= config.MAX_ENTRIES: - changes_overflow = True - break + try: + for change in readwiki.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 + except ReadTimeout as ex: + log.debug("Read TimeOut: %s", ex) log.debug("got the following changes: %s", changes) From c597d0153602f432d7451a1e58b433c87148123b Mon Sep 17 00:00:00 2001 From: bison-- Date: Fri, 9 May 2025 19:24:40 +0200 Subject: [PATCH 7/7] stop read timeouts from emailing errors by creating a ReadWiki class --- messager.py | 8 +- readwiki.py | 259 ++++++++++++++++++++++++++++------------------------ 2 files changed, 144 insertions(+), 123 deletions(-) diff --git a/messager.py b/messager.py index 0d7144c..aba983f 100644 --- a/messager.py +++ b/messager.py @@ -8,8 +8,7 @@ from mastodon import Mastodon import config import helper -from readwiki import WikiChange -import readwiki +from readwiki import ReadWiki import CanMessage log = logging.getLogger(__name__) @@ -98,7 +97,8 @@ def run(last_revid): new_messages_count = 0 try: - for change in readwiki.get_changes(): + read_wiki = ReadWiki() + for change in read_wiki.get_changes(): if change.revId <= last_revid: break @@ -120,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) 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())