async def antichanpin_cleanlinked(c: Alita, m: Message): try: msg_id = m.message_id pins_db = Pins(m.chat.id) curr = pins_db.get_settings() if curr["antichannelpin"]: await c.unpin_chat_message(chat_id=m.chat.id, message_id=msg_id) LOGGER.info( f"AntiChannelPin: msgid-{m.message_id} unpinned in {m.chat.id}" ) if curr["cleanlinked"]: await c.delete_messages(m.chat.id, msg_id) LOGGER.info( f"CleanLinked: msgid-{m.message_id} cleaned in {m.chat.id}") except ChatAdminRequired: await m.reply_text( "Disabled antichannelpin as I don't have enough admin rights!", ) pins_db.antichannelpin_off() LOGGER.warning( f"Disabled antichannelpin in {m.chat.id} as i'm not an admin.") except Exception as ef: LOGGER.error(ef) LOGGER.error(format_exc()) return
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"))
async def start(c: Alita, m: Message): me = await c.get_users("self") _ = GetLang(m).strs if m.chat.type == "private": if errors.UserIsBlocked: LOGGER.warning(f"Bot blocked by {m.from_user.id}") pass keyboard = InlineKeyboardMarkup(inline_keyboard=[ [ InlineKeyboardButton("📚 " + _("start.commands_btn"), callback_data="commands") ] + [ InlineKeyboardButton("ℹ️ " + _("start.infos_btn"), callback_data="infos") ], [ InlineKeyboardButton("🌐 " + _("start.language_btn"), callback_data="chlang") ] + [ InlineKeyboardButton( "➕ " + _("start.add_chat_btn"), url=f"https://t.me/{me.username}?startgroup=new", ) ], ]) await m.reply_text(_("start.private"), reply_markup=keyboard, reply_to_message_id=m.message_id) else: await m.reply_text(_("start.group"), reply_to_message_id=m.message_id) return
def repair_db(collection): all_data = collection.find_all() keys = {"privrules": False, "rules": ""} for data in all_data: for key, val in keys.items(): try: _ = data[key] except KeyError: LOGGER.warning( f"Repairing Rules Database - setting '{key}:{val}' for {data['_id']}", ) collection.update({"_id": data["_id"]}, {key: val})
def repair_db(collection): all_data = collection.find_all() keys = {"antichannelpin": False, "cleanlinked": False} for data in all_data: for key, val in keys.items(): try: _ = data[key] except KeyError: LOGGER.warning( f"Repairing Pins Database - setting '{key}:{val}' for {data['_id']}", ) collection.update({"_id": data["_id"]}, {key: val})
def repair_db(collection): all_data = collection.find_all() keys = {"chat_name": "", "users": []} for data in all_data: for key, val in keys.items(): try: _ = data[key] except KeyError: LOGGER.warning( f"Repairing Chats Database - setting '{key}:{val}' for {data['_id']}", ) collection.update({"_id": data["_id"]}, {key: val})
def repair_db(collection): all_data = collection.find_all() keys = {"status": True, "chat_type": ""} for data in all_data: for key, val in keys.items(): try: _ = data[key] except KeyError: LOGGER.warning( f"Repairing Reporting Database - setting '{key}:{val}' for {data['_id']}", ) collection.update({"_id": data["_id"]}, {key: val})
async def start(c: Alita, m: Message): me = await c.get_users("self") _ = GetLang(m).strs if m.chat.type == "private": if errors.UserIsBlocked: LOGGER.warning(f"Bot blocked by {m.from_user.id}") await m.reply_text( _("start.private"), reply_markup=(await gen_start_kb(m, me)), reply_to_message_id=m.message_id, ) else: await m.reply_text(_("start.group"), reply_to_message_id=m.message_id) return
async def start(_, m: Message): if m.chat.type == "private": try: await m.reply_text( tlang(m, "start.private"), reply_markup=(await gen_start_kb(m)), reply_to_message_id=m.message_id, ) except UserIsBlocked: LOGGER.warning(f"Bot blocked by {m.from_user.id}") else: await m.reply_text(tlang(m, "start.group"), reply_to_message_id=m.message_id) return
def snipe(bot: Bot, update: Update, args: List[str]): try: chat_id = str(args[0]) del args[0] except TypeError as excp: update.effective_message.reply_text( "Please give me a chat to echo to!") to_send = " ".join(args) if len(to_send) >= 2: try: bot.sendMessage(int(chat_id), str(to_send)) except TelegramError: LOGGER.warning("Couldn't send to group %s", str(chat_id)) update.effective_message.reply_text( "Couldn't send the message. Perhaps I'm not part of that group?" )
def repair_db(collection): all_data = collection.find_all() keys = { "triggers": [], "action": "none", "reason": "Automated blacklisted word: {{}}", } for data in all_data: for key, val in keys.items(): try: _ = data[key] except KeyError: LOGGER.warning( f"Repairing Blacklist Database - setting '{key}:{val}' for {data['_id']}", ) collection.update({"_id": data["_id"]}, {key: val})
def user_join_fed(bot: Bot, update: Update, args: List[str]): chat = update.effective_chat user = update.effective_user msg = update.effective_message fed_id = sql.get_fed_id(chat.id) if is_user_fed_owner(fed_id, user.id): user_id = extract_user(msg, args) if user_id: user = bot.get_chat(user_id) elif not msg.reply_to_message and not args: user = msg.from_user elif not msg.reply_to_message and ( not args or (len(args) >= 1 and not args[0].startswith("@") and not args[0].isdigit() and not msg.parse_entities([MessageEntity.TEXT_MENTION]))): msg.reply_text(tld(chat.id, "common_err_no_user")) return else: LOGGER.warning('error') getuser = sql.search_user_in_fed(fed_id, user_id) fed_id = sql.get_fed_id(chat.id) info = sql.get_fed_info(fed_id) get_owner = eval(info['fusers'])['owner'] get_owner = bot.get_chat(get_owner).id if user_id == get_owner: update.effective_message.reply_text( tld(chat.id, "feds_promote_owner")) return if getuser: update.effective_message.reply_text( tld(chat.id, "feds_promote_owner")) return if user_id == bot.id: update.effective_message.reply_text( tld(chat.id, "feds_promote_bot")) return res = sql.user_join_fed(fed_id, user_id) if res: update.effective_message.reply_text( tld(chat.id, "feds_promote_success")) else: update.effective_message.reply_text("") else: update.effective_message.reply_text(tld(chat.id, "feds_owner_only"))
def broadcast(bot: Bot, update: Update): to_send = update.effective_message.text.split(None, 1) if len(to_send) >= 2: chats = sql.get_all_chats() or [] failed = 0 for chat in chats: try: bot.sendMessage(int(chat.chat_id), to_send[1]) sleep(0.1) except TelegramError: failed += 1 LOGGER.warning("Couldn't send broadcast to %s, group name %s", str(chat.chat_id), str(chat.chat_name)) update.effective_message.reply_text( "Broadcast complete. {} groups failed to receive the message, probably " "due to being kicked.".format(failed))
def user_demote_fed(bot: Bot, update: Update, args: List[str]): chat = update.effective_chat user = update.effective_user fed_id = sql.get_fed_id(chat.id) if is_user_fed_owner(fed_id, user.id): msg = update.effective_message user_id = extract_user(msg, args) if user_id: user = bot.get_chat(user_id) elif not msg.reply_to_message and not args: user = msg.from_user elif not msg.reply_to_message and ( not args or (len(args) >= 1 and not args[0].startswith("@") and not args[0].isdigit() and not msg.parse_entities([MessageEntity.TEXT_MENTION]))): msg.reply_text(tld(chat.id, "common_err_no_user")) return else: LOGGER.warning('error') if user_id == bot.id: update.effective_message.reply_text(tld(chat.id, "feds_demote_bot")) return if sql.search_user_in_fed(fed_id, user_id) is False: update.effective_message.reply_text( tld(chat.id, "feds_demote_target_not_admin")) return res = sql.user_demote_fed(fed_id, user_id) if res is True: update.effective_message.reply_text( tld(chat.id, "feds_demote_success")) else: update.effective_message.reply_text( tld(chat.id, "feds_demote_failed")) else: update.effective_message.reply_text(tld(chat.id, "feds_owner_only")) return
async def start(c: Alita, m: Message): if m.chat.type == "private": if len(m.text.split()) > 1: help_option = (m.text.split(None, 1)[1]).lower() if help_option.startswith("note") and ( help_option not in ("note", "notes") ): await get_private_note(c, m, help_option) return if help_option.startswith("rules"): LOGGER.info(f"{m.from_user.id} fetched privaterules in {m.chat.id}") await get_private_rules(c, m, help_option) return help_msg, help_kb = await get_help_msg(m, help_option) if not help_msg: return await m.reply_text( help_msg, parse_mode="markdown", reply_markup=ikb(help_kb), quote=True, disable_web_page_preview=True, ) return try: await m.reply_text( (tlang(m, "start.private")), reply_markup=(await gen_start_kb(m)), quote=True, disable_web_page_preview=True, ) except UserIsBlocked: LOGGER.warning(f"Bot blocked by {m.from_user.id}") else: await m.reply_text( (tlang(m, "start.group")), quote=True, ) return
async def chats(c: Alita, m: Message): exmsg = await m.reply_text("`Exporting Chatlist...`") await c.send_message( MESSAGE_DUMP, f"#CHATLIST\n\n**User:** {(await mention_markdown(m.from_user.first_name, m.from_user.id))}", ) all_chats = userdb.get_all_chats() or [] chatfile = "List of chats.\n\nChat name | Chat ID | Members count\n" P = 1 for chat in all_chats: try: chat_info = await c.get_chat(chat.chat_id) chat_members = chat_info.members_count try: invitelink = chat_info.invite_link except KeyError: invitelink = "No Link!" chatfile += "{}. {} | {} | {} | {}\n".format( P, chat.chat_name, chat.chat_id, chat_members, invitelink, ) P += 1 except ChatAdminRequired: pass except ChannelPrivate: userdb.rem_chat(chat.chat_id) except PeerIdInvalid: LOGGER.warning(f"Group not loaded {chat.chat_id}") except RPCError as ef: LOGGER.error(ef) await m.reply_text(f"**Error:**\n{ef}") with BytesIO(str.encode(chatfile)) as f: f.name = "chatlist.txt" await m.reply_document( document=f, caption=tlang(m, "dev.chats_in_db"), ) await exmsg.delete() return
async def chats(c: Alita, m: Message): exmsg = await m.reply_text(tlang(m, "dev.chatlist.exporting")) await c.send_message( MESSAGE_DUMP, f"#CHATLIST\n\n**User:** {(await mention_markdown(m.from_user.first_name, m.from_user.id))}", ) all_chats = (chatdb.get_all_chats()) or {} chatfile = tlang(m, "dev.chatlist.header") P = 1 for chat, val in all_chats.items(): try: chat_info = await c.get_chat(chat) chat_members = chat_info.members_count try: invitelink = chat_info.invite_link except KeyError: invitelink = "No Link!" chatfile += ( f"{P}. {val['chat_name']} | {chat} | {chat_members} | {invitelink}\n" ) P += 1 except ChatAdminRequired: pass except (ChannelPrivate, ChannelInvalid): chatdb.remove_chat(chat) except PeerIdInvalid: LOGGER.warning(f"Peer not found {chat}") except FloodWait as ef: LOGGER.error("FloodWait required, Sleeping for 60s") LOGGER.error(ef) sleep(60) except RPCError as ef: LOGGER.error(ef) await m.reply_text(f"**Error:**\n{ef}") with BytesIO(str.encode(await remove_markdown_and_html(chatfile))) as f: f.name = "chatlist.txt" await m.reply_document( document=f, caption=(tlang(m, "dev.chatlist.chats_in_db")), ) await exmsg.delete() return
def unfban(bot: Bot, update: Update, args: List[str]): chat = update.effective_chat user = update.effective_user message = update.effective_message fed_id = sql.get_fed_id(chat.id) if not fed_id: update.effective_message.reply_text( "This group is not a part of any federation!") return if is_user_fed_admin(fed_id, user.id) is False: update.effective_message.reply_text( "Only federation admins can do this!") return user_id = extract_user(message, args) if not user_id: message.reply_text("You do not 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 fban, fbanreason = sql.get_fban_user(fed_id, user_id) if fban is False: message.reply_text("This user is not fbanned!") if not fbanreason: return return message.reply_text( "I'll give {} a second chance in this federation".format( user_chat.first_name)) chat_list = sql.all_fed_chats(fed_id) for chat in chat_list: try: member = bot.get_chat_member(chat, user_id) if member.status == 'kicked': bot.unban_chat_member(chat, user_id) except BadRequest as excp: if excp.message in UNFBAN_ERRORS: pass else: LOGGER.warning("Cannot remove fban on {} because: {}".format( chat, excp.message)) except TelegramError: pass try: x = sql.un_fban_user(fed_id, user_id) if not x: message.reply_text( "Fban failure, this user may have been un-fedbanned!") return except Exception: pass message.reply_text("This person is un-fbanned.")
def fed_ban(bot: Bot, update: Update, args: List[str]): chat = update.effective_chat user = update.effective_user fed_id = sql.get_fed_id(chat.id) if not fed_id: update.effective_message.reply_text( "This group is not a part of any federation!") return info = sql.get_fed_info(fed_id) OW = bot.get_chat(info['owner']) HAHA = OW.id FEDADMIN = sql.all_fed_users(fed_id) FEDADMIN.append(int(HAHA)) if is_user_fed_admin(fed_id, user.id) is False: update.effective_message.reply_text( "Only federation admins can do this!") return message = update.effective_message user_id, reason = extract_user_and_text(message, args) fban, fbanreason = sql.get_fban_user(fed_id, user_id) if not user_id: message.reply_text("You don't seem to be referring to a user") return if user_id == bot.id: message.reply_text( "What is funnier than fbanning the bot? Self sacrifice.") return if is_user_fed_owner(fed_id, user_id) is True: message.reply_text("Why did you try the federation fban?") return if is_user_fed_admin(fed_id, user_id) is True: message.reply_text("He is a federation admin, I can't fban him.") return if user_id == OWNER_ID: message.reply_text( "I don't want to fban my master, that's a very stupid idea!") return if int(user_id) in SUDO_USERS: message.reply_text("I will not fban sudos!") return if int(user_id) in WHITELIST_USERS: message.reply_text( "This person is whitelisted, so they can't be fbanned!") 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 fban: user_target = mention_html(user_chat.id, user_chat.first_name) fed_name = info['fname'] starting = "The reason of federation ban has been replaced for {} in the Federation <b>{}</b>.".format( user_target, fed_name) update.effective_message.reply_text(starting, parse_mode=ParseMode.HTML) if reason == "": reason = "No reason given." temp = sql.un_fban_user(fed_id, user_id) if not temp: message.reply_text("Failed to update the reason for fban!") return x = sql.fban_user(fed_id, user_id, user_chat.first_name, user_chat.last_name, user_chat.username, reason) if not x: message.reply_text( "Failed to ban from the federation! If this problem continues, ask in @HitsukiAyaGroup for help!" ) return fed_chats = sql.all_fed_chats(fed_id) for chat in fed_chats: try: bot.kick_chat_member(chat, user_id) except BadRequest as excp: if excp.message in FBAN_ERRORS: pass else: LOGGER.warning("Could not fban in {} because: {}".format( chat, excp.message)) except TelegramError: pass send_to_list(bot, FEDADMIN, "<b>FedBan reason updated</b>" \ "\n<b>Federation:</b> {}" \ "\n<b>Federation Admin:</b> {}" \ "\n<b>User:</b> {}" \ "\n<b>User ID:</b> <code>{}</code>" \ "\n<b>Reason:</b> {}".format(fed_name, mention_html(user.id, user.first_name), mention_html(user_chat.id, user_chat.first_name), user_chat.id, reason), html=True) message.reply_text("FedBan reason has been updated.") return user_target = mention_html(user_chat.id, user_chat.first_name) fed_name = info['fname'] starting = "Starting a federation ban for {} in the Federation <b>{}</b>.".format( user_target, fed_name) update.effective_message.reply_text(starting, parse_mode=ParseMode.HTML) if reason == "": reason = "No reason given." x = sql.fban_user(fed_id, user_id, user_chat.first_name, user_chat.last_name, user_chat.username, reason) if not x: message.reply_text( "Failed to ban from the federation! If this problem continues, ask in @HitsukiAyaGroup for help." ) return fed_chats = sql.all_fed_chats(fed_id) for chat in fed_chats: try: bot.kick_chat_member(chat, user_id) except BadRequest as excp: if excp.message in FBAN_ERRORS: try: dispatcher.bot.getChat(chat) except Unauthorized: sql.chat_leave_fed(chat) LOGGER.info( "Chat {} has leave fed {} because bot is kicked". format(chat, info['fname'])) continue else: LOGGER.warning("Cannot fban on {} because: {}".format( chat, excp.message)) except TelegramError: pass send_to_list(bot, FEDADMIN, "<b>New FedBan</b>" \ "\n<b>Federation:</b> {}" \ "\n<b>Federation Admin:</b> {}" \ "\n<b>User:</b> {}" \ "\n<b>User ID:</b> <code>{}</code>" \ "\n<b>Reason:</b> {}".format(fed_name, mention_html(user.id, user.first_name), mention_html(user_chat.id, user_chat.first_name), user_chat.id, reason), html=True) message.reply_text("This person has been fbanned")
async def my_info(c: Alita, m: Message): try: user_id, name, user_name = await extract_user(c, m) except PeerIdInvalid: await m.reply_text(tlang(m, "utils.user_info.peer_id_error")) return except ValueError as ef: if "Peer id invalid" in str(ef): await m.reply_text(tlang(m, "utils.user_info.id_not_found")) return try: user = Users.get_user_info(int(user_id)) name = user["name"] user_name = user["username"] user_id = user["_id"] except KeyError: LOGGER.warning(f"Calling api to fetch info about user {user_id}") user = await c.get_users(user_id) name = (escape(user["first_name"] + " " + user["last_name"]) if user["last_name"] else user["first_name"]) user_name = user["username"] user_id = user["id"] except PeerIdInvalid: await m.reply_text(tlang(m, "utils.no_user_db")) return except (RPCError, Exception) as ef: await m.reply_text((tlang(m, "general.some_error")).format( SUPPORT_GROUP=SUPPORT_GROUP, ef=ef, ), ) return gbanned, reason_gban = gban_db.get_gban(user_id) LOGGER.info(f"{m.from_user.id} used info cmd for {user_id} in {m.chat.id}") text = (tlang(m, "utils.user_info.info_text.main")).format( user_id=user_id, user_name=name, ) if user_name: text += (tlang(m, "utils.user_info.info_text.username")).format( username=user_name, ) text += (tlang(m, "utils.user_info.info_text.perma_link")).format( perma_link=(await mention_html("Click Here", user_id)), ) if gbanned: text += f"\nThis user is Globally banned beacuse: {reason_gban}\n" if user_id == OWNER_ID: text += tlang(m, "utils.user_info.support_user.owner") elif user_id in DEV_USERS: text += tlang(m, "utils.user_info.support_user.dev") elif user_id in SUDO_USERS: text += tlang(m, "utils.user_info.support_user.sudo") elif user_id in WHITELIST_USERS: text += tlang(m, "utils.user_info.support_user.whitelist") await m.reply_text(text, parse_mode="html", disable_web_page_preview=True) return