From de270e2d8649586dfdda92088f0d9d50d4bb9cbf Mon Sep 17 00:00:00 2001 From: Sumit Singh Date: Sat, 23 Apr 2022 15:11:11 +0530 Subject: [PATCH] feat: Fix messages and refactor code (#21) * feat: Fix messages and refactor code :art: * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com> --- constants.py | 11 +++++++ kick_members.py | 79 ++++++++++++++++++++++++++++++++++-------------- requirements.txt | 2 +- 3 files changed, 68 insertions(+), 24 deletions(-) create mode 100644 constants.py diff --git a/constants.py b/constants.py new file mode 100644 index 0000000..95a0d9e --- /dev/null +++ b/constants.py @@ -0,0 +1,11 @@ +class ErrorMessages: + CHAT_ADMIN_REQUIRED: str = "CHAT_ADMIN_REQUIRED" + CAN_NOT_REMOVE_CHAT_OWNER: str = "can't remove chat owner" + USER_IS_AN_ADMIN: str = "user is an administrator of the chat" + BOT_USED_IN_PRIVATE_CHAT: str = "can't ban members in private chats" + NOT_ENOUGH_RIGHTS: str = "not enough rights to restrict/unrestrict chat member" + + +class BotPermissions: + CREATOR: str = "creator" + ADMINISTRATOR: str = "administrator" diff --git a/kick_members.py b/kick_members.py index a10423b..aa7ddc7 100644 --- a/kick_members.py +++ b/kick_members.py @@ -6,6 +6,7 @@ import datetime import logging import os +from typing import List import sentry_sdk import telebot @@ -13,6 +14,9 @@ from sentry_sdk.integrations.logging import LoggingIntegration from telebot.apihelper import ApiTelegramException +from constants import BotPermissions +from constants import ErrorMessages + logger = logging.getLogger(__name__) # initialize dot env @@ -40,14 +44,11 @@ bot = telebot.TeleBot(token) # i'm setting one day time limit to unban group members (update this as per need) -untildate = datetime.datetime.today() + datetime.timedelta(days=1) - -# convert time limit to unix timestamp -unix_untildate = untildate.strftime("%s") +until_date: datetime = datetime.datetime.now() + datetime.timedelta(days=1) @bot.message_handler(func=lambda m: True) -def kick_member(message): +def kick_member(message: [telebot.types.Message]): """ This methods kicks out members whose messages contains `aww` """ @@ -57,39 +58,71 @@ def kick_member(message): user_id = message.from_user.id first_name = message.from_user.first_name try: - bot.kick_chat_member( + bot.ban_chat_member( chat_id=chat_id, user_id=user_id, - until_date=unix_untildate, + until_date=until_date, ) except ApiTelegramException as err: # check if bot has admin permissions - if "CHAT_ADMIN_REQUIRED" in err.result_json.get("description"): - bot.send_message( - chat_id, - "Forbidden Word used but I don't have enough permissions to kick members. \ - Please make me an admin.", - ) + err_msg: str = err.result_json.get("description") + if ErrorMessages.CHAT_ADMIN_REQUIRED in err_msg: + handle_chat_admin_required(chat_id, first_name, user_id) + elif ErrorMessages.NOT_ENOUGH_RIGHTS in err_msg: + send_not_enough_permissions(chat_id) # check if message which contains `aww` sent by group owner - elif "can't remove chat owner" in err.result_json.get("description"): - bot.send_message(chat_id, "Oops, Chat Owner can use these forbidden words!") + elif ErrorMessages.CAN_NOT_REMOVE_CHAT_OWNER in err_msg: + send_user_is_owner(chat_id, first_name) # check if the message which contains `aww` sent by group admin - elif "user is an administrator of the chat" in err.result_json.get( - "description" - ): - bot.send_message(chat_id, "Chat Admins can also use these forbidden words!") + elif ErrorMessages.USER_IS_AN_ADMIN in err_msg: + send_user_is_admin(chat_id, first_name) # checks if message is sent directly to bot - elif "can't ban members in private chats" in err.result_json.get("description"): - bot.send_message(chat_id, "Sorry, This doesn't work in private chats!") - # otherwise log errors to sentry + elif ErrorMessages.BOT_USED_IN_PRIVATE_CHAT in err_msg: + bot.send_message(chat_id, "Sorry mate, this doesn't work in private chats!") + # otherwise, log errors to sentry else: logger.error(err) sentry_sdk.capture_exception(err) else: bot.send_message( chat_id, - f"{first_name} have used a forbidden word and will be banned for a day from this group.", # noqa + f"🚨 {first_name} have used a forbidden word and will be banned for a day from this group.", # noqa ) +def handle_chat_admin_required(chat_id, first_name, user_id): + admins: List[telebot.types.ChatMember] = bot.get_chat_administrators(chat_id) + if any(admin.user.is_bot for admin in admins): + # somehow we're getting wrong error message even if bot has admin permissions + # handling it here + if bot.get_chat_member(chat_id, user_id).status == BotPermissions.CREATOR: + send_user_is_owner(chat_id, first_name) + else: + send_user_is_admin(chat_id, first_name) + else: + send_not_enough_permissions(chat_id) + + +def send_user_is_admin(chat_id, first_name): + bot.send_message( + chat_id, + f"{first_name} is an admin and admins are allowed to say forbidden words!", + ) + + +def send_user_is_owner(chat_id, first_name): + bot.send_message( + chat_id=chat_id, + text=f"Sorry folks, {first_name} is owner here . I can't do anything.", + ) + + +def send_not_enough_permissions(chat_id): + bot.send_message( + chat_id, + "Forbidden Word used but I don't have enough permissions to kick members. " + "Please make me an admin 🙏 .", + ) + + bot.polling() diff --git a/requirements.txt b/requirements.txt index bf66bea..68f8c6b 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,3 +1,3 @@ -pyTelegramBotAPI==3.7.3 +pyTelegramBotAPI==4.4.1 python-dotenv==0.20.0 sentry-sdk==1.5.10