auto-ban-bot/autobanbot.py

52 lines
2.0 KiB
Python
Executable File

#!/usr/bin/env python
from telegram import Update
from telegram.ext import Application, MessageHandler, filters
import re
import logging
import json
def load_config(filename: str = "config.json"):
retval = {}
with open(filename) as config_file:
config = json.load(config_file)
retval["telegramApiKey"] = config["telegramApiKey"]
retval["allowedChats"] = config["allowedChats"]
retval["regexes"] = list(map(lambda r: re.compile(r, re.I), config["regexes"]))
return retval
async def new_msg(update, context, regexes, allowed_chats):
if update.message is None and update.edited_message is None:
logging.info(f"Got following unknown update: {update}")
return
message = update.message
if update.edited_message is not None:
message = update.edited_message
if message is None:
return
if message.chat.id not in allowed_chats:
return
for regex in regexes:
if message.text is not None and regex.search(message.text) is not None:
logging.info(f"Banning {message.from_user.name} from {message.chat.effective_name} for posting a message matching {regex.pattern}")
await message.chat.ban_member(message.from_user.id)
await message.delete()
return
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)
logging.info("Starting")
config = load_config()
application = Application.builder().token(config["telegramApiKey"]).build()
application.add_handler(MessageHandler(filters.ALL, (
lambda update, context: new_msg(update, context, config['regexes'], config['allowedChats'])
)))
application.add_error_handler(handle_error, block=False)
application.run_polling(allowed_updates=Update.ALL_TYPES)