auto-ban-bot/autobanbot.py

70 lines
2.2 KiB
Python
Raw Normal View History

2018-07-24 13:31:04 +00:00
#!/usr/bin/env python
from telegram.ext import Updater, MessageHandler
from telegram.ext.filters import Filters
import re
import logging
import json
SPAM_REGEXES = []
TELEGRAM_API_KEY = "unknown"
def load_config():
with open("config.json") as config_file:
config = json.load(config_file)
for regex in config["regexes"]:
SPAM_REGEXES.append(re.compile(regex, re.I))
return config
def handle_spam_message(bot, chat, member, message_id):
logging.warning("SPAM USER JOINED: {} | {} | {} | {}".format(
member.id,
member.first_name,
member.last_name,
member.username
))
logging.debug("WILL BAN: chat_id: {} | user_id: {} | AND DELETE MSG ID = {}".format(
chat.id,
member.id,
message_id
))
kick_result = bot.kick_chat_member(chat.id, member.id)
if not kick_result:
logging.error("Bankick success: {}".format(kick_result))
delete_result = bot.delete_message(chat.id, message_id)
if not delete_result:
logging.error("Message delete success: {}".format(delete_result))
def hello(bot, update):
for user in update.message.new_chat_members:
is_spam = False
for regex in SPAM_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:
is_spam = True
if is_spam == True:
break
logging.info("User joined: {} | {} | {} | {} | {}".format(
user.id,
user.first_name,
user.last_name,
user.username,
is_spam
))
if is_spam:
handle_spam_message(bot, update.effective_chat, user, update.message.message_id)
return True
return False
if __name__ == '__main__':
logging.basicConfig(format='%(asctime)s|%(levelname)s|%(message)s', level=logging.INFO)
logging.info("Starting")
config = load_config()
updater = Updater(config["telegramApiKey"])
updater.dispatcher.add_handler(MessageHandler(Filters.status_update.new_chat_members, hello))
updater.start_polling()
updater.idle()