def __list_all_modules(): from os.path import dirname, basename, isfile import glob # This generates a list of modules in this folder for the * in __main__ to work. mod_paths = glob.glob(dirname(__file__) + "/*.py") all_modules = [ basename(f)[:-3] for f in mod_paths if isfile(f) and f.endswith(".py") and not f.endswith('__init__.py') ] if LOAD or NO_LOAD: to_load = LOAD if to_load: if not all( any(mod == module_name for module_name in all_modules) for mod in to_load): LOGGER.error("Invalid load order names. Quitting.") quit(1) else: to_load = all_modules if NO_LOAD: LOGGER.info("Not loading: {}".format(NO_LOAD)) return [item for item in to_load if item not in NO_LOAD] return to_load return all_modules
def fed_broadcast(bot: Bot, update: Update, args: List[str]): msg = update.effective_message # type: Optional[Message] user = update.effective_user # type: Optional[User] if args: chat = update.effective_chat # type: Optional[Chat] fed_id = sql.get_fed_id(chat.id) fedinfo = sql.get_fed_info(fed_id) text = "*New broadcast from the Federation {}*\n".format(fedinfo['fname']) # Parsing md raw_text = msg.text args = raw_text.split(None, 1) # use python's maxsplit to separate cmd and args txt = args[1] offset = len(txt) - len(raw_text) # set correct offset relative to command text_parser = markdown_parser(txt, entities=msg.parse_entities(), offset=offset) text += text_parser try: broadcaster = user.first_name except: broadcaster = user.first_name + " " + user.last_name text += "\n\n- {}".format(mention_markdown(user.id, broadcaster)) chat_list = sql.all_fed_chats(fed_id) failed = 0 for chat in chat_list: try: bot.sendMessage(chat, text, parse_mode="markdown") except TelegramError: failed += 1 LOGGER.warning("Couldn't send broadcast to %s, group name %s", str(chat.chat_id), str(chat.chat_name)) send_text = "The federation broadcast is complete" if failed >= 1: send_text += "{} the group failed to receive the message, probably because it left the Federation.".format(failed) update.effective_message.reply_text(send_text)
def get_user_id(username): # ensure valid userid if len(username) <= 5: return None if username.startswith('@'): username = username[1:] users = sql.get_userid_by_name(username) if not users: return None elif len(users) == 1: return users[0].user_id else: for user_obj in users: try: userdat = dispatcher.bot.get_chat(user_obj.user_id) if userdat.username == username: return userdat.id except BadRequest as excp: if excp.message == 'Chat not found': pass else: LOGGER.exception("Error extracting user ID") return None
def new_fed(bot: Bot, update: Update): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] message = update.effective_message if chat.type != "private": update.effective_message.reply_text("Do it in PM?") 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("Federation creation failed! Keep in the mind that this rarely happened! Ask in @HarukaAyaGroup for help!") return update.effective_message.reply_text("*You have successfully created a new federation!*"\ "\nName: `{}`"\ "\nID: `{}`" "\n\nUse the command below to join the federation:" "\n`/joinfed {}`".format(fed_name, fed_id, fed_id), parse_mode=ParseMode.MARKDOWN) try: bot.send_message(MESSAGE_DUMP, "Federation <b>{}</b> have been created with ID: <pre>{}</pre>".format(fed_name, fed_id), parse_mode=ParseMode.HTML) except: LOGGER.warning("Cannot send a message to MESSAGE_DUMP") else: update.effective_message.reply_text("Please write down the name of the federation")
def main(): #test_handler = CommandHandler("test", test) #Unused variable start_handler = CommandHandler("start", start, pass_args=True) help_handler = CommandHandler("help", get_help) help_callback_handler = CallbackQueryHandler(help_button, pattern=r"help_") start_callback_handler = CallbackQueryHandler(send_start, pattern=r"bot_start") dispatcher.add_handler(start_callback_handler) cntrl_panel = CommandHandler("controlpanel", control_panel) cntrl_panel_callback_handler = CallbackQueryHandler(control_panel, pattern=r"cntrl_panel") dispatcher.add_handler(cntrl_panel_callback_handler) dispatcher.add_handler(cntrl_panel) settings_handler = CommandHandler("settings", get_settings) settings_callback_handler = CallbackQueryHandler(settings_button, pattern=r"stngs_") migrate_handler = MessageHandler(Filters.status_update.migrate, migrate_chats) # dispatcher.add_handler(test_handler) dispatcher.add_handler(start_handler) dispatcher.add_handler(help_handler) dispatcher.add_handler(settings_handler) dispatcher.add_handler(help_callback_handler) dispatcher.add_handler(settings_callback_handler) dispatcher.add_handler(migrate_handler) # dispatcher.add_error_handler(error_callback) # add antiflood processor Dispatcher.process_update = process_update if WEBHOOK: LOGGER.info("Using webhooks.") updater.start_webhook(listen="127.0.0.1", port=PORT, url_path=TOKEN) if CERT_PATH: updater.bot.set_webhook(url=URL + TOKEN, certificate=open(CERT_PATH, 'rb')) else: updater.bot.set_webhook(url=URL + TOKEN) else: LOGGER.info("Using long polling.") # updater.start_polling(timeout=15, read_latency=4, clean=True) updater.start_polling(poll_interval=0.0, timeout=10, clean=True, bootstrap_retries=-1, read_latency=3.0) updater.idle()
def purge(bot: Bot, update: Update, args: List[str]) -> str: msg = update.effective_message # type: Optional[Message] if msg.reply_to_message: user = update.effective_user # type: Optional[User] chat = update.effective_chat # type: Optional[Chat] if can_delete(chat, bot.id): message_id = msg.reply_to_message.message_id if args and args[0].isdigit(): if int(args[0]) < int(1): return delete_to = message_id + int(args[0]) else: delete_to = msg.message_id - 1 for m_id in range(delete_to, message_id - 1, -1): # Reverse iteration over message ids try: bot.deleteMessage(chat.id, m_id) except BadRequest as err: if err.message == "Message can't be deleted": bot.send_message( chat.id, "Cannot delete all messages. The messages may be too old, I might " "not have delete rights, or this might not be a supergroup." ) elif err.message != "Message to delete not found": LOGGER.exception("Error while purging chat messages.") try: msg.delete() except BadRequest as err: if err.message == "Message can't be deleted": bot.send_message( chat.id, "Cannot delete all messages. The messages may be too old, I might " "not have delete rights, or this might not be a supergroup." ) elif err.message != "Message to delete not found": LOGGER.exception("Error while purging chat messages.") bot.send_message(chat.id, "Purge complete.") return "<b>{}:</b>" \ "\n#PURGE" \ "\n<b>• Admin:</b> {}" \ "\nPurged <code>{}</code> messages.".format(html.escape(chat.title), mention_html(user.id, user.first_name), delete_to - message_id) else: msg.reply_text( "Reply to a message to select where to start purging from.") return ""
def help_button(bot: Bot, update: Update): query = update.callback_query chat = update.effective_chat # type: Optional[Chat] mod_match = re.match(r"help_module\((.+?)\)", query.data) prev_match = re.match(r"help_prev\((.+?)\)", query.data) next_match = re.match(r"help_next\((.+?)\)", query.data) back_match = re.match(r"help_back", query.data) try: if mod_match: module = mod_match.group(1) mod_name = tld(chat.id, HELPABLE[module].__mod_name__) help_txt = tld_help(chat.id, HELPABLE[module].__mod_name__) if help_txt == False: help_txt = HELPABLE[module].__help__ text = tld(chat.id, "Here is the help for the *{}* module:\n{}").format(mod_name, help_txt) query.message.reply_text(text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( [[InlineKeyboardButton(text=tld(chat.id, "Back"), callback_data="help_back")]])) elif prev_match: curr_page = int(prev_match.group(1)) query.message.reply_text(tld(chat.id, "send-help").format( dispatcher.bot.first_name, "" if not ALLOW_EXCL else tld(chat.id, "\nAll commands can either be used with `/` or `!`.\n") ), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(paginate_modules(chat.id, curr_page - 1, HELPABLE, "help"))) elif next_match: next_page = int(next_match.group(1)) query.message.reply_text(tld(chat.id, "send-help").format( dispatcher.bot.first_name, "" if not ALLOW_EXCL else tld(chat.id, "\nAll commands can either be used with `/` or `!`.\n") ), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(paginate_modules(chat.id, next_page + 1, HELPABLE, "help"))) elif back_match: query.message.reply_text(text=tld(chat.id, "send-help").format( dispatcher.bot.first_name, "" if not ALLOW_EXCL else tld(chat.id, "\nAll commands can either be used with `/` or `!`.\n") ), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(paginate_modules(chat.id, 0, HELPABLE, "help"))) # ensure no spinny white circle bot.answer_callback_query(query.id) query.message.delete() except BadRequest as excp: if excp.message == "Message is not modified": pass elif excp.message == "Query_id_invalid": pass elif excp.message == "Message can't be deleted": pass else: LOGGER.exception("Exception in help buttons. %s", str(query.data))
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 setlog(bot: Bot, update: Update): message = update.effective_message # type: Optional[Message] chat = update.effective_chat # type: Optional[Chat] if chat.type == chat.CHANNEL: message.reply_text( tld( chat.id, "Now, forward the /setlog to the group you want to tie this channel to!" )) elif message.forward_from_chat: sql.set_chat_log_channel(chat.id, message.forward_from_chat.id) try: message.delete() except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception( "Error deleting message in log channel. Should work anyway though." ) try: bot.send_message( message.forward_from_chat.id, tld( chat.id, "This channel has been set as the log channel for {}." ).format(chat.title or chat.first_name)) except Unauthorized as excp: if excp.message == "Forbidden: bot is not a member of the channel chat": bot.send_message( chat.id, tld(chat.id, "Successfully set log channel!")) else: LOGGER.exception("ERROR in setting the log channel.") bot.send_message(chat.id, tld(chat.id, "Successfully set log channel!")) else: message.reply_text( tld( chat.id, "*The steps to set a log channel are:*\n" " • add bot to the desired channel\n" " • send /setlog to the channel\n" " • forward the /setlog to the group\n"), ParseMode.MARKDOWN)
def sban(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] update.effective_message.delete() 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": return "" else: raise if is_user_ban_protected(chat, user_id, member): return "" if user_id == bot.id: return "" log = "<b>{}:</b>" \ "\n# SILENTBAN" \ "\n<b>• Admin:</b> {}" \ "\n<b>• User:</b> {}" \ "\n<b>• ID:</b> <code>{}</code>".format(html.escape(chat.title), mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name), user_id) if reason: log += "\n<b>• Reason:</b> {}".format(reason) try: chat.kick_member(user_id) return log except BadRequest as excp: if excp.message == "Reply message not found": 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) return ""
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 del_blacklist_url(bot: Bot, update: Update): chat = update.effective_chat message = update.effective_message parsed_entities = message.parse_entities(types=["url"]) extracted_domains = [] for obj, url in parsed_entities.items(): extract_url = tldextract.extract(url) extracted_domains.append(extract_url.domain + "." + extract_url.suffix) for url in sql.get_blacklisted_urls(chat.id): if url in extracted_domains: try: message.delete() except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception("Error while deleting blacklist message.") break
def del_blacklist(bot: Bot, update: Update): chat = update.effective_chat # type: Optional[Chat] message = update.effective_message # type: Optional[Message] to_match = extract_text(message) if not to_match: return 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: message.delete() except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception("Error while deleting blacklist message.") break
def log_action(bot: Bot, update: Update, *args, **kwargs): result = func(bot, update, *args, **kwargs) chat = update.effective_chat # type: Optional[Chat] message = update.effective_message # type: Optional[Message] if result: if chat.type == chat.SUPERGROUP and chat.username: result += "\n<b>Link:</b> " \ "<a href=\"http://telegram.me/{}/{}\">click here</a>".format(chat.username, message.message_id) log_chat = sql.get_chat_log_channel(chat.id) if log_chat: send_log(bot, log_chat, chat.id, result) elif result == "": pass else: LOGGER.warning( "%s was set as loggable, but had no return statement.", func) return result
def user_join_fed(bot: Bot, update: Update, args: List[str]): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] msg = update.effective_message # type: Optional[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("I cannot extract users from this message") 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("Why are you trying to promote a federation owner?") return if getuser: update.effective_message.reply_text("I cannot promote users who are already federation admins! But I can remove them if you want!") return if user_id == bot.id: update.effective_message.reply_text("I already am a federation admin in all federations!") return res = sql.user_join_fed(fed_id, user_id) if res: update.effective_message.reply_text("Successfully Promoted!") else: update.effective_message.reply_text("Failed to promote!") else: update.effective_message.reply_text("Only federation owners can do this!")
def user_demote_fed(bot: Bot, update: Update, args: List[str]): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] fed_id = sql.get_fed_id(chat.id) if is_user_fed_owner(fed_id, user.id): msg = update.effective_message # type: Optional[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("I cannot extract users from this message") return else: LOGGER.warning('error') if user_id == bot.id: update.effective_message.reply_text("Are you trying to demote me as a federation admin? Do you think I am stupid?") return if sql.search_user_in_fed(fed_id, user_id) == False: update.effective_message.reply_text("I cannot demote people who are not federation admins!") return res = sql.user_demote_fed(fed_id, user_id) if res == True: update.effective_message.reply_text("Get out of here!") else: update.effective_message.reply_text("Demotion failed!") else: update.effective_message.reply_text("Only federation owners can do this!") return
def send_log(bot: Bot, log_chat_id: str, orig_chat_id: str, result: str): try: bot.send_message(log_chat_id, result, parse_mode=ParseMode.HTML) except BadRequest as excp: if excp.message == "Chat not found": bot.send_message( orig_chat_id, "This log channel has been deleted - unsetting.") sql.stop_chat_logging(orig_chat_id) else: LOGGER.warning(excp.message) LOGGER.warning(result) LOGGER.exception("Could not parse") bot.send_message( log_chat_id, result + "\n\nFormatting has been disabled due to an unexpected error." )
def report(bot: Bot, update: Update) -> str: message = update.effective_message # type: Optional[Message] chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] if chat and message.reply_to_message and sql.chat_should_report(chat.id): reported_user = message.reply_to_message.from_user # type: Optional[User] chat_name = chat.title or chat.first or chat.username admin_list = chat.get_administrators() #if reported_user == "483808054": # continue # #if user.id == "435606081": # continue if chat.username and chat.type == Chat.SUPERGROUP: msg = "<b>{}:</b>" \ "\n<b>Reported user:</b> {} (<code>{}</code>)" \ "\n<b>Reported by:</b> {} (<code>{}</code>)".format(html.escape(chat.title), mention_html( reported_user.id, reported_user.first_name), reported_user.id, mention_html(user.id, user.first_name), user.id) link = "\n<b>Link:</b> " \ "<a href=\"http://telegram.me/{}/{}\">click here</a>".format(chat.username, message.message_id) should_forward = True keyboard = [[ InlineKeyboardButton( u"➡ Message", url="https://t.me/{}/{}".format( chat.username, str(message.reply_to_message.message_id))) ], [ InlineKeyboardButton( u"⚠ Kick", callback_data="report_{}=kick={}={}".format( chat.id, reported_user.id, reported_user.first_name)), InlineKeyboardButton( u"⛔️ Ban", callback_data="report_{}=banned={}={}".format( chat.id, reported_user.id, reported_user.first_name)) ], [ InlineKeyboardButton( u"❎ Delete Message", callback_data="report_{}=delete={}={}".format( chat.id, reported_user.id, message.reply_to_message.message_id)) ]] reply_markup = InlineKeyboardMarkup(keyboard) else: msg = "{} is calling for admins in \"{}\"!".format( mention_html(user.id, user.first_name), html.escape(chat_name)) link = "" should_forward = True for admin in admin_list: if admin.user.is_bot: # can't message bots continue if sql.user_should_report(admin.user.id): try: if not chat.type == Chat.SUPERGROUP: bot.send_message(admin.user.id, msg + link, parse_mode=ParseMode.HTML) if should_forward: message.reply_to_message.forward(admin.user.id) if len( message.text.split() ) > 1: # If user is giving a reason, send his message too message.forward(admin.user.id) if not chat.username: bot.send_message(admin.user.id, msg + link, parse_mode=ParseMode.HTML) if should_forward: message.reply_to_message.forward(admin.user.id) if len( message.text.split() ) > 1: # If user is giving a reason, send his message too message.forward(admin.user.id) if chat.username and chat.type == Chat.SUPERGROUP: bot.send_message(admin.user.id, msg + link, parse_mode=ParseMode.HTML, reply_markup=reply_markup) if should_forward: message.reply_to_message.forward(admin.user.id) if len( message.text.split() ) > 1: # If user is giving a reason, send his message too message.forward(admin.user.id) except Unauthorized: pass except BadRequest as excp: # TODO: cleanup exceptions LOGGER.exception("Exception while reporting user") message.reply_to_message.reply_text( "{} reported the message to the admins.".format( mention_html(user.id, user.first_name)), parse_mode=ParseMode.HTML) return msg return ""
def unfban(bot: Bot, update: Update, args: List[str]): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] message = update.effective_message # type: Optional[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 info = sql.get_fed_info(fed_id) if is_user_fed_admin(fed_id, user.id) == 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 == False: message.reply_text("This user is not fbanned!") return banner = update.effective_user # type: Optional[User] 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) """ bot.send_message(chat, "<b>Un-FedBan</b>" \ "\n<b>Federation:</b> {}" \ "\n<b>Federation Admin:</b> {}" \ "\n<b>User:</b> {}" \ "\n<b>User ID:</b> <code>{}</code>".format(info['fname'], mention_html(user.id, user.first_name), mention_html(user_chat.id, user_chat.first_name), user_chat.id), parse_mode="HTML") """ 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: pass message.reply_text("This person is un-fbanned.") FEDADMIN = sql.all_fed_users(fed_id)
def fed_ban(bot: Bot, update: Update, args: List[str]): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[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) == False: update.effective_message.reply_text("Only federation admins can do this!") return message = update.effective_message # type: Optional[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 kicking the group creator? Self sacrifice.") return if is_user_fed_owner(fed_id, user_id) == True: message.reply_text("Why did you try the federation fban?") return if is_user_fed_admin(fed_id, user_id) == 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 block my master, that's a very stupid idea!") return if int(user_id) in SUDO_USERS: message.reply_text("I will not use sudo fban!") return if int(user_id) in WHITELIST_USERS: message.reply_text("This person is whitelisted, so they can't be fban!") 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 fban is 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 fedban!") 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, contact @onepunchsupport.") 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 on {} 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, contact @onepunchsupport.") 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")
from obsq.modules.disable import DisableAbleCommandHandler import obsq.modules.sql.feds_sql as sql # Hello bot owner, I spended for feds many hours of my life. # Federation by MrYacha 2018-2019 # Federation rework by Mizukito Akito 2019 # Federation update v2 by Ayra Hikari 2019 # # Time spended on feds = 10h by #MrYacha # Time spended on reworking on the whole feds = 22+ hours by @obsquriel # Time spended on updating version to v2 = 26+ hours by @obsquriel # # Total spended for making this features is 68+ hours LOGGER.info("I am @obsquriel on Telegram.") FBAN_ERRORS = { "User is an administrator of the chat", "Chat not found", "Not enough rights to restrict/unrestrict chat member", "User_not_participant", "Peer_id_invalid", "Group chat was deactivated", "Need to be inviter of a user to kick it from a basic group", "Chat_admin_required", "Only the creator of a basic group can kick group administrators", "Channel_private", "Not in the chat", "Have no rights to send a message"
def get(bot, update, notename, show_none=True, no_format=False): chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] conn = connected(bot, update, chat, user.id, need_admin=False) if conn: chat_id = conn send_id = user.id else: chat_id = update.effective_chat.id send_id = chat_id note = sql.get_note(chat_id, notename) message = update.effective_message # type: Optional[Message] if note: # If we're replying to a message, reply to that message (unless it's an error) if message.reply_to_message: reply_id = message.reply_to_message.message_id else: reply_id = message.message_id if note.is_reply: if MESSAGE_DUMP: try: bot.forward_message(chat_id=chat_id, from_chat_id=MESSAGE_DUMP, message_id=note.value) except BadRequest as excp: if excp.message == "Message to forward not found": message.reply_text( "This message seems to have been lost - I'll remove it " "from your notes list.") sql.rm_note(chat_id, notename) else: raise else: try: bot.forward_message(chat_id=chat_id, from_chat_id=chat_id, message_id=note.value) except BadRequest as excp: if excp.message == "Message to forward not found": message.reply_text( "Looks like the original sender of this note has deleted " "their message - sorry! Get your bot admin to start using a " "message dump to avoid this. I'll remove this note from " "your saved notes.") sql.rm_note(chat_id, notename) else: raise else: text = note.value keyb = [] parseMode = ParseMode.MARKDOWN buttons = sql.get_buttons(chat_id, notename) if no_format: parseMode = None text += revert_buttons(buttons) else: keyb = build_keyboard(buttons) keyboard = InlineKeyboardMarkup(keyb) try: if note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT): try: bot.send_message(send_id, text, reply_to_message_id=reply_id, parse_mode=parseMode, disable_web_page_preview=True, reply_markup=keyboard) except BadRequest as excp: if excp.message == "Wrong http url": failtext = "The URL on the button is invalid! Please update this note!" failtext += "\n\n```\n{}```".format( note.value + revert_buttons(buttons)) message.reply_text(failtext, parse_mode="markdown") print("Gagal mengirim catatan: " + excp.message) pass else: ENUM_FUNC_MAP[note.msgtype](send_id, note.file, caption=text, reply_to_message_id=reply_id, parse_mode=parseMode, disable_web_page_preview=True, reply_markup=keyboard) except BadRequest as excp: if excp.message == "Entity_mention_user_invalid": message.reply_text( "Looks like you tried to mention someone I've never seen before. If you really " "want to mention them, forward one of their messages to me, and I'll be able " "to tag them!") elif FILE_MATCHER.match(note.value): message.reply_text( "This note was an incorrectly imported file from another bot - I can't use " "it. If you really need it, you'll have to save it again. In " "the meantime, I'll remove it from your notes list.") sql.rm_note(chat_id, notename) else: message.reply_text( "This note could not be sent, as it is incorrectly formatted, Please ask in @HarukaAyaGroup if you can't figure out why!" ) LOGGER.exception("Could not parse message #%s in chat %s", notename, str(chat_id)) LOGGER.warning("Message was: %s", str(note.value)) return elif show_none: message.reply_text("This note doesn't exist")
def settings_button(bot: Bot, update: Update): query = update.callback_query user = update.effective_user chatP = update.effective_chat # type: Optional[Chat] mod_match = re.match(r"stngs_module\((.+?),(.+?)\)", query.data) prev_match = re.match(r"stngs_prev\((.+?),(.+?)\)", query.data) next_match = re.match(r"stngs_next\((.+?),(.+?)\)", query.data) back_match = re.match(r"stngs_back\((.+?)\)", query.data) try: if mod_match: chat_id = mod_match.group(1) module = mod_match.group(2) chat = bot.get_chat(chat_id) text = "*{}* has the following settings for the *{}* module:\n\n".format(escape_markdown(chat.title), CHAT_SETTINGS[ module].__mod_name__) + \ CHAT_SETTINGS[module].__chat_settings__(bot, update, chat, chatP, user) query.message.reply_text( text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( text="Back", callback_data="stngs_back({})".format(chat_id)) ]])) elif prev_match: chat_id = prev_match.group(1) curr_page = int(prev_match.group(2)) chat = bot.get_chat(chat_id) query.message.reply_text(tld( user.id, "send-group-settings").format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules(curr_page - 1, 0, CHAT_SETTINGS, "stngs", chat=chat_id))) elif next_match: chat_id = next_match.group(1) next_page = int(next_match.group(2)) chat = bot.get_chat(chat_id) query.message.reply_text(tld( user.id, "send-group-settings").format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules(next_page + 1, 0, CHAT_SETTINGS, "stngs", chat=chat_id))) elif back_match: chat_id = back_match.group(1) chat = bot.get_chat(chat_id) query.message.reply_text(text=tld(user.id, "send-group-settings").format( escape_markdown(chat.title)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules(user.id, 0, CHAT_SETTINGS, "stngs", chat=chat_id))) # ensure no spinny white circle bot.answer_callback_query(query.id) query.message.delete() except BadRequest as excp: if excp.message == "Message is not modified": pass elif excp.message == "Query_id_invalid": pass elif excp.message == "Message can't be deleted": pass else: LOGGER.exception("Exception in settings buttons. %s", str(query.data))
def error_callback(bot, update, error): try: raise error except Unauthorized: LOGGER.warning(error) # remove update.message.chat_id from conversation list except BadRequest: LOGGER.warning(error) # handle malformed requests - read more below! except TimedOut: LOGGER.warning("NO NONO3") # handle slow connection problems except NetworkError: LOGGER.warning("NO NONO4") # handle other connection problems except ChatMigrated as err: LOGGER.warning(err) # the chat_id of a group has changed, use e.new_chat_id instead except TelegramError: LOGGER.warning(error)
# Stop processing with any other handler. except DispatcherHandlerStop: self.logger.debug( 'Stopping further handlers due to DispatcherHandlerStop') break # Dispatch any error. except TelegramError as te: self.logger.warning( 'A TelegramError was raised while processing the Update') try: self.dispatch_error(update, te) except DispatcherHandlerStop: self.logger.debug('Error handler stopped further handlers') break except Exception: self.logger.exception( 'An uncaught error was raised while handling the error') # Errors should not stop the thread. except Exception: self.logger.exception( 'An uncaught error was raised while processing the update') if __name__ == '__main__': LOGGER.info("Successfully loaded modules: " + str(ALL_MODULES)) LOGGER.info("Successfully loaded") main()
from obsq import dispatcher, LOGGER from obsq.__main__ import GDPR from obsq.__main__ import STATS, USER_INFO from obsq.modules.disable import DisableAbleCommandHandler from obsq.modules.helper_funcs.extraction import extract_user from obsq.modules.helper_funcs.filters import CustomFilters from requests import get # DO NOT DELETE THIS, PLEASE. # Made by @obsquriel on GitHub and Telegram. # This module was inspired by @RealAkito. # None of the code is taken from the bot itself, to avoid any more confusion. LOGGER.info("Original Android Modules by @obsquriel on Telegram") @run_async def havoc(bot: Bot, update: Update): message = update.effective_message device = message.text[len('/havoc '):] fetch = get( f'https://raw.githubusercontent.com/Havoc-Devices/android_vendor_OTA/pie/{device}.json' ) if device == '': reply_text = "Please type your device **codename** into it!\nFor example, `/havoc tissot`" message.reply_text(reply_text, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True)
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, "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(tld(chat.id, "I can't seem to find this user")) return "" else: raise if user_id == bot.id: message.reply_text( tld(chat.id, "I'm not gonna BAN myself, are you crazy?")) return "" if is_user_ban_protected(chat, user_id, member): message.reply_text( tld( chat.id, "Why would I ban an admin? That sounds like a pretty dumb idea." )) return "" log = "<b>{}:</b>" \ "\n#BANNED" \ "\n<b>• Admin:</b> {}" \ "\n<b>• User:</b> {}" \ "\n<b>• ID:</b> <code>{}</code>".format(html.escape(chat.title), mention_html(user.id, user.first_name), mention_html(member.user.id, member.user.first_name), user_id) reply = "{} has been banned!".format( mention_html(member.user.id, member.user.first_name)) if reason: log += "\n<b>Reason:</b> {}".format(reason) try: chat.kick_member(user_id) #bot.send_sticker(chat.id, BAN_STICKER) # banhammer marie sticker message.reply_text(tld(chat.id, "Banned!")) return log except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply #bot.send_sticker(chat.id, BAN_STICKER) # banhammer marie sticker message.reply_text(tld(chat.id, "Banned!"), quote=False) 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, "Well damn, I can't ban that user.")) return ""
def temp_nomedia(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] conn = connected(bot, update, chat, user.id) if not conn == False: chatD = dispatcher.bot.getChat(conn) else: if chat.type == "private": exit(1) else: chatD = chat user_id, reason = extract_user_and_text(message, args) if not user_id: message.reply_text( tld(chat.id, "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(tld(chat.id, "I can't seem to find this user")) return "" else: raise if is_user_admin(chat, user_id, member): message.reply_text( tld(chat.id, "I really wish I could restrict admins...")) return "" if user_id == bot.id: message.reply_text( tld(chat.id, "I'm not gonna RESTRICT myself, are you crazy?")) return "" if not reason: message.reply_text( tld(chat.id, "You haven't specified a time to restrict 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 RESTRICTED" \ "\n<b>• Admin:</b> {}" \ "\n<b>• User:</b> {}" \ "\n<b>• ID:</b> <code>{}</code>" \ "\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), user_id, time_val) if reason: log += "\n<b>• Reason:</b> {}".format(reason) try: if member.can_send_messages is None or member.can_send_messages: bot.restrict_chat_member(chat.id, user_id, until_date=mutetime, can_send_messages=True, can_send_media_messages=False, can_send_other_messages=False, can_add_web_page_previews=False) message.reply_text( tld(chat.id, "Restricted from sending media for {} in {}!").format( time_val, chatD.title)) return log else: message.reply_text( tld(chat.id, "This user is already restricted in {}.").format( chatD.title)) except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text(tld(chat.id, "Restricted for {} in {}!").format( time_val, chatD.title), 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( tld(chat.id, "Well damn, I can't restrict that user.")) return ""
def import_data(bot: Bot, update): msg = update.effective_message # type: Optional[Message] chat = update.effective_chat # type: Optional[Chat] user = update.effective_user # type: Optional[User] # TODO: allow uploading doc with command, not just as reply # only work with a doc conn = connected(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_message.reply_text( "This command can only be runned on group, not PM.") return "" chat = update.effective_chat chat_id = update.effective_chat.id chat_name = update.effective_message.chat.title if msg.reply_to_message and msg.reply_to_message.document: try: file_info = bot.get_file(msg.reply_to_message.document.file_id) except BadRequest: msg.reply_text( "Try downloading and uploading the file yourself again, This one seem broken!" ) return with BytesIO() as file: file_info.download(out=file) file.seek(0) data = json.load(file) # only import one group if len(data) > 1 and str(chat.id) not in data: msg.reply_text( "There are more than one group in this file and the chat.id is not same! How am i supposed to import it?" ) return # Check if backup is this chat try: if data.get(str(chat.id)) == None: if conn: text = "Backup comes from another chat, I can't return another chat to chat *{}*".format( chat_name) else: text = "Backup comes from another chat, I can't return another chat to this chat" return msg.reply_text(text, parse_mode="markdown") except: return msg.reply_text( "There is problem while importing the data!.") # Check if backup is from self try: if str(bot.id) != str(data[str(chat.id)]['bot']): return msg.reply_text( "Backup from another bot that is not suggested might cause the problem, documents, photos, videos, audios, records might not work as it should be. However, You can still request a feature regarding this in @HarukaAyaGroup !" ) except: pass # Select data source if str(chat.id) in data: data = data[str(chat.id)]['hashes'] else: data = data[list(data.keys())[0]]['hashes'] try: for mod in DATA_IMPORT: mod.__import_data__(str(chat.id), data) except Exception: msg.reply_text( "An error occurred while recovering your data. The process failed. If you experience a problem with this, please ask in @HarukaAyaGroup . My owner and community will be happy to help. Also, bugs report makes me even better!\nThank you!" ) LOGGER.exception("Imprt for the chat %s with the name %s failed.", str(chat.id), str(chat.title)) return # TODO: some of that link logic # NOTE: consider default permissions stuff? if conn: text = "Backup fully restored on *{}*.".format(chat_name) else: text = "Backup fully restored" msg.reply_text(text, parse_mode="markdown")
def temp_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, "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(tld(chat.id, "I can't seem to find this user")) return "" else: raise if is_user_ban_protected(chat, user_id, member): message.reply_text( tld( chat.id, "This user is ban protected, meaning that you cannot ban this user!" )) return "" if user_id == bot.id: message.reply_text( tld(chat.id, "I'm not gonna BAN myself, are you crazy?")) return "" if not reason: message.reply_text( tld(chat.id, "You haven't specified a time to ban 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 = "" bantime = extract_time(message, time_val) if not bantime: return "" log = "<b>{}:</b>" \ "\n#TEMP BANNED" \ "\n<b>Admin:</b> {}" \ "\n<b>User:</b> {} (<code>{}</code>)" \ "\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), member.user.id, time_val) if reason: log += "\n<b>Reason:</b> {}".format(reason) try: chat.kick_member(user_id, until_date=bantime) #bot.send_sticker(chat.id, BAN_STICKER) # banhammer marie sticker message.reply_text( "Banned! User will be banned for {}.".format(time_val)) return log except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply #bot.send_sticker(chat.id, BAN_STICKER) # banhammer marie sticker message.reply_text( tld(chat.id, "Banned! User will be banned for {}.").format(time_val), quote=False) 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, "Well damn, I can't ban that user.")) return ""