def control_panel(bot, update): LOGGER.info("Control panel") chat = update.effective_chat user = update.effective_user # ONLY send help in PM if chat.type != chat.PRIVATE: update.effective_message.reply_text( "Contact me in PM to access the control panel.", reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton( text="Control Panel", url=f"t.me/{bot.username}?start=controlpanel") ]])) return #Support to run from command handler query = update.callback_query if query: query.message.delete() M_match = re.match(r"cntrl_panel_M", query.data) U_match = re.match(r"cntrl_panel_U", query.data) G_match = re.match(r"cntrl_panel_G", query.data) back_match = re.match(r"help_back", query.data) LOGGER.info(query.data) else: M_match = "ThaNos is the best bot" #LMAO, don't uncomment if M_match: text = "*Control panel* 🛠" keyboard = [[ InlineKeyboardButton(text="👤 My settings", callback_data="cntrl_panel_U(1)") ]] #Show connected chat and add chat settings button conn = connected(bot, update, chat, user.id, need_admin=False) if conn: chatG = bot.getChat(conn) #admin_list = chatG.get_administrators() #Unused variable #If user admin member = chatG.get_member(user.id) if member.status in ('administrator', 'creator'): text += f"\nConnected chat - *{chatG.title}* (you {member.status})" keyboard += [[ InlineKeyboardButton(text="👥 Group settings", callback_data="cntrl_panel_G_back") ]] elif user.id in SUDO_USERS: text += f"\nConnected chat - *{chatG.title}* (you sudo)" keyboard += [[ InlineKeyboardButton(text="👥 Group settings (SUDO)", callback_data="cntrl_panel_G_back") ]] else: text += f"\nConnected chat - *{chatG.title}* (you aren't an admin!)" else: text += "\nNo chat connected!" keyboard += [[ InlineKeyboardButton(text="Back", callback_data="bot_start") ]] update.effective_message.reply_text( text, reply_markup=InlineKeyboardMarkup(keyboard), parse_mode=ParseMode.MARKDOWN) elif U_match: mod_match = re.match(r"cntrl_panel_U_module\((.+?)\)", query.data) back_match = re.match(r"cntrl_panel_U\((.+?)\)", query.data) chatP = update.effective_chat # type: Optional[Chat] if mod_match: module = mod_match.group(1) R = CHAT_SETTINGS[module].__user_settings__(bot, update, user) text = "You has the following settings for the *{}* module:\n\n".format( CHAT_SETTINGS[module].__mod_name__) + R[0] keyboard = R[1] keyboard += [[ InlineKeyboardButton(text="Back", callback_data="cntrl_panel_U(1)") ]] query.message.reply_text( text=text, arse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(keyboard)) elif back_match: text = "*User control panel* 🛠" query.message.reply_text(text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules( user.id, 0, USER_SETTINGS, "cntrl_panel_U"))) elif G_match: mod_match = re.match(r"cntrl_panel_G_module\((.+?)\)", query.data) prev_match = re.match(r"cntrl_panel_G_prev\((.+?)\)", query.data) next_match = re.match(r"cntrl_panel_G_next\((.+?)\)", query.data) back_match = re.match(r"cntrl_panel_G_back", query.data) chatP = chat conn = connected(bot, update, chat, user.id) if not conn == False: chat = bot.getChat(conn) else: query.message.reply_text(text="Error with connection to chat") exit(1) if mod_match: module = mod_match.group(1) R = CHAT_SETTINGS[module].__chat_settings__( bot, update, chat, chatP, user) if type(R) is list: text = R[0] keyboard = R[1] else: text = R keyboard = [] text = "*{}* has the following settings for the *{}* module:\n\n".format( escape_markdown(chat.title), CHAT_SETTINGS[module].__mod_name__) + text keyboard += [[ InlineKeyboardButton(text="Back", callback_data="cntrl_panel_G_back") ]] query.message.reply_text( text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(keyboard)) 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, "cntrl_panel_G", 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, "cntrl_panel_G", chat=chat_id))) elif back_match: text = "Test" query.message.reply_text(text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( paginate_modules( user.id, 0, CHAT_SETTINGS, "cntrl_panel_G")))
def search(bot, update, session, user): """Handle inline queries for sticker search.""" query = update.inline_query.query.strip() # Also search for closed polls if the `closed_polls` keyword is found closed = False if 'closed_polls' in query: closed = True query = query.replace('closed_polls', '').strip() if query == '': # Just display all polls polls = session.query(Poll) \ .filter(Poll.user == user) \ .filter(Poll.closed.is_(closed)) \ .filter(Poll.created.is_(True)) \ .order_by(Poll.created_at.desc()) \ .all() else: # Find polls with search parameter in name or description polls = session.query(Poll) \ .filter(Poll.user == user) \ .filter(Poll.closed.is_(closed)) \ .filter(Poll.created.is_(True)) \ .filter(or_( Poll.name.ilike(f'%{query}%'), Poll.description.ilike(f'%{query}%'), )) \ .order_by(Poll.created_at.desc()) \ .all() if len(polls) == 0: update.inline_query.answer( [], cache_time=0, is_personal=True, switch_pm_text=i18n.t('inline_query.create_first', locale=user.locale), switch_pm_parameter='inline', ) else: results = [] for poll in polls: text, keyboard = get_poll_text_and_vote_keyboard( session, poll, show_warning=False) if poll.closed: keyboard = InlineKeyboardMarkup([[ InlineKeyboardButton('Please ignore this', callback_data='100') ]]) content = InputTextMessageContent( text, parse_mode='markdown', disable_web_page_preview=True, ) results.append( InlineQueryResultArticle( poll.id, poll.name, description=poll.description, input_message_content=content, reply_markup=keyboard, )) update.inline_query.answer(results, cache_time=0, is_personal=True, switch_pm_text=i18n.t( 'inline_query.create_poll', locale=user.locale), switch_pm_parameter='inline')
def new_member(update: Update, context: CallbackContext): bot, job_queue = context.bot, context.job_queue chat = update.effective_chat user = update.effective_user msg = update.effective_message should_welc, cust_welcome, cust_content, welc_type = sql.get_welc_pref( chat.id) welc_mutes = sql.welcome_mutes(chat.id) human_checks = sql.get_human_checks(user.id, chat.id) new_members = update.effective_message.new_chat_members for new_mem in new_members: welcome_log = None res = None sent = None should_mute = True welcome_bool = True media_wel = False if sw is not None: sw_ban = sw.get_ban(new_mem.id) if sw_ban: return if should_welc: reply = update.message.message_id cleanserv = sql.clean_service(chat.id) # Clean service welcome if cleanserv: try: dispatcher.bot.delete_message(chat.id, update.message.message_id) except BadRequest: pass reply = False # Give the owner a special welcome if new_mem.id == OWNER_ID: update.effective_message.reply_text( "Oh, Genos? Let's get this moving.", reply_to_message_id=reply) welcome_log = (f"{html.escape(chat.title)}\n" f"#USER_JOINED\n" f"Bot Owner just joined the chat") continue # Welcome Devs elif new_mem.id in DEV_USERS: update.effective_message.reply_text( "Whoa! A member of the Heroes Association just joined!", reply_to_message_id=reply, ) continue # Welcome Sudos elif new_mem.id in DRAGONS: update.effective_message.reply_text( "Huh! A Dragon disaster just joined! Stay Alert!", reply_to_message_id=reply, ) continue # Welcome Support elif new_mem.id in DEMONS: update.effective_message.reply_text( "Huh! Someone with a Demon disaster level just joined!", reply_to_message_id=reply, ) continue # Welcome Whitelisted elif new_mem.id in TIGERS: update.effective_message.reply_text( "Oof! A Tiger disaster just joined!", reply_to_message_id=reply) continue # Welcome Tigers elif new_mem.id in WOLVES: update.effective_message.reply_text( "Oof! A Wolf disaster just joined!", reply_to_message_id=reply) continue # Welcome yourself elif new_mem.id == bot.id: creator = None for x in bot.bot.get_chat_administrators( update.effective_chat.id): if x.status == 'creator': creator = x.user break if creator: bot.send_message( JOIN_LOGGER, "#NEW_GROUP\n<b>Group name:</b> {}\n<b>ID:</b> <code>{}</code>\n<b>Creator:</b> <code>{}</code>" .format(html.escape(chat.title), chat.id, html.escape(creator)), parse_mode=ParseMode.HTML) else: bot.send_message( JOIN_LOGGER, "#NEW_GROUP\n<b>Group name:</b> {}\n<b>ID:</b> <code>{}</code>" .format(html.escape(chat.title), chat.id), parse_mode=ParseMode.HTML) update.effective_message.reply_text("Watashi ga kita!", reply_to_message_id=reply) continue else: buttons = sql.get_welc_buttons(chat.id) keyb = build_keyboard(buttons) if welc_type not in (sql.Types.TEXT, sql.Types.BUTTON_TEXT): media_wel = True first_name = ( new_mem.first_name or "PersonWithNoName" ) # edge case of empty name - occurs for some bugs. if cust_welcome: if cust_welcome == sql.DEFAULT_WELCOME: cust_welcome = random.choice( sql.DEFAULT_WELCOME_MESSAGES).format( first=escape_markdown(first_name)) if new_mem.last_name: fullname = escape_markdown( f"{first_name} {new_mem.last_name}") else: fullname = escape_markdown(first_name) count = chat.get_members_count() mention = mention_markdown(new_mem.id, escape_markdown(first_name)) if new_mem.username: username = "******" + escape_markdown(new_mem.username) else: username = mention valid_format = escape_invalid_curly_brackets( cust_welcome, VALID_WELCOME_FORMATTERS) res = valid_format.format( first=escape_markdown(first_name), last=escape_markdown(new_mem.last_name or first_name), fullname=escape_markdown(fullname), username=username, mention=mention, count=count, chatname=escape_markdown(chat.title), id=new_mem.id, ) else: res = random.choice(sql.DEFAULT_WELCOME_MESSAGES).format( first=escape_markdown(first_name)) keyb = [] backup_message = random.choice( sql.DEFAULT_WELCOME_MESSAGES).format( first=escape_markdown(first_name)) keyboard = InlineKeyboardMarkup(keyb) else: welcome_bool = False res = None keyboard = None backup_message = None reply = None # User exceptions from welcomemutes if (is_user_ban_protected(chat, new_mem.id, chat.get_member( new_mem.id)) or human_checks): should_mute = False # Join welcome: soft mute if new_mem.is_bot: should_mute = False if user.id == new_mem.id: if should_mute: if welc_mutes == "soft": bot.restrict_chat_member( chat.id, new_mem.id, permissions=ChatPermissions( can_send_messages=True, can_send_media_messages=False, can_send_other_messages=False, can_invite_users=False, can_pin_messages=False, can_send_polls=False, can_change_info=False, can_add_web_page_previews=False, ), until_date=(int(time.time() + 24 * 60 * 60)), ) if welc_mutes == "strong": welcome_bool = False if not media_wel: VERIFIED_USER_WAITLIST.update({ new_mem.id: { "should_welc": should_welc, "media_wel": False, "status": False, "update": update, "res": res, "keyboard": keyboard, "backup_message": backup_message, } }) else: VERIFIED_USER_WAITLIST.update({ new_mem.id: { "should_welc": should_welc, "chat_id": chat.id, "status": False, "media_wel": True, "cust_content": cust_content, "welc_type": welc_type, "res": res, "keyboard": keyboard, } }) new_join_mem = f'<a href="tg://user?id={user.id}">{html.escape(new_mem.first_name)}</a>' message = msg.reply_text( f"{new_join_mem}, click the button below to prove you're human.\nYou have 120 seconds.", reply_markup=InlineKeyboardMarkup([{ InlineKeyboardButton( text="Yes, I'm human.", callback_data=f"user_join_({new_mem.id})", ) }]), parse_mode=ParseMode.HTML, reply_to_message_id=reply, ) bot.restrict_chat_member( chat.id, new_mem.id, permissions=ChatPermissions( can_send_messages=False, can_invite_users=False, can_pin_messages=False, can_send_polls=False, can_change_info=False, can_send_media_messages=False, can_send_other_messages=False, can_add_web_page_previews=False, ), ) job_queue.run_once( partial(check_not_bot, new_mem, chat.id, message.message_id), 120, name="welcomemute", ) if welcome_bool: if media_wel: sent = ENUM_FUNC_MAP[welc_type]( chat.id, cust_content, caption=res, reply_markup=keyboard, reply_to_message_id=reply, parse_mode="markdown", ) else: sent = send(update, res, keyboard, backup_message) prev_welc = sql.get_clean_pref(chat.id) if prev_welc: try: bot.delete_message(chat.id, prev_welc) except BadRequest: pass if sent: sql.set_clean_welcome(chat.id, sent.message_id) if welcome_log: return welcome_log return (f"{html.escape(chat.title)}\n" f"#USER_JOINED\n" f"<b>User</b>: {mention_html(user.id, user.first_name)}\n" f"<b>ID</b>: <code>{user.id}</code>") return ""
def start(update: Update, context: CallbackContext): args = context.args uptime = get_readable_time((time.time() - StartTime)) if update.effective_chat.type == "private": if len(args) >= 1: if args[0].lower() == "help": send_help(update.effective_chat.id, HELP_STRINGS) elif args[0].lower().startswith("ghelp_"): mod = args[0].lower().split('_', 1)[1] if not HELPABLE.get(mod, False): return send_help( update.effective_chat.id, HELPABLE[mod].__help__, InlineKeyboardMarkup([[ InlineKeyboardButton(text="Back", callback_data="help_back") ]])) elif args[0].lower() == "markdownhelp": IMPORTED["extras"].markdown_help_sender(update) elif args[0].lower() == "disasters": IMPORTED["disasters"].send_disasters(update) elif args[0].lower().startswith("stngs_"): match = re.match("stngs_(.*)", args[0].lower()) chat = dispatcher.bot.getChat(match.group(1)) if is_user_admin(chat, update.effective_user.id): send_settings(match.group(1), update.effective_user.id, False) else: send_settings(match.group(1), update.effective_user.id, True) elif args[0][1:].isdigit() and "rules" in IMPORTED: IMPORTED["rules"].send_rules(update, args[0], from_pm=True) else: first_name = update.effective_user.first_name update.effective_message.reply_animation( AKENOIMG, caption=PM_START_TEXT.format( escape_markdown(first_name), escape_markdown(context.bot.first_name)), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup([ [ InlineKeyboardButton( text="💍 Summon me in your chat 💍", url="t.me/{}?startgroup=true".format( context.bot.username)) ], [ InlineKeyboardButton( text="🦋 Repo 🦋", url= f"https://github.com/riasugremory/AkenoHimejimabot" ), InlineKeyboardButton( text="🦋 Support 🦋", url=f"https://t.me/{SUPPORT_CHAT}"), ] ])) else: update.effective_message.reply_video(AKENOPINGIMG) update.effective_message.reply_text( "Ara Ara! \n<b>Queen in command! since:</b> <code>{}</code>". format(uptime), parse_mode=ParseMode.HTML)
def new_member(bot: Bot, update: Update, job_queue: JobQueue): chat = update.effective_chat user = update.effective_user msg = update.effective_message should_welc, cust_welcome, welc_type = sql.get_welc_pref(chat.id) welc_mutes = sql.welcome_mutes(chat.id) human_checks = sql.get_human_checks(user.id, chat.id) new_members = update.effective_message.new_chat_members for new_mem in new_members: welcome_log = None sent = None should_mute = True welcome_bool = True if should_welc: # Give the owner a special welcome if new_mem.id == OWNER_ID: update.effective_message.reply_text("Oh, Genos? Let's get this moving.") welcome_log = (f"{html.escape(chat.title)}\n" f"#USER_JOINED\n" f"Bot Owner just joined the chat") # Welcome Devs elif new_mem.id in DEV_USERS: update.effective_message.reply_text("Whoa! A member of the Heroes Association just joined!") # Welcome Sudos elif new_mem.id in SUDO_USERS: update.effective_message.reply_text("Huh! A Dragon disaster just joined! Stay Alert!") # Welcome Support elif new_mem.id in SUPPORT_USERS: update.effective_message.reply_text("Huh! Someone with a Demon disaster level just joined!") # Welcome Whitelisted elif new_mem.id in TIGER_USERS: update.effective_message.reply_text("Oof! A Tiger disaster just joined!") # Welcome Tigers elif new_mem.id in WHITELIST_USERS: update.effective_message.reply_text("Oof! A Wolf disaster just joined!") # Welcome yourself elif new_mem.id == bot.id: update.effective_message.reply_text("hello Join @AnieSupport 😎") else: # If welcome message is media, send with appropriate function if welc_type not in (sql.Types.TEXT, sql.Types.BUTTON_TEXT): ENUM_FUNC_MAP[welc_type](chat.id, cust_welcome) continue # else, move on first_name = new_mem.first_name or "PersonWithNoName" # edge case of empty name - occurs for some bugs. if cust_welcome: if cust_welcome == sql.DEFAULT_WELCOME: cust_welcome = random.choice(sql.DEFAULT_WELCOME_MESSAGES).format(first=escape_markdown(first_name)) if new_mem.last_name: fullname = escape_markdown(f"{first_name} {new_mem.last_name}") else: fullname = escape_markdown(first_name) count = chat.get_members_count() mention = mention_markdown(new_mem.id, escape_markdown(first_name)) if new_mem.username: username = "******" + escape_markdown(new_mem.username) else: username = mention valid_format = escape_invalid_curly_brackets(cust_welcome, VALID_WELCOME_FORMATTERS) res = valid_format.format(first=escape_markdown(first_name), last=escape_markdown(new_mem.last_name or first_name), fullname=escape_markdown(fullname), username=username, mention=mention, count=count, chatname=escape_markdown(chat.title), id=new_mem.id) buttons = sql.get_welc_buttons(chat.id) keyb = build_keyboard(buttons) else: res = random.choice(sql.DEFAULT_WELCOME_MESSAGES).format(first=escape_markdown(first_name)) keyb = [] backup_message = random.choice(sql.DEFAULT_WELCOME_MESSAGES).format(first=escape_markdown(first_name)) keyboard = InlineKeyboardMarkup(keyb) else: welcome_bool = False res = None keyboard = None backup_message = None # User exceptions from welcomemutes if is_user_ban_protected(chat, new_mem.id, chat.get_member(new_mem.id)) or human_checks: should_mute = False # Join welcome: soft mute if new_mem.is_bot: should_mute = False if user.id == new_mem.id: if should_mute: if welc_mutes == "soft": bot.restrict_chat_member(chat.id, new_mem.id, can_send_messages=True, can_send_media_messages=False, can_send_other_messages=False, can_add_web_page_previews=False, until_date=(int(time.time() + 24 * 60 * 60))) if welc_mutes == "strong": welcome_bool = False VERIFIED_USER_WAITLIST.update({ new_mem.id : { "should_welc" : should_welc, "status" : False, "update" : update, "res" : res, "keyboard" : keyboard, "backup_message" : backup_message } }) new_join_mem = f"[{escape_markdown(new_mem.first_name)}](tg://user?id={user.id})" message = msg.reply_text(f"{new_join_mem}, click the button below to prove you're human.\nYou have 160 seconds.", reply_markup=InlineKeyboardMarkup([{InlineKeyboardButton( text="Yes, I'm human.", callback_data=f"user_join_({new_mem.id})")}]), parse_mode=ParseMode.MARKDOWN) bot.restrict_chat_member(chat.id, new_mem.id, can_send_messages=False, can_send_media_messages=False, can_send_other_messages=False, can_add_web_page_previews=False) job_queue.run_once( partial( check_not_bot, new_mem, chat.id, message.message_id ), 160, name="welcomemute" ) if welcome_bool: sent = send(update, res, keyboard, backup_message) prev_welc = sql.get_clean_pref(chat.id) if prev_welc: try: bot.delete_message(chat.id, prev_welc) except BadRequest: pass if sent: sql.set_clean_welcome(chat.id, sent.message_id) if welcome_log: return welcome_log return (f"{html.escape(chat.title)}\n" f"#USER_JOINED\n" f"<b>User</b>: {mention_html(user.id, user.first_name)}\n" f"<b>ID</b>: <code>{user.id}</code>") return ""
def features(update: Update, context: CallbackContext): """Показать все возможности бота по запросу /features со справкой.""" # настраиваем кнопки feature_0 = InlineKeyboardButton('/start', callback_data="0-doc-start") feature_1 = InlineKeyboardButton('/help', callback_data="1-doc-chat_help") feature_2 = InlineKeyboardButton('/echo', callback_data="2-doc-echo") feature_3 = InlineKeyboardButton('/features', callback_data="3-doc-features") feature_4 = InlineKeyboardButton('/history', callback_data="4-doc-history") feature_5 = InlineKeyboardButton('/history_size', callback_data="5-doc-history_size") feature_6 = InlineKeyboardButton('/change_history_size', callback_data="6-doc-change_history_size") feature_7 = InlineKeyboardButton('/ping_intel', callback_data="7-doc-ping_intel") feature_8 = InlineKeyboardButton('/git_pic', callback_data="8-doc-git_pic") feature_9 = InlineKeyboardButton('/сat_facts_best', callback_data="9-doc-cat_facts_best") feature_10 = InlineKeyboardButton('/сat_facts_random', callback_data="10-doc-cat_facts_random") feature_11 = InlineKeyboardButton('/corono_stats', callback_data="11-doc-corono_stats") # настраиваем клавиатуру keyboard = [[feature_0, feature_1, feature_2], [feature_3], [feature_4, feature_5], [feature_6], [feature_7, feature_8], [feature_9, feature_10], [feature_11]] keyboard_markup = InlineKeyboardMarkup(keyboard) update.message.reply_text('Про какую из функций ты хочешь узнать?', reply_markup=keyboard_markup)
def button(update, context): query = update.callback_query data = query.data.split() if data[0] == 'SubGroup': if int(data[1]) == update.effective_user.id: query.edit_message_text( text='Введите номер группы в формате БПМИ195') return SUBGROUP elif data[0] == 'SubStudent': if int(data[1]) == update.effective_user.id: query.edit_message_text(text='Введите ФИО') return SUBSTUDENT elif data[0] == 'StudentId' or data[0] == 'GroupId': if data[1] != '0': if int(data[3]) == update.effective_user.id: subscribe(data[0], data[1], data[2]) query.edit_message_text(text='Вы успешно подписались!') else: if int(data[3]) == update.effective_user.id: query.edit_message_text( text='Попробуйте уточнить правильность написания. ' 'Если не поможет, то Вас нет в базе данных РУЗа') return ConversationHandler.END elif data[0] == 'UnSubGroup' or data[0] == 'UnSubStudent': print(data[1], update.effective_user.id) if int(data[1]) == update.effective_user.id: if data[0] == 'UnSubGroup': id_type = 'GroupId' text = 'От какой группы Вы хотите отписаться?' chosen_type = 'GroupChosen' else: id_type = 'StudentId' text = 'От какого студента Вы хотите отписаться?' chosen_type = 'StudentChosen' markup = [] for (ruz_id, ruz_name) in chat_ids[update.effective_chat.id][id_type]: markup.append([ InlineKeyboardButton( text=f'{ruz_name}', callback_data=f'{chosen_type} {ruz_id} ' f'{update.effective_chat.id} {update.effective_user.id}' ) ]) if not markup: query.edit_message_text( text='Вы ещё ни на кого не подписались. ' 'Подписаться вы можете командой /subscribe') return ConversationHandler.END query.edit_message_text(text=text, reply_markup=InlineKeyboardMarkup(markup)) return UNSUB elif data[0] == 'StudentChosen' or data[0] == 'GroupChosen': if int(data[3]) == update.effective_user.id: if data[0] == 'StudentChosen': id_type = 'StudentId' else: id_type = 'GroupId' unsubscribe(id_type, data[2], data[1], query) return ConversationHandler.END elif data[0] == 'GetGroup' or data[0] == 'GetStudent': if int(data[1]) == update.effective_user.id: if data[0] == 'GetStudent': id_type = 'StudentId' send_type = 'PrintStudent' message_text = 'Для кого вы хотите получить расписание?' else: id_type = 'GroupId' send_type = 'PrintGroup' message_text = 'Для какой группы вы хотите получить расписание?' chat_id = update.effective_chat.id if not chat_ids[chat_id][id_type]: query.edit_message_text( text='Вы ещё ни на кого не подписались. ' 'Подписатьсяs вы можете командой /subscribe') return ConversationHandler.END if len(chat_ids[chat_id][id_type]) == 1: for (user_id, user_name) in chat_ids[chat_id][id_type]: query.edit_message_text( text= f'Расписание для: {user_name}\n{print_nearest_lesson(id_type, user_id)}' ) return ConversationHandler.END markup = [] for (user_id, user_name) in chat_ids[chat_id][id_type]: markup.append([ InlineKeyboardButton( text=f'{user_name}', callback_data=f'{send_type} {user_id}') ]) query.edit_message_text(text=message_text, reply_markup=InlineKeyboardMarkup(markup)) return PRINTNEXT elif data[0] == 'PrintGroup' or data[0] == 'PrintStudent': chat_id = update.effective_chat.id if data[0] == 'PrintStudent': id_type = 'StudentId' else: id_type = 'GroupId' for (user_id, user_name) in chat_ids[chat_id][id_type]: if int(user_id) == int(data[1]): query.edit_message_text( text= f'Расписание для: {user_name}\n{print_nearest_lesson(id_type, user_id)}' ) return ConversationHandler.END
def user(bot: Bot, update: Update): message = update.effective_message args = message.text.strip().split(" ", 1) try: search_query = args[1] except: if message.reply_to_message: search_query = message.reply_to_message.text else: update.effective_message.reply_text("Format : /user <username>") return jikan = jikanpy.jikan.Jikan() try: user = jikan.user(search_query) except jikanpy.APIException: update.effective_message.reply_text("Username not found.") return progress_message = update.effective_message.reply_text("Searching.... ") date_format = "%Y-%m-%d" if user['image_url'] is None: img = "https://cdn.myanimelist.net/images/questionmark_50.gif" else: img = user['image_url'] try: user_birthday = datetime.datetime.fromisoformat(user['birthday']) user_birthday_formatted = user_birthday.strftime(date_format) except: user_birthday_formatted = "Unknown" user_joined_date = datetime.datetime.fromisoformat(user['joined']) user_joined_date_formatted = user_joined_date.strftime(date_format) for entity in user: if user[entity] == None: user[entity] = "Unknown" about = user['about'].split(" ", 60) try: about.pop(60) except IndexError: pass about_string = ' '.join(about) about_string = about_string.replace("<br>", "").strip().replace("\r\n", "\n") caption = "" caption += textwrap.dedent(f""" *Username*: [{user['username']}]({user['url']}) *Gender*: `{user['gender']}` *Birthday*: `{user_birthday_formatted}` *Joined*: `{user_joined_date_formatted}` *Days wasted watching anime*: `{user['anime_stats']['days_watched']}` *Days wasted reading manga*: `{user['manga_stats']['days_read']}` """) caption += f"*About*: {about_string}" buttons = [[InlineKeyboardButton(info_btn, url=user['url'])], [ InlineKeyboardButton( close_btn, callback_data=f"anime_close, {message.from_user.id}") ]] update.effective_message.reply_photo( photo=img, caption=caption, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons), disable_web_page_preview=False) progress_message.delete()
def get_anime_manga(mal_id, search_type, user_id): jikan = jikanpy.jikan.Jikan() if search_type == "anime_anime": result = jikan.anime(mal_id) image = getBannerLink(mal_id) studio_string = ', '.join( [studio_info['name'] for studio_info in result['studios']]) producer_string = ', '.join( [producer_info['name'] for producer_info in result['producers']]) elif search_type == "anime_manga": result = jikan.manga(mal_id) image = result['image_url'] caption = f"<a href=\'{result['url']}\'>{result['title']}</a>" if result['title_japanese']: caption += f" ({result['title_japanese']})\n" else: caption += "\n" alternative_names = [] if result['title_english'] is not None: alternative_names.append(result['title_english']) alternative_names.extend(result['title_synonyms']) if alternative_names: alternative_names_string = ", ".join(alternative_names) caption += f"\n<b>Also known as</b>: <code>{alternative_names_string}</code>" genre_string = ', '.join( [genre_info['name'] for genre_info in result['genres']]) if result['synopsis'] is not None: synopsis = result['synopsis'].split(" ", 60) try: synopsis.pop(60) except IndexError: pass synopsis_string = ' '.join(synopsis) + "..." else: synopsis_string = "Unknown" for entity in result: if result[entity] is None: result[entity] = "Unknown" if search_type == "anime_anime": caption += textwrap.dedent(f""" <b>Type</b>: <code>{result['type']}</code> <b>Status</b>: <code>{result['status']}</code> <b>Aired</b>: <code>{result['aired']['string']}</code> <b>Episodes</b>: <code>{result['episodes']}</code> <b>Score</b>: <code>{result['score']}</code> <b>Premiered</b>: <code>{result['premiered']}</code> <b>Duration</b>: <code>{result['duration']}</code> <b>Genres</b>: <code>{genre_string}</code> <b>Studios</b>: <code>{studio_string}</code> <b>Producers</b>: <code>{producer_string}</code> 📖 <b>Synopsis</b>: {synopsis_string} <a href='{result['url']}'>read more</a> <i>Search an encode on..</i> """) elif search_type == "anime_manga": caption += textwrap.dedent(f""" <b>Type</b>: <code>{result['type']}</code> <b>Status</b>: <code>{result['status']}</code> <b>Volumes</b>: <code>{result['volumes']}</code> <b>Chapters</b>: <code>{result['chapters']}</code> <b>Score</b>: <code>{result['score']}</code> <b>Genres</b>: <code>{genre_string}</code> 📖 <b>Synopsis</b>: {synopsis_string} """) related = result['related'] mal_url = result['url'] prequel_id, sequel_id = None, None buttons, related_list = [], [] if "Prequel" in related: try: prequel_id = related["Prequel"][0]["mal_id"] except IndexError: pass if "Sequel" in related: try: sequel_id = related["Sequel"][0]["mal_id"] except IndexError: pass if search_type == "anime_anime": kaizoku = f"https://animekaizoku.com/?s={result['title']}" kayo = f"https://animekayo.com/?s={result['title']}" buttons.append([ InlineKeyboardButton(kaizoku_btn, url=kaizoku), InlineKeyboardButton(kayo_btn, url=kayo) ]) elif search_type == "anime_manga": buttons.append([InlineKeyboardButton(info_btn, url=mal_url)]) if prequel_id: related_list.append( InlineKeyboardButton( prequel_btn, callback_data=f"{search_type}, {user_id}, {prequel_id}")) if sequel_id: related_list.append( InlineKeyboardButton( sequel_btn, callback_data=f"{search_type}, {user_id}, {sequel_id}")) if related_list: buttons.append(related_list) buttons.append([ InlineKeyboardButton(close_btn, callback_data=f"anime_close, {user_id}") ]) return caption, buttons, image
I'm here to make your group management fun and easy! I have lots of handy features, such as flood control, a warning system, a note keeping system, and even replies on predetermined filters. Please Click Help Button For Assistance And Help Regarding Special Modules You can find the list of available commands with Help Module. Any issues or need help related to me? ========================== [Updates Channel](t.me/NidhiUpdates) [Support Group](t.me/NidhiSupportChat) ========================== Wanna Add me to your Group? Just click the button below! """ buttons = [ [ InlineKeyboardButton( text="Add Me To Group ➕", url="t.me/meikob?startgroup=true" ), InlineKeyboardButton(text="Updates & Info 📃", url="https://t.me/NidhiUpdates"), ] ] HELP_STRINGS = f""" Hello there! My name is *{dispatcher.bot.first_name}*. I'm a modular group management bot with a few fun extras! Have a look at the following for an idea of some of \ the things I can help you with. *Main* commands available: - `/start` : Starts me, can be used to check i'm alive or no... - `/help` : PM's you this message.
def character(bot: Bot, update: Update): message = update.effective_message args = message.text.strip().split(" ", 1) try: search_query = args[1] except: if message.reply_to_message: search_query = message.reply_to_message.text else: update.effective_message.reply_text( "Format : /character <charactername>") return progress_message = update.effective_message.reply_text("Searching.... ") jikan = jikanpy.jikan.Jikan() try: search_result = jikan.search("character", search_query) except jikanpy.APIException: progress_message.delete() update.effective_message.reply_text("Character not found.") return first_mal_id = search_result["results"][0]["mal_id"] character = jikan.character(first_mal_id) caption = f"[{character['name']}]({character['url']})" if character['name_kanji'] != "Japanese": caption += f" ({character['name_kanji']})\n" else: caption += "\n" if character['nicknames']: nicknames_string = ", ".join(character['nicknames']) caption += f"\n*Nicknames* : `{nicknames_string}`" about = character['about'].split(" ", 60) try: about.pop(60) except IndexError: pass about_string = ' '.join(about) for entity in character: if character[entity] == None: character[entity] = "Unknown" caption += f"\n*About*: {about_string}..." buttons = [[InlineKeyboardButton(info_btn, url=character['url'])], [ InlineKeyboardButton( close_btn, callback_data=f"anime_close, {message.from_user.id}") ]] update.effective_message.reply_photo( photo=character['image_url'], caption=caption, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons), disable_web_page_preview=False) progress_message.delete()
def start(update: Update, context: CallbackContext): args = context.args uptime = get_readable_time((time.time() - StartTime)) if update.effective_chat.type == "private": if len(args) >= 1: if args[0].lower() == "help": send_help(update.effective_chat.id, HELP_STRINGS) elif args[0].lower().startswith("ghelp_"): mod = args[0].lower().split('_', 1)[1] if not HELPABLE.get(mod, False): return send_help( update.effective_chat.id, HELPABLE[mod].__help__, InlineKeyboardMarkup([[ InlineKeyboardButton(text="Back", callback_data="help_back") ]])) elif args[0].lower() == "markdownhelp": IMPORTED["extras"].markdown_help_sender(update) elif args[0].lower() == "disasters": IMPORTED["disasters"].send_disasters(update) elif args[0].lower().startswith("stngs_"): match = re.match("stngs_(.*)", args[0].lower()) chat = dispatcher.bot.getChat(match.group(1)) if is_user_admin(chat, update.effective_user.id): send_settings(match.group(1), update.effective_user.id, False) else: send_settings(match.group(1), update.effective_user.id, True) elif args[0][1:].isdigit() and "rules" in IMPORTED: IMPORTED["rules"].send_rules(update, args[0], from_pm=True) else: first_name = update.effective_user.first_name update.effective_message.reply_photo( THOR_IMG, PM_START_TEXT.format(escape_markdown(first_name), escape_markdown(context.bot.first_name)), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup( [[ InlineKeyboardButton( text="☑️ Add Phantom to your group", url="t.me/{}?startgroup=true".format( context.bot.username)) ], [ InlineKeyboardButton( text="🚑 Support Channel", url=f"https://t.me/t.me/PhantomRedXD"), InlineKeyboardButton(text="Support Chat 🚑", url="https://t.me/") ], [ InlineKeyboardButton(text="🧑💻Developer🧑💻", url="https://t.me/PhantomRedXD") ], [ InlineKeyboardButton( text="🗄 Source code", url="https://github.com/souravk12/THOR-BOT") ]])) else: update.effective_message.reply_text( "Yuus, I'm Online!😉😉\n<b>Haven't slept since:👀</b> <code>{}</code>" .format(uptime), parse_mode=ParseMode.HTML)
def start(update: Update, context: CallbackContext): args = context.args uptime = get_readable_time((time.time() - StartTime)) if update.effective_chat.type == "private": if len(args) >= 1: if args[0].lower() == "help": send_help(update.effective_chat.id, HELP_STRINGS) elif args[0].lower().startswith("ghelp_"): mod = args[0].lower().split('_', 1)[1] if not HELPABLE.get(mod, False): return send_help( update.effective_chat.id, HELPABLE[mod].__help__, InlineKeyboardMarkup([[ InlineKeyboardButton(text="Back", callback_data="help_back") ]])) elif args[0].lower() == "markdownhelp": IMPORTED["extras"].markdown_help_sender(update) elif args[0].lower() == "disasters": IMPORTED["disasters"].send_disasters(update) elif args[0].lower().startswith("stngs_"): match = re.match("stngs_(.*)", args[0].lower()) chat = dispatcher.bot.getChat(match.group(1)) if is_user_admin(chat, update.effective_user.id): send_settings(match.group(1), update.effective_user.id, False) else: send_settings(match.group(1), update.effective_user.id, True) elif args[0][1:].isdigit() and "rules" in IMPORTED: IMPORTED["rules"].send_rules(update, args[0], from_pm=True) else: first_name = update.effective_user.first_name update.effective_message.reply_photo( SAITAMA_IMG, PM_START_TEXT.format(escape_markdown(first_name), escape_markdown(context.bot.first_name)), parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True, reply_markup=InlineKeyboardMarkup([ [ InlineKeyboardButton( text="☑️ Add Saitama to your group", url="t.me/{}?startgroup=true".format( context.bot.username)) ], [ InlineKeyboardButton( text="🚑 Support Group", url=f"https://t.me/{SUPPORT_CHAT}"), InlineKeyboardButton( text="🔔 Updates Channel", url="https://t.me/OnePunchUpdates") ], [ InlineKeyboardButton( text="🧾 Getting started guide", url="https://t.me/OnePunchUpdates/29") ], [ InlineKeyboardButton( text="🗄 Source code", url="https://github.com/AnimeKaizoku/SaitamaRobot") ] ])) else: update.effective_message.reply_text( "I'm online!\n<b>Up since:</b> <code>{}</code>".format(uptime), parse_mode=ParseMode.HTML)
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 proyecto_elegido(bot, update, user_data): bot.sendChatAction(chat_id=update.callback_query.from_user.id, action=ChatAction.TYPING) # Es la primera vez que entra o cambia tipo de tareas? if not user_data.get('proyecto'): user_data['proyecto'] = update.callback_query.data user_data['pagging'] = [0, max_issues_per_page] user_data['tipo_tarea'] = '#{Sin resolver}' logger.info('Elegir Proyecto Opción {}'.format(user_data['proyecto'])) elif update.callback_query.data == '>': user_data['pagging'] = [ user_data['pagging'][0] + max_issues_per_page, user_data['pagging'][1] + max_issues_per_page ] elif update.callback_query.data == '<': user_data['pagging'] = [ user_data['pagging'][0] - max_issues_per_page, user_data['pagging'][1] - max_issues_per_page ] else: user_data['tipo_tarea'] = update.callback_query.data user_data['pagging'] = [0, max_issues_per_page] logger.info('Elegir Proyecto Opción {} {}'.format( user_data['proyecto'], user_data['tipo_tarea'])) logger.info('paginas {}/{}'.format(user_data['pagging'][0], user_data['pagging'][1])) connection = Connection(user_data['host']['host'], user_data['host']['username'], user_data['host']['pass']) username, email = splitEmail(user_data['host']['username']) #of #me #{Sin asignar} -Resolved query = '(asignado a: ' + username + ' o #{Sin asignar}) y ' + user_data[ 'tipo_tarea'] logger.info(query) issues = connection.getIssues(user_data['proyecto'], query, user_data['pagging'][0], max_issues_per_page) #Necesito guardar el numero de issues segun query para el paginado pq es lento if user_data['tipo_tarea'] == '#resuelta': if not user_data.get('issue_count_resueltas'): user_data['issue_count_resueltas'] = connection.getNumberOfIssues( query + ' y #' + user_data['proyecto']) issue_count = user_data['issue_count_resueltas'] else: if not user_data.get('issue_count_no_resueltas'): user_data[ 'issue_count_no_resueltas'] = connection.getNumberOfIssues( query + ' y #' + user_data['proyecto']) issue_count = user_data['issue_count_no_resueltas'] keyboard = [] texto = '*Tareas:* \n ' for issue in issues: texto += '\n *[{}]* _{}, {}_\n *Prioridad:* _{}_\n *Resumen:* {} \n'.format( issue['id'], issue['Type'], issue['State'], issue['Priority'], escapeMarkdown(utf8(issue['summary']))) keyboard.append( InlineKeyboardButton(issue['id'], callback_data=issue['id'])) # Agrego posibilidad de ver otras tareas if user_data['tipo_tarea'] == '#{Sin resolver}': keyboard.append( InlineKeyboardButton('Ver solucionadas', callback_data='#resuelta')) else: keyboard.append( InlineKeyboardButton('Ver no solucionadas', callback_data='#{Sin resolver}')) #Paginado if user_data['pagging'][0] > 0: keyboard.append(InlineKeyboardButton('<', callback_data='<')) if len(issues) >= 5: keyboard.append(InlineKeyboardButton('>', callback_data='>')) # Acomodo el teclado keyboard = [keyboard[i:i + 3] for i in range(0, len(keyboard), 3)] reply_markup = InlineKeyboardMarkup(keyboard, resize_keyboard=True, one_time_keyboard=True) texto += '\n *Elegí la tarea:*' if len(keyboard) > 0: update.callback_query.edit_message_text(text=texto, reply_markup=reply_markup, parse_mode='Markdown') return ISSUE else: update.callback_query.edit_message_text( text="No hay tareas asignadas a vos! Chau") return ConversationHandler.END
import requests import html import json # Randomization from random import choice ## Constants # Load the config.json into a 'CONFIG' variable. with open('config.json') as f: CONFIG = json.load(f) # The inline keyboard markup for the two buttons (Red and Blue). # Used in: Would You Rather, Will You Press The Button, and This Or That. RED_BLUE_KEYBOARD = InlineKeyboardMarkup([[ InlineKeyboardButton("🔴", callback_data='red'), InlineKeyboardButton("🔵", callback_data='blue') ]]) ## Info. print("=" * 25) print("Conversational Games Bot") print("=" * 25) print("1.0.0 | Release | By Alan", '\n') ## Functions. def parse_list_file(file_path: str) -> list: """Parse a text file into a list containing each line.""" with open(file_path) as f:
def identificar(bot, update, user_data): info = update.message.text bot.sendChatAction(chat_id=update.message.chat_id, action=ChatAction.TYPING) if not user_data.get('host', None) or not user_data['host'].get( 'host', None): logger.info("Host received {}".format(info)) try: info = checkAndFixUrl(info) user_data['host'] = {} user_data['host']['host'] = info keyboard = [[ InlineKeyboardButton(text="Correcto", callback_data='host_ok'), InlineKeyboardButton(text="Corregir", callback_data='host_ko') ]] reply_markup = InlineKeyboardMarkup(keyboard, resize_keyboard=False, one_time_keyboard=True) update.message.reply_text("Es correcto el host? {}:".format( user_data['host']['host']), reply_markup=reply_markup) return CONFIRMAR except Exception as e: logger.error(e) update.message.reply_text( "{} no parece ser un host correcto, intentá de nuevo".format( info)) return IDENTIFICAR elif not user_data['host'].get('username', None): logger.info("Username received {}".format(info)) user_data['host']['username'] = info keyboard = [[ InlineKeyboardButton(text="Correcto", callback_data='username_ok'), InlineKeyboardButton(text="Corregir", callback_data='username_ko') ]] reply_markup = InlineKeyboardMarkup(keyboard, resize_keyboard=False, one_time_keyboard=True) update.message.reply_text("Es correcto el usuario? {}:".format( user_data['host']['username']), reply_markup=reply_markup) return CONFIRMAR else: logger.info("Password received") # Try to login user_data['host']['pass'] = info try: connection = Connection(user_data['host']['host'], user_data['host']['username'], user_data['host']['pass']) logger.info("good login") usuario = usuarios.getCollection().find_one( {'chat_id': update.message.chat_id}) if not usuario: usuarios.getCollection().insert_one({ 'chat_id': update.message.chat_id, 'hosts': [user_data['host']] }) else: usuarios.getCollection().update_one( {'chat_id': update.message.chat_id}, {'$push': { 'hosts': user_data['host'] }}) logger.info(user_data['host']) proyectos = connection.getProjects() keyboard = [] for proyecto in proyectos.keys(): keyboard.append([ InlineKeyboardButton(proyectos[proyecto], callback_data=proyecto) ]) reply_markup = InlineKeyboardMarkup(keyboard, resize_keyboard=True, one_time_keyboard=True) update.message.reply_text("Bien! Elegí un proyecto", reply_markup=reply_markup) return PROYECTO except Exception as e: logger.error(e) update.message.reply_text("Clave incorrecta") return IDENTIFICAR return CONFIRMAR
def books(update, context): page = 1 per_page = 5 shelf = 'etc' if not update.message: logger.info(f"message: {update.callback_query.data}") shelf = update.callback_query.data.split('_')[1] page = int(update.callback_query.data.split('_')[2]) user_id = update.callback_query.from_user.id else: logger.info(f"message: {update.message.text}") user_id = update.message.from_user.id logger.info((f"user_id: {user_id}, " f"shelf:{shelf}, " f" page:{page}")) try: books = goodreads_api.get_books(user_id, page, per_page, shelf) except AuthError as ex: logger.error(f"AuthError: user_id {user_id}") return context.bot.send_message(user_id, text=str(ex)) result = [] for book in books: book['link'] = f"[→]({book['link']})" book_md = ( f"*{strip_tags(book['title'])}* " f"{book['link']}\n" f"{', '.join(book['authors'])}\n" f"/book\_{book['id']} " # noqa ) result.append(book_md) result = "\n\n".join(result) if result else "*Это всё!*" logger.info(str(result)) buttons = [[]] if page > 1: buttons[0].append( InlineKeyboardButton("⬅️", callback_data=f'books_{shelf}_{page-1}')) if len(books) == per_page: buttons[0].append( InlineKeyboardButton("➡️", callback_data=f'books_{shelf}_{page+1}')) buttons.append( [InlineKeyboardButton("Список полок ↩️", callback_data='shelves')]) params = { "text": result, "parse_mode": ParseMode.MARKDOWN, "disable_web_page_preview": True, "reply_markup": InlineKeyboardMarkup(buttons), } if update.callback_query: update.callback_query.edit_message_text(**params) else: update.message.reply_markdown(**params)
def error_callback(update: Update, context: CallbackContext): if not update: return if context.error in errors: return try: stringio = io.StringIO() pretty_errors.output_stderr = stringio output = pretty_errors.excepthook( type(context.error), context.error, context.error.__traceback__, ) pretty_errors.output_stderr = sys.stderr pretty_error = stringio.getvalue() stringio.close() except: pretty_error = "Failed to create pretty error." tb_list = traceback.format_exception( None, context.error, context.error.__traceback__, ) tb = "".join(tb_list) pretty_message = ( "{}\n" "-------------------------------------------------------------------------------\n" "An exception was raised while handling an update\n" "User: {}\n" "Chat: {} {}\n" "Callback data: {}\n" "Message: {}\n\n" "Full Traceback: {}").format( pretty_error, update.effective_user.id, update.effective_chat.title if update.effective_chat else "", update.effective_chat.id if update.effective_chat else "", update.callback_query.data if update.callback_query else "None", update.effective_message.text if update.effective_message else "No message", tb, ) key = scrapper.post( "https://nekobin.com/api/documents", json={ "content": pretty_message }, ).json() e = html.escape(f"{context.error}") if not key.get("result", {}).get("key"): with open("error.txt", "w+") as f: f.write(pretty_message) context.bot.send_document( OWNER_USERID, open("error.txt", "rb"), caption= f"#{context.error.identifier}\n<b>An unknown error occured:</b>\n<code>{e}</code>", parse_mode="html", ) return key = key.get("result").get("key") url = f"https://nekobin.com/{key}.py" context.bot.send_message( OWNER_USERID, text= f"#{context.error.identifier}\n<b>An unknown error occured:</b>\n<code>{e}</code>", reply_markup=InlineKeyboardMarkup( [[InlineKeyboardButton("Nekobin", url=url)]], ), parse_mode="html", )
def report(update: Update, context: CallbackContext) -> str: bot = context.bot args = context.args message = update.effective_message chat = update.effective_chat user = update.effective_user if chat and message.reply_to_message and sql.chat_should_report(chat.id): reported_user = message.reply_to_message.from_user chat_name = chat.title or chat.first or chat.username admin_list = chat.get_administrators() message = update.effective_message if not args: message.reply_text("Add a reason for reporting first.") return "" if user.id == reported_user.id: message.reply_text("Uh yeah, Sure sure...maso much?") return "" if user.id == bot.id: message.reply_text("Nice try.") return "" if reported_user.id in REPORT_IMMUNE_USERS: message.reply_text("Uh? You reporting a disaster?") return "" if chat.username and chat.type == Chat.SUPERGROUP: reported = f"{mention_html(user.id, user.first_name)} reported {mention_html(reported_user.id, reported_user.first_name)} to the admins!" msg = ( f"<b>⚠️ Report: </b>{html.escape(chat.title)}\n" f"<b> • Report by:</b> {mention_html(user.id, user.first_name)}(<code>{user.id}</code>)\n" f"<b> • Reported user:</b> {mention_html(reported_user.id, reported_user.first_name)} (<code>{reported_user.id}</code>)\n" ) link = f'<b> • Reported message:</b> <a href="https://t.me/{chat.username}/{message.reply_to_message.message_id}">click here</a>' should_forward = False keyboard = [ [ InlineKeyboardButton( u"➡ Message", url= f"https://t.me/{chat.username}/{message.reply_to_message.message_id}" ) ], [ InlineKeyboardButton( u"⚠ Kick", callback_data= f"report_{chat.id}=kick={reported_user.id}={reported_user.first_name}" ), InlineKeyboardButton( u"⛔️ Ban", callback_data= f"report_{chat.id}=banned={reported_user.id}={reported_user.first_name}" ) ], [ InlineKeyboardButton( u"❎ Delete Message", callback_data= f"report_{chat.id}=delete={reported_user.id}={message.reply_to_message.message_id}" ) ] ] reply_markup = InlineKeyboardMarkup(keyboard) else: reported = f"{mention_html(user.id, user.first_name)} reported " \ f"{mention_html(reported_user.id, reported_user.first_name)} to the admins!" msg = f'{mention_html(user.id, user.first_name)} is calling for admins in "{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( f"{mention_html(user.id, user.first_name)} reported the message to the admins.", parse_mode=ParseMode.HTML) return msg return ""
def dice(update, context): six = InlineKeyboardButton(text='6', callback_data='six') reply_keyboard = [six] markup = InlineKeyboardMarkup(reply_keyboard) markup.r update.message.reply_text(randint(1, 6), reply_markup=reply_keyboard)
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, run_async import requests from bs4 import BeautifulSoup as bs from telegram import Bot, InlineKeyboardButton, InlineKeyboardMarkup # from instaloader import Instaloader, Profile, Post import sys import shutil import glob import os import zipfile import pathlib bot_token = os.environ.get("BOT_TOKEN", "") bot = Bot(token=bot_token) help_keyboard = [[InlineKeyboardButton("Updates Channel", url="https://t.me/MBNUpdates"), InlineKeyboardButton("Support Chat", url="https://t.me/MBNChat")]] help_reply_markup = InlineKeyboardMarkup(help_keyboard) def start(update, context): user = update.message.from_user chat_member = context.bot.get_chat_member( chat_id='-1001225141087', user_id=update.message.chat_id) status = chat_member["status"] if(status == 'left'): context.bot.send_message(chat_id=update.message.chat_id, text=f"Hi {user.first_name}, to use me you have to be a member of the updates channel in order to stay updated with the latest developments.\nPlease click below button to join and /start the bot again.", reply_markup=help_reply_markup) return else: context.bot.send_message(chat_id=update.message.chat_id,
def get_keyboard_2(): """Фунция отвечает за создание кнопок.""" keyboard = [[InlineKeyboardButton("Продолжить", callback_data=A)], [InlineKeyboardButton("Закончить", callback_data=B)]] return InlineKeyboardMarkup(keyboard)
def help(update, context): keyboard = [[InlineKeyboardButton("Updates Channel", url="https://t.me/MBNUpdates"), InlineKeyboardButton("Support Chat", url="https://t.me/MBNChat")]] reply_markup = InlineKeyboardMarkup(keyboard) update.message.reply_text('''<b>Usage:</b>\n/stories username - Download stories from the username’s profile.\n/igtv username - Download IGTV videos from the username’s profile.\n/feed username - Download all posts from the username’s profile as a zip file.\n\n<b>How to find the username?</b>\nOpen Instagram app & then go to a profile that you want to download items. Username must be on the top.\nIn case you are using a browser you can find it in the Address bar.\n<b>Example : </b>Username for instagram.com/rashmika_mandanna & @rashmika_mandanna is 'rashmika_mandanna' 😉''', parse_mode=telegram.ParseMode.HTML, reply_markup=reply_markup)
def warn(user: User, chat: Chat, reason: str, message: Message, warner: User = None) -> str: if is_user_admin(chat, user.id): # message.reply_text("Damn admins, They are too far to be One Punched!") return if is_approved(chat.id, user.id): if warner: message.reply_text( "This user is approved in this chat and Approved users can't be warned!" ) else: message.reply_text( "Approved user triggered an auto filter! But they can't be warned." ) return if user.id in FAFNIRS: if warner: message.reply_text("Scouts cant be warned.") else: message.reply_text( "Scout triggered an auto warn filter!\n I can't warn scouts but they should avoid abusing this." ) return if user.id in LUINORS: if warner: message.reply_text("Garrisons are warn immune.") else: message.reply_text( "Garrison triggered an auto warn filter!\nI can't warn garrisons but they should avoid abusing this." ) return if warner: warner_tag = mention_html(warner.id, warner.first_name) else: warner_tag = "Automated warn filter." limit, soft_warn = sql.get_warn_setting(chat.id) num_warns, reasons = sql.warn_user(user.id, chat.id, reason) if num_warns >= limit: sql.reset_warns(user.id, chat.id) if soft_warn: # punch chat.unban_member(user.id) reply = ( f"<code>�</code><b>kick Event</b>\n" f"<code> </code><b>• User:</b> {mention_html(user.id, user.first_name)}\n" f"<code> </code><b>• Count:</b> {limit}") else: # ban chat.ban_member(user.id) reply = ( f"<code>�</code><b>Ban Event</b>\n" f"<code> </code><b>• User:</b> {mention_html(user.id, user.first_name)}\n" f"<code> </code><b>• Count:</b> {limit}") for warn_reason in reasons: reply += f"\n - {html.escape(warn_reason)}" # message.bot.send_sticker(chat.id, BAN_STICKER) # Saitama's sticker keyboard = None log_reason = ( f"<b>{html.escape(chat.title)}:</b>\n" f"#WARN_BAN\n" f"<b>Admin:</b> {warner_tag}\n" f"<b>User:</b> {mention_html(user.id, user.first_name)}\n" f"<b>Reason:</b> {reason}\n" f"<b>Counts:</b> <code>{num_warns}/{limit}</code>") else: keyboard = InlineKeyboardMarkup([[ InlineKeyboardButton("🔘 Remove warn", callback_data="rm_warn({})".format(user.id)) ]]) reply = ( f"<code>�</code><b>Warn Event</b>\n" f"<code> </code><b>• User:</b> {mention_html(user.id, user.first_name)}\n" f"<code> </code><b>• Count:</b> {num_warns}/{limit}") if reason: reply += f"\n<code> </code><b>• Reason:</b> {html.escape(reason)}" log_reason = ( f"<b>{html.escape(chat.title)}:</b>\n" f"#WARN\n" f"<b>Admin:</b> {warner_tag}\n" f"<b>User:</b> {mention_html(user.id, user.first_name)}\n" f"<b>Reason:</b> {reason}\n" f"<b>Counts:</b> <code>{num_warns}/{limit}</code>") try: message.reply_text(reply, reply_markup=keyboard, parse_mode=ParseMode.HTML) except BadRequest as excp: if excp.message == "Reply message not found": # Do not reply message.reply_text(reply, reply_markup=keyboard, parse_mode=ParseMode.HTML, quote=False) else: raise return log_reason
def about(update, context): keyboard = [[InlineKeyboardButton( "Source Code", url="https://github.com/NandiyaLive/xIGDLBot")]] reply_markup = InlineKeyboardMarkup(keyboard) context.bot.send_message(chat_id=update.message.chat_id, text='''I can help you to download media from any public instagram account without leaving Telegram.\n\nMade with ❤️ + python-telegram-bot by @NandiyaLive''', parse_mode=telegram.ParseMode.HTML, reply_markup=reply_markup)
def settings_button(bot: Bot, update: Update): query = update.callback_query user = update.effective_user 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__(chat_id, user.id) 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("Hi there! There are quite a few settings for {} - go ahead and pick what " "you're interested in.".format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules(curr_page - 1, 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("Hi there! There are quite a few settings for {} - go ahead and pick what " "you're interested in.".format(chat.title), reply_markup=InlineKeyboardMarkup( paginate_modules(next_page + 1, 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="Hi there! There are quite a few settings for {} - go ahead and pick what " "you're interested in.".format(escape_markdown(chat.title)), parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(paginate_modules(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))
'<i>Weiter</i>.', QUESTION_ATTRIBUTES: '<b>3/4 - Fragen</b>\n\n' 'Alaska. Bitte wähle nun aus, nach welchen Eigenschaften eines ' 'AkaBlasen Du gefragt wirst. Um die Auswahl zu ändern, klicke auf die ' 'Felder.\n\nWenn Du fertig bist, klicke unten auf <i>Weiter</i>.', NUMBER_QUESTIONS: '<b>4/4 - Anzahl der Fragen</b>\n\n' 'Supidupi. Wie viele Fragen möchtest Du insgesamt erhalten?', } """Dict[:obj:`str`,:obj:`str`]: Texts for the different states.""" # Keyboards FREE_TEXT = 'Freitext' NUMBER_QUESTIONS_KEYBOARD = InlineKeyboardMarkup.from_column([ InlineKeyboardButton(text=i, callback_data=str(i)) for i in [10, 25, 50, 100] ]) """:class:`telegram.InlineKeyboardMarkup`: Keyboard for selection the number of questions.""" MULTIPLE_CHOICE_KEYBOARD = InlineKeyboardMarkup.from_row([ InlineKeyboardButton(text=MULTIPLE_CHOICE, callback_data=str(True)), InlineKeyboardButton(text=FREE_TEXT, callback_data=str(False)), ]) """:class:`telegram.InlineKeyboardMarkup`: Keyboard for selection the type of questions.""" # ----------------------------------------------------------------------------------------------- # @dataclass class GameSettings: """
def connect_chat(update, context): chat = update.effective_chat user = update.effective_user args = context.args if update.effective_chat.type == "private": if args and len(args) >= 1: try: connect_chat = int(args[0]) getstatusadmin = context.bot.get_chat_member( connect_chat, update.effective_message.from_user.id) except ValueError: try: connect_chat = str(args[0]) get_chat = context.bot.getChat(connect_chat) connect_chat = get_chat.id getstatusadmin = context.bot.get_chat_member( connect_chat, update.effective_message.from_user.id) except BadRequest: send_message(update.effective_message, "Invalid Chat ID!") return except BadRequest: send_message(update.effective_message, "Invalid Chat ID!") return isadmin = getstatusadmin.status in ("administrator", "creator") ismember = getstatusadmin.status in ("member") isallow = sql.allow_connect_to_chat(connect_chat) if (isadmin) or (isallow and ismember) or (user.id in DRAGONS): connection_status = sql.connect( update.effective_message.from_user.id, connect_chat) if connection_status: conn_chat = dispatcher.bot.getChat( connected(context.bot, update, chat, user.id, need_admin=False)) chat_name = conn_chat.title send_message( update.effective_message, "Successfully connected to *{}*. \nUse /helpconnect to check available commands." .format(chat_name), parse_mode=ParseMode.MARKDOWN, ) sql.add_history_conn(user.id, str(conn_chat.id), chat_name) else: send_message(update.effective_message, "Connection failed!") else: send_message(update.effective_message, "Connection to this chat is not allowed!") else: gethistory = sql.get_history_conn(user.id) if gethistory: buttons = [ InlineKeyboardButton(text="❎ Close button", callback_data="connect_close"), InlineKeyboardButton(text="🧹 Clear history", callback_data="connect_clear"), ] else: buttons = [] conn = connected(context.bot, update, chat, user.id, need_admin=False) if conn: connectedchat = dispatcher.bot.getChat(conn) text = "You are currently connected to *{}* (`{}`)".format( connectedchat.title, conn) buttons.append( InlineKeyboardButton(text="🔌 Disconnect", callback_data="connect_disconnect")) else: text = "Write the chat ID or tag to connect!" if gethistory: text += "\n\n*Connection history:*\n" text += "╒═══「 *Info* 」\n" text += "│ Sorted: `Newest`\n" text += "│\n" buttons = [buttons] for x in sorted(gethistory.keys(), reverse=True): htime = time.strftime("%d/%m/%Y", time.localtime(x)) text += "╞═「 *{}* 」\n│ `{}`\n│ `{}`\n".format( gethistory[x]["chat_name"], gethistory[x]["chat_id"], htime) text += "│\n" buttons.append([ InlineKeyboardButton( text=gethistory[x]["chat_name"], callback_data="connect({})".format( gethistory[x]["chat_id"]), ) ]) text += "╘══「 Total {} Chats 」".format( str(len(gethistory)) + " (max)" if len(gethistory) == 5 else str(len(gethistory))) conn_hist = InlineKeyboardMarkup(buttons) elif buttons: conn_hist = InlineKeyboardMarkup([buttons]) else: conn_hist = None send_message( update.effective_message, text, parse_mode="markdown", reply_markup=conn_hist, ) else: getstatusadmin = context.bot.get_chat_member( chat.id, update.effective_message.from_user.id) isadmin = getstatusadmin.status in ("administrator", "creator") ismember = getstatusadmin.status in ("member") isallow = sql.allow_connect_to_chat(chat.id) if (isadmin) or (isallow and ismember) or (user.id in DRAGONS): connection_status = sql.connect( update.effective_message.from_user.id, chat.id) if connection_status: chat_name = dispatcher.bot.getChat(chat.id).title send_message( update.effective_message, "Successfully connected to *{}*.".format(chat_name), parse_mode=ParseMode.MARKDOWN, ) try: sql.add_history_conn(user.id, str(chat.id), chat_name) context.bot.send_message( update.effective_message.from_user.id, "You are connected to *{}*. \nUse `/helpconnect` to check available commands." .format(chat_name), parse_mode="markdown", ) except BadRequest: pass except Unauthorized: pass else: send_message(update.effective_message, "Connection failed!") else: send_message(update.effective_message, "Connection to this chat is not allowed!")
def back_home_keyboard(): keyboard=[ [InlineKeyboardButton('Main menu', callback_data='main')] ] return InlineKeyboardMarkup(keyboard)