Skip to content

Commit

Permalink
feat: Fix messages and refactor code (#21)
Browse files Browse the repository at this point in the history
* feat: Fix messages and refactor code 🎨

* [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>
  • Loading branch information
sumit4613 and pre-commit-ci[bot] authored Apr 23, 2022
1 parent b43b9f2 commit de270e2
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 24 deletions.
11 changes: 11 additions & 0 deletions constants.py
Original file line number Diff line number Diff line change
@@ -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"
79 changes: 56 additions & 23 deletions kick_members.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,17 @@
import datetime
import logging
import os
from typing import List

import sentry_sdk
import telebot
from dotenv import load_dotenv
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
Expand Down Expand Up @@ -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`
"""
Expand All @@ -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()
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
pyTelegramBotAPI==3.7.3
pyTelegramBotAPI==4.4.1
python-dotenv==0.20.0
sentry-sdk==1.5.10

0 comments on commit de270e2

Please sign in to comment.