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 spongemocktext(bot: Bot, update: Update, args: List[str]): message = update.effective_message chat = update.effective_chat noreply = False if message.reply_to_message: data = message.reply_to_message.text elif args: noreply = True data = message.text.split(None, 1)[1] else: noreply = True data = tld(chat.id, "memes_no_message") if not Path('images/bob.jpg').is_file(): LOGGER.warning( "images/bob.jpg not found! Spongemock memes module is turned off!") return for mocked in glob.glob("images/mocked*"): os.remove(mocked) reply_text = spongemock.mock(data) randint = random.randint(1, 699) magick = """convert images/bob.jpg -font Impact -pointsize 30 -size 512x300 -stroke black -strokewidth 1 -fill white -background none -gravity north caption:"{}" -flatten images/mocked{}.jpg""".format( reply_text, randint) os.system(magick) with open('images/mocked{}.jpg'.format(randint), 'rb') as mockedphoto: if noreply: message.reply_photo(photo=mockedphoto, reply=message.reply_to_message) else: message.reply_to_message.reply_photo( photo=mockedphoto, reply=message.reply_to_message) os.remove('images/mocked{}.jpg'.format(randint))
async def emailPhase(message): user = message.from_user LOGGER.info(f"Email from : {user.id} | {user.first_name}") if not await isUserMember(user.id): return await message.reply("press /start first.") if await isUserInDb(user.id): return await message.reply( f"You already have access to the drives, for any queries join {config.get('group_link')} and seek admins assistance" ) email_id = message.text out = "" out += f"<b>FirstName:</b> <code>{user.first_name}</code>\n" if user.last_name: out += f"<b>LastName:</b> <code>{user.last_name}</code>\n" if user.username: out += f"<b>UserName:</b> @{user.username}\n" out += f"<b>UserId:</b> <code>{user.id}</code>\n" out += f"<b>EmailId:</b> <code>{email_id}</code>\n" out += f"<b>Link:</b> <a href='tg://user?id={user.id}'>here</a>" await bot.send_message(config.get('admin_chat'), out) await addAccessUser(user.id, email_id) await message.reply( "Aight, we received your application now be patient and wait for approval (approval process take upto a week)." )
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 __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 bannedUserFilter(message): banned = isUserBanned(message.from_user.id) if banned: LOGGER.info( f"Message from banned user: {message.from_user.id} : {message.from_user.first_name}" ) return not banned
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 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 ""
async def getAllBannedUsers(): users = [] try: async for user in bannedUserDb.find({}): LOGGER.info(f"Adding {user.userId} in banned.") users.append(user.userId) except Exception as e: LOGGER.error(e) return users
async def isUserMember(userId): LOGGER.info(f"Checking if {userId} is in our kholi!") try: member = await bot.get_chat_member(config.get("base_chat"),userId) if member.status == "left" or member.status == "kicked": return False except Exception as e: LOGGER.error(e) return False return True
async def startPhase(message): user = message.from_user LOGGER.info(f"Start from : {user.id} | {user.first_name}") if not await isUserMember(user.id): return await message.reply( f"Join my group first : {config.get('group_link')}") if await isUserInDb(user.id): return await message.reply( f"You already have access to the drives, for any queries join {config.get('group_link')} and seek admins assistance" ) await message.reply("Send your EMAIL-ID.")
def rest_handler(bot: Bot, update: Update): msg = update.effective_message chat = update.effective_chat for restriction, filter in RESTRICTION_TYPES.items(): if filter(msg) and sql.is_restr_locked( chat.id, restriction) and can_delete(chat, bot.id): try: msg.delete() except BadRequest as excp: if excp.message == "Message to delete not found": pass else: LOGGER.exception("ERROR in restrictions") break
def get_help(bot: Bot, update: Update): chat = update.effective_chat args = update.effective_message.text.split(None, 1) # ONLY send help in PM if chat.type != chat.PRIVATE: update.effective_message.reply_text( tld(chat.id, 'help_pm_only'), reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton(text=tld(chat.id, 'btn_help'), url="t.me/{}?start=help".format( bot.username)) ]])) return if len(args) >= 2: mod_name = None for x in HELPABLE: if args[1].lower() == HELPABLE[x].lower(): mod_name = tld(chat.id, "modname_" + x).strip() module = x break if mod_name: help_txt = tld(chat.id, module + "_help") if not help_txt: LOGGER.exception(f"Help string for {module} not found!") text = tld(chat.id, "here_is_help").format(mod_name, help_txt) send_help( chat.id, text, InlineKeyboardMarkup([[ InlineKeyboardButton(text=tld(chat.id, "btn_go_back"), callback_data="help_back") ]])) return update.effective_message.reply_text(tld( chat.id, "help_not_found").format(args[1]), parse_mode=ParseMode.HTML) return send_help( chat.id, tld(chat.id, "send-help").format(dispatcher.bot.first_name, tld(chat.id, "cmd_multitrigger")))
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 help_button(bot: Bot, update: Update): query = update.callback_query chat = update.effective_chat back_match = re.match(r"help_back", query.data) mod_match = re.match(r"help_module\((.+?)\)", query.data) try: if mod_match: module = mod_match.group(1) mod_name = tld(chat.id, "modname_" + module).strip() help_txt = tld( chat.id, module + "_help") # tld_help(chat.id, HELPABLE[module].__mod_name__) if not help_txt: LOGGER.exception(f"Help string for {module} not found!") text = tld(chat.id, "here_is_help").format(mod_name, help_txt) bot.edit_message_text(chat_id=query.message.chat_id, message_id=query.message.message_id, text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( text=tld(chat.id, "btn_go_back"), callback_data="help_back") ]]), disable_web_page_preview=True) elif back_match: bot.edit_message_text(chat_id=query.message.chat_id, message_id=query.message.message_id, text=tld(chat.id, "send-help").format( dispatcher.bot.first_name, tld(chat.id, "cmd_multitrigger")), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules(chat.id, 0, HELPABLE, "help")), disable_web_page_preview=True) # ensure no spinny white circle bot.answer_callback_query(query.id) # query.message.delete() except BadRequest: pass
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 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 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 = tld(chat.id, "bans_sban_logger").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 += tld(chat.id, "bans_logger_reason").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 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) == 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 == 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
def del_blacklist(bot: Bot, update: Update): chat = update.effective_chat message = update.effective_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): try: result = func(bot, update, *args, **kwargs) except Exception: return 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 += tld(chat.id, "log_channel_link").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 tld_list(chat_id, t): LANGUAGE = prev_locale(chat_id) if LANGUAGE: LOCALE = LANGUAGE.locale_name if LOCALE in ('en-US') and t in strings['en-US']: return strings['en-US'][t] elif LOCALE in ('en-GB') and t in strings['en-GB']: return strings['en-GB'][t] elif LOCALE in ('id') and t in strings['id']: return strings['id'][t] elif LOCALE in ('ru') and t in strings['ru']: return strings['ru'][t] elif LOCALE in ('tr') and t in strings['tr']: return strings['tr'][t] if t in strings['en-US']: return strings['en-US'][t] LOGGER.warning(f"#NOSTR No string found for {t}.") return f"No string found for {t}.\nReport it in @tgbotAyaGroup."
def tld(chat_id, t, show_none=True): LANGUAGE = prev_locale(chat_id) if LANGUAGE: LOCALE = LANGUAGE.locale_name if LOCALE in ('en-US') and t in strings['en-US']: result = decode( encode(strings['en-US'][t], 'latin-1', 'backslashreplace'), 'unicode-escape') return result elif LOCALE in ('en-GB') and t in strings['en-GB']: result = decode( encode(strings['en-GB'][t], 'latin-1', 'backslashreplace'), 'unicode-escape') return result elif LOCALE in ('id') and t in strings['id']: result = decode( encode(strings['id'][t], 'latin-1', 'backslashreplace'), 'unicode-escape') return result elif LOCALE in ('ru') and t in strings['ru']: result = decode( encode(strings['ru'][t], 'latin-1', 'backslashreplace'), 'unicode-escape') return result elif LOCALE in ('tr') and t in strings['tr']: result = decode( encode(strings['tr'][t], 'latin-1', 'backslashreplace'), 'unicode-escape') return result if t in strings['en-US']: result = decode( encode(strings['en-US'][t], 'latin-1', 'backslashreplace'), 'unicode-escape') return result err = f"No string found for {t}.\nReport it in @tgbotAyaGroup." LOGGER.warning(err) return err
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") migrate_handler = MessageHandler(Filters.status_update.migrate, migrate_chats) # dispatcher.add_handler(test_handler) dispatcher.add_handler(start_handler) dispatcher.add_handler(start_callback_handler) dispatcher.add_handler(help_handler) dispatcher.add_handler(help_callback_handler) dispatcher.add_handler(migrate_handler) # dispatcher.add_error_handler(error_callback) # add antiflood processor Dispatcher.process_update = process_update 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) LOGGER.info("Successfully loaded") if len(argv) not in (1, 3, 4): tbot.disconnect() else: tbot.run_until_disconnected() updater.idle()
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, "log_channel_fwd_cmd")) 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, "log_channel_chn_curr_conf").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, "log_channel_link_success")) else: LOGGER.exception("ERROR in setting the log channel.") bot.send_message(chat.id, tld(chat.id, "log_channel_link_success")) else: message.reply_text(tld(chat.id, "log_channel_invalid_message"), ParseMode.MARKDOWN)
async def addBanUser(userId): LOGGER.info(f"Banning User: {userId}") try: result = await bannedUserDb.insert_one({"userId": userId}) LOGGER.info(result) except Exception as e: LOGGER.error(e) return False BANNED_USERS.append(userId) return True
async def removeBanUser(userId): LOGGER.info(f"UnBanning User: {userId}") try: result = await bannedUserDb.delete_one({"userId": userId}) LOGGER.info(result) except Exception as e: LOGGER.error(e) return False BANNED_USERS.remove(userId) return True
async def isUserInDb(userId): LOGGER.info(f"Checking {userId} in db") try: result = await accessUserDb.find_one({"userId": userId}) LOGGER.info(result) if result is None: return False except Exception as e: LOGGER.error(e) return False return True
async def addAccessUser(userId, email): LOGGER.info(f"Adding {userId} : {email}") try: result = await accessUserDb.insert_one({ "userId": userId, "email": email }) LOGGER.info(result) except Exception as e: LOGGER.error(e) return False return True