-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathkick_members.py
132 lines (111 loc) · 4.25 KB
/
kick_members.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
"""
This is a simple script to create a telegram bot.
This telegram bot removes group member for a day
if member uses words which contains `aww`.
"""
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
load_dotenv()
sentry_logging = LoggingIntegration(
level=logging.INFO, # Capture info and above as breadcrumbs
event_level=logging.ERROR, # Send errors as events
)
# initialize sentry
sentry_sdk.init(
dsn=os.getenv("SENTRY_DSN"),
environment=os.getenv("SENTRY_ENV"),
release=os.getenv("SENTRY_RELEASE"),
traces_sample_rate=1.0,
integrations=[sentry_logging],
)
# load BOT_TOKEN from env file
token = os.getenv("BOT_TOKEN")
# initialize bot with API TOKEN
# use https://t.me/botfather to generate your own
bot = telebot.TeleBot(token)
# i'm setting one day time limit to unban group members (update this as per need)
until_date: datetime = datetime.datetime.now() + datetime.timedelta(days=1)
@bot.message_handler(func=lambda m: True)
def kick_member(message: [telebot.types.Message]):
"""
This method kicks out members whose messages contain `aww`
"""
if "aww" not in message.text.lower():
return
chat_id = message.chat.id
user_id = message.from_user.id
first_name = message.from_user.first_name
try:
bot.ban_chat_member(
chat_id=chat_id,
user_id=user_id,
until_date=until_date,
)
except ApiTelegramException as err:
# check if bot has admin permissions
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 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 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 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
)
def handle_chat_admin_required(chat_id, first_name, user_id):
"""Method to handle chat admin required error"""
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):
"""Method to send user is admin message"""
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):
"""Method to send user is owner message"""
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):
"""Method to send not enough permissions message"""
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()