Error handling, more tests

This commit is contained in:
Michał Rudowicz 2024-06-15 06:47:55 +02:00
parent 2d4bf992de
commit a7299d65ad
3 changed files with 18 additions and 13 deletions

View File

@ -6,28 +6,33 @@ import re
import logging
import json
def load_config():
def load_config(filename: str = "config.json"):
retval = {}
with open("config.json") as config_file:
with open(filename) as config_file:
config = json.load(config_file)
retval["telegramApiKey"] = config["telegramApiKey"]
retval["regexes"] = []
for regex in config["regexes"]:
retval["regexes"].append(re.compile(regex, re.I))
retval["regexes"] = list(map(lambda r: re.compile(r, re.I), config["regexes"]))
return retval
async def new_msg(update, context, regexes):
is_spam = False
for regex in regexes:
if update.message.text is not None and regex.search(update.message.text) is not None:
if update.message is not None and \
update.message.text is not None and \
regex.search(update.message.text) is not None:
is_spam = True
break
if update.message is None:
logging.info(f"Got following update: {update}")
if is_spam:
logging.info(f"Banning {update.message.from_user.name} from {update.message.chat.effective_name}")
await update.message.chat.ban_member(update.message.from_user.id)
await update.message.delete()
logging.info("Banned.")
async def handle_error(update, context):
logging.error("Exception while handling an update:", exc_info=context.error)
if __name__ == '__main__':
logging.basicConfig(format='%(asctime)s|%(levelname)s|%(message)s', level=logging.INFO)
logging.getLogger("httpx").setLevel(logging.WARNING)
@ -38,5 +43,6 @@ if __name__ == '__main__':
application.add_handler(MessageHandler(filters.ALL, (
lambda update, context: new_msg(update, context, config['regexes'])
)))
application.add_error_handler(handle_error, block=False)
application.run_polling(allowed_updates=Update.ALL_TYPES)

View File

@ -1,7 +1,7 @@
{
"telegramApiKey": "PUT YOUR KEY HERE",
"regexes": [
"ready-made telegram accounts",
"253239090.*473157472"
"test123",
"(?:@|(?:(?:(?:https?://)?t(?:elegram)?)\\.me\\/))(\\w{4,})bot"
]
}

View File

@ -53,10 +53,7 @@ def make_update(msg: str) -> Update:
class TestAutoBanBot(unittest.IsolatedAsyncioTestCase):
def setUp(self):
self.regexes = list(map(lambda r: re.compile(r, re.I), [
"test123",
"(?:@|(?:(?:(?:https?://)?t(?:elegram)?)\.me\/))(\w{4,})bot"
]))
self.regexes = autobanbot.load_config("config.json.example")['regexes']
async def test_not_bannable(self):
messages = ["not bannable message", "siematest_123elo", "i am not a bot", "t.me, i'm not a bot"]
@ -69,8 +66,10 @@ class TestAutoBanBot(unittest.IsolatedAsyncioTestCase):
update.message.delete.assert_not_called()
update.message.chat.ban_member.assert_not_called()
async def test_not_bannable(self):
async def test_bannable(self):
messages = [
"hitest123hello",
"HiTeSt123HeLlO",
"t.me/whatever_bot?not bannable message",
"https://www.t.me/ohhaaaaaaaibot/siematest123elo",
"@Hello_BoT"