VALID_WELCOME_FORMATTERS = ['first', 'last', 'fullname', 'username', 'id', 'count', 'chatname', 'mention'] client = spamwatch.Client(SPAMWATCH_TOKEN) ENUM_FUNC_MAP = { sql.Types.TEXT.value: dispatcher.bot.send_message, sql.Types.BUTTON_TEXT.value: dispatcher.bot.send_message, sql.Types.STICKER.value: dispatcher.bot.send_sticker, sql.Types.DOCUMENT.value: dispatcher.bot.send_document, sql.Types.PHOTO.value: dispatcher.bot.send_photo, sql.Types.AUDIO.value: dispatcher.bot.send_audio, sql.Types.VOICE.value: dispatcher.bot.send_voice, sql.Types.VIDEO.value: dispatcher.bot.send_video } WELCOME_PERMISSIONS_SOFT = ChatPermissions(can_send_messages=True, can_send_media_messages=False, can_send_other_messages=False, can_add_web_page_previews=False) WELCOME_PERMISSIONS_STRONG = ChatPermissions(can_send_messages=False, can_send_media_messages=False, can_send_other_messages=False, can_add_web_page_previews=False) WELCOME_PERMISSIONS_AGGRESSIVE = ChatPermissions(can_send_messages=False, can_send_media_messages=False, can_send_other_messages=False, can_add_web_page_previews=False) USER_PERMISSIONS_UNMUTE = ChatPermissions(can_send_messages=True, can_send_media_messages=True, can_send_other_messages=True,
def temp_mute(update, context): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] message = update.effective_message # type: Optional[Message] args = context.args if user_can_ban(chat, user, context.bot.id) == False: message.reply_text( "You don't have enough rights to restrict someone from talking!") return "" user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text("You don't seem to be referring to a user.") return "" try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found": message.reply_text("I can't seem to find this user") return "" else: raise if is_user_admin(chat, user_id, member): message.reply_text("I really wish I could mute admins...") return "" if user_id == context.bot.id: message.reply_text("I'm not gonna MUTE myself, are you crazy?") return "" if not reason: message.reply_text( "You haven't specified a time to mute this user for!") return "" split_reason = reason.split(None, 1) time_val = split_reason[0].lower() if len(split_reason) > 1: reason = split_reason[1] else: reason = "" mutetime = extract_time(message, time_val) if not mutetime: return "" log = ("<b>{}:</b>" "\n#TEMP MUTED" "\n<b>Admin:</b> {}" "\n<b>User:</b> {}" "\n<b>Time:</b> {}".format( html.escape(chat.title), mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name), time_val, )) if reason: log += "\n<b>Reason:</b> {}".format(reason) try: if member.can_send_messages is None or member.can_send_messages: context.bot.restrict_chat_member( chat.id, user_id, until_date=mutetime, permissions=ChatPermissions(can_send_messages=False), ) message.reply_text("shut up! 🤐 Taped for {}!".format(time_val)) return log else: message.reply_text("This user is already muted.") except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text("shut up! 🤐 Taped for {}!".format(time_val), quote=False) return log else: LOGGER.warning(update) LOGGER.exception( "ERROR muting user %s in chat %s (%s) due to %s", user_id, chat.title, chat.id, excp.message, ) message.reply_text("Well damn, I can't mute that user.") return ""
def rmute(update: Update, context: CallbackContext): bot, args = context.bot, context.args message = update.effective_message if not args: message.reply_text("You don't seem to be referring to a chat/user.") return user_id, chat_id = extract_user_and_text(message, args) if not user_id: message.reply_text( "You don't seem to be referring to a user or the ID specified is incorrect.." ) return elif not chat_id: message.reply_text("You don't seem to be referring to a chat.") return try: chat = bot.get_chat(chat_id.split()[0]) except BadRequest as excp: if excp.message == "Chat not found": message.reply_text( "Chat not found! Make sure you entered a valid chat ID and I'm part of that chat." ) return else: raise if chat.type == 'private': message.reply_text("I'm sorry, but that's a private chat!") return if not is_bot_admin(chat, bot.id) or not chat.get_member( bot.id).can_restrict_members: message.reply_text( "I can't restrict people there! Make sure I'm admin and can mute users." ) return try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found": message.reply_text("I can't seem to find this user") return else: raise if is_user_ban_protected(chat, user_id, member): message.reply_text("I really wish I could mute admins...") return if user_id == bot.id: message.reply_text("I'm not gonna MUTE myself, are you crazy?") return try: bot.restrict_chat_member( chat.id, user_id, permissions=ChatPermissions(can_send_messages=False)) message.reply_text("Muted from the chat!") except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text('Muted!', quote=False) elif excp.message in RMUTE_ERRORS: message.reply_text(excp.message) else: LOGGER.warning(update) LOGGER.exception("ERROR mute user %s in chat %s (%s) due to %s", user_id, chat.title, chat.id, excp.message) message.reply_text("Well damn, I can't mute that user.")
def del_blackliststicker(update: Update, context: CallbackContext): bot = context.bot chat = update.effective_chat # type: Optional[Chat] message = update.effective_message # type: Optional[Message] user = update.effective_user to_match = message.sticker if not to_match: return bot = context.bot getmode, value = sql.get_blacklist_setting(chat.id) chat_filters = sql.get_chat_stickers(chat.id) for trigger in chat_filters: if to_match.set_name.lower() == trigger.lower(): try: if getmode == 0: return elif getmode == 1: message.delete() elif getmode == 2: message.delete() warn(update.effective_user, chat, "Using sticker '{}' which in blacklist stickers". format(trigger), message, update.effective_user, conn=False) return elif getmode == 3: message.delete() bot.restrict_chat_member( chat.id, update.effective_user.id, permissions=ChatPermissions(can_send_messages=False)) bot.sendMessage( chat.id, "{} muted because using '{}' which in blacklist stickers" .format(mention_markdown(user.id, user.first_name), trigger), parse_mode="markdown") return elif getmode == 4: message.delete() res = chat.unban_member(update.effective_user.id) if res: bot.sendMessage( chat.id, "{} kicked because using '{}' which in blacklist stickers" .format(mention_markdown(user.id, user.first_name), trigger), parse_mode="markdown") return elif getmode == 5: message.delete() chat.kick_member(user.id) bot.sendMessage( chat.id, "{} banned because using '{}' which in blacklist stickers" .format(mention_markdown(user.id, user.first_name), trigger), parse_mode="markdown") return elif getmode == 6: message.delete() bantime = extract_time(message, value) chat.kick_member(user.id, until_date=bantime) bot.sendMessage( chat.id, "{} banned for {} because using '{}' which in blacklist stickers" .format(mention_markdown(user.id, user.first_name), value, trigger), parse_mode="markdown") return elif getmode == 7: message.delete() mutetime = extract_time(message, value) bot.restrict_chat_member(chat.id, user.id, permissions=ChatPermissions( can_send_messages=False, until_date=mutetime)) bot.sendMessage( chat.id, "{} muted for {} because using '{}' which in blacklist stickers" .format(mention_markdown(user.id, user.first_name), value, trigger), parse_mode="markdown") return except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception("Error while deleting blacklist message.") break
def temp_mute(update: Update, context: CallbackContext) -> str: bot, args = context.bot, context.args chat = update.effective_chat user = update.effective_user message = update.effective_message user_id, reason = extract_user_and_text(message, args) reply = check_user(user_id, bot, chat) if reply: message.reply_text(reply) return "" member = chat.get_member(user_id) if not reason: message.reply_text( "You haven't specified a time to mute this user for!") return "" split_reason = reason.split(None, 1) time_val = split_reason[0].lower() if len(split_reason) > 1: reason = split_reason[1] else: reason = "" mutetime = extract_time(message, time_val) if not mutetime: return "" log = ( f"<b>{html.escape(chat.title)}:</b>\n" f"#TEMP MUTED\n" f"<b>Admin:</b> {mention_html(user.id, user.first_name)}\n" f"<b>User:</b> {mention_html(member.user.id, member.user.first_name)}\n" f"<b>Time:</b> {time_val}") if reason: log += f"\n<b>Reason:</b> {reason}" try: if member.can_send_messages is None or member.can_send_messages: chat_permissions = ChatPermissions(can_send_messages=False) bot.restrict_chat_member( chat.id, user_id, chat_permissions, until_date=mutetime, ) bot.sendMessage( chat.id, f"Muted <b>{html.escape(member.user.first_name)}</b> for {time_val}!", parse_mode=ParseMode.HTML, ) return log else: message.reply_text("This user is already muted.") except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text(f"Muted for {time_val}!", quote=False) return log else: LOGGER.warning(update) LOGGER.exception( "ERROR muting user %s in chat %s (%s) due to %s", user_id, chat.title, chat.id, excp.message, ) message.reply_text("Well damn, I can't mute that user.") return ""
def user_button(update: Update, context: CallbackContext): chat = update.effective_chat user = update.effective_user query = update.callback_query bot = context.bot match = re.match(r"user_join_\((.+?)\)", query.data) message = update.effective_message join_user = int(match.group(1)) if join_user == user.id: sql.set_human_checks(user.id, chat.id) member_dict = VERIFIED_USER_WAITLIST.pop(user.id) member_dict["status"] = True VERIFIED_USER_WAITLIST.update({user.id: member_dict}) query.answer(text="Yeet! You're a human, unmuted!") bot.restrict_chat_member( chat.id, user.id, permissions=ChatPermissions( can_send_messages=True, can_invite_users=True, can_pin_messages=True, can_send_polls=True, can_change_info=True, can_send_media_messages=True, can_send_other_messages=True, can_add_web_page_previews=True, ), ) try: bot.deleteMessage(chat.id, message.message_id) except: pass if member_dict["should_welc"]: if member_dict["media_wel"]: sent = ENUM_FUNC_MAP[member_dict["welc_type"]]( member_dict["chat_id"], member_dict["cust_content"], caption=member_dict["res"], reply_markup=member_dict["keyboard"], parse_mode="markdown", ) else: sent = send( member_dict["update"], member_dict["res"], member_dict["keyboard"], member_dict["backup_message"], ) prev_welc = sql.get_clean_pref(chat.id) if prev_welc: try: bot.delete_message(chat.id, prev_welc) except BadRequest: pass if sent: sql.set_clean_welcome(chat.id, sent.message_id) else: query.answer(text="You're not allowed to do this!")
def new_member(update, context): chat = update.effective_chat user = update.effective_user msg = update.effective_message chat_name = chat.title or chat.first or chat.username should_welc, cust_welcome, cust_content, welc_type = sql.get_welc_pref( chat.id) cust_welcome = markdown_to_html(cust_welcome) welc_mutes = sql.welcome_mutes(chat.id) user_id = user.id human_checks = sql.get_human_checks(user_id, chat.id) if should_welc: sent = None new_members = update.effective_message.new_chat_members for new_mem in new_members: reply = update.message.message_id cleanserv = sql.clean_service(chat.id) # Clean service welcome if cleanserv: reply = False try: dispatcher.bot.delete_message(chat.id, update.message.message_id) except BadRequest: pass # Ignore spamwatch banned users try: sw = spamwtc.get_ban(int(new_mem.id)) if sw: return except Exception: pass # Ignore gbanned users if is_user_gbanned(new_mem.id): return # Give the owner a special welcome if new_mem.id == OWNER_ID: update.effective_message.reply_text( "My Owner is in the houseeee, let's get this party started!", reply_to_message_id=reply, ) continue # Give the DEV a special welcome if new_mem.id in DEV_USERS: update.effective_message.reply_text( "My Dev Here, Let's See What Happened Now.. 🔥", reply_to_message_id=reply, ) continue # Make bot greet admins elif new_mem.id == context.bot.id: update.effective_message.reply_text( "Hey 😍 {}, I'm {}! Thank you for adding me to {}".format( user.first_name, context.bot.first_name, chat_name), reply_to_message_id=reply, ) context.bot.send_message( MESSAGE_DUMP, "UserbotindoBot have been added to <pre>{}</pre> with ID: \n<pre>{}</pre>" .format(chat.title, chat.id), parse_mode=ParseMode.HTML, ) else: # If welcome message is media, send with appropriate function if welc_type != sql.Types.TEXT and welc_type != sql.Types.BUTTON_TEXT: # edge case of empty name - occurs for some bugs. first_name = new_mem.first_name or "PersonWithNoName" # Start formating text if new_mem.last_name: fullname = "{} {}".format(first_name, new_mem.last_name) else: fullname = first_name count = chat.get_members_count() mention = mention_html(new_mem.id, first_name) if new_mem.username: username = "******" + escape(new_mem.username) else: username = mention valid_format = escape_invalid_curly_brackets( cust_welcome, VALID_WELCOME_FORMATTERS) formated_text = valid_format.format( first=escape(first_name), last=escape(new_mem.last_name or first_name), fullname=escape(fullname), username=username, mention=mention, count=count, chatname=escape(chat.title), id=new_mem.id, ) # build the button buttons = sql.get_welc_buttons(chat.id) if buttons: keyb = build_keyboard_parser(context.bot, chat.id, buttons) keyboard = InlineKeyboardMarkup(keyb) else: keyboard = None sent = ENUM_FUNC_MAP[welc_type]( chat.id, cust_content, caption=formated_text, reply_markup=keyboard, parse_mode="html", reply_to_message_id=reply, ) # else, move on else: # edge case of empty name - occurs for some bugs. first_name = new_mem.first_name or "PersonWithNoName" if cust_welcome: if new_mem.last_name: fullname = "{} {}".format(first_name, new_mem.last_name) else: fullname = first_name count = chat.get_members_count() mention = mention_html(new_mem.id, first_name) if new_mem.username: username = "******" + escape(new_mem.username) else: username = mention valid_format = escape_invalid_curly_brackets( cust_welcome, VALID_WELCOME_FORMATTERS) res = valid_format.format( first=escape(first_name), last=escape(new_mem.last_name or first_name), fullname=escape(fullname), username=username, mention=mention, count=count, chatname=escape(chat.title), id=new_mem.id, ) buttons = sql.get_welc_buttons(chat.id) keyb = build_keyboard(buttons) else: res = sql.DEFAULT_WELCOME.format(first=first_name) keyb = [] keyboard = InlineKeyboardMarkup(keyb) sent = send( update, res, keyboard, sql.DEFAULT_WELCOME.format(first=first_name), ) if (is_user_ban_protected(chat, new_mem.id, chat.get_member(new_mem.id)) or human_checks): continue # Join welcome: soft mute if welc_mutes == "soft": context.bot.restrict_chat_member( chat.id, new_mem.id, permissions=ChatPermissions( can_send_messages=True, can_send_media_messages=False, can_send_other_messages=False, can_invite_users=False, can_pin_messages=False, can_send_polls=False, can_change_info=False, can_add_web_page_previews=False, until_date=(int(time.time() + 24 * 60 * 60)), ), ) # Join welcome: strong mute if welc_mutes == "strong": new_join_mem = "Hey {}!".format( mention_html(user.id, new_mem.first_name)) msg.reply_text( "{}\nClick the button below to start talking.". format(new_join_mem), reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( text="Yus, I'm a human", callback_data="user_join_({})".format( new_mem.id), ) ]]), parse_mode=ParseMode.HTML, reply_to_message_id=reply, ) context.bot.restrict_chat_member( chat.id, new_mem.id, permissions=ChatPermissions( can_send_messages=False, can_invite_users=False, can_pin_messages=False, can_send_polls=False, can_change_info=False, can_send_media_messages=False, can_send_other_messages=False, can_add_web_page_previews=False, ), ) prev_welc = sql.get_clean_pref(chat.id) if prev_welc: try: context.bot.delete_message(chat.id, prev_welc) except BadRequest: pass if sent: sql.set_clean_welcome(chat.id, sent.message_id)
def unmute(update, context): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] message = update.effective_message # type: Optional[Message] args = context.args user_id = extract_user(message, args) if not user_id or user_id == "error": send_message( update.effective_message, tl( update.effective_message, "Anda harus memberi saya nama pengguna untuk menyuarakan, atau membalas seseorang untuk disuarakan." )) return "" conn = connected(context.bot, update, chat, user.id, need_admin=True) if conn: chat = dispatcher.bot.getChat(conn) chat_id = conn chat_name = dispatcher.bot.getChat(conn).title text = tl(update.effective_message, "Pengguna ini sudah bisa untuk berbicara pada *{}*.").format( chat_name) text2 = tl(update.effective_message, "Dia telah disuarakan pada *{}*.").format(chat_name) else: if update.effective_message.chat.type == "private": update.effective_send_message( update.effective_message, tl(update.effective_message, "Anda bisa lakukan command ini pada grup, bukan pada PM")) return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title text = tl(update.effective_message, "Pengguna ini sudah bisa untuk berbicara.") text2 = "Dia telah disuarakan." check = context.bot.getChatMember(chat.id, user.id) if check['can_restrict_members'] == False: send_message( update.effective_message, tl(update.effective_message, "Anda tidak punya hak untuk membatasi seseorang.")) return "" member = chat.get_member(int(user_id)) if member: if is_user_admin(chat, user_id, member=member): send_message( update.effective_message, tl(update.effective_message, "Dia adalah admin, apa yang Anda harapkan kepada saya?")) return "" elif member.status != 'kicked' and member.status != 'left': if member.can_send_messages and member.can_send_media_messages \ and member.can_send_other_messages and member.can_add_web_page_previews: send_message(update.effective_message, text, parse_mode="markdown") return "" else: context.bot.restrict_chat_member( chat.id, int(user_id), permissions=ChatPermissions( can_send_messages=True, can_send_media_messages=True, can_send_other_messages=True, can_add_web_page_previews=True)) send_message(update.effective_message, text2, parse_mode="markdown") return "<b>{}:</b>" \ "\n#UNMUTE" \ "\n<b>Admin:</b> {}" \ "\n<b>User:</b> {}".format(html.escape(chat.title), mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name)) else: send_message( update.effective_message, tl( update.effective_message, "Pengguna ini bahkan tidak dalam obrolan, menyuarakannya tidak akan membuat mereka berbicara lebih dari " "yang sudah mereka lakukan!")) return ""
def temp_mute(update, context): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] message = update.effective_message # type: Optional[Message] args = context.args user_id, reason = extract_user_and_text(message, args) if user_id == "error": send_message(update.effective_message, tl(update.effective_message, reason)) return "" if not user_id: send_message( update.effective_message, tl(update.effective_message, "Anda sepertinya tidak mengacu pada pengguna.")) return "" conn = connected(context.bot, update, chat, user.id, need_admin=True) if conn: chat = dispatcher.bot.getChat(conn) chat_id = conn chat_name = dispatcher.bot.getChat(conn).title else: if update.effective_message.chat.type == "private": update.effective_send_message( update.effective_message, tl(update.effective_message, "Anda bisa lakukan command ini pada grup, bukan pada PM")) return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found": send_message( update.effective_message, tl(update.effective_message, "Saya tidak dapat menemukan pengguna ini")) return "" else: raise if is_user_admin(chat, user_id, member): send_message( update.effective_message, tl(update.effective_message, "Saya benar-benar berharap dapat membisukan admin...")) return "" if user_id == context.bot.id: send_message( update.effective_message, tl( update.effective_message, "Saya tidak akan membisukan diri saya sendiri, apakah kamu gila?" )) return "" check = context.bot.getChatMember(chat.id, user.id) if check['can_restrict_members'] == False: send_message( update.effective_message, tl(update.effective_message, "Anda tidak punya hak untuk membatasi seseorang.")) return "" if not reason: send_message( update.effective_message, tl( update.effective_message, "Anda belum menetapkan waktu untuk menonaktifkan pengguna ini!" )) return "" split_reason = reason.split(None, 1) time_val = split_reason[0].lower() if len(split_reason) > 1: reason = split_reason[1] else: reason = "" mutetime = extract_time(message, time_val) if not mutetime: return "" log = "<b>{}:</b>" \ "\n#TMUTE" \ "\n<b>Admin:</b> {}" \ "\n<b>User:</b> {}" \ "\n<b>Time:</b> {}".format(html.escape(chat.title), mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name), time_val) if reason: log += "\n<b>Reason:</b> {}".format(reason) try: if member.can_send_messages is None or member.can_send_messages: context.bot.restrict_chat_member( chat.id, user_id, until_date=mutetime, permissions=ChatPermissions(can_send_messages=False)) if conn: text = tl(update.effective_message, "Dibisukan untuk *{}* pada *{}*!").format( time_val, chat_name) else: text = tl(update.effective_message, "Dibisukan untuk *{}*!").format(time_val) send_message(update.effective_message, text, parse_mode="markdown") return log else: send_message( update.effective_message, tl(update.effective_message, "Pengguna ini sudah dibungkam.")) except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply send_message(update.effective_message, tl(update.effective_message, "Dibisukan untuk *{}*!").format(time_val), quote=False) return log else: LOGGER.warning(update) LOGGER.exception("ERROR muting user %s in chat %s (%s) due to %s", user_id, chat.title, chat.id, excp.message) send_message( update.effective_message, tl(update.effective_message, "Yah sial, aku tidak bisa membisukan pengguna itu.")) return ""
def test(self): command = NewChatMembersFilter() self.bot.bot = MagicMock(return_value=AttrDict({"id": 123})) self.bot.get_my_commands = MagicMock(return_value=None) self.bot.get_me = MagicMock(return_value={ "is_bot": True, "username": "******" }) self.bot.restrict_chat_member = MagicMock(return_value=None) command.send_bot_link = MagicMock(return_value={ "message_id": "123", "chat": { "id": "123" } }) command.add_message_info = MagicMock(return_value=None) # when bot first join self.bot.get_updates = MagicMock( return_value=[self.fake_update(new_chat_members=[self.bot])]) update_event = self.bot.get_updates().pop() context = MagicMock() context.bot = self.bot command.handle_invitation = MagicMock(return_value=None) with patch("app.lib.handlers.chat_created.ChatCreatedFilter.handler", return_value=None) as mock_handler: command.handler(update_event, context) mock_handler.assert_called() self.assertEqual(mock_handler.call_count, 1) self.bot.restrict_chat_member.assert_not_called() command.send_bot_link.assert_not_called() # when a user joins and we can't restrict user = User(id=101, first_name="tt", username="******", is_bot=False) self.bot.get_updates = MagicMock( return_value=[self.fake_update(new_chat_members=[user])]) update_event = self.bot.get_updates().pop() command.can_restrict_channel = MagicMock(return_value=False) with self.assertLogs("bot", level="INFO") as cm: command.handler(update_event, context) self.assertTrue( "INFO:bot:we can't restrict this chat: 1" in cm.output) self.bot.restrict_chat_member.assert_not_called() command.send_bot_link.assert_not_called() # when a user joins and we shouldn't restrict command.can_restrict_channel = MagicMock(return_value=True) command.should_restrict_channel = MagicMock(return_value=False) with self.assertLogs("bot", level="INFO") as cm: command.handler(update_event, context) self.assertTrue( "INFO:bot:we shouldn't restrict this chat: 1" in cm.output) self.bot.restrict_chat_member.assert_not_called() command.send_bot_link.assert_not_called() # when a user joins and they are verified command.should_restrict_channel = MagicMock(return_value=True) command.is_verified = MagicMock(return_value=True) with self.assertLogs("bot", level="INFO") as cm: command.handler(update_event, context) self.assertTrue( "INFO:bot:user: 101 is already verified" in cm.output) self.bot.restrict_chat_member.assert_not_called() command.send_bot_link.assert_not_called() # when a user joins and they aren't verified command.is_verified = MagicMock(return_value=False) # First update the channel chan = Channel.query.filter_by(chat_id="1").first() chan.restrict = True db.session.commit() command.handler(update_event, context) # This must create new Human & HumanChannelMember records in the db new_human = db.session.query(Human).filter( Human.user_id == "101").one() assert new_human is not None new_human_channel_member = ( db.session.query(HumanChannelMember).filter( HumanChannelMember.human_id == new_human.id, HumanChannelMember.channel_id == 1, ).one()) assert new_human_channel_member is not None self.bot.restrict_chat_member.assert_called() command.send_bot_link.assert_called() command.add_message_info.assert_called_with("123", "123", 101) self.assertEqual(self.bot.restrict_chat_member.call_count, 1) self.bot.restrict_chat_member.assert_has_calls([ call( 1, 101, permissions=ChatPermissions( can_send_messages=False, can_send_media_messages=False, can_send_other_messages=False, ), ) ]) # when a bot joins and they aren't verified user = User(id=102, first_name="bot1", username="******", is_bot=True) self.bot.get_updates = MagicMock( return_value=[self.fake_update(new_chat_members=[user])]) update_event = self.bot.get_updates().pop() command.handler(update_event, context) # This must create new Bot & BotChannelMember records in the db new_bot = db.session.query(Bot).filter(Bot.user_id == "102").one() assert new_bot is not None new_bot_channel_member = (db.session.query(BotChannelMember).filter( BotChannelMember.bot_id == new_bot.id, BotChannelMember.channel_id == 1).one()) assert new_bot_channel_member is not None
def new_member(update: Update, context: CallbackContext): bot, job_queue = context.bot, context.job_queue chat = update.effective_chat user = update.effective_user result = extract_status_change(update.chat_member) if chat.type != "supergroup": return if result is None: return was_member, is_member = result should_welc, cust_welcome, cust_content, welc_type = sql.get_welc_pref( chat.id) welc_mutes = sql.welcome_mutes(chat.id) human_checks = sql.get_human_checks(user.id, chat.id) if not was_member and is_member: new_mem = update.chat_member.new_chat_member.user if new_mem.id == bot.id and not SaitamaRobot.ALLOW_CHATS: with suppress(BadRequest): update.effective_message.send_message( f"Groups are disabled for {bot.first_name}, I'm outta here." ) bot.leave_chat(update.effective_chat.id) return welcome_log = None res = None sent = None should_mute = True welcome_bool = True media_wel = False if sw is not None: sw_ban = sw.get_ban(new_mem.id) if sw_ban: return if is_user_gbanned(new_mem.id): return reply = None if should_welc: # Give the owner a special welcome if new_mem.id == OWNER_ID: update.effective_chat.send_message( text="Oh, Genos? Let's get this moving.", reply_to_message_id=reply, ) welcome_log = (f"{html.escape(chat.title)}\n" f"#USER_JOINED\n" f"Bot Owner just joined the group") # Welcome Devs if new_mem.id in DEV_USERS: update.effective_chat.send_message( text= "Be cool! A member of the Heroes Association just joined.", reply_to_message_id=reply, ) welcome_log = (f"{html.escape(chat.title)}\n" f"#USER_JOINED\n" f"Bot Dev just joined the group") # Welcome Sudos if new_mem.id in DRAGONS: update.effective_chat.send_message( text="Whoa! A Dragon disaster just joined! Stay Alert!", reply_to_message_id=reply, ) welcome_log = (f"{html.escape(chat.title)}\n" f"#USER_JOINED\n" f"Bot Sudo just joined the group") # Welcome Support if new_mem.id in DEMONS: update.effective_chat.send_message( text= "Huh! Someone with a Demon disaster level just joined!", reply_to_message_id=reply, ) welcome_log = (f"{html.escape(chat.title)}\n" f"#USER_JOINED\n" f"Bot Support just joined the group") # Welcome Whitelisted if new_mem.id in TIGERS: update.effective_chat.send_message( text="Roar! A Tiger disaster just joined!", reply_to_message_id=reply, ) welcome_log = (f"{html.escape(chat.title)}\n" f"#USER_JOINED\n" f"A whitelisted user joined the chat") # Welcome Tigers if new_mem.id in WOLVES: update.effective_chat.send_message( text="Awoo! A Wolf disaster just joined!", reply_to_message_id=reply, ) welcome_log = (f"{html.escape(chat.title)}\n" f"#USER_JOINED\n" f"A whitelisted user joined the chat") # Welcome yourself if new_mem.id == bot.id: bot.send_message( JOIN_LOGGER, "#NEW_GROUP\n<b>Group name:</b> {}\n<b>ID:</b> <code>{}</code>" .format(html.escape(chat.title), chat.id), parse_mode=ParseMode.HTML, ) update.effective_chat.send_message( text= "Thanks for adding me! Join {@SUPPORT_CHAT} for support.", ) else: buttons = sql.get_welc_buttons(chat.id) keyb = build_keyboard(buttons) if welc_type not in (sql.Types.TEXT, sql.Types.BUTTON_TEXT): media_wel = True first_name = (new_mem.first_name or "PersonWithNoName" ) # edge case of empty name - occurs for some bugs. if cust_welcome: if cust_welcome == sql.DEFAULT_WELCOME: cust_welcome = random.choice( sql.DEFAULT_WELCOME_MESSAGES, ).format( first=escape_markdown(first_name)) if new_mem.last_name: fullname = escape_markdown( f"{first_name} {new_mem.last_name}") else: fullname = escape_markdown(first_name) count = chat.get_member_count() mention = mention_markdown(new_mem.id, escape_markdown(first_name)) if new_mem.username: username = "******" + escape_markdown(new_mem.username) else: username = mention valid_format = escape_invalid_curly_brackets( cust_welcome, VALID_WELCOME_FORMATTERS, ) res = valid_format.format( first=escape_markdown(first_name), last=escape_markdown(new_mem.last_name or first_name), fullname=escape_markdown(fullname), username=username, mention=mention, count=count, chatname=escape_markdown(chat.title), id=new_mem.id, ) else: res = random.choice(sql.DEFAULT_WELCOME_MESSAGES).format( first=escape_markdown(first_name), ) keyb = [] backup_message = random.choice( sql.DEFAULT_WELCOME_MESSAGES).format( first=escape_markdown(first_name), ) keyboard = InlineKeyboardMarkup(keyb) else: welcome_bool = False res = None keyboard = None backup_message = None reply = None # User exceptions from welcomemutes if (is_user_ban_protected(chat, new_mem.id, chat.get_member( new_mem.id)) or human_checks): should_mute = False # Join welcome: soft mute if new_mem.is_bot: should_mute = False if user.id == new_mem.id and should_mute: if welc_mutes == "soft": bot.restrict_chat_member( chat.id, new_mem.id, permissions=ChatPermissions( can_send_messages=True, can_send_media_messages=False, can_send_other_messages=False, can_invite_users=False, can_pin_messages=False, can_send_polls=False, can_change_info=False, can_add_web_page_previews=False, ), until_date=(int(time.time() + 24 * 60 * 60)), ) if welc_mutes == "strong": welcome_bool = False if not media_wel: VERIFIED_USER_WAITLIST.update( { new_mem.id: { "should_welc": should_welc, "media_wel": False, "status": False, "update": update, "res": res, "keyboard": keyboard, "backup_message": backup_message, }, }, ) else: VERIFIED_USER_WAITLIST.update( { new_mem.id: { "should_welc": should_welc, "chat_id": chat.id, "status": False, "media_wel": True, "cust_content": cust_content, "welc_type": welc_type, "res": res, "keyboard": keyboard, }, }, ) new_join_mem = f'<a href="tg://user?id={user.id}">{html.escape(new_mem.first_name)}</a>' message = bot.send_message( chat.id, f"{new_join_mem}, click the button below to prove you're human.\nYou have 120 seconds.", reply_markup=InlineKeyboardMarkup([ { InlineKeyboardButton( text="Yes, I'm human.", callback_data=f"user_join_({new_mem.id})", ), }, ], ), parse_mode=ParseMode.HTML, reply_to_message_id=reply, ) bot.restrict_chat_member( chat.id, new_mem.id, permissions=ChatPermissions( can_send_messages=False, can_invite_users=False, can_pin_messages=False, can_send_polls=False, can_change_info=False, can_send_media_messages=False, can_send_other_messages=False, can_add_web_page_previews=False, ), ) job_queue.run_once( partial(check_not_bot, new_mem, chat.id, message.message_id), 120, name="welcomemute", ) if welcome_bool: if media_wel: sent = ENUM_FUNC_MAP[welc_type]( chat.id, cust_content, caption=res, reply_markup=keyboard, reply_to_message_id=None, parse_mode="markdown", ) else: sent = send(update, res, keyboard, backup_message) prev_welc = sql.get_clean_pref(chat.id) if prev_welc: try: bot.delete_message(chat.id, prev_welc) except BadRequest: pass if sent: sql.set_clean_welcome(chat.id, sent.message_id) if welcome_log: return welcome_log if user.id == new_mem.id: welcome_log = ( f"{html.escape(chat.title)}\n" f"#USER_JOINED\n" f"<b>User</b>: {mention_html(user.id, user.first_name)}\n" f"<b>ID</b>: <code>{user.id}</code>") elif new_mem.is_bot: welcome_log = ( f"{html.escape(chat.title)}\n" f"#BOT_ADDED\n" f"<b>Bot</b>: {mention_html(new_mem.id, new_mem.first_name)}\n" f"<b>ID</b>: <code>{new_mem.id}</code>") else: welcome_log = ( f"{html.escape(chat.title)}\n" f"#USER_ADDED\n" f"<b>User</b>: {mention_html(new_mem.id, new_mem.first_name)}\n" f"<b>ID</b>: <code>{new_mem.id}</code>") return welcome_log return ""
class TestChat(object): id_ = -28767330 title = 'ToledosPalaceBot - Group' type_ = 'group' username = '******' all_members_are_administrators = False sticker_set_name = 'stickers' can_set_sticker_set = False permissions = ChatPermissions( can_send_messages=True, can_change_info=False, can_invite_users=True, ) slow_mode_delay = 30 def test_de_json(self, bot): json_dict = { 'id': self.id_, 'title': self.title, 'type': self.type_, 'username': self.username, 'all_members_are_administrators': self.all_members_are_administrators, 'sticker_set_name': self.sticker_set_name, 'can_set_sticker_set': self.can_set_sticker_set, 'permissions': self.permissions.to_dict(), 'slow_mode_delay': self.slow_mode_delay } chat = Chat.de_json(json_dict, bot) assert chat.id == self.id_ assert chat.title == self.title assert chat.type == self.type_ assert chat.username == self.username assert chat.all_members_are_administrators == self.all_members_are_administrators assert chat.sticker_set_name == self.sticker_set_name assert chat.can_set_sticker_set == self.can_set_sticker_set assert chat.permissions == self.permissions assert chat.slow_mode_delay == self.slow_mode_delay def test_de_json_default_quote(self, bot): json_dict = { 'id': self.id_, 'type': self.type_, 'pinned_message': Message(message_id=123, from_user=None, date=None, chat=None).to_dict(), 'default_quote': True } chat = Chat.de_json(json_dict, bot) assert chat.pinned_message.default_quote is True def test_to_dict(self, chat): chat_dict = chat.to_dict() assert isinstance(chat_dict, dict) assert chat_dict['id'] == chat.id assert chat_dict['title'] == chat.title assert chat_dict['type'] == chat.type assert chat_dict['username'] == chat.username assert chat_dict[ 'all_members_are_administrators'] == chat.all_members_are_administrators assert chat_dict['permissions'] == chat.permissions.to_dict() assert chat_dict['slow_mode_delay'] == chat.slow_mode_delay def test_link(self, chat): assert chat.link == 'https://t.me/{}'.format(chat.username) chat.username = None assert chat.link is None def test_send_action(self, monkeypatch, chat): def test(*args, **kwargs): id_ = args[0] == chat.id action = kwargs['action'] == ChatAction.TYPING return id_ and action monkeypatch.setattr(chat.bot, 'send_chat_action', test) assert chat.send_action(action=ChatAction.TYPING) def test_leave(self, monkeypatch, chat): def test(*args, **kwargs): return args[0] == chat.id monkeypatch.setattr(chat.bot, 'leave_chat', test) assert chat.leave() def test_get_administrators(self, monkeypatch, chat): def test(*args, **kwargs): return args[0] == chat.id monkeypatch.setattr(chat.bot, 'get_chat_administrators', test) assert chat.get_administrators() def test_get_members_count(self, monkeypatch, chat): def test(*args, **kwargs): return args[0] == chat.id monkeypatch.setattr(chat.bot, 'get_chat_members_count', test) assert chat.get_members_count() def test_get_member(self, monkeypatch, chat): def test(*args, **kwargs): chat_id = args[0] == chat.id user_id = args[1] == 42 return chat_id and user_id monkeypatch.setattr(chat.bot, 'get_chat_member', test) assert chat.get_member(42) def test_kick_member(self, monkeypatch, chat): def test(*args, **kwargs): chat_id = args[0] == chat.id user_id = args[1] == 42 until = kwargs['until_date'] == 43 return chat_id and user_id and until monkeypatch.setattr(chat.bot, 'kick_chat_member', test) assert chat.kick_member(42, until_date=43) def test_unban_member(self, monkeypatch, chat): def test(*args, **kwargs): chat_id = args[0] == chat.id user_id = args[1] == 42 return chat_id and user_id monkeypatch.setattr(chat.bot, 'unban_chat_member', test) assert chat.unban_member(42) def test_set_permissions(self, monkeypatch, chat): def test(*args, **kwargs): chat_id = args[0] == chat.id permissions = args[1] == self.permissions return chat_id and permissions monkeypatch.setattr(chat.bot, 'set_chat_permissions', test) assert chat.set_permissions(self.permissions) def test_set_administrator_custom_title(self, monkeypatch, chat): def test(*args, **kwargs): chat_id = args[1] == chat.id user_id = args[2] == 42 custom_title = args[3] == 'custom_title' return chat_id and user_id and custom_title monkeypatch.setattr('telegram.Bot.set_chat_administrator_custom_title', test) assert chat.set_administrator_custom_title(42, 'custom_title') def test_instance_method_send_message(self, monkeypatch, chat): def test(*args, **kwargs): return args[0] == chat.id and args[1] == 'test' monkeypatch.setattr(chat.bot, 'send_message', test) assert chat.send_message('test') def test_instance_method_send_photo(self, monkeypatch, chat): def test(*args, **kwargs): return args[0] == chat.id and args[1] == 'test_photo' monkeypatch.setattr(chat.bot, 'send_photo', test) assert chat.send_photo('test_photo') def test_instance_method_send_audio(self, monkeypatch, chat): def test(*args, **kwargs): return args[0] == chat.id and args[1] == 'test_audio' monkeypatch.setattr(chat.bot, 'send_audio', test) assert chat.send_audio('test_audio') def test_instance_method_send_document(self, monkeypatch, chat): def test(*args, **kwargs): return args[0] == chat.id and args[1] == 'test_document' monkeypatch.setattr(chat.bot, 'send_document', test) assert chat.send_document('test_document') def test_instance_method_send_sticker(self, monkeypatch, chat): def test(*args, **kwargs): return args[0] == chat.id and args[1] == 'test_sticker' monkeypatch.setattr(chat.bot, 'send_sticker', test) assert chat.send_sticker('test_sticker') def test_instance_method_send_video(self, monkeypatch, chat): def test(*args, **kwargs): return args[0] == chat.id and args[1] == 'test_video' monkeypatch.setattr(chat.bot, 'send_video', test) assert chat.send_video('test_video') def test_instance_method_send_video_note(self, monkeypatch, chat): def test(*args, **kwargs): return args[0] == chat.id and args[1] == 'test_video_note' monkeypatch.setattr(chat.bot, 'send_video_note', test) assert chat.send_video_note('test_video_note') def test_instance_method_send_voice(self, monkeypatch, chat): def test(*args, **kwargs): return args[0] == chat.id and args[1] == 'test_voice' monkeypatch.setattr(chat.bot, 'send_voice', test) assert chat.send_voice('test_voice') def test_instance_method_send_animation(self, monkeypatch, chat): def test(*args, **kwargs): return args[0] == chat.id and args[1] == 'test_animation' monkeypatch.setattr(chat.bot, 'send_animation', test) assert chat.send_animation('test_animation') def test_instance_method_send_poll(self, monkeypatch, chat): def test(*args, **kwargs): return args[0] == chat.id and args[1] == 'test_poll' monkeypatch.setattr(chat.bot, 'send_poll', test) assert chat.send_poll('test_poll') def test_equality(self): a = Chat(self.id_, self.title, self.type_) b = Chat(self.id_, self.title, self.type_) c = Chat(self.id_, '', '') d = Chat(0, self.title, self.type_) e = User(self.id_, '', False) assert a == b assert hash(a) == hash(b) assert a is not b assert a == c assert hash(a) == hash(c) assert a != d assert hash(a) != hash(d) assert a != e assert hash(a) != hash(e)
def temp_mute(update: Update, context: CallbackContext) -> str: bot, args = context.bot, context.args chat = update.effective_chat user = update.effective_user message = update.effective_message user_id, reason = extract_user_and_text(message, args) if not user_id: reply = "You don't seem to be referring to a user or the ID specified is incorrect.." return "" try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found": reply = "I can't seem to find this user" return "" else: raise if user_id == bot.id: reply = "I'm not gonna MUTE myself, How high are you?" return "" if is_user_admin(chat, user_id, member) or user_id in TIGERS: reply = "Can't. Find someone else to mute but not this one." return "" member = chat.get_member(user_id) if not reason: message.reply_text( "You haven't specified a time to mute this user for!") return "" split_reason = reason.split(None, 1) time_val = split_reason[0].lower() if len(split_reason) > 1: reason = split_reason[1] else: reason = "" mutetime = extract_time(message, time_val) if not mutetime: return "" log = ( f"<b>{html.escape(chat.title)}:</b>\n" f"#TEMP MUTED\n" f"<b>Admin:</b> {mention_html(user.id, user.first_name)}\n" f"<b>User:</b> {mention_html(member.user.id, member.user.first_name)}\n" f"<b>Time:</b> {time_val}") if reason: log += f"\n<b>Reason:</b> {reason}" try: if member.can_send_messages is None or member.can_send_messages: chat_permissions = ChatPermissions(can_send_messages=False) bot.restrict_chat_member(chat.id, user_id, chat_permissions, until_date=mutetime) bot.sendMessage( chat.id, f"Muted <b>{html.escape(member.user.first_name)}</b> for {time_val}!", parse_mode=ParseMode.HTML) return log else: message.reply_text("This user is already muted.") except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text(f"Muted for {time_val}!", quote=False) return log else: LOGGER.warning(update) LOGGER.exception("ERROR muting user %s in chat %s (%s) due to %s", user_id, chat.title, chat.id, excp.message) message.reply_text("Well damn, I can't mute that user.") return ""
def verify_button_pressed(update, context): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] query = update.callback_query # type: Optional[CallbackQuery] match = re.match(r"verify_me\((.+?)\)", query.data) match = match.group(1).split("|") is_ok = match[0] user_id = match[1] chat_id = match[2] message = update.effective_message # type: Optional[Message] print("-> {} was clicked welcome verify button".format(user.id)) if is_ok == "y": if context.bot.getChatMember(chat_id, user_id).status in ('left'): query.answer( text=tl(update.effective_message, "Failed: user left chat")) return try: context.bot.restrict_chat_member( chat_id, user_id, permissions=ChatPermissions(can_send_messages=True, can_send_media_messages=True, can_send_polls=True, can_send_other_messages=True, can_add_web_page_previews=True, can_change_info=True, can_invite_users=True, can_pin_messages=True)) sql.add_to_userlist(chat_id, user_id, True) sql.rm_from_timeout(chat_id, user_id) except BadRequest as err: if not update.effective_chat.get_member( context.bot.id).can_restrict_members: query.answer(text=tl( update.effective_message, "Saya tidak dapat membatasi orang disini, tanya admin untuk unmute!" )) else: query.answer(text="Error: " + str(err)) return chat_name = context.bot.get_chat(chat_id).title # query.message.delete() # context.bot.send_photo(chat.id, photo="https://telegra.ph/file/06d2c5ec80af3858c2d4b.jpg", caption=tl(update.effective_message, "*Berhasil!*\n\nKerja bagus manusia, kini Anda dapat chatting di: *{}*").format(chat_name), parse_mode="markdown") context.bot.edit_message_media( chat.id, message_id=query.message.message_id, media=InputMediaPhoto( media=open("emilia/modules/helper_funcs/emojis/done.jpg", 'rb'), caption=tl( update.effective_message, "*Berhasil!*\n\nKerja bagus manusia, kini Anda dapat chatting di: *{}*" ).format(chat_name), parse_mode="markdown")) query.answer(text=tl( update.effective_message, "Berhasil! Anda dapat chatting di {} sekarang").format(chat_name), show_alert=True) elif is_ok == "re": user_id = update.effective_user.id is_clicked = sql.get_chat_userlist(chat_id) if user_id not in list(is_clicked): context.bot.edit_message_text( chat.id, message_id=query.message.message_id, text=tl( update.effective_message, "Anda sedang tidak dalam mode verifikasi, jika anda sedang di bisukan, anda dapat meminta tolong pada admin di grup yang bersangkutan" )) return query.answer(text=tl(update.effective_message, "Error"), show_alert=False) elif user_id in list(is_clicked) and is_clicked[user_id] == True: context.bot.edit_message_text( chat.id, message_id=query.message.message_id, text=tl( update.effective_message, "Anda sedang tidak dalam mode verifikasi, jika anda sedang di bisukan, anda dapat meminta tolong pada admin di grup yang bersangkutan" )) return query.answer(text=tl(update.effective_message, "Error"), show_alert=False) verify_code = [ "🙏", "👈", "👉", "👇", "👆", "❤️", "🅰️", "🅱️", "0️⃣", "1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟" ] real_btn = random.choice(verify_code) print(real_btn) verify_code.remove(real_btn) verbox = (random.randint(1, 3), random.randint(1, 3)) buttons = [] linebox = [] was_set = False for x in range(3): x += 1 for y in range(3): y += 1 if verbox[0] == y and verbox[1] == x: was_set = True print("button was set to " + real_btn + "at " + str(verbox[0]) + " - " + str(verbox[1])) linebox.append( InlineKeyboardButton( text=real_btn, callback_data="verify_me(y|{}|{})".format( user_id, chat_id))) else: verify_emoji = random.choice(verify_code) linebox.append( InlineKeyboardButton( text=verify_emoji, callback_data="verify_me(n|{}|{})".format( user_id, chat_id))) verify_code.remove(verify_emoji) buttons.append(linebox) linebox = [] if not was_set: verbox = (random.randint(1, 3), random.randint(1, 3)) linebox[verbox[0] - 1][verbox[1] - 1] = InlineKeyboardButton( text=real_btn, callback_data="verify_me(y|{}|{})".format(user_id, chat_id)) print("[x] button was set to " + real_btn + "at " + str(verbox[0]) + " - " + str(verbox[1])) buttons.append([ InlineKeyboardButton(text="Refresh", callback_data="verify_me(re|{}|{})".format( user_id, chat_id)) ]) # query.message.delete() # context.bot.send_photo(chat.id, photo=open("emilia/modules/helper_funcs/emojis/" + verify_code_images[real_btn], 'rb'), caption=tl(update.effective_message, "Tolong pilih emoji yang sama dibawah ini:") + "\n" + tl(update.effective_message, "Jika tidak ada emoji yang sama, harap klik tombol refresh"), parse_mode="markdown", reply_markup=InlineKeyboardMarkup(buttons)) context.bot.edit_message_media( chat.id, message_id=query.message.message_id, media=InputMediaPhoto( media=open( "emilia/modules/helper_funcs/emojis/" + verify_code_images[real_btn], 'rb'), caption=tl(update.effective_message, "Tolong pilih emoji yang sama dibawah ini:") + "\n" + tl( update.effective_message, "Jika tidak ada emoji yang sama, harap klik tombol refresh" ), parse_mode="markdown"), reply_markup=InlineKeyboardMarkup(buttons)) query.answer(text=tl(update.effective_message, "Done"), show_alert=False) else: # query.message.delete() # context.bot.send_photo(chat.id, photo=open("emilia/modules/helper_funcs/emojis/fail.jpg", 'rb'), caption=tl(update.effective_message, "Maaf robot, kamu telah salah klik tombol verifikasi.\n\nCoba lagi dengan klik tombol verifikasi pada pesan selamat datang."), parse_mode="markdown") context.bot.edit_message_media( chat.id, message_id=query.message.message_id, media=InputMediaPhoto( media=open("emilia/modules/helper_funcs/emojis/fail.jpg", 'rb'), caption=tl( update.effective_message, "Maaf robot, kamu telah salah klik tombol verifikasi.\n\nCoba lagi dengan klik tombol verifikasi pada pesan selamat datang." ), parse_mode="markdown")) query.answer(text=tl( update.effective_message, "Gagal! Kamu telah salah mengklik tombol verifikasi"), show_alert=True)
def gkick(update, context): message = update.effective_message args = context.args bot = context.bot user_id = extract_user(message, args) try: user_chat = context.bot.get_chat(user_id) except BadRequest as excp: if excp.message in GKICK_ERRORS: pass else: message.reply_text("Unexpected Error!") context.bot.send_message( ERROR_DUMP, "User cannot be Globally kicked because: {}".format( excp.message)) return except TelegramError: pass if not user_id or int(user_id) == 777000: message.reply_text("You don't seem to be referring to a user.") return if int(user_id) in OFFICERS: message.reply_text("Error! (^_-)") return if user_id == context.bot.id: message.reply_text("Error! (¯―¯٥)") return chats = get_all_chats() banner = update.effective_user # type: Optional[User] message.reply_text("Globally kicking user @{}".format(user_chat.username)) sql.gkick_user(user_id, user_chat.username, 1) for chat in chats: try: member = context.bot.get_chat_member(chat.chat_id, user_id) if member.can_send_messages is False: context.bot.unban_chat_member( chat.chat_id, user_id) # Unban_member = kick (and not ban) context.bot.restrict_chat_member( chat.chat_id, user_id, permissions=ChatPermissions(can_send_messages=False)) else: context.bot.unban_chat_member(chat.chat_id, user_id) except BadRequest as excp: if excp.message in GKICK_ERRORS: pass else: message.reply_text("Unexpected Error!") context.bot.send_message( ERROR_DUMP, "User cannot be Globally kicked because: {}".format( excp.message)) return except TelegramError: pass
def mute(update, context): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] message = update.effective_message # type: Optional[Message] args = context.args user_id = extract_user(message, args) if not user_id or user_id == "error": send_message( update.effective_message, tl( update.effective_message, "Anda harus memberi saya nama pengguna untuk membungkam, atau membalas seseorang untuk dibisukan." )) return "" conn = connected(context.bot, update, chat, user.id, need_admin=True) if conn: chat = dispatcher.bot.getChat(conn) chat_id = conn chat_name = dispatcher.bot.getChat(conn).title text = tl(update.effective_message, "Terbisukan pada *{}*! 😆").format(chat_name) else: if update.effective_message.chat.type == "private": update.effective_send_message( update.effective_message, tl(update.effective_message, "Anda bisa lakukan command ini pada grup, bukan pada PM")) return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title text = tl(update.effective_message, "Terbisukan! 😆") if user_id == context.bot.id: send_message( update.effective_message, tl(update.effective_message, "Saya tidak akan membungkam diri saya sendiri!")) return "" check = context.bot.getChatMember(chat.id, user.id) if check['can_restrict_members'] == False: send_message( update.effective_message, tl(update.effective_message, "Anda tidak punya hak untuk membatasi seseorang.")) return "" member = chat.get_member(int(user_id)) if member: if is_user_admin(chat, user_id, member=member): send_message( update.effective_message, tl(update.effective_message, "Saya tidak bisa menghentikan seorang admin berbicara!")) elif member.can_send_messages is None or member.can_send_messages: context.bot.restrict_chat_member( chat.id, user_id, permissions=ChatPermissions(can_send_messages=False)) send_message(update.effective_message, text, parse_mode="markdown") return "<b>{}:</b>" \ "\n#MUTE" \ "\n<b>Admin:</b> {}" \ "\n<b>User:</b> {}".format(html.escape(chat.title), mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name)) else: send_message( update.effective_message, tl(update.effective_message, "Pengguna ini sudah dibungkam!")) else: send_message( update.effective_message, tl(update.effective_message, "Pengguna ini tidak ada dalam obrolan!")) return ""
def check_flood(update, context) -> str: user = update.effective_user # type: Optional[User] chat = update.effective_chat # type: Optional[Chat] msg = update.effective_message # type: Optional[Message] if not user: # ignore channels return "" # ignore admins and whitelists if is_user_admin(chat, user.id) or user.id in WOLVES or user.id in TIGERS: sql.update_flood(chat.id, None) return "" # ignore approved users if is_approved(chat.id, user.id): sql.update_flood(chat.id, None) return should_ban = sql.update_flood(chat.id, user.id) if not should_ban: return "" try: getmode, getvalue = sql.get_flood_setting(chat.id) if getmode == 1: chat.kick_member(user.id) execstrings = "Banned" tag = "BANNED" elif getmode == 2: chat.kick_member(user.id) chat.unban_member(user.id) execstrings = "Kicked" tag = "KICKED" elif getmode == 3: context.bot.restrict_chat_member( chat.id, user.id, permissions=ChatPermissions(can_send_messages=False), ) execstrings = "Muted" tag = "MUTED" elif getmode == 4: bantime = extract_time(msg, getvalue) chat.kick_member(user.id, until_date=bantime) execstrings = "Banned for {}".format(getvalue) tag = "TBAN" elif getmode == 5: mutetime = extract_time(msg, getvalue) context.bot.restrict_chat_member( chat.id, user.id, until_date=mutetime, permissions=ChatPermissions(can_send_messages=False), ) execstrings = "Muted for {}".format(getvalue) tag = "TMUTE" send_message( update.effective_message, "Beep Boop! Boop Beep!\n{}!".format(execstrings), ) return ("<b>{}:</b>" "\n#{}" "\n<b>User:</b> {}" "\nFlooded the group.".format( tag, html.escape(chat.title), mention_html(user.id, html.escape(user.first_name)), )) except BadRequest: msg.reply_text( "Mình không thể hạn chế mọi người ở đây, hãy cho mình quyền trước! Cho đến lúc đó, mình sẽ tắt tính năng anti-flood", ) sql.set_flood(chat.id, 0) return ( "<b>{}:</b>" "\n#INFO" "\nKhông có đủ quyền hạn chế người dùng nên tính năng anti-flood sẽ tự động tắt" .format(chat.title, ))
def del_blacklist(update, context): chat = update.effective_chat message = update.effective_message user = update.effective_user bot = context.bot to_match = extract_text(message) if not to_match: return if is_approved(chat.id, user.id): return getmode, value = sql.get_blacklist_setting(chat.id) chat_filters = sql.get_chat_blacklist(chat.id) for trigger in chat_filters: pattern = r"( |^|[^\w])" + re.escape(trigger) + r"( |$|[^\w])" if re.search(pattern, to_match, flags=re.IGNORECASE): try: if getmode == 0: return elif getmode == 1: try: message.delete() except BadRequest: pass elif getmode == 2: try: message.delete() except BadRequest: pass warn( update.effective_user, chat, ("Using blacklisted trigger: {}".format(trigger)), message, update.effective_user, ) return elif getmode == 3: message.delete() bot.restrict_chat_member( chat.id, update.effective_user.id, permissions=ChatPermissions(can_send_messages=False), ) bot.sendMessage( chat.id, f"Muted {user.first_name} for using Blacklisted word: {trigger}!", ) return elif getmode == 4: message.delete() res = chat.unban_member(update.effective_user.id) if res: bot.sendMessage( chat.id, f"Kicked {user.first_name} for using Blacklisted word: {trigger}!", ) return elif getmode == 5: message.delete() chat.kick_member(user.id) bot.sendMessage( chat.id, f"Banned {user.first_name} for using Blacklisted word: {trigger}", ) return elif getmode == 6: message.delete() bantime = extract_time(message, value) chat.kick_member(user.id, until_date=bantime) bot.sendMessage( chat.id, f"Banned {user.first_name} until '{value}' for using Blacklisted word: {trigger}!", ) return elif getmode == 7: message.delete() mutetime = extract_time(message, value) bot.restrict_chat_member( chat.id, user.id, until_date=mutetime, permissions=ChatPermissions(can_send_messages=False), ) bot.sendMessage( chat.id, f"Muted {user.first_name} until '{value}' for using Blacklisted word: {trigger}!", ) return except BadRequest as excp: if excp.message != "Message to delete not found": LOGGER.exception("Error while deleting blacklist message.") break
def stemp_mute(update: Update, context: CallbackContext) -> str: bot = context.bot chat = update.effective_chat user = update.effective_user message = update.effective_message args = context.args user_id, reason = extract_user_and_text(message, args) update.effective_message.delete() if not user_id: return "" try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found": return "" else: raise if user_id == bot.id: return "" if is_user_admin(chat, user_id, member) or user_id in TIGERS: return "" member = chat.get_member(user_id) if not reason: message.reply_text( "You haven't specified a time to mute this user for!") return "" split_reason = reason.split(None, 1) time_val = split_reason[0].lower() if len(split_reason) > 1: reason = split_reason[1] else: reason = "" mutetime = extract_time(message, time_val) if not mutetime: return "" log = ( f"<b>{html.escape(chat.title)}:</b>\n" f"#STEMP MUTED\n" f"<b>Eksekutor:</b> {mention_html(user.id, user.first_name)}\n" f"<b>Korban:</b> {mention_html(member.user.id, member.user.first_name)}\n" f"<b>Waktu:</b> {time_val}") if reason: log += f"\n<b>Alasan:</b> {reason}" try: if member.can_send_messages is None or member.can_send_messages: chat_permissions = ChatPermissions(can_send_messages=False) bot.restrict_chat_member(chat.id, user_id, chat_permissions, until_date=mutetime) return log except BadRequest as excp: if excp.message == "Reply message not found": return log else: LOGGER.warning(update) LOGGER.exception( "ERROR muting user %s in chat %s (%s) due to %s", user_id, chat.title, chat.id, excp.message, ) return ""
def new_member(update: Update, context: CallbackContext): bot = context.bot chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] msg = update.effective_message # type: Optional[Message] chat_name = chat.title or chat.first or chat.username # type: Optional:[chat name] should_welc, cust_welcome, cust_media, welc_type = sql.get_welc_pref( chat.id) welc_mutes = sql.welcome_mutes(chat.id) casPrefs = sql.get_cas_status(str(chat.id)) #check if enabled, obviously autoban = sql.get_cas_autoban(str(chat.id)) chatbanned = sql.isBanned(str(chat.id)) defense = sql.getDefenseStatus(str(chat.id)) time_value = sql.getKickTime(str(chat.id)) isUserGbanned = gbansql.is_user_gbanned(user.id) if isUserGbanned: return if chatbanned: bot.leave_chat(int(chat.id)) elif casPrefs and not autoban and cas.banchecker(user.id): bot.restrict_chat_member(chat.id, user.id, permissions=ChatPermissions( can_send_messages=False, can_send_media_messages=False, can_send_other_messages=False, can_add_web_page_previews=False)) msg.reply_text( "Warning! This user is CAS Banned. I have muted them to avoid spam. Ban is advised." ) if not isUserGbanned: report = "CAS Banned user detected: <code>{}</code>".format( user.id) send_to_list(bot, SUDO_USERS + SUPPORT_USERS, report, html=True) if defense: bantime = int(time.time()) + 60 chat.kick_member(new_mem.id, until_date=bantime) elif casPrefs and autoban and cas.banchecker(user.id): chat.kick_member(user.id) msg.reply_text( "CAS banned user detected! User has been automatically banned!") isUserGbanned = gbansql.is_user_gbanned(user.id) if not isUserGbanned: report = "CAS Banned user detected: <code>{}</code>".format( user.id) send_to_list(bot, SUDO_USERS + SUPPORT_USERS, report, html=True) elif defense and (user.id not in SUDO_USERS + SUPPORT_USERS): bantime = int(time.time()) + 60 chat.kick_member(user.id, until_date=bantime) elif should_welc: sent = None new_members = update.effective_message.new_chat_members for new_mem in new_members: # Give the owner a special welcome if new_mem.id == OWNER_ID: update.effective_message.reply_text( "Master is in the houseeee, let's get this party started!") continue # Give the sudos/support a special welcome too elif new_mem.id in SUDO_USERS or new_mem.id in SUPPORT_USERS: update.effective_message.reply_text( "Welcome to the Dark Side! May the force be with you...") continue # Make bot greet admins elif new_mem.id == bot.id: update.effective_message.reply_text( "Hey {}, I'm {}! Thank you for adding me to {}" " and be sure to check /help in PM for more commands and tricks!" .format(user.first_name, bot.first_name, chat_name)) else: first_name = new_mem.first_name or "PersonWithNoName" # edge case of empty name - occurs for some bugs. if cust_welcome: if new_mem.last_name: fullname = "{} {}".format(first_name, new_mem.last_name) else: fullname = first_name count = chat.get_members_count() mention = mention_markdown(new_mem.id, first_name) if new_mem.username: username = "******" + escape_markdown(new_mem.username) else: username = mention valid_format = escape_invalid_curly_brackets( cust_welcome, VALID_WELCOME_FORMATTERS) res = valid_format.format( first=escape_markdown(first_name), last=escape_markdown(new_mem.last_name or first_name), fullname=escape_markdown(fullname), username=username, mention=mention, count=count, chatname=escape_markdown(chat.title), id=new_mem.id) buttons = sql.get_welc_buttons(chat.id) keyb = build_keyboard(buttons) else: res = sql.DEFAULT_WELCOME.format(first=first_name) keyb = [] keyboard = InlineKeyboardMarkup(keyb) # If welcome message is media, send with appropriate function if welc_type != sql.Types.TEXT and welc_type != sql.Types.BUTTON_TEXT: sent = ENUM_FUNC_MAP[welc_type]( chat.id, cust_media, caption=res, reply_to_message_id=msg.message_id, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) pass else: sent = send( update, res, keyboard, sql.DEFAULT_WELCOME.format( first=first_name)) # type: Optional[Message] #Sudo user exception from mutes: if is_user_ban_protected(chat, new_mem.id, chat.get_member(new_mem.id)): continue #Safe mode newMember = chat.get_member(int(new_mem.id)) if welc_mutes == "on" and ((newMember.can_send_messages is None or newMember.can_send_messages)): text = "" if time_value: text = " else you'll be kicked after {} seconds.".format( str(time_value)) buttonMsg = msg.reply_text( "Click the button below to prove you're human" + text, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( text="I'm not a bot!", callback_data="userverify_({})".format( new_mem.id)) ]])) bot.restrict_chat_member( chat.id, new_mem.id, permissions=ChatPermissions( can_send_messages=False, can_send_media_messages=False, can_send_other_messages=False, can_add_web_page_previews=False)) if time_value: time.sleep(time_value) member = chat.get_member(int(new_mem.id)) if not (member.can_send_messages or member.status == 'left'): print("kicking user..") bantime = int(time.time()) + 60 chat.kick_member(new_mem.id, until_date=bantime) buttonMsg.delete() sent.delete() update.message.delete() delete_join(bot, update) prev_welc = sql.get_clean_pref(chat.id) if prev_welc: try: bot.delete_message(chat.id, prev_welc) except BadRequest as excp: pass if sent: sql.set_clean_welcome(chat.id, sent.message_id)
def check_flood(update, context) -> str: user = update.effective_user # type: Optional[User] chat = update.effective_chat # type: Optional[Chat] msg = update.effective_message # type: Optional[Message] if not user: # ignore channels return "" # ignore admins and whitelists if is_user_admin(chat, user.id) or user.id in WOLVES: sql.update_flood(chat.id, None) return "" # ignore approved users if is_approved(chat.id, user.id): sql.update_flood(chat.id, None) return should_ban = sql.update_flood(chat.id, user.id) if not should_ban: return "" try: getmode, getvalue = sql.get_flood_setting(chat.id) if getmode == 1: chat.kick_member(user.id) execstrings = "Banned" tag = "BANNED" elif getmode == 2: chat.kick_member(user.id) chat.unban_member(user.id) execstrings = "Kicked" tag = "KICKED" elif getmode == 3: context.bot.restrict_chat_member( chat.id, user.id, permissions=ChatPermissions(can_send_messages=False)) execstrings = "Muted" tag = "MUTED" elif getmode == 4: bantime = extract_time(msg, getvalue) chat.kick_member(user.id, until_date=bantime) execstrings = "Banned for {}".format(getvalue) tag = "TBAN" elif getmode == 5: mutetime = extract_time(msg, getvalue) context.bot.restrict_chat_member( chat.id, user.id, until_date=mutetime, permissions=ChatPermissions(can_send_messages=False), ) execstrings = "Muted for {}".format(getvalue) tag = "TMUTE" send_message(update.effective_message, "Beep Boop! Boop Beep!\n{}!".format(execstrings)) return ("<b>{}:</b>" "\n#{}" "\n<b>User:</b> {}" "\nFlooded the group.".format( tag, html.escape(chat.title), mention_html(user.id, html.escape(user.first_name)), )) except BadRequest: msg.reply_text( "I can't restrict people here, give me permissions first! Until then, I'll disable anti-flood." ) sql.set_flood(chat.id, 0) return ( "<b>{}:</b>" "\n#INFO" "\nDon't have enough permission to restrict users so automatically disabled anti-flood" .format(chat.title))
def check_flood(update, context) -> str: user = update.effective_user # type: Optional[User] chat = update.effective_chat # type: Optional[Chat] msg = update.effective_message # type: Optional[Message] if not user: # ignore channels return "" # ignore admins and whitelists if (is_user_admin(chat, user.id) or user.id in WOLVES or user.id in TIGERS): sql.update_flood(chat.id, None) return "" should_ban = sql.update_flood(chat.id, user.id) if not should_ban: return "" try: getmode, getvalue = sql.get_flood_setting(chat.id) if getmode == 1: chat.kick_member(user.id) execstrings = ("Banlandı") tag = "BANNED" elif getmode == 2: chat.kick_member(user.id) chat.unban_member(user.id) execstrings = ("Atıldı") tag = "KICKED" elif getmode == 3: context.bot.restrict_chat_member( chat.id, user.id, permissions=ChatPermissions(can_send_messages=False)) execstrings = ("Susduruldu") tag = "MUTED" elif getmode == 4: bantime = extract_time(msg, getvalue) chat.kick_member(user.id, until_date=bantime) execstrings = ("{} müddətlik susduruldu".format(getvalue)) tag = "TBAN" elif getmode == 5: mutetime = extract_time(msg, getvalue) context.bot.restrict_chat_member( chat.id, user.id, until_date=mutetime, permissions=ChatPermissions(can_send_messages=False)) execstrings = ("{} müddətlik susduruldu".format(getvalue)) tag = "TMUTE" send_message(update.effective_message, "Beep Boop! Boop Beep!\n{}!".format(execstrings)) return "<b>{}:</b>" \ "\n#{}" \ "\n<b>User:</b> {}" \ "\nFlooded the group.".format(tag, html.escape(chat.title), mention_html(user.id, html.escape(user.first_name))) except BadRequest: msg.reply_text( "Mən burada insanları məhdudlaşdıra bilmirəm, mənə lazımi səlahiyyətləri ver!" ) sql.set_flood(chat.id, 0) return "<b>{}:</b>" \ "\n#INFO" \ "\nDon't have enough permission to restrict users so automatically disabled anti-flood".format(chat.title)
def rmute(update: Update, context: CallbackContext): bot, args = context.bot, context.args message = update.effective_message if not args: message.reply_text("You don't seem to be referring to a chat/user.") return user_id, chat_id = extract_user_and_text(message, args) if not user_id: message.reply_text("You don't seem to be referring to a user.") return if not chat_id: message.reply_text("You don't seem to be referring to a chat.") return try: chat = bot.get_chat(chat_id.split()[0]) except BadRequest as excp: if excp.message == "Chat not found": message.reply_text( "Chat not found! Make sure you entered a valid chat ID and I'm part of that chat." ) return raise if chat.type == "private": message.reply_text("I'm sorry, but that's a private chat!") return if (not is_bot_admin(chat, bot.id) or not chat.get_member(bot.id).can_restrict_members): message.reply_text( "I can't restrict people there! Make sure I'm admin and can mute users." ) return try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found": message.reply_text("I can't seem to find this user") return raise if is_user_ban_protected(chat, user_id, member): message.reply_text("I really wish I could mute admins...") return if user_id == bot.id: message.reply_text("I'm not gonna MUTE myself, are you crazy?") return try: bot.restrict_chat_member( chat.id, user_id, permissions=ChatPermissions(can_send_messages=False)) rmuting = "It is so quiet...\n{} has been remotely muted from {}! \n".format( mention_html(member.user.id, member.user.first_name), (chat.title or chat.first or chat.username), ) message.reply_text(rmuting, parse_mode=ParseMode.HTML) except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text("Muted!", quote=False) elif excp.message in RMUTE_ERRORS: message.reply_text(excp.message) else: LOGGER.warning(update) LOGGER.exception( "ERROR mute user %s in chat %s (%s) due to %s", user_id, chat.title, chat.id, excp.message, ) message.reply_text("Well damn, I can't mute that user.")
def ungmute(update, context): message = update.effective_message # type: Optional[Message] bot = context.bot args = context.args user_id = extract_user(message, args) if not user_id: message.reply_text("You don't seem to be referring to a user.") return user_chat = bot.get_chat(user_id) if user_chat.type != "private": message.reply_text("That's not a user!") return if not sql.is_user_gmuted(user_id): message.reply_text("This user is not gmuted!") return muter = update.effective_user # type: Optional[User] message.reply_text(f"I'll let {user_chat.first_name} speak again, globally.") chats = get_all_chats() for chat in chats: chat_id = chat.chat_id # Check if this group has disabled gmutes if not sql.does_chat_gmute(chat_id): continue try: member = context.bot.get_chat_member(chat_id, user_id) if member.status == "restricted": context.bot.restrict_chat_member( chat_id, int(user_id), permissions=ChatPermissions( can_send_messages=True, can_invite_users=True, can_pin_messages=True, can_send_polls=True, can_change_info=True, can_send_media_messages=True, can_send_other_messages=True, can_add_web_page_previews=True, ), ) except BadRequest as excp: if excp.message == "User is an administrator of the chat": pass elif excp.message == "Chat not found": pass elif excp.message == "Not enough rights to restrict/unrestrict chat member": pass elif excp.message == "User_not_participant": pass elif ( excp.message == "Method is available for supergroup and channel chats only" ): pass elif excp.message == "Not in the chat": pass elif excp.message == "Channel_private": pass elif excp.message != "Chat_admin_required": message.reply_text("Unexpected Error!") bot.send_message( ERROR_DUMP, f"Could not un-gmute due to: {excp.message}" ) return except TelegramError: pass sql.ungmute_user(user_id) message.reply_text("Person has been un-gmuted.")
def new_member(update: Update, context: CallbackContext): bot, job_queue = context.bot, context.job_queue chat = update.effective_chat user = update.effective_user msg = update.effective_message should_welc, cust_welcome, cust_content, welc_type = sql.get_welc_pref(chat.id) welc_mutes = sql.welcome_mutes(chat.id) human_checks = sql.get_human_checks(user.id, chat.id) new_members = update.effective_message.new_chat_members for new_mem in new_members: welcome_log = None res = None sent = None should_mute = True welcome_bool = True media_wel = False if sw is not None: sw_ban = sw.get_ban(new_mem.id) if sw_ban: return if should_welc: reply = update.message.message_id cleanserv = sql.clean_service(chat.id) # Clean service welcome if cleanserv: try: dispatcher.bot.delete_message(chat.id, update.message.message_id) except BadRequest: pass reply = False # Give the owner a special welcome if new_mem.id == OWNER_ID: update.effective_message.reply_text( "Oh, Genos? Let's get this moving.", reply_to_message_id=reply ) welcome_log = ( f"{html.escape(chat.title)}\n" f"#USER_JOINED\n" f"Bot Owner just joined the chat" ) continue # Welcome Devs elif new_mem.id in DEV_USERS: update.effective_message.reply_text( "Whoa! A member of the Heroes Association just joined!", reply_to_message_id=reply, ) continue # Welcome Sudos elif new_mem.id in DRAGONS: update.effective_message.reply_text( "Huh! A Dragon disaster just joined! Stay Alert!", reply_to_message_id=reply, ) continue # Welcome Support elif new_mem.id in DEMONS: update.effective_message.reply_text( "Huh! Someone with a Demon disaster level just joined!", reply_to_message_id=reply, ) continue # Welcome Whitelisted elif new_mem.id in TIGERS: update.effective_message.reply_text( "Oof! A Tiger disaster just joined!", reply_to_message_id=reply ) continue # Welcome Tigers elif new_mem.id in WOLVES: update.effective_message.reply_text( "Oof! A Wolf disaster just joined!", reply_to_message_id=reply ) continue # Welcome yourself elif new_mem.id == bot.id: creator = None for x in bot.bot.get_chat_administrators(update.effective_chat.id): if x.status == "creator": creator = x.user break if creator: bot.send_message( JOIN_LOGGER, "#NEW_GROUP\n<b>Group name:</b> {}\n<b>ID:</b> <code>{}</code>\n<b>Creator:</b> <code>{}</code>".format( html.escape(chat.title), chat.id, html.escape(creator) ), parse_mode=ParseMode.HTML, ) else: bot.send_message( JOIN_LOGGER, "#NEW_GROUP\n<b>Group name:</b> {}\n<b>ID:</b> <code>{}</code>".format( html.escape(chat.title), chat.id ), parse_mode=ParseMode.HTML, ) update.effective_message.reply_text( "Watashi ga kita!", reply_to_message_id=reply ) continue else: buttons = sql.get_welc_buttons(chat.id) keyb = build_keyboard(buttons) if welc_type not in (sql.Types.TEXT, sql.Types.BUTTON_TEXT): media_wel = True first_name = ( new_mem.first_name or "PersonWithNoName" ) # edge case of empty name - occurs for some bugs. if cust_welcome: if cust_welcome == sql.DEFAULT_WELCOME: cust_welcome = random.choice( sql.DEFAULT_WELCOME_MESSAGES ).format(first=escape_markdown(first_name)) if new_mem.last_name: fullname = escape_markdown(f"{first_name} {new_mem.last_name}") else: fullname = escape_markdown(first_name) count = chat.get_members_count() mention = mention_markdown(new_mem.id, escape_markdown(first_name)) if new_mem.username: username = "******" + escape_markdown(new_mem.username) else: username = mention valid_format = escape_invalid_curly_brackets( cust_welcome, VALID_WELCOME_FORMATTERS ) res = valid_format.format( first=escape_markdown(first_name), last=escape_markdown(new_mem.last_name or first_name), fullname=escape_markdown(fullname), username=username, mention=mention, count=count, chatname=escape_markdown(chat.title), id=new_mem.id, ) else: res = random.choice(sql.DEFAULT_WELCOME_MESSAGES).format( first=escape_markdown(first_name) ) keyb = [] backup_message = random.choice(sql.DEFAULT_WELCOME_MESSAGES).format( first=escape_markdown(first_name) ) keyboard = InlineKeyboardMarkup(keyb) else: welcome_bool = False res = None keyboard = None backup_message = None reply = None # User exceptions from welcomemutes if ( is_user_ban_protected(chat, new_mem.id, chat.get_member(new_mem.id)) or human_checks ): should_mute = False # Join welcome: soft mute if new_mem.is_bot: should_mute = False if user.id == new_mem.id: if should_mute: if welc_mutes == "soft": bot.restrict_chat_member( chat.id, new_mem.id, permissions=ChatPermissions( can_send_messages=True, can_send_media_messages=False, can_send_other_messages=False, can_invite_users=False, can_pin_messages=False, can_send_polls=False, can_change_info=False, can_add_web_page_previews=False, ), until_date=(int(time.time() + 24 * 60 * 60)), ) if welc_mutes == "strong": welcome_bool = False if not media_wel: VERIFIED_USER_WAITLIST.update( { new_mem.id: { "should_welc": should_welc, "media_wel": False, "status": False, "update": update, "res": res, "keyboard": keyboard, "backup_message": backup_message, } } ) else: VERIFIED_USER_WAITLIST.update( { new_mem.id: { "should_welc": should_welc, "chat_id": chat.id, "status": False, "media_wel": True, "cust_content": cust_content, "welc_type": welc_type, "res": res, "keyboard": keyboard, } } ) new_join_mem = f'<a href="tg://user?id={user.id}">{html.escape(new_mem.first_name)}</a>' message = msg.reply_text( f"{new_join_mem}, click the button below to prove you're human.\nYou have 120 seconds.", reply_markup=InlineKeyboardMarkup( [ { InlineKeyboardButton( text="Yes, I'm human.", callback_data=f"user_join_({new_mem.id})", ) } ] ), parse_mode=ParseMode.HTML, reply_to_message_id=reply, ) bot.restrict_chat_member( chat.id, new_mem.id, permissions=ChatPermissions( can_send_messages=False, can_invite_users=False, can_pin_messages=False, can_send_polls=False, can_change_info=False, can_send_media_messages=False, can_send_other_messages=False, can_add_web_page_previews=False, ), ) job_queue.run_once( partial(check_not_bot, new_mem, chat.id, message.message_id), 120, name="welcomemute", ) if welcome_bool: if media_wel: sent = ENUM_FUNC_MAP[welc_type]( chat.id, cust_content, caption=res, reply_markup=keyboard, reply_to_message_id=reply, parse_mode="markdown", ) else: sent = send(update, res, keyboard, backup_message) prev_welc = sql.get_clean_pref(chat.id) if prev_welc: try: bot.delete_message(chat.id, prev_welc) except BadRequest: pass if sent: sql.set_clean_welcome(chat.id, sent.message_id) if welcome_log: return welcome_log return ( f"{html.escape(chat.title)}\n" f"#USER_JOINED\n" f"<b>User</b>: {mention_html(user.id, user.first_name)}\n" f"<b>ID</b>: <code>{user.id}</code>" ) return ""
def gmute(update, context): message = update.effective_message # type: Optional[Message] chat = update.effective_chat args = context.args user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text("You don't seem to be referring to a user.") return if int(user_id) in OFFICERS: message.reply_text("I Can't Gmute My Sudo Users .") return if user_id == context.bot.id: message.reply_text("I can't gmute myself.") return if not reason: message.reply_text("Please give a reason why are you want to gmute this user!") return try: user_chat = context.bot.get_chat(user_id) except BadRequest as excp: message.reply_text(excp.message) return if user_chat.type != "private": message.reply_text("That's not a user!") return if sql.is_user_gmuted(user_id): if not reason: message.reply_text( "This user is already gmuted; I'd change the reason, but you haven't given me one..." ) return success = sql.update_gmute_reason( user_id, user_chat.username or user_chat.first_name, reason ) if success: message.reply_text( "This user is already gmuted; I've gone and updated the gmute reason though!" ) else: message.reply_text("I thought this person was gmuted.") return message.reply_text("Gets duct tape ready 😉") muter = update.effective_user # type: Optional[User] sql.gmute_user(user_id, user_chat.username or user_chat.first_name, reason) chats = get_all_chats() for chat in chats: chat_id = chat.chat_id # Check if this group has disabled gmutes if not sql.does_chat_gmute(chat_id): continue try: context.bot.restrict_chat_member( chat_id, user_id, permissions=ChatPermissions(can_send_messages=False) ) except BadRequest as excp: if excp.message == "User is an administrator of the chat": pass elif excp.message == "Chat not found": pass elif excp.message == "Not enough rights to restrict/unrestrict chat member": pass elif excp.message == "User_not_participant": pass elif ( excp.message == "Peer_id_invalid" ): # Suspect this happens when a group is suspended by telegram. pass elif excp.message == "Group chat was deactivated": pass elif ( excp.message == "Need to be inviter of a user to kick it from a basic group" ): pass elif excp.message == "Chat_admin_required": pass elif ( excp.message == "Only the creator of a basic group can kick group administrators" ): pass elif excp.message == "Method is available only for supergroups": pass elif excp.message != "Can't demote chat creator": message.reply_text("Unexpected Error!") context.bot.send_message( ERROR_DUMP, f"Could not gmute due to: {excp.message}" ) sql.ungmute_user(user_id) return except TelegramError: pass message.reply_text("They won't be talking again anytime soon.")
def game_end(context, text, chat_id, chameleon_id, winner_ids, lang): chat_data = context.chat_data players = chat_data["players"] context.bot.send_message(chat_id, text, parse_mode=ParseMode.HTML, reply_markup=ReplyKeyboardRemove()) context.bot.edit_message_reply_markup(chat_id, chat_data["word_list"], reply_markup=None) player_ids = [] for player in players: player_ids.append(player["user_id"]) if chat_data["tournament"]: tournament = chat_data["tournament"] # first game of tournament if not isinstance(tournament, dict): database.end_game(chat_id, player_ids, chameleon_id, winner_ids, chat_data["starter"]["user_id"]) tournament = {} for player_id in player_ids: tournament[player_id] = 0 else: database.end_game(chat_id, player_ids, chameleon_id, winner_ids) # that means the chameleon won if len(winner_ids) == 1: # that means the chameleon had to guess, but won, so gets a point, no one else does if "guesses" in chat_data: tournament[chameleon_id] += 1 # that means the chameleon escaped undetected, so gets two points else: tournament[chameleon_id] += 2 # that means everyone else won, they get two points else: for user_id in winner_ids: if user_id is not chameleon_id: tournament[user_id] += 2 tournament_winners = [] for user_id in tournament: if tournament[user_id] >= 5: tournament_winners.append(user_id) # that means we have winner(s), the tournament is over if tournament_winners: database.end_tournament(chat_id, player_ids, tournament_winners) if len(tournament_winners) == 1: winner_mention = None contestant_mentions_points = [] for player in players: if player["user_id"] in tournament_winners: winner_mention = mention_html(player["user_id"], player["first_name"]) else: contestant_mentions_points.append(f"{mention_html(player['user_id'], player['first_name'])}: " f"<b>{tournament[player['user_id']]}</b>") text = get_string(lang, "tournament_end_one").format(winner_mention, tournament[tournament_winners[0]], "\n".join(contestant_mentions_points)) else: winner_mention_points = [] contestant_mentions_points = [] for player in players: if player["user_id"] in tournament_winners: winner_mention_points.append(f"{mention_html(player['user_id'], player['first_name'])}: " f"<b>{tournament[player['user_id']]}</b>") else: contestant_mentions_points.append(f"{mention_html(player['user_id'], player['first_name'])}: " f"<b>{tournament[player['user_id']]}</b>") text = get_string(lang, "tournament_end_several").format("\n".join(winner_mention_points), "\n".join(contestant_mentions_points)) context.bot.send_message(chat_id, text, parse_mode=ParseMode.HTML) if chat_data["pin"]: if not isinstance(chat_data["pin"], bool): try: context.bot.pin_chat_message(chat_id, chat_data["pin"], True) except BadRequest as e: if e.message != "Not enough rights to pin a message": context.bot.unpin_chat_message(chat_id) e.message += "handled in game L363" else: chat_data["pin"] = False e.message += "handled in game L363, 2" raise e else: context.bot.unpin_chat_message(chat_id) chat_data.clear() chat_data["lang"] = lang # that means we dont, lets play another round else: chat_data["tournament"] = tournament for player in chat_data["players"]: player.pop("word", None) player.pop("votes", None) deck = Deck(*chat_data["deck"].split("_")) chameleon = random.choice(list(chat_data["players"])) chat_data["players"] = chat_data["players"][1:] + [chat_data["players"][0]] game_id = ''.join(random.choices(string.ascii_lowercase, k=10)) chat_data.update({"chameleon": chameleon, "secret": deck.secret, "game_id": game_id, "words": deck.words}) contestant_mentions_points = [] for player in players: contestant_mentions_points.append(f"{mention_html(player['user_id'], player['first_name'])}: " f"<b>{tournament[player['user_id']]}</b>") text = get_string(lang, "tournament_end").format("\n".join(contestant_mentions_points), deck.topic, deck.word_list) button = InlineKeyboardMarkup([[InlineKeyboardButton(get_string(lang, "play_button"), callback_data="word" + game_id)]]) send_message = context.bot.send_message(chat_id, text, reply_markup=button, parse_mode=ParseMode.HTML) if chat_data["pin"]: context.bot.pin_chat_message(chat_id, send_message.message_id, True) user = chat_data["players"][0] text = get_string(lang, "first_player_say_word").format(mention_html(user["user_id"], user["first_name"])) if not chat_data["restrict"]: if chat_data["exclamation"]: text += "\n\n" + get_string(lang, "exclamation_activated") else: text += "\n\n" + get_string(lang, "exclamation_deactivated") context.bot.send_message(chat_id, text, reply_to_message_id=send_message.message_id, parse_mode=ParseMode.HTML) if chat_data["restrict"]: context.bot.set_chat_permissions(chat_id, ChatPermissions(can_send_messages=False)) if not is_admin(context.bot, user["user_id"], context.bot.get_chat(chat_id)): context.bot.promote_chat_member(chat_id, user["user_id"], can_invite_users=True) chat_data["restrict"]["skip"] = False else: chat_data["restrict"]["skip"] = True chat_data["word_list"] = send_message.message_id # we dont care if other values exist or not, but this is needed in calculating of our points, so we pop it chat_data.pop("guesses", None) chat_data.pop("voted", None) else: database.end_game(chat_id, player_ids, chameleon_id, winner_ids, chat_data["starter"]["user_id"]) if chat_data["pin"]: if not isinstance(chat_data["pin"], bool): try: context.bot.pin_chat_message(chat_id, chat_data["pin"], True) except BadRequest as e: if e.message != "Not enough rights to pin a message": context.bot.unpin_chat_message(chat_id) e.message += "handled in game L419" else: chat_data["pin"] = False e.message += "handled in game L419, 2" raise e else: context.bot.unpin_chat_message(chat_id) chat_data.clear() chat_data["lang"] = lang
def check_flood(update, context) -> str: user = update.effective_user # type: Optional[User] chat = update.effective_chat # type: Optional[Chat] msg = update.effective_message # type: Optional[Message] if not user: # ignore channels return "" # ignore admins if is_user_admin(chat, user.id): sql.update_flood(chat.id, None) return "" should_ban = sql.update_flood(chat.id, user.id) if not should_ban: return "" try: getmode, getvalue = sql.get_flood_setting(chat.id) if getmode == 1: chat.kick_member(user.id) execstrings = tl(update.effective_message, "Keluar!") tag = "BANNED" elif getmode == 2: chat.kick_member(user.id) chat.unban_member(user.id) execstrings = tl(update.effective_message, "Keluar!") tag = "KICKED" elif getmode == 3: context.bot.restrict_chat_member( chat.id, user.id, permissions=ChatPermissions(can_send_messages=False)) execstrings = tl(update.effective_message, "Sekarang kamu diam!") tag = "MUTED" elif getmode == 4: bantime = extract_time(msg, getvalue) chat.kick_member(user.id, until_date=bantime) execstrings = tl(update.effective_message, "Keluar selama {}!").format(getvalue) tag = "TBAN" elif getmode == 5: mutetime = extract_time(msg, getvalue) context.bot.restrict_chat_member( chat.id, user.id, until_date=mutetime, permissions=ChatPermissions(can_send_messages=False)) execstrings = tl(update.effective_message, "Sekarang kamu diam selama {}!").format(getvalue) tag = "TMUTE" send_message( update.effective_message, tl( update.effective_message, "Saya tidak suka orang yang mengirim pesan beruntun. Tapi kamu hanya membuat " "saya kecewa. {}").format(execstrings)) return "<b>{}:</b>" \ "\n#{}" \ "\n<b>User:</b> {}" \ "\nFlooded the group.".format(tag, html.escape(chat.title), mention_html(user.id, user.first_name)) except BadRequest: send_message( update.effective_message, tl( update.effective_message, "Saya tidak bisa menendang orang di sini, beri saya izin terlebih dahulu! Sampai saat itu, saya akan menonaktifkan antiflood." )) sql.set_flood(chat.id, 0) return "<b>{}:</b>" \ "\n#INFO" \ "\n{}".format(chat.title, tl(update.effective_message, "Tidak memiliki izin kick, jadi secara otomatis menonaktifkan antiflood."))
def runmute(update: Update, context: CallbackContext): bot, args = context.bot, context.args message = update.effective_message if not args: message.reply_text("You don't seem to be referring to a chat/user.") return user_id, chat_id = extract_user_and_text(message, args) if not user_id: message.reply_text( "You don't seem to be referring to a user or the ID specified is incorrect.." ) return elif not chat_id: message.reply_text("You don't seem to be referring to a chat.") return try: chat = bot.get_chat(chat_id.split()[0]) except BadRequest as excp: if excp.message == "Chat not found": message.reply_text( "Chat not found! Make sure you entered a valid chat ID and I'm part of that chat." ) return else: raise if chat.type == 'private': message.reply_text("I'm sorry, but that's a private chat!") return if not is_bot_admin(chat, bot.id) or not chat.get_member( bot.id).can_restrict_members: message.reply_text( "I can't unrestrict people there! Make sure I'm admin and can unban users." ) return try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found": message.reply_text("I can't seem to find this user there") return else: raise if is_user_in_chat(chat, user_id): if member.can_send_messages and member.can_send_media_messages \ and member.can_send_other_messages and member.can_add_web_page_previews: message.reply_text( "This user already has the right to speak in that chat.") return if user_id == bot.id: message.reply_text("I'm not gonna UNMUTE myself, I'm an admin there!") return try: bot.restrict_chat_member(chat.id, int(user_id), permissions=ChatPermissions( can_send_messages=True, can_send_media_messages=True, can_send_other_messages=True, can_add_web_page_previews=True)) message.reply_text("Yep, this user can talk in that chat!") except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text('Unmuted!', quote=False) elif excp.message in RUNMUTE_ERRORS: message.reply_text(excp.message) else: LOGGER.warning(update) LOGGER.exception( "ERROR unmnuting user %s in chat %s (%s) due to %s", user_id, chat.title, chat.id, excp.message) message.reply_text("Well damn, I can't unmute that user.")
def verify_button_pressed(update, context): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] query = update.callback_query # type: Optional[CallbackQuery] match = re.match(r"verify_me\((.+?)\)", query.data) match = match.group(1).split("|") is_ok = match[0] user_id = match[1] chat_id = match[2] message = update.effective_message # type: Optional[Message] print("-> {} was clicked welcome verify button".format(user.id)) if is_ok == "y": if context.bot.getChatMember(chat_id, user_id).status in ('left'): query.answer( text=tl(update.effective_message, "Failed: user left chat")) return try: context.bot.restrict_chat_member( chat_id, user_id, permissions=ChatPermissions(can_send_messages=True, can_send_media_messages=True, can_send_polls=True, can_send_other_messages=True, can_add_web_page_previews=True, can_change_info=True, can_invite_users=True, can_pin_messages=True)) sql.add_to_userlist(chat_id, user_id, True) sql.rm_from_timeout(chat_id, user_id) except BadRequest as err: if not update.effective_chat.get_member( context.bot.id).can_restrict_members: query.answer(text=tl( update.effective_message, "I can't limit people here, asked the admin to unmute!")) else: query.answer(text="Error: " + str(err)) return chat_name = context.bot.get_chat(chat_id).title # query.message.delete() # context.bot.send_photo(chat.id, photo="https://telegra.ph/file/06d2c5ec80af3858c2d4b.jpg", caption=tl(update.effective_message, "*It works!*\n\nGreat job man, now you can chat on: *{}*").format(chat_name), parse_mode="markdown") context.bot.edit_message_media( chat.id, message_id=query.message.message_id, media=InputMediaPhoto( media=open("emilia/modules/helper_funcs/emojis/done.jpg", 'rb'), caption=tl( update.effective_message, "*It works!*\n\nGreat job man, now you can chat on: *{}*"). format(chat_name), parse_mode="markdown")) query.answer( text=tl(update.effective_message, "It works! You can chat on {} now").format(chat_name), show_alert=True) elif is_ok == "re": user_id = update.effective_user.id is_clicked = sql.get_chat_userlist(chat_id) if user_id not in list(is_clicked): context.bot.edit_message_text( chat.id, message_id=query.message.message_id, text=tl( update.effective_message, "You are not in verification mode, if you are muted, you can ask the admin in the group concerned for help" )) return query.answer(text=tl(update.effective_message, "Error"), show_alert=False) elif user_id in list(is_clicked) and is_clicked[user_id] == True: context.bot.edit_message_text( chat.id, message_id=query.message.message_id, text=tl( update.effective_message, "You are not in verification mode, if you are muted, you can ask the admin in the group concerned for help" )) return query.answer(text=tl(update.effective_message, "Error"), show_alert=False) verify_code = [ "🙏", "👈", "👉", "👇", "👆", "❤️", "🅰️", "🅱️", "0️⃣", "1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟" ] real_btn = random.choice(verify_code) print(real_btn) verify_code.remove(real_btn) verbox = (random.randint(1, 3), random.randint(1, 3)) buttons = [] linebox = [] was_set = False for x in range(3): x += 1 for y in range(3): y += 1 if verbox[0] == y and verbox[1] == x: was_set = True print("button was set to " + real_btn + "at " + str(verbox[0]) + " - " + str(verbox[1])) linebox.append( InlineKeyboardButton( text=real_btn, callback_data="verify_me(y|{}|{})".format( user_id, chat_id))) else: verify_emoji = random.choice(verify_code) linebox.append( InlineKeyboardButton( text=verify_emoji, callback_data="verify_me(n|{}|{})".format( user_id, chat_id))) verify_code.remove(verify_emoji) buttons.append(linebox) linebox = [] if not was_set: verbox = (random.randint(1, 3), random.randint(1, 3)) linebox[verbox[0] - 1][verbox[1] - 1] = InlineKeyboardButton( text=real_btn, callback_data="verify_me(y|{}|{})".format(user_id, chat_id)) print("[x] button was set to " + real_btn + "at " + str(verbox[0]) + " - " + str(verbox[1])) buttons.append([ InlineKeyboardButton(text="Refresh", callback_data="verify_me(re|{}|{})".format( user_id, chat_id)) ]) # query.message.delete() # context.bot.send_photo(chat.id, photo=open("emilia/modules/helper_funcs/emojis/" + verify_code_images[real_btn], 'rb'), caption=tl(update.effective_message, "Please choose the same emoji below:") + "\n" + tl(update.effective_message, "If none of the emojis are the same, please click the refresh button"), parse_mode="markdown", reply_markup=InlineKeyboardMarkup(buttons)) context.bot.edit_message_media( chat.id, message_id=query.message.message_id, media=InputMediaPhoto( media=open( "emilia/modules/helper_funcs/emojis/" + verify_code_images[real_btn], 'rb'), caption=tl(update.effective_message, "Please choose the same emoji below:") + "\n" + tl( update.effective_message, "If none of the emojis are the same, please click the refresh button" ), parse_mode="markdown"), reply_markup=InlineKeyboardMarkup(buttons)) query.answer(text=tl(update.effective_message, "Done"), show_alert=False) else: # query.message.delete() # context.bot.send_photo(chat.id, photo=open("emilia/modules/helper_funcs/emojis/fail.jpg", 'rb'), caption=tl(update.effective_message, "Sorry robot, you have clicked the wrong verification button.\n\nTry again by clicking the verify button in the welcome message."), parse_mode="markdown") context.bot.edit_message_media( chat.id, message_id=query.message.message_id, media=InputMediaPhoto( media=open("emilia/modules/helper_funcs/emojis/fail.jpg", 'rb'), caption=tl( update.effective_message, "Sorry robot, you have clicked the wrong verification button..\n\nTry again by clicking the verify button in the welcome message." ), parse_mode="markdown")) query.answer(text=tl( update.effective_message, "Failed! You have clicked the verification button incorrectly"), show_alert=True)