From b593ca20d2c69939baa972497683c2997934717b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Micha=C5=82=20Rudowicz?= Date: Wed, 25 Jul 2018 12:03:11 +0200 Subject: [PATCH] Little refactoring - got rid of static variables --- autobanbot.py | 18 ++++++++++-------- tests.py | 6 +++--- 2 files changed, 13 insertions(+), 11 deletions(-) diff --git a/autobanbot.py b/autobanbot.py index c2a1137..1c3fd31 100755 --- a/autobanbot.py +++ b/autobanbot.py @@ -6,15 +6,15 @@ import re import logging import json -SPAM_REGEXES = [] -TELEGRAM_API_KEY = "unknown" - def load_config(): + retval = {} with open("config.json") as config_file: config = json.load(config_file) + retval["telegramApiKey"] = config["telegramApiKey"] + retval["regexes"] = [] for regex in config["regexes"]: - SPAM_REGEXES.append(re.compile(regex, re.I)) - return config + retval["regexes"].append(re.compile(regex, re.I)) + return retval def handle_spam_message(bot, chat, member, message_id): logging.warning("SPAM USER JOINED: {} | {} | {} | {}".format( @@ -35,10 +35,10 @@ def handle_spam_message(bot, chat, member, message_id): if not delete_result: logging.error("Message delete success: {}".format(delete_result)) -def hello(bot, update): +def hello(bot, update, regexes): for user in update.message.new_chat_members: is_spam = False - for regex in SPAM_REGEXES: + for regex in regexes: if user.first_name is not None and regex.search(user.first_name) is not None: is_spam = True if user.last_name is not None and regex.search(user.last_name) is not None: @@ -63,7 +63,9 @@ if __name__ == '__main__': config = load_config() updater = Updater(config["telegramApiKey"]) - updater.dispatcher.add_handler(MessageHandler(Filters.status_update.new_chat_members, hello)) + updater.dispatcher.add_handler(MessageHandler(Filters.status_update.new_chat_members, ( + lambda bot, update: hello(bot, update, config["regexes"]) + ))) updater.start_polling() updater.idle() diff --git a/tests.py b/tests.py index 1f6c896..c7be551 100644 --- a/tests.py +++ b/tests.py @@ -32,12 +32,12 @@ class Update: class TestAutoBanBot(unittest.TestCase): def setUp(self): - autobanbot.load_config() + self.regexes = autobanbot.load_config()["regexes"] def banned_join(self, user_id, first_name, last_name, username): bot = Mock(spec=BOT_SPEC) self.assertTrue(autobanbot.hello( - bot, Update(user_id, first_name, last_name, username) + bot, Update(user_id, first_name, last_name, username), self.regexes )) bot.kick_chat_member.assert_called_once_with(CHAT_ID, USER_ID) bot.delete_message.assert_called_once_with(CHAT_ID, MESSAGE_ID) @@ -45,7 +45,7 @@ class TestAutoBanBot(unittest.TestCase): def legit_join(self, user_id, first_name, last_name, username): bot = Mock(spec=BOT_SPEC) self.assertFalse(autobanbot.hello( - bot, Update(user_id, first_name, last_name, username) + bot, Update(user_id, first_name, last_name, username), self.regexes )) bot.kick_chat_member.assert_not_called() bot.delete_message.assert_not_called()