def remove_warn_filter(bot: Bot, update: Update): chat = update.effective_chat msg = update.effective_message args = msg.text.split( None, 1) # use python's maxsplit to separate Cmd, keyword, and reply_text if len(args) < 2: return extracted = split_quotes(args[1]) if len(extracted) < 1: return to_remove = extracted[0] chat_filters = sql.get_chat_warn_triggers(chat.id) if not chat_filters: msg.reply_text(tld(chat.id, 'warns_filters_list_empty')) return for filt in chat_filters: if filt == to_remove: sql.remove_warn_filter(chat.id, to_remove) msg.reply_text(tld(chat.id, 'warns_filters_remove_success')) raise DispatcherHandlerStop msg.reply_text(tld(chat.id, 'warns_filter_doesnt_exist'))
def warns(bot: Bot, update: Update, args: List[str]): message = update.effective_message chat = update.effective_chat user_id = extract_user(message, args) or update.effective_user.id result = sql.get_warns(user_id, chat.id) num = 1 if result and result[0] != 0: num_warns, reasons = result limit, soft_warn = sql.get_warn_setting(chat.id) if reasons: text = tld(chat.id, 'warns_list_warns').format(num_warns, limit) for reason in reasons: text += "\n {}. {}".format(num, reason) num += 1 msgs = split_message(text) for msg in msgs: update.effective_message.reply_text(msg) else: update.effective_message.reply_text( tld(chat.id, 'warns_list_warns_no_reason').format(num_warns, limit)) else: update.effective_message.reply_text( tld(chat.id, 'warns_list_warns_none'))
def remove_all_notes(bot: Bot, update: Update): chat = update.effective_chat user = update.effective_user message = update.effective_message if chat.type == "private": chat.title = tld(chat.id, "note_is_local") else: owner = chat.get_member(user.id) chat.title = chat.title if owner.status != 'creator': message.reply_text(tld(chat.id, "notes_must_be_creator")) return note_list = sql.get_all_chat_notes(chat.id) if not note_list: message.reply_text(tld(chat.id, "note_none_in_chat").format(chat.title), parse_mode=ParseMode.MARKDOWN) return x = 0 a_note = [] for notename in note_list: x += 1 note = notename.name.lower() a_note.append(note) for note in a_note: sql.rm_note(chat.id, note) message.reply_text(tld(chat.id, "notes_cleanup_success").format(x))
def rmwarn_handler(bot: Bot, update: Update) -> str: chat = update.effective_chat query = update.callback_query user = update.effective_user match = re.match(r"rm_warn\((.+?)\)", query.data) if match: user_id = match.group(1) if not is_user_admin(chat, int(user.id)): query.answer(text=tld(chat.id, 'warns_remove_admin_only'), show_alert=True) return "" res = sql.remove_warn(user_id, chat.id) if res: update.effective_message.edit_text(tld( chat.id, 'warns_remove_success').format( mention_html(user.id, user.first_name)), parse_mode=ParseMode.HTML) user_member = chat.get_member(user_id) return tld(chat.id, 'warns_remove_log_channel').format( html.escape(chat.title), mention_html(user.id, user.first_name), mention_html(user_member.user.id, user_member.user.first_name), user_member.user.id) else: update.effective_message.edit_text(tld( chat.id, 'warns_user_has_no_warns').format( mention_html(user.id, user.first_name)), parse_mode=ParseMode.HTML) return ""
def check_and_ban(update, user_id, should_message=True): chat = update.effective_chat message = update.effective_message try: if sw != None: sw_ban = sw.get_ban(user_id) if sw_ban: spamwatch_reason = sw_ban.reason chat.kick_member(user_id) if should_message: message.reply_text(tld( chat.id, "antispam_spamwatch_banned").format(spamwatch_reason), parse_mode=ParseMode.HTML) return else: return except Exception: pass if sql.is_user_gbanned(user_id): chat.kick_member(user_id) if should_message: userr = sql.get_gbanned_user(user_id) usrreason = userr.reason if not usrreason: usrreason = tld(chat.id, "antispam_no_reason") message.reply_text(tld( chat.id, "antispam_checkban_user_removed").format(usrreason), parse_mode=ParseMode.MARKDOWN) return
def stop_all_filters(bot: Bot, update: Update): chat = update.effective_chat user = update.effective_user message = update.effective_message if chat.type == "private": chat.title = tld(chat.id, "cust_filters_local") else: owner = chat.get_member(user.id) chat.title = chat.title if owner.status != 'creator': message.reply_text(tld(chat.id, "notes_must_be_creator")) return x = 0 flist = sql.get_chat_triggers(chat.id) if not flist: message.reply_text( tld(chat.id, "cust_filters_list_empty").format(chat.title)) return f_flist = [] for f in flist: x += 1 f_flist.append(f) for fx in f_flist: sql.remove_filter(chat.id, fx) message.reply_text(tld(chat.id, "cust_filters_cleanup_success").format(x))
def set_rules(bot: Bot, update: Update): chat = update.effective_chat user = update.effective_user msg = update.effective_message conn = connected(bot, update, chat, user.id) if conn: chat_id = conn else: if chat.type == 'private': msg.reply_text(tld(chat.id, 'common_cmd_group_only')) return chat_id = chat.id raw_text = msg.text args = raw_text.split(None, 1) # use python's maxsplit to separate cmd and args if len(args) == 2: txt = args[1] offset = len(txt) - len( raw_text) # set correct offset relative to command markdown_rules = markdown_parser(txt, entities=msg.parse_entities(), offset=offset) sql.set_rules(chat_id, markdown_rules) msg.reply_text(tld(chat.id, "rules_success"))
def extract_time(message, time_val): if any(time_val.endswith(unit) for unit in ('m', 'h', 'd')): chat = message.chat unit = time_val[-1] time_num = time_val[:-1] # type: str if not time_num.isdigit(): message.reply_text( tld(chat.id, 'helpers_string_handling_invalid_time_amount')) return "" if unit == 'm': bantime = int(time.time() + int(time_num) * 60) elif unit == 'h': bantime = int(time.time() + int(time_num) * 60 * 60) elif unit == 'd': bantime = int(time.time() + int(time_num) * 24 * 60 * 60) else: # how even...? return "" return bantime else: message.reply_text( tld(chat.id, 'helpers_string_handling_invalid_time_type').format( time_val[-1])) return ""
def del_lockables(bot: Bot, update: Update): chat = update.effective_chat message = update.effective_message for lockable, filter in LOCK_TYPES.items(): if filter(message) and sql.is_locked(chat.id, lockable) and can_delete( chat, bot.id): if lockable == "bots": new_members = update.effective_message.new_chat_members for new_mem in new_members: if new_mem.is_bot: if not is_bot_admin(chat, bot.id): message.reply_text( tld(chat.id, "locks_lock_bots_no_admin")) return chat.kick_member(new_mem.id) message.reply_text(tld(chat.id, "locks_lock_bots_kick")) else: try: message.delete() except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception("ERROR in lockables") break
def covid(bot: Bot, update: Update): message = update.effective_message chat = update.effective_chat country = str(message.text[len(f'/covid '):]) if country == '': country = "world" if country.lower() in ["south korea", "korea"]: country = "s. korea" try: c_case = cvid.get_status_by_country_name(country) except Exception: message.reply_text(tld(chat.id, "misc_covid_error")) return active = format_integer(c_case["active"]) confirmed = format_integer(c_case["confirmed"]) country = c_case["country"] critical = format_integer(c_case["critical"]) deaths = format_integer(c_case["deaths"]) new_cases = format_integer(c_case["new_cases"]) new_deaths = format_integer(c_case["new_deaths"]) recovered = format_integer(c_case["recovered"]) total_tests = c_case["total_tests"] if total_tests == 0: total_tests = "N/A" else: total_tests = format_integer(c_case["total_tests"]) reply = tld(chat.id, "misc_covid").format(country, confirmed, new_cases, active, critical, deaths, new_deaths, recovered, total_tests) message.reply_markdown(reply)
def get_id(bot: Bot, update: Update, args: List[str]): user_id = extract_user(update.effective_message, args) chat = update.effective_chat # type: Optional[Chat] if user_id: if update.effective_message.reply_to_message and update.effective_message.reply_to_message.forward_from: user1 = update.effective_message.reply_to_message.from_user user2 = update.effective_message.reply_to_message.forward_from update.effective_message.reply_markdown( tld(chat.id, "misc_get_id_1").format(escape_markdown(user2.first_name), user2.id, escape_markdown(user1.first_name), user1.id)) else: user = bot.get_chat(user_id) update.effective_message.reply_markdown( tld(chat.id, "misc_get_id_2").format(escape_markdown(user.first_name), user.id)) else: chat = update.effective_chat # type: Optional[Chat] if chat.type == "private": update.effective_message.reply_markdown( tld(chat.id, "misc_id_1").format(chat.id)) else: update.effective_message.reply_markdown( tld(chat.id, "misc_id_2").format(chat.id))
def paste(bot: Bot, update: Update, args: List[str]): chat = update.effective_chat # type: Optional[Chat] BURL = 'https://del.dog' message = update.effective_message if message.reply_to_message: data = message.reply_to_message.text elif len(args) >= 1: data = message.text.split(None, 1)[1] else: message.reply_text(tld(chat.id, "misc_paste_invalid")) return r = requests.post(f'{BURL}/documents', data=data.encode('utf-8')) if r.status_code == 404: update.effective_message.reply_text(tld(chat.id, "misc_paste_404")) r.raise_for_status() res = r.json() if r.status_code != 200: update.effective_message.reply_text(res['message']) r.raise_for_status() key = res['key'] if res['isUrl']: reply = tld(chat.id, "misc_paste_success").format(BURL, key, BURL, key) else: reply = f'{BURL}/{key}' update.effective_message.reply_text(reply, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
async def purge(event): if event.from_id == None: return chat = event.chat_id if not await user_is_admin(user_id=event.from_id, message=event): await event.reply(tld(chat, "helpers_user_not_admin")) return if not await can_delete_messages(message=event): await event.reply(tld(chat, "helpers_bot_cant_delete")) return msg = await event.get_reply_message() if not msg: await event.reply(tld(chat, "purge_invalid")) return msgs = [] msg_id = msg.id delete_to = event.message.id - 1 await event.client.delete_messages(chat, event.message.id) msgs.append(event.reply_to_msg_id) for m_id in range(delete_to, msg_id - 1, -1): msgs.append(m_id) if len(msgs) == 100: await event.client.delete_messages(chat, msgs) msgs = [] await event.client.delete_messages(chat, msgs) text = tld(chat, "purge_msg_success") await event.respond(text, parse_mode='md')
def add_blacklist_url(bot: Bot, update: Update): chat = update.effective_chat message = update.effective_message urls = message.text.split(None, 1) if len(urls) > 1: urls = urls[1] to_blacklist = list( set(uri.strip() for uri in urls.split("\n") if uri.strip())) blacklisted = [] for uri in to_blacklist: extract_url = tldextract.extract(uri) if extract_url.domain and extract_url.suffix: blacklisted.append(extract_url.domain + "." + extract_url.suffix) sql.blacklist_url( chat.id, extract_url.domain + "." + extract_url.suffix) if len(to_blacklist) == 1: extract_url = tldextract.extract(to_blacklist[0]) if extract_url.domain and extract_url.suffix: message.reply_text(tld( chat.id, "url_blacklist_success").format( html.escape(extract_url.domain + "." + extract_url.suffix)), parse_mode=ParseMode.HTML) else: message.reply_text(tld(chat.id, "url_blacklist_invalid")) else: message.reply_text(tld(chat.id, "url_blacklist_success_2").format( len(blacklisted)), parse_mode=ParseMode.HTML) else: message.reply_text(tld(chat.id, "url_blacklist_invalid_2"))
def check_flood(bot: Bot, update: Update) -> str: user = update.effective_user chat = update.effective_chat msg = update.effective_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: bot.restrict_chat_member(chat.id, user.id, can_send_messages=False) msg.reply_text(tld(chat.id, "flood_mute")) return tld(chat.id, "flood_logger_success").format( html.escape(chat.title), mention_html(user.id, user.first_name)) except BadRequest: msg.reply_text(tld(chat.id, "flood_err_no_perm")) sql.set_flood(chat.id, 0) return tld(chat.id, "flood_logger_fail").format(chat.title)
def set_welcome(bot: Bot, update: Update) -> str: chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] msg = update.effective_message # type: Optional[Message] # If user is not set text and not reply a message if not msg.reply_to_message: if len(msg.text.split()) == 1: msg.reply_text(tld(chat.id, 'welcome_set_welcome_no_text'), parse_mode="markdown") return "" text, data_type, content, buttons = get_welcome_type(msg) if data_type is None: msg.reply_text(tld(chat.id, "welcome_set_welcome_no_datatype")) return "" sql.set_custom_welcome(chat.id, content, text, data_type, buttons) msg.reply_text(tld(chat.id, 'welcome_set_welcome_success')) return "<b>{}:</b>" \ "\n#SET_WELCOME" \ "\n<b>Admin:</b> {}" \ "\nSet the welcome message.".format(escape(chat.title), mention_html(user.id, user.first_name))
def security(bot: Bot, update: Update, args: List[str]) -> str: chat = update.effective_chat # type: Optional[Chat] getcur, cur_value, cust_text = sql.welcome_security(chat.id) if len(args) >= 1: var = args[0].lower() if (var == "yes" or var == "y" or var == "on"): check = bot.getChatMember(chat.id, bot.id) if check.status == 'member' or check[ 'can_restrict_members'] == False: text = tld(chat.id, 'welcome_mute_bot_cant_mute') update.effective_message.reply_text(text, parse_mode="markdown") return "" sql.set_welcome_security(chat.id, True, str(cur_value), cust_text) update.effective_message.reply_text( tld(chat.id, 'welcome_mute_enabled')) elif (var == "no" or var == "n" or var == "off"): sql.set_welcome_security(chat.id, False, str(cur_value), cust_text) update.effective_message.reply_text( tld(chat.id, 'welcome_mute_disabled')) else: update.effective_message.reply_text(tld(chat.id, 'common_invalid_arg'), parse_mode=ParseMode.MARKDOWN) else: getcur, cur_value, cust_text = sql.welcome_security(chat.id) if getcur: getcur = "True" else: getcur = "False" if cur_value[:1] == "0": cur_value = "None" text = tld(chat.id, 'welcome_mute_curr_settings').format( getcur, cur_value, cust_text) update.effective_message.reply_text(text, parse_mode="markdown")
def blacklist(bot: Bot, update: Update, args: List[str]): msg = update.effective_message chat = update.effective_chat user = update.effective_user conn = connected(bot, update, chat, user.id, need_admin=False) if conn: chat_id = conn chat_name = dispatcher.bot.getChat(conn).title else: if chat.type == "private": return else: chat_id = update.effective_chat.id chat_name = chat.title filter_list = tld(chat.id, "blacklist_active_list").format(chat_name) all_blacklisted = sql.get_chat_blacklist(chat_id) if len(args) > 0 and args[0].lower() == 'copy': for trigger in all_blacklisted: filter_list += "<code>{}</code>\n".format(html.escape(trigger)) else: for trigger in all_blacklisted: filter_list += " • <code>{}</code>\n".format(html.escape(trigger)) split_text = split_message(filter_list) for text in split_text: if filter_list == tld(chat.id, "blacklist_active_list").format( chat_name): #We need to translate msg.reply_text(tld(chat.id, "blacklist_no_list").format(chat_name), parse_mode=ParseMode.HTML) return msg.reply_text(text, parse_mode=ParseMode.HTML)
def del_fed(bot: Bot, update: Update, args: List[str]): chat = update.effective_chat user = update.effective_user if chat.type != "private": update.effective_message.reply_text(tld(chat.id, "common_cmd_pm_only")) return if args: is_fed_id = args[0] getinfo = sql.get_fed_info(is_fed_id) if getinfo == False: update.effective_message.reply_text( tld(chat.id, "feds_delete_not_found")) return if int(getinfo['owner']) == int(user.id): fed_id = is_fed_id else: update.effective_message.reply_text(tld(chat.id, "feds_owner_only")) return else: update.effective_message.reply_text(tld(chat.id, "feds_err_no_args")) return if is_user_fed_owner(fed_id, user.id) == False: update.effective_message.reply_text(tld(chat.id, "feds_owner_only")) return update.effective_message.reply_text( "feds_delete_confirm".format(getinfo['fname']), reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton(text="⚠️ Delete Federation ⚠️", callback_data="rmfed_{}".format(fed_id)) ], [InlineKeyboardButton(text="Cancel", callback_data="rmfed_cancel")]]))
def invite(bot: Bot, update: Update): chat = update.effective_chat user = update.effective_user conn = connected(bot, update, chat, user.id, need_admin=False) if conn: chatP = dispatcher.bot.getChat(conn) else: chatP = update.effective_chat if chat.type == "private": return if chatP.username: update.effective_message.reply_text(chatP.username) elif chatP.type == chatP.SUPERGROUP or chatP.type == chatP.CHANNEL: bot_member = chatP.get_member(bot.id) if bot_member.can_invite_users: invitelink = chatP.invite_link #print(invitelink) if not invitelink: invitelink = bot.exportChatInviteLink(chatP.id) update.effective_message.reply_text(invitelink) else: update.effective_message.reply_text( tld(chat.id, "admin_err_no_perm_invitelink")) else: update.effective_message.reply_text( tld(chat.id, "admin_chat_no_invitelink"))
def connected(bot, update, chat, user_id, need_admin=True): chat = update.effective_chat # type: Optional[Chat] if chat.type == chat.PRIVATE and sql.get_connected_chat(user_id): conn_id = sql.get_connected_chat(user_id).chat_id if (bot.get_chat_member( conn_id, user_id).status in ('administrator', 'creator') or (sql.allow_connect_to_chat(connect_chat) == True) and bot.get_chat_member( user_id, update.effective_message.from_user.id).status in ('member')) or (user_id in SUDO_USERS): if need_admin: if bot.get_chat_member( conn_id, update.effective_message.from_user.id).status in ( 'administrator', 'creator') or user_id in SUDO_USERS: return conn_id else: update.effective_message.reply_text( tld(chat.id, "connection_err_no_admin")) return else: return conn_id else: update.effective_message.reply_text( tld(chat.id, "connection_err_unknown")) disconnect_chat(bot, update) return else: return False
def new_fed(bot: Bot, update: Update): chat = update.effective_chat user = update.effective_user message = update.effective_message if chat.type != "private": update.effective_message.reply_text(tld(chat.id, "common_cmd_pm_only")) return fednam = message.text.split(None, 1)[1] if not fednam == '': fed_id = str(uuid.uuid4()) fed_name = fednam LOGGER.info(fed_id) if user.id == int(OWNER_ID): fed_id = fed_name x = sql.new_fed(user.id, fed_name, fed_id) if not x: update.effective_message.reply_text( tld(chat.id, "feds_create_fail")) return update.effective_message.reply_text(tld(chat.id, "feds_create_success").format( fed_name, fed_id, fed_id), parse_mode=ParseMode.MARKDOWN) try: bot.send_message(MESSAGE_DUMP, tld(chat.id, "feds_create_success_logger").format( fed_name, fed_id), parse_mode=ParseMode.HTML) except Exception: LOGGER.warning("Cannot send a message to MESSAGE_DUMP") else: update.effective_message.reply_text(tld(chat.id, "feds_err_no_args"))
def unban(bot: Bot, update: Update, args: List[str]) -> str: message = update.effective_message # type: Optional[Message] user = update.effective_user # type: Optional[User] chat = update.effective_chat # type: Optional[Chat] user_id, reason = extract_user_and_text(message, args) if not user_id: return "" try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found": message.reply_text(tld(chat.id, "common_err_no_user")) return "" else: raise if is_user_in_chat(chat, user_id): message.reply_text(tld(chat.id, "bans_unban_user_in_chat")) return "" chat.unban_member(user_id) message.reply_text(tld(chat.id, "bans_unban_success")) log = tld(chat.id, "bans_unban_logger").format( html.escape(chat.title), mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name), member.user.id) if reason: log += tld(chat.id, "bans_logger_reason").format(reason) return log
def security_text_reset(bot: Bot, update: Update): chat = update.effective_chat # type: Optional[Chat] getcur, cur_value, cust_text = sql.welcome_security(chat.id) sql.set_welcome_security(chat.id, getcur, cur_value, tld(chat.id, 'welcome_mute_btn_default_text')) update.effective_message.reply_text(tld( chat.id, 'welcome_mute_btn_text_reset').format( tld(chat.id, 'welcome_mute_btn_default_text')), parse_mode="markdown")
def gdpr(bot: Bot, update: Update): update.effective_message.reply_text( tld(update.effective_chat.id, "misc_gdpr")) for mod in GDPR: mod.__gdpr__(update.effective_user.id) update.effective_message.reply_text(tld(update.effective_chat.id, "send_gdpr"), parse_mode=ParseMode.MARKDOWN)
def flood(bot: Bot, update: Update): chat = update.effective_chat limit = sql.get_flood_limit(chat.id) if limit == 0: update.effective_message.reply_text(tld(chat.id, "flood_status_off")) else: update.effective_message.reply_text( tld(chat.id, "flood_status_on").format(limit))
def build_curr_disabled(chat_id: Union[str, int]) -> str: disabled = sql.get_all_disabled(chat_id) if not disabled: return tld(chat_id, "disable_chatsettings_none_disabled") result = "" for cmd in disabled: result += " - `{}`\n".format(escape_markdown(cmd)) return tld(chat_id, "disable_chatsettings_list_disabled").format(result)
def stickerid(bot: Bot, update: Update): chat = update.effective_chat msg = update.effective_message if msg.reply_to_message and msg.reply_to_message.sticker: update.effective_message.reply_text(tld( chat.id, 'stickers_stickerid').format( escape_markdown(msg.reply_to_message.sticker.file_id)), parse_mode=ParseMode.MARKDOWN) else: update.effective_message.reply_text( tld(chat.id, 'stickers_stickerid_no_reply'))
def __user_info__(user_id, chat_id): bio = html.escape(sql.get_user_bio(user_id) or "") me = html.escape(sql.get_user_me_info(user_id) or "") if bio and me: return tld(chat_id, "userinfo_what_i_and_other_say").format(me, bio) elif bio: return tld(chat_id, "userinfo_what_other_say").format(bio) elif me: return tld(chat_id, "userinfo_what_i_say").format(me) else: return ""
def ban(bot: Bot, update: Update, args: List[str]) -> str: chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] message = update.effective_message # type: Optional[Message] user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text(tld(chat.id, "common_err_no_user")) return "" try: member = chat.get_member(user_id) except BadRequest as excp: if excp.message == "User not found.": message.reply_text(tld(chat.id, "bans_err_usr_not_found")) return "" else: raise if user_id == bot.id: message.reply_text(tld(chat.id, "bans_err_usr_is_bot")) return "" if is_user_ban_protected(chat, user_id, member): message.reply_text(tld(chat.id, "bans_err_usr_is_admin")) return "" log = tld(chat.id, "bans_logger").format( html.escape(chat.title), mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name), user_id) reply = tld(chat.id, "bans_banned_success").format( mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name), html.escape(chat.title)) if reason: log += tld(chat.id, "bans_logger_reason").format(reason) reply += tld(chat.id, "bans_logger_reason").format(reason) try: chat.kick_member(user_id) message.reply_text(reply, parse_mode=ParseMode.HTML) return log except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text(reply, quote=False, parse_mode=ParseMode.HTML) return log else: LOGGER.warning(update) LOGGER.exception("ERROR banning user %s in chat %s (%s) due to %s", user_id, chat.title, chat.id, excp.message) message.reply_text( tld(chat.id, "bans_err_unknown").format("banning")) return ""