def __user_info__(user_id, chat_id): is_gbanned = sql.is_user_gbanned(user_id) is_gmuted = sql.is_user_gmuted(user_id) text = tld(chat_id, "Globally banned: <b>{}</b>") if is_gbanned: text = text.format(tld(chat_id, "Yes")) user = sql.get_gbanned_user(user_id) if user.reason: text += tld(chat_id, "\nReason: {}").format(html.escape(user.reason)) else: text = text.format(tld(chat_id, "No")) text += tld(chat_id, "\nGlobally muted: <b>{}</b>") if is_gmuted: text = text.format(tld(chat_id, "Yes")) user = sql.get_gmuted_user(user_id) if user.reason: text += tld(chat_id, "\nReason: {}").format(html.escape(user.reason)) else: text = text.format(tld(chat_id, "No")) return text
def check_and_ban(update, user_id, should_message=True): chat = update.effective_chat # type: Optional[Chat] try: sw_ban = sw.get_ban(int(user_id)) except AttributeError: sw_ban = None except (SpamWatchError, Error, UnauthorizedError, NotFoundError, Forbidden, TooManyRequests) as e: log.warning(f" SpamWatch Error: {e}") sw_ban = None if sw_ban: chat.ban_member(user_id) if should_message: update.effective_message.reply_text( f"This person has been detected as a spammer by @SpamWatch and has been removed!\nReason: <code>{sw_ban.reason}</code>", parse_mode=ParseMode.HTML, ) return if sql.is_user_gbanned(user_id): update.effective_chat.ban_member(user_id) if should_message: text = (f"<b>Alert</b>: this user is globally banned.\n" f"<code>*bans them from here*</code>.\n" f"<b>Appeal chat</b>: @YorkTownEagleUnion\n" f"<b>User ID</b>: <code>{user_id}</code>") user = sql.get_gbanned_user(user_id) if user.reason: text += f"\n<b>Ban Reason:</b> <code>{html.escape(user.reason)}</code>" update.effective_message.reply_text(text, parse_mode=ParseMode.HTML)
def read_item(user_id: int): try: a = sql1.is_user_gbanned(user_id) if a: user = sql1.get_gbanned_user(user_id) areason = user.reason else: areason = None b = sql2.is_user_blacklisted(user_id) breason = sql2.get_reason(user_id) if b else None return { "status": "ok", "user_id": user_id, "gbanned": a, "gban_reason": areason, "blacklisted": b, "blacklist_reason": breason } except Exception: a = None areason = None b = None breason = None return { "status": "ok", "user_id": user_id, "gbanned": a, "gban_reason": areason, "blacklisted": b, "blacklist_reason": breason }
def ungban(bot: Bot, update: Update, args: List[str]): message = update.effective_message # type: Optional[Message] 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_gbanned(user_id): message.reply_text("This user is not gbanned!") return banner = update.effective_user # type: Optional[User] message.reply_text("I'll give {} a second chance, globally.".format( user_chat.first_name)) send_to_list(bot, SUDO_USERS + OWNER_ID, "{} has ungbanned user {}".format( mention_html(banner.id, banner.first_name), mention_html(user_chat.id, user_chat.first_name)), html=True) chats = get_all_chats() for chat in chats: chat_id = chat.chat_id # Check if this group has disabled gbans if not sql.does_chat_gban(chat_id): continue try: member = bot.get_chat_member(chat_id, user_id) if member.status == 'kicked': bot.unban_chat_member(chat_id, user_id) except BadRequest as excp: if excp.message in UNGBAN_ERRORS: pass else: message.reply_text("Could not un-gban due to: {}".format( excp.message)) bot.send_message( OWNER_ID, "Could not un-gban due to: {}".format(excp.message)) return except TelegramError: pass sql.ungban_user(user_id) send_to_list(bot, SUDO_USERS + OWNER_ID, "un-gban complete!") message.reply_text("Person has been un-gbanned.")
def check_and_ban(update, user_id, should_message=True): from tg_bot import SPB_MODE chat = update.effective_chat # type: Optional[Chat] if SPB_MODE: try: apst = requests.get( f'https://api.intellivoid.net/spamprotection/v1/lookup?query={update.effective_user.id}') api_status = apst.status_code if api_status == 200: try: status = client.raw_output(int(user_id)) try: bl_check = (status["results"]["attributes"]["is_blacklisted"]) except: bl_check = False if bl_check: bl_res = (status["results"]["attributes"]["blacklist_reason"]) update.effective_chat.kick_member(user_id) if should_message: update.effective_message.reply_text( f"This person was blacklisted on @SpamProtectionBot and has been removed!\nReason: <code>{bl_res}</code>", parse_mode=ParseMode.HTML, ) except HostDownError: log.warning("Spam Protection API is unreachable.") except BaseException as e: log.info(f'SpamProtection was disabled due to {e}') try: sw_ban = sw.get_ban(int(user_id)) except AttributeError: sw_ban = None except (SpamWatchError, Error, UnauthorizedError, NotFoundError, Forbidden, TooManyRequests) as e: log.warning(f" SpamWatch Error: {e}") sw_ban = None if sw_ban: update.effective_chat.kick_member(user_id) if should_message: update.effective_message.reply_text( f"This person has been detected as a spammer by @SpamWatch and has been removed!\nReason: <code>{sw_ban.reason}</code>", parse_mode=ParseMode.HTML, ) return if sql.is_user_gbanned(user_id): update.effective_chat.kick_member(user_id) if should_message: text = ( f"<b>Alert</b>: this user is globally banned.\n" f"<code>*bans them from here*</code>.\n" f"<b>Appeal chat</b>: @zerounions\n" f"<b>User ID</b>: <code>{user_id}</code>" ) user = sql.get_gbanned_user(user_id) if user.reason: text += f"\n<b>Ban Reason:</b> <code>{html.escape(user.reason)}</code>" update.effective_message.reply_text(text, parse_mode=ParseMode.HTML)
def check_and_ban(update, user_id, should_message=True): chat = update.effective_chat # type: Optional[Chat] if SPB_MODE: try: status = client.raw_output(int(user_id)) try: bl_check = (status["results"]["attributes"]["is_blacklisted"]) except: bl_check = False if bl_check is True: bl_res = (status["results"]["attributes"]["blacklist_reason"]) update.effective_chat.kick_member(user_id) if should_message: update.effective_message.reply_text( f"This person was blacklisted on @SpamProtectionBot and has been removed!\nReason: <code>{bl_res}</code>", parse_mode=ParseMode.HTML, ) except HostDownError: log.warning("Spam Protection API is unreachable.") try: sw_ban = sw.get_ban(int(user_id)) except AttributeError: sw_ban = None except (SpamWatchError, Error, UnauthorizedError, NotFoundError, Forbidden, TooManyRequests) as e: log.warning(f" SpamWatch Error: {e}") sw_ban = None if sw_ban: update.effective_chat.kick_member(user_id) if should_message: update.effective_message.reply_text( f"This person has been detected as a spammer by @SpamWatch and has been removed!\nReason: <code>{sw_ban.reason}</code>", parse_mode=ParseMode.HTML, ) return if sql.is_user_gbanned(user_id): update.effective_chat.kick_member(user_id) if should_message: text = (f"<b>Alert</b>: this user is globally banned.\n" f"<code>*bans them from here*</code>.\n" f"<b>Appeal chat</b>: @YorkTownEagleUnion\n" f"<b>User ID</b>: <code>{user_id}</code>") user = sql.get_gbanned_user(user_id) if user.reason: text += f"\n<b>Ban Reason:</b> <code>{html.escape(user.reason)}</code>" update.effective_message.reply_text(text, parse_mode=ParseMode.HTML)
def __user_info__(user_id): if user_id in (777000, 1087968824): return "" is_gbanned = sql.is_user_gbanned(user_id) text = "Gbanned: <b>{}</b>" if user_id in [777000, 1087968824]: return "" if user_id == dispatcher.bot.id: return "" if int(user_id) in SUDO_USERS + SARDEGNA_USERS + WHITELIST_USERS: return "" if is_gbanned: text = text.format("Yes") user = sql.get_gbanned_user(user_id) if user.reason: text += f"\n<b>Reason:</b> <code>{html.escape(user.reason)}</code>" text += f"\n<b>Appeal Chat:</b> @YorkTownEagleUnion" else: text = text.format("No") return text
def gban(update: Update, context: CallbackContext): bot, args = context.bot, context.args message = update.effective_message user = update.effective_user chat = update.effective_chat log_message = "" 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 or the ID specified is incorrect.." ) return if int(user_id) in DEV_USERS: message.reply_text( "That user is part of the Union\nI can't act against our own.") return if int(user_id) in SUDO_USERS: message.reply_text( "I spy, with my little eye... a nation! Why are you guys turning on each other?" ) return if int(user_id) in SUPPORT_USERS: message.reply_text( "OOOH someone's trying to gban a Sakura Nation! *grabs popcorn*") return if int(user_id) in SARDEGNA_USERS: message.reply_text("That's a Sardegna! They cannot be banned!") return if int(user_id) in WHITELIST_USERS: message.reply_text("That's a Neptunia! They cannot be banned!") return if int(user_id) in (777000, 1087968824): message.reply_text("Huh, why would I gban Telegram bots?") return if user_id == bot.id: message.reply_text("You uhh...want me to kill myself?") return try: user_chat = bot.get_chat(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: return if user_chat.type != "private": message.reply_text("That's not a user!") return if sql.is_user_gbanned(user_id): if not reason: message.reply_text( "This user is already gbanned; I'd change the reason, but you haven't given me one..." ) return old_reason = sql.update_gban_reason( user_id, user_chat.username or user_chat.first_name, reason) if old_reason: message.reply_text( "This user is already gbanned, for the following reason:\n" "<code>{}</code>\n" "I've gone and updated it with your new reason!".format( html.escape(old_reason)), parse_mode=ParseMode.HTML, ) else: message.reply_text( "This user is already gbanned, but had no reason set; I've gone and updated it!" ) return message.reply_text("On it!") start_time = time.time() datetime_fmt = "%Y-%m-%dT%H:%M" current_time = datetime.utcnow().strftime(datetime_fmt) if chat.type != "private": chat_origin = "<b>{} ({})</b>\n".format(html.escape(chat.title), chat.id) else: chat_origin = "<b>{}</b>\n".format(chat.id) log_message = ( f"#GBANNED\n" f"<b>Originated from:</b> <code>{chat_origin}</code>\n" f"<b>Admin:</b> {mention_html(user.id, user.first_name)}\n" f"<b>Banned User:</b> {mention_html(user_chat.id, user_chat.first_name)}\n" f"<b>Banned User ID:</b> <code>{user_chat.id}</code>\n" f"<b>Event Stamp:</b> <code>{current_time}</code>") if reason: if chat.type == chat.SUPERGROUP and chat.username: log_message += f'\n<b>Reason:</b> <a href="https://telegram.me/{chat.username}/{message.message_id}">{reason}</a>' else: log_message += f"\n<b>Reason:</b> <code>{reason}</code>" if GBAN_LOGS: try: log = bot.send_message(GBAN_LOGS, log_message, parse_mode=ParseMode.HTML) except BadRequest as excp: log = bot.send_message( GBAN_LOGS, log_message + "\n\nFormatting has been disabled due to an unexpected error.", ) else: send_to_list(bot, SUDO_USERS + SUPPORT_USERS, log_message, html=True) sql.gban_user(user_id, user_chat.username or user_chat.first_name, reason) chats = get_user_com_chats(user_id) gbanned_chats = 0 for chat in chats: chat_id = int(chat) # Check if this group has disabled gbans if not sql.does_chat_gban(chat_id): continue try: bot.kick_chat_member(chat_id, user_id) gbanned_chats += 1 except BadRequest as excp: if excp.message in GBAN_ERRORS: pass else: message.reply_text(f"Could not gban due to: {excp.message}") if GBAN_LOGS: bot.send_message( GBAN_LOGS, f"Could not gban due to {excp.message}", parse_mode=ParseMode.HTML, ) else: send_to_list( bot, SUDO_USERS + SUPPORT_USERS, f"Could not gban due to: {excp.message}", ) sql.ungban_user(user_id) return except TelegramError: pass if GBAN_LOGS: log.edit_text( log_message + f"\n<b>Chats affected:</b> <code>{gbanned_chats}</code>", parse_mode=ParseMode.HTML, ) else: send_to_list( bot, SUDO_USERS + SUPPORT_USERS, f"Gban complete! (User banned in <code>{gbanned_chats}</code> chats)", html=True, ) end_time = time.time() gban_time = round((end_time - start_time), 2) if gban_time > 60: gban_time = round((gban_time / 60), 2) message.reply_text("Done! Gbanned.", parse_mode=ParseMode.HTML) else: message.reply_text("Done! Gbanned.", parse_mode=ParseMode.HTML) try: bot.send_message( user_id, "#GBAN" "You have been marked as Malicious and as such have been banned from any future groups we manage." f"\n<b>Reason:</b> <code>{html.escape(user.reason)}</code>" f"</b>Appeal Chat:</b> @YorkTownEagleUnion", parse_mode=ParseMode.HTML, ) except: pass # bot probably blocked by user
def ungban(update: Update, context: CallbackContext): bot, args = context.bot, context.args message = update.effective_message user = update.effective_user chat = update.effective_chat log_message = "" user_id = extract_user(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 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_gbanned(user_id): message.reply_text("This user is not gbanned!") return message.reply_text( f"I'll give {user_chat.first_name} a second chance, globally.") start_time = time.time() datetime_fmt = "%Y-%m-%dT%H:%M" current_time = datetime.utcnow().strftime(datetime_fmt) if chat.type != "private": chat_origin = f"<b>{html.escape(chat.title)} ({chat.id})</b>\n" else: chat_origin = f"<b>{chat.id}</b>\n" log_message = ( f"#UNGBANNED\n" f"<b>Originated from:</b> <code>{chat_origin}</code>\n" f"<b>Admin:</b> {mention_html(user.id, user.first_name)}\n" f"<b>Unbanned User:</b> {mention_html(user_chat.id, user_chat.first_name)}\n" f"<b>Unbanned User ID:</b> <code>{user_chat.id}</code>\n" f"<b>Event Stamp:</b> <code>{current_time}</code>") if GBAN_LOGS: try: log = bot.send_message(GBAN_LOGS, log_message, parse_mode=ParseMode.HTML) except BadRequest as excp: log = bot.send_message( GBAN_LOGS, log_message + "\n\nFormatting has been disabled due to an unexpected error.", ) else: send_to_list(bot, SUDO_USERS + SUPPORT_USERS, log_message, html=True) chats = get_user_com_chats(user_id) ungbanned_chats = 0 for chat in chats: chat_id = int(chat) # Check if this group has disabled gbans if not sql.does_chat_gban(chat_id): continue try: member = bot.get_chat_member(chat_id, user_id) if member.status == "kicked": bot.unban_chat_member(chat_id, user_id) ungbanned_chats += 1 except BadRequest as excp: if excp.message in UNGBAN_ERRORS: pass else: message.reply_text(f"Could not un-gban due to: {excp.message}") if GBAN_LOGS: bot.send_message( GBAN_LOGS, f"Could not un-gban due to: {excp.message}", parse_mode=ParseMode.HTML, ) else: bot.send_message( OWNER_ID, f"Could not un-gban due to: {excp.message}") return except TelegramError: pass sql.ungban_user(user_id) if GBAN_LOGS: log.edit_text( log_message + f"\n<b>Chats affected:</b> {ungbanned_chats}", parse_mode=ParseMode.HTML, ) else: send_to_list(bot, SUDO_USERS + SUPPORT_USERS, "un-gban complete!") end_time = time.time() ungban_time = round((end_time - start_time), 2) if ungban_time > 60: ungban_time = round((ungban_time / 60), 2) message.reply_text( f"Person has been un-gbanned. Took {ungban_time} min") else: message.reply_text( f"Person has been un-gbanned. Took {ungban_time} sec")
def left_member(update: Update, context: CallbackContext): # sourcery no-metrics bot = context.bot chat = update.effective_chat user = update.effective_user should_goodbye, cust_goodbye, goodbye_type = sql.get_gdbye_pref(chat.id) if user.id == bot.id: return 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 if should_goodbye: left_mem = update.effective_message.left_chat_member if left_mem: # Thingy for spamwatched users if sw != None: sw_ban = sw.get_ban(left_mem.id) if sw_ban: return # Dont say goodbyes to gbanned users if is_user_gbanned(left_mem.id): return # Ignore bot being kicked if left_mem.id == bot.id: return # Give the owner a special goodbye if left_mem.id == OWNER_ID: update.effective_message.reply_text( "Sorry to see you leave :(", reply_to_message_id=reply) return # Give the devs a special goodbye elif left_mem.id in DEV_USERS: update.effective_message.reply_text( "See you later at the Eagle Union!", reply_to_message_id=reply, ) return # if media goodbye, use appropriate function for it if goodbye_type not in [sql.Types.TEXT, sql.Types.BUTTON_TEXT]: ENUM_FUNC_MAP[goodbye_type](chat.id, cust_goodbye) return first_name = (left_mem.first_name or "PersonWithNoName" ) # edge case of empty name - occurs for some bugs. if cust_goodbye: if cust_goodbye == sql.DEFAULT_GOODBYE: cust_goodbye = random.choice( sql.DEFAULT_GOODBYE_MESSAGES).format( first=escape_markdown(first_name)) if left_mem.last_name: fullname = escape_markdown( f"{first_name} {left_mem.last_name}") else: fullname = escape_markdown(first_name) count = chat.get_members_count() mention = mention_markdown(left_mem.id, first_name) if left_mem.username: username = "******" + escape_markdown(left_mem.username) else: username = mention valid_format = escape_invalid_curly_brackets( cust_goodbye, VALID_WELCOME_FORMATTERS) res = valid_format.format( first=escape_markdown(first_name), last=escape_markdown(left_mem.last_name or first_name), fullname=escape_markdown(fullname), username=username, mention=mention, count=count, chatname=escape_markdown(chat.title), id=left_mem.id, ) buttons = sql.get_gdbye_buttons(chat.id) keyb = build_keyboard(buttons) else: res = random.choice( sql.DEFAULT_GOODBYE_MESSAGES).format(first=first_name) keyb = [] keyboard = InlineKeyboardMarkup(keyb) send( update, res, keyboard, random.choice( sql.DEFAULT_GOODBYE_MESSAGES).format(first=first_name), )
def gban(bot: Bot, update: Update, args: List[str]): message = update.effective_message # type: Optional[Message] 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 SUDO_USERS: message.reply_text("I spy, with my little eye... a sudo user war! Why are you guys turning on each other?") return if int(user_id) in SUPPORT_USERS: message.reply_text("OOOH someone's trying to gban a support user! *grabs popcorn*") return if user_id == bot.id: message.reply_text("-_- So funny, lets gban myself why don't I? Nice try.") return try: user_chat = 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_gbanned(user_id): if not reason: message.reply_text("This user is already gbanned; I'd change the reason, but you haven't given me one...") return old_reason = sql.update_gban_reason(user_id, user_chat.username or user_chat.first_name, reason) if old_reason: message.reply_text("This user is already gbanned, for the following reason:\n" "<code>{}</code>\n" "I've gone and updated it with your new reason!".format(html.escape(old_reason)), parse_mode=ParseMode.HTML) else: message.reply_text("This user is already gbanned, but had no reason set; I've gone and updated it!") return message.reply_text("*Calls MSFJarvis* 😉") banner = update.effective_user # type: Optional[User] send_to_list(bot, SUDO_USERS + SUPPORT_USERS, "<b>Global Ban</b>" \ "\n#GBAN" \ "\n<b>Status:</b> <code>Enforcing</code>" \ "\n<b>Sudo Admin:</b> {}" \ "\n<b>User:</b> {}" \ "\n<b>ID:</b> <code>{}</code>" \ "\n<b>Reason:</b> {}".format(mention_html(banner.id, banner.first_name), mention_html(user_chat.id, user_chat.first_name), user_chat.id, reason or "No reason given"), html=True) sql.gban_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 gbans if not sql.does_chat_gban(chat_id): continue try: bot.kick_chat_member(chat_id, user_id) except BadRequest as excp: if excp.message in GBAN_ERRORS: pass else: message.reply_text("Could not gban due to: {}".format(excp.message)) send_to_list(bot, SUDO_USERS + SUPPORT_USERS, "Could not gban due to: {}".format(excp.message)) sql.ungban_user(user_id) return except TelegramError: pass send_to_list(bot, SUDO_USERS + SUPPORT_USERS, "{} has been successfully gbanned!".format(mention_html(user_chat.id, user_chat.first_name)), html=True) message.reply_text("Person has been gbanned.")
def check_and_ban(update, user_id, should_message=True): if sql.is_user_gbanned(user_id): update.effective_chat.kick_member(user_id) if should_message: update.effective_message.reply_text("This is a bad person, they shouldn't be here!")
def gban(bot: Bot, update: Update, args: List[str]): message = update.effective_message # type: Optional[Message] user = update.effective_user # type: Optional[User] user_id, reason = extract_user_and_text(message, args) if os.environ['GPROCESS'] == '1': message.reply_text( "Leave me alone, I'm busy, Someone is using global stuff.") return os.environ['GPROCESS'] = '1' if not user_id: message.reply_text("You don't seem to be referring to a user.") os.environ['GPROCESS'] = '0' return if int(user_id) in SUDO_USERS: message.reply_text( "I spy, with my little eye... a sudo user war! Why are you guys turning on each other?" ) os.environ['GPROCESS'] = '0' return if int(user_id) in SUPPORT_USERS: message.reply_text( "OOOH someone's trying to gban a support user! *grabs popcorn*") os.environ['GPROCESS'] = '0' return if user_id == bot.id: message.reply_text( "-_- So funny, lets gban myself why don't I? Nice try.") os.environ['GPROCESS'] = '0' return try: user_chat = bot.get_chat(user_id) except BadRequest as excp: message.reply_text(excp.message) os.environ['GPROCESS'] = '0' return if user_chat.type != 'private': message.reply_text("That's not a user!") os.environ['GPROCESS'] = '0' return if user_chat.first_name == '': message.reply_text( "That's a deleted account! Why even bother gbanning them?") os.environ['GPROCESS'] = '0' return if sql.is_user_gbanned(user_id): if not reason: message.reply_text( "This user is already gbanned; I'd change the reason, but you haven't given me one..." ) os.environ['GPROCESS'] = '0' return old_reason = sql.update_gban_reason( user_id, user_chat.username or user_chat.first_name, reason) user_id, new_reason = extract_user_and_text(message, args) if old_reason: banner = update.effective_user # type: Optional[User] bot.send_message( MESSAGE_DUMP, "<b>New Reason of Global Ban</b>" \ "\n<b>Sudo Admin:</b> {}" \ "\n<b>User:</b> {}" \ "\n<b>ID:</b> <code>{}</code>" \ "\n<b>Previous Reason:</b> {}" \ "\n<b>New Reason:</b> {}".format(mention_html(banner.id, banner.first_name), mention_html(user_chat.id, user_chat.first_name or "Deleted Account"), user_chat.id, old_reason, new_reason), parse_mode=ParseMode.HTML ) message.reply_text( "This user is already gbanned, for the following reason:\n" "<code>{}</code>\n" "I've gone and updated it with your new reason!".format( html.escape(old_reason)), parse_mode=ParseMode.HTML) os.environ['GPROCESS'] = '0' else: banner = update.effective_user # type: Optional[User] bot.send_message( MESSAGE_DUMP, "<b>New reason of Global Ban</b>" \ "\n<b>Sudo Admin:</b> {}" \ "\n<b>User:</b> {}" \ "\n<b>ID:</b> <code>{}</code>" \ "\n<b>New Reason:</b> {}".format(mention_html(banner.id, banner.first_name or "Deleted Account"), mention_html(user_chat.id, user_chat.first_name), user_chat.id, new_reason), parse_mode=ParseMode.HTML ) message.reply_text( "This user is already gbanned, but had no reason set; I've gone and updated it!" ) os.environ['GPROCESS'] = '0' return message.reply_text("*Blows dust off of banhammer* 😉") banner = update.effective_user # type: Optional[User] bot.send_message(MESSAGE_DUMP, "{} is gbanning user {} " "because:\n{}".format( mention_html(banner.id, banner.first_name), mention_html(user_chat.id, user_chat.first_name), reason or "No reason given"), parse_mode=ParseMode.HTML) os.environ['GPROCESS'] = '1' sql.gban_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 gbans #if not sql.does_chat_gban(chat_id): # continue #try: # bot.kick_chat_member(chat_id, user_id) #except BadRequest as excp: # if excp.message in GBAN_ERRORS: # pass # else: # message.reply_text("Could not gban due to: {}".format(excp.message)) # bot.send_message(MESSAGE_DUMP, "Could not gban due to: {}".format(excp.message)) # sql.ungban_user(user_id) # os.environ['GPROCESS'] = '0' # return #except TelegramError: # pass os.environ['GPROCESS'] = '0' message.reply_text("User have been global banned!") bot.send_message(MESSAGE_DUMP, "{} has been successfully gbanned!".format( mention_html(user_chat.id, user_chat.first_name)), parse_mode=ParseMode.HTML)
def ungban(bot: Bot, update: Update, args: List[str]): message = update.effective_message # type: Optional[Message] 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_gbanned(user_id): message.reply_text("This user is not gbanned!") return if user_chat.first_name == '': message.reply_text("That's a deleted account!") return if os.environ['GPROCESS'] == '1': message.reply_text( "Leave me alone, I'm busy, Someone is using global stuff.") return banner = update.effective_user # type: Optional[User] message.reply_text("I'll give {} a second chance, globally.".format( user_chat.first_name)) bot.send_message(MESSAGE_DUMP, "{} has ungbanned user {}".format( mention_html(banner.id, banner.first_name), mention_html(user_chat.id, user_chat.first_name)), parse_mode=ParseMode.HTML) os.environ['GPROCESS'] = '1' chats = get_all_chats() for chat in chats: chat_id = chat.chat_id # Check if this group has disabled gbans if not sql.does_chat_gban(chat_id): continue try: member = bot.get_chat_member(chat_id, user_id) if member.status == 'kicked': bot.unban_chat_member(chat_id, user_id) except BadRequest as excp: if excp.message in UNGBAN_ERRORS: pass else: message.reply_text("Could not un-gban due to: {}".format( excp.message)) bot.send_message( MESSAGE_DUMP, "Could not un-gban due to: {}".format(excp.message)) os.environ['GPROCESS'] = '0' return except TelegramError: pass sql.ungban_user(user_id) os.environ['GPROCESS'] = '0' bot.send_message(MESSAGE_DUMP, "un-gban complete!") message.reply_text("Person has been un-gbanned.")
def left_member(bot: Bot, update: Update): chat = update.effective_chat # type: Optional[Chat] should_goodbye, cust_goodbye, cust_content, goodbye_type = sql.get_gdbye_pref( chat.id) cust_goodbye = markdown_to_html(cust_goodbye) if should_goodbye: left_mem = update.effective_message.left_chat_member if left_mem: if is_user_gbanned(left_mem.id): return # Ignore bot being kicked if left_mem.id == bot.id: return # Give the owner a special goodbye if left_mem.id == OWNER_ID: update.effective_message.reply_text( tld(chat.id, 'welcome_bot_owner_left')) return # if media goodbye, use appropriate function for it if goodbye_type != sql.Types.TEXT and goodbye_type != sql.Types.BUTTON_TEXT: 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 # Formatting text first_name = left_mem.first_name or "PersonWithNoName" # edge case of empty name - occurs for some bugs. if left_mem.last_name: fullname = "{} {}".format(first_name, left_mem.last_name) else: fullname = first_name count = chat.get_members_count() mention = mention_html(left_mem.id, first_name) if left_mem.username: username = "******" + escape(left_mem.username) else: username = mention rules = "http://t.me/" + bot.username + "?start=" + str( chat.id) buttons = sql.get_gdbye_buttons(chat.id) keyb = build_keyboard_parser(bot, chat.id, buttons) formatted_text = cust_goodbye.format( first=escape(first_name), last=escape(left_mem.last_name or first_name), fullname=escape(fullname), username=username, mention=mention, count=count, chatname=escape(chat.title), id=left_mem.id, rules=keyb.append( [InlineKeyboardButton("Rules", url=rules)])) # Build keyboard keyboard = InlineKeyboardMarkup(keyb) # Send message ENUM_FUNC_MAP[goodbye_type](chat.id, cust_content, caption=formatted_text, reply_markup=keyboard, parse_mode="html", reply_to_message_id=reply) return first_name = left_mem.first_name or "PersonWithNoName" # edge case of empty name - occurs for some bugs. if cust_goodbye: if left_mem.last_name: fullname = "{} {}".format(first_name, left_mem.last_name) else: fullname = first_name count = chat.get_members_count() mention = mention_html(left_mem.id, first_name) if left_mem.username: username = "******" + escape(left_mem.username) else: username = mention rules = "http://t.me/" + bot.username + "?start=" + str( chat.id) buttons = sql.get_gdbye_buttons(chat.id) keyb = build_keyboard_parser(bot, chat.id, buttons) valid_format = escape_invalid_curly_brackets( cust_goodbye, VALID_WELCOME_FORMATTERS) res = valid_format.format(first=escape(first_name), last=escape(left_mem.last_name or first_name), fullname=escape(fullname), username=username, mention=mention, count=count, chatname=escape(chat.title), id=left_mem.id, rules=keyb.append([ InlineKeyboardButton("Rules", url=rules) ])) keyb = build_keyboard_parser(bot, chat.id, buttons) else: res = sql.DEFAULT_GOODBYE keyb = [] keyboard = InlineKeyboardMarkup(keyb) send(update, res, keyboard, sql.DEFAULT_GOODBYE)
def new_member(bot: Bot, update: Update): chat = update.effective_chat # type: Optional[Chat] should_welc, cust_welcome, cust_content, welc_type = sql.get_welc_pref( chat.id) cust_welcome = markdown_to_html(cust_welcome) if should_welc: sent = None new_members = update.effective_message.new_chat_members for new_mem in new_members: # Give start information when add bot to group if is_user_gbanned(new_mem.id): return if new_mem.id == bot.id: bot.send_message( MESSAGE_DUMP, "I have been added to {} with ID: <pre>{}</pre>".format( chat.title, chat.id), parse_mode=ParseMode.HTML) bot.send_message(chat.id, tld(chat.id, 'welcome_added_to_grp')) else: if is_user_gbanned(new_mem.id): return # If welcome message is media, send with appropriate function if welc_type != sql.Types.TEXT and welc_type != sql.Types.BUTTON_TEXT: 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 # Formatting text first_name = new_mem.first_name or "PersonWithNoName" # edge case of empty name - occurs for some bugs. 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 rules = "http://t.me/" + bot.username + "?start=" + str( chat.id) # Build keyboard buttons = sql.get_welc_buttons(chat.id) keyb = build_keyboard_parser(bot, chat.id, buttons) formatted_text = cust_welcome.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, rules=keyb.append( [InlineKeyboardButton("Rules", url=rules)])) getsec, mutetime, custom_text = sql.welcome_security( chat.id) member = chat.get_member(new_mem.id) # If user ban protected don't apply security on him if is_user_ban_protected(chat, new_mem.id, chat.get_member(new_mem.id)): pass elif getsec: # If mute time is turned on if mutetime: if mutetime[:1] == "0": if member.can_send_messages is None or member.can_send_messages: try: bot.restrict_chat_member( chat.id, new_mem.id, can_send_messages=False) canrest = True except BadRequest: canrest = False else: canrest = False else: mutetime = extract_time( update.effective_message, mutetime) if member.can_send_messages is None or member.can_send_messages: try: bot.restrict_chat_member( chat.id, new_mem.id, until_date=mutetime, can_send_messages=False) canrest = True except BadRequest: canrest = False else: canrest = False # If security welcome is turned on if canrest: sql.add_to_userlist(chat.id, new_mem.id) keyb.append([ InlineKeyboardButton( text=str(custom_text), callback_data="check_bot_({})".format( new_mem.id)) ]) keyboard = InlineKeyboardMarkup(keyb) # Send message ENUM_FUNC_MAP[welc_type](chat.id, cust_content, caption=formatted_text, reply_markup=keyboard, parse_mode="html", reply_to_message_id=reply) return # else, move on 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_html(new_mem.id, first_name) if new_mem.username: username = "******" + escape(new_mem.username) else: username = mention rules = "http://t.me/" + bot.username + "?start=" + str( chat.id) valid_format = escape_invalid_curly_brackets( cust_welcome, VALID_WELCOME_FORMATTERS) buttons = sql.get_welc_buttons(chat.id) keyb = build_keyboard_parser(bot, chat.id, buttons) 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, rules=keyb.append( [InlineKeyboardButton("Rules", url=rules)])) else: res = sql.DEFAULT_WELCOME.format(first=first_name) keyb = [] getsec, mutetime, custom_text = sql.welcome_security(chat.id) member = chat.get_member(new_mem.id) # If user ban protected don't apply security on him if is_user_ban_protected(chat, new_mem.id, chat.get_member(new_mem.id)): pass elif getsec: if mutetime: if mutetime[:1] == "0": if member.can_send_messages is None or member.can_send_messages: try: bot.restrict_chat_member( chat.id, new_mem.id, can_send_messages=False) canrest = True except BadRequest: canrest = False else: canrest = False else: mutetime = extract_time(update.effective_message, mutetime) if member.can_send_messages is None or member.can_send_messages: try: bot.restrict_chat_member( chat.id, new_mem.id, until_date=mutetime, can_send_messages=False) canrest = True except BadRequest: canrest = False else: canrest = False if canrest: sql.add_to_userlist(chat.id, new_mem.id) keyb.append([ InlineKeyboardButton( text=str(custom_text), callback_data="check_bot_({})".format( new_mem.id)) ]) keyboard = InlineKeyboardMarkup(keyb) sent = send(update, res, keyboard, sql.DEFAULT_WELCOME.format( first=first_name)) # type: Optional[Message] 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)