def start(update: Update, context: CallbackContext): base_message = context.user_data.get("baseMessage", None) database = context.bot_data["database"] chat = update.effective_chat sess_type = context.user_data["sessionType"] user_id = update.effective_user.id if sess_type == Constants.FICTION_SESSION: genre = Constants.FICTION_GENRE max_count = Constants.FICTION_COUNT elif sess_type == Constants.NONFICTION_SESSION: genre = Constants.NONFICTION_GENRE max_count = Constants.NONFICTION_COUNT if base_message: books_iter = context.user_data["books"] else: if sess_type == Constants.FICTION_SESSION: books_iter = database.get_fiction_books(user_id) elif sess_type == Constants.NONFICTION_SESSION: books_iter = database.get_nonfiction_books(user_id) books = [] books_str = [] count = 0 for book_name, authors in books_iter: authors_str = " ,".join(authors) books.append((book_name, authors)) books_str.append(Message.BOOK.format(BOOK_NAME=book_name, AUTHORS=authors_str)) count += 1 context.user_data["books"] = books books_txt = "\n".join(books_str) if count == 0: text = Message.EMPTY_SUGGESTIONS.format(GENRE=genre) buttons = InlineKeyboardMarkup.from_button(Button.SUGGEST) elif count < max_count: left = max_count - count s = "s" * (left != 1) text = Message.HALF_SUGGESTIONS.format( BOOKS=books_txt, GENRE=genre, LEFT=left, S=s ) buttons = InlineKeyboardMarkup.from_row([Button.SUGGEST, Button.REMOVE]) else: s = "s" * (max_count != 1) text = Message.FULL_SUGGESTIONS.format(BOOKS=books_txt, GENRE=genre, S=s) buttons = InlineKeyboardMarkup.from_button(Button.REMOVE, COUNT=count) if context.user_data.pop("newMessage", False): base_msg = chat.send_message(text=text, reply_markup=buttons, parse_mode=HTML) else: base_msg = base_message.edit_text( text=text, reply_markup=buttons, parse_mode=HTML ) context.user_data["baseMessage"] = base_msg
def share_podcast(user, keywords): podcasts = Podcast.objects( Q(name__icontains=keywords) & Q(subscribers=user)) if not podcasts: podcasts_of_user = Podcast.objects(subscribers=user).only('episodes') episodes = Episode.objects( Q(title__icontains=keywords) & Q(from_podcast__in=podcasts_of_user)) if not episodes: yield InlineQueryResultArticle( id=0, title='没有找到相关的播客', description=f'换个关键词试试 :)', input_message_content=InputTextMessageContent(':)')) return else: for index, episode in enumerate(episodes): podcast = episode.from_podcast email = f'\n✉️ {podcast.email}' if podcast.email else '' yield InlineQueryResultArticle( id=index, title=episode.title, description=podcast.name, thumb_url=episode.logo.url, thumb_width=60, thumb_height=60, input_message_content=InputTextMessageContent(message_text=( f'*{podcast.name}*' f'\n[{SPEAKER_MARK}]({podcast.logo.url}) {podcast.host or podcast.name}' f'{email}')), reply_markup=InlineKeyboardMarkup.from_button( InlineKeyboardButton( '订阅', url= f"https://t.me/{manifest.bot_id}?start=p{podcast.id}" ))) for index, podcast in enumerate(podcasts): email = f'\n✉️ {podcast.email}' if podcast.email else '' yield InlineQueryResultArticle( id=index, title=podcast.name, description=podcast.host, thumb_url=podcast.logo.url, thumb_width=60, thumb_height=60, input_message_content=InputTextMessageContent(message_text=( f'*{podcast.name}*' f'\n[{SPEAKER_MARK}]({podcast.logo.url}) {podcast.host or podcast.name}' f'{email}')), reply_markup=InlineKeyboardMarkup.from_button( InlineKeyboardButton( '订阅', url=f"https://t.me/{manifest.bot_id}?start=p{podcast.id}") ))
def message_button_url(update: Update, context: CallbackContext, text, button_text, button_url): if update.message.reply_to_message: return update.message.reply_to_message.reply_text( text, ParseMode.HTML, reply_markup=InlineKeyboardMarkup.from_button( InlineKeyboardButton(button_text, button_url))) return context.bot.send_message( update.message.chat_id, text, ParseMode.HTML, reply_markup=InlineKeyboardMarkup.from_button( InlineKeyboardButton(button_text, button_url)))
def registertoken_handler(update, context): chat_id = update.effective_chat.id chat_name = update.effective_chat.title #create deeplink url = helpers.create_deep_linked_url(context.bot.get_me().username) #create button with deeplink to bot buttonmarkup = InlineKeyboardMarkup.from_button(InlineKeyboardButton(text="Start chat", url=url)) #check if its group/private chat if update.effective_chat.type != 'private': print('grup') msg = open_message("user","regtokengroup") #update.message.reply_text(text="Sorry, register token not supported for group type.\nPlease invoke this cmd inside private chat, click button below", reply_markup=buttonmarkup) update.message.reply_text(text=msg, reply_markup=buttonmarkup) return ConversationHandler.END else: db = dbhelper.Database() db.connection() if db.getOwner(chat_id=chat_id): msg = open_message("owner","regtoken") #update.message.reply_text(text=f"You have already imported your token.\n\nIf you want to change it, please unregister first then register it again", parse_mode=ParseMode.HTML) update.message.reply_text(text=msg, parse_mode=ParseMode.HTML) return ConversationHandler.END else: msg = open_message("user","regtoken") #update.message.reply_text(text=f"Hi, Please send me your <b>.sdtid</b> file\n\nor url token that look like this \n<code>http://127.0.0.1/securidxxxxx</code>\n\n Click /cancel to cancel", parse_mode=ParseMode.HTML) update.message.reply_text(text=msg, parse_mode=ParseMode.HTML) return TOKEN
def test(update, context): button = InlineKeyboardButton('Deploy', callback_data='Test 123') keyboard = InlineKeyboardMarkup.from_button(button) bot = context.bot bot.send_message(chat_id=update.message.chat_id, text='Isso é um teste de botão.', reply_markup=keyboard)
def on_request(update: Update, context: CallbackContext) -> Optional[db.Quote]: quote_obj = get_random_quote(update, context) if not quote_obj: text = 'Закончились уникальные цитаты' user = db.User.get_from(update.effective_user) filter_quote_by_max_length_text = user.get_filter_quote_by_max_length_text( ) if any(user.get_years_of_quotes().values()) \ or (filter_quote_by_max_length_text and filter_quote_by_max_length_text > 0): text += '. Попробуйте в настройках убрать фильтрацию цитат по году или размеру.\n/settings' reply_info(text, update, context) return log.debug('Quote text (%s)', quote_obj.url) if quote_obj.has_comics(): reply_markup = InlineKeyboardMarkup.from_button( InlineKeyboardButton("Комикс", callback_data=str(quote_obj.id))) else: # Недостаточно при запуске отправить ReplyKeyboardMarkup, чтобы она всегда оставалась. # Удаление сообщения, которое принесло клавиатуру, уберет ее. # Поэтому при любой возможности, добавляем клавиатуру reply_markup = REPLY_KEYBOARD_MARKUP reply_quote(quote_obj, update, context, reply_markup) return quote_obj
def ud(update: Update, context: CallbackContext): """ Reply with all the imported modules :param update: object representing the incoming update. :param context: object containing data about the command call. """ if context.args: try: result = get(f'https://api.urbandictionary.com/v0/define?term={" ".join(context.args)}').json()["list"][0] update.effective_message.reply_markdown( f"***{result['word']}***\n\n{result['definition']}", reply_markup=InlineKeyboardMarkup.from_button( InlineKeyboardButton(text="Click here to learn more", url=result["permalink"]) ), ) except IndexError: update.effective_message.reply_markdown( "Urban Dictionary doesn't know the answer to this, ask God or offer tuna to a passing cat to gain the " "wisdom you seek. Preferably the second option. When I'm passing by." ) else: update.effective_message.reply_markdown( f"***{update.effective_user.first_name}***\n\n" f"A dumbass eternally high on cheap catnip who doesn't know that I can't get a word's " f"meaning they don't tell me what the bloody word is.\n\n", )
def on_get_comics_stats(update: Update, context: CallbackContext): message = update.effective_message query = update.callback_query query.answer() quote_query = db.Quote.get_all_with_comics() quote_count = quote_query.count() year_by_number = {k: 0 for k in db.Quote.get_years()} for quote in quote_query.select(db.Quote.date): year = quote.date.year year_by_number[year] += 1 text_year_by_counts = "\n".join(f' <b>{year}</b>: {count}' for year, count in year_by_number.items()) text = f'''\ <b>Статистика по комиксам.</b> Всего <b>{quote_count}</b>: {text_year_by_counts} ''' reply_markup = InlineKeyboardMarkup.from_button( InlineKeyboardButton( '⬅️ Назад', callback_data=fill_string_pattern(PATTERN_QUERY_QUOTE_STATS))) message.edit_text( text, parse_mode=ParseMode.HTML, reply_markup=reply_markup, )
def start(update: Update, context: CustomContext) -> None: """Display a message with a button.""" update.message.reply_html( 'This button was clicked <i>0</i> times.', reply_markup=InlineKeyboardMarkup.from_button( InlineKeyboardButton(text='Click me!', callback_data='button')), )
def deeplink_handler(update, context): if not context.args: return token = context.args[0] if storage.uses_left(token) <= 0: if update.message: update.message.reply_text(TEXT_ERROR, parse_mode="Markdown") return payload = storage.get_payload(token) joinchat_key = payload["joinchat_key"] keyboard = InlineKeyboardMarkup.from_button( InlineKeyboardButton(text=TEXT_JOINCHAT_BUTTON, url=generate_joinchat_link(joinchat_key))) channel_id = payload["channel_id"] user_id = update.effective_user.id storage.add_subscription(channel_id, user_id) storage.count_new_use(token) time.sleep(2) if update.message: update.message.reply_text(TEXT_SUCCESS, reply_markup=keyboard, parse_mode="Markdown")
def dist_cards(update, context): logger.info( f'dist_cards from {getattr(update.effective_user, "id", None)}') (from_user, _) = _msg_users(update) if not from_user: return try: if context.args and len(context.args) == 2: (cards, damount) = [int(a) for a in context.args] assert (cards > 0 and damount > 0) fplayer = get_player(int(from_user.id)) assert fplayer.immunity_cards >= cards fplayer.immunity_cards -= cards fplayer.save() red_packets = context.chat_data.setdefault('red_packets', dict()) rphash = str( hash( f"{update.effective_chat.id} {update.effective_message.message_id}" ))[:8] red_packets[rphash] = [cards, damount] update.message.reply_text( f'{display_username(from_user)}的红包🧧', parse_mode="Markdown", reply_markup=InlineKeyboardMarkup.from_button( InlineKeyboardButton(text=f"{cards} / {damount}", callback_data=f"dist {rphash}"))) else: raise ValueError('') except (ValueError, AssertionError): update.message.reply_text(f'数字不合法: /dist 卡 红包数量')
def search(update, context): context.dispatcher.run_async( update.message.reply_text, text=RIGHT_SEARCH_MARK, reply_markup=InlineKeyboardMarkup.from_button( InlineKeyboardButton('搜索播客', switch_inline_query_current_chat='')) )
def show_subscription(user): podcasts = Podcast.objects(subscribers=user).order_by('-updated_time') if not podcasts: yield InlineQueryResultArticle( id=0, title='请输入关键词…', description=f'在 @{manifest.bot_id} 后输入关键词,寻找喜欢的播客吧!', input_message_content=InputTextMessageContent('🔍️'), reply_markup=InlineKeyboardMarkup.from_button( InlineKeyboardButton('搜索播客', switch_inline_query_current_chat=''))) else: for index, podcast in enumerate(podcasts): if podcast.logo.file_id: yield InlineQueryResultCachedPhoto( id=str(index), photo_file_id=podcast.logo.file_id, title=str(podcast.name), description=podcast.host or podcast.name, # photo_url=podcast.logo.url, input_message_content=InputTextMessageContent( podcast.name), caption=podcast.name) else: yield InlineQueryResultPhoto( id=str(index), description=podcast.host or podcast.name, photo_url=podcast.logo.url, thumb_url=podcast.logo.url, photo_width=80, photo_height=80, title=str(podcast.name), caption=podcast.name, input_message_content=InputTextMessageContent( podcast.name))
def ask_for_confirmation(update: Update, context: CallbackContext) -> str: """ Requests the user to confirm the cancellation request and informs them on what a cancellation will mean for them. Args: update: The update. context: The context as provided by the :class:`telegram.ext.Dispatcher`. """ context.user_data[CONVERSATION_KEY] = CONVERSATION_VALUE text = ( 'Bist Du Dir <i>ganz</i> sicher, dass Du das möchtest? 🥺 Wenn Du Dich abmeldest, ' 'kannst Du den AkaNamen-Bot nicht mehr nutzen und andere AkaBlasen können nicht mehr ' 'Deinen Namen lernen.\n\n<b>Bitte beachte:</b> Wenn Du Dich abmeldest, werden alle ' 'Deine Daten vom AkaNamen-Bot gelöscht.Ob/wann sie von den Telegram-Servern gelöscht ' 'werden, kann der AkaNamen-Bot nicht beeinflussen.\n\nWenn Du Dich <i>wirklich</i> ' 'abmelden möchtest, sende mir eine Nachricht mit dem Text ' f'\n\n<code>{CONFIRMATION_TEXT}</code>\n\n Wenn Du doch lieber bleiben möchtest, ' 'nutze den Knopf unten.') reply_markup = InlineKeyboardMarkup.from_button( InlineKeyboardButton( text='Nein, nein, das war ein Versehen! Abbruch! 😱', callback_data='cancel_cancellation', )) msg = update.effective_message.reply_text(text, reply_markup=reply_markup) context.user_data[CANCELLATION_MESSAGE_KEY] = msg return CONFIRMATION
def show_interactive_progress(update, context): text = get_printable_interactive_config(context) keyboard = InlineKeyboardMarkup.from_button( InlineKeyboardButton(text="Go back", callback_data='GO_BACK_FROM_INTERACTIVE_RESULTS') ) update.callback_query.answer() update.callback_query.edit_message_text(text=text, reply_markup=keyboard)
async def start(update: Update, context: CustomContext) -> None: """Display a message with a button.""" await update.message.reply_html( "This button was clicked <i>0</i> times.", reply_markup=InlineKeyboardMarkup.from_button( InlineKeyboardButton(text="Click me!", callback_data="button") ), )
def _return(update, text='Сохранено.'): button = InlineKeyboardButton(text='Вернуться', callback_data=SHOWING) keyboard = InlineKeyboardMarkup.from_button(button) if update.message: update.message.reply_text(text=text, reply_markup=keyboard) else: update.callback_query.edit_message_text(text=text, reply_markup=keyboard) return SHOWING
def _show_button(self, user_id: int, callback_data: str): keyboard = InlineKeyboardMarkup.from_button( InlineKeyboardButton(text='Скрыть', callback_data=str(callback_data))) self._bot.editMessageReplyMarkup(self._id, self._forms[user_id][-1], reply_markup=keyboard)
def broadcast_html(context: CallbackContext, text: str): context.bot.send_message(chat_id=CHANNEL, text=text, parse_mode=ParseMode.HTML, reply_markup=InlineKeyboardMarkup.from_button( InlineKeyboardButton( text='🔰 Weitere Meldungen 🔰', url='https://t.me/militaernews')))
def make_vote_keyboard(bot, inline_message_id): if not inline_message_id: return return InlineKeyboardMarkup.from_button( InlineKeyboardButton( text='➕', url=f'https://t.me/{bot.username}?start={inline_message_id}', ))
def test_clear_cutoff(self, callback_data_cache, time_method, tz_bot): # Fill the cache with some fake data for i in range(50): reply_markup = InlineKeyboardMarkup.from_button( InlineKeyboardButton('changing', callback_data=str(i))) out = callback_data_cache.process_keyboard(reply_markup) callback_query = CallbackQuery( str(i), from_user=None, chat_instance=None, data=out.inline_keyboard[0][0].callback_data, ) callback_data_cache.process_callback_query(callback_query) # sleep a bit before saving the time cutoff, to make test more reliable time.sleep(0.1) if time_method == 'time': cutoff = time.time() elif time_method == 'datetime': cutoff = datetime.now(pytz.utc) else: cutoff = datetime.now(tz_bot.defaults.tzinfo).replace(tzinfo=None) callback_data_cache.bot = tz_bot time.sleep(0.1) # more fake data after the time cutoff for i in range(50, 100): reply_markup = InlineKeyboardMarkup.from_button( InlineKeyboardButton('changing', callback_data=str(i))) out = callback_data_cache.process_keyboard(reply_markup) callback_query = CallbackQuery( str(i), from_user=None, chat_instance=None, data=out.inline_keyboard[0][0].callback_data, ) callback_data_cache.process_callback_query(callback_query) callback_data_cache.clear_callback_data(time_cutoff=cutoff) assert len(callback_data_cache.persistence_data[0]) == 50 assert len(callback_data_cache.persistence_data[1]) == 100 callback_data = [ list(data[2].values())[0] for data in callback_data_cache.persistence_data[0] ] assert callback_data == list(str(i) for i in range(50, 100))
def test_webhook_arbitrary_callback_data(self, monkeypatch, updater, invalid_data): """Here we only test one simple setup. telegram.ext.ExtBot.insert_callback_data is tested extensively in test_bot.py in conjunction with get_updates.""" updater.bot.arbitrary_callback_data = True try: q = Queue() monkeypatch.setattr(updater.bot, 'set_webhook', lambda *args, **kwargs: True) monkeypatch.setattr(updater.bot, 'delete_webhook', lambda *args, **kwargs: True) monkeypatch.setattr('telegram.ext.Dispatcher.process_update', lambda _, u: q.put(u)) ip = '127.0.0.1' port = randrange(1024, 49152) # Select random port updater.start_webhook(ip, port, url_path='TOKEN') sleep(0.2) try: # Now, we send an update to the server via urlopen reply_markup = InlineKeyboardMarkup.from_button( InlineKeyboardButton(text='text', callback_data='callback_data')) if not invalid_data: reply_markup = updater.bot.callback_data_cache.process_keyboard( reply_markup) message = Message( 1, None, None, reply_markup=reply_markup, ) update = Update(1, message=message) self._send_webhook_msg(ip, port, update.to_json(), 'TOKEN') sleep(0.2) received_update = q.get(False) assert received_update == update button = received_update.message.reply_markup.inline_keyboard[ 0][0] if invalid_data: assert isinstance(button.callback_data, InvalidCallbackData) else: assert button.callback_data == 'callback_data' # Test multiple shutdown() calls updater.httpd.shutdown() finally: updater.httpd.shutdown() sleep(0.2) assert not updater.httpd.is_running updater.stop() finally: updater.bot.arbitrary_callback_data = False updater.bot.callback_data_cache.clear_callback_data() updater.bot.callback_data_cache.clear_callback_queries()
def start(chat_id): text = ("You need to authenticate with DBS.") url = "%s?client_id=%s&redirect_uri=%s&scope=Read&response_type=code&state=0399" % ( DBS_AUTH_URL, DBS_CLIENT_ID, REDIRECT_URL_PARSED) keyboard = InlineKeyboardMarkup.from_button( InlineKeyboardButton(text="Authenticate", url=url)) bot.sendMessage(chat_id=chat_id, text=text, reply_markup=keyboard)
def invite(update, context): update.message.reply_text( text=f"邀请你的伙伴一起听播客!", reply_markup=InlineKeyboardMarkup.from_button( InlineKeyboardButton( '呼朋唤友', switch_inline_query=f"#invite" ) ) )
def start(update, context): """Send a message when the command /start is issued.""" mw_logo = "https://dictionaryapi.com/images/info/branding-guidelines/MWLogo_LightBG_120x120_2x.png" kb_markup = InlineKeyboardMarkup.from_button( InlineKeyboardButton('Try in this chat', switch_inline_query_current_chat='')) update.message.reply_photo(mw_logo, caption=INFO_MESSAGES['start'], reply_markup=kb_markup)
def deep_linked_level_1(update, context): """Reached through the CHECK_THIS_OUT payload""" bot = context.bot url = helpers.create_deep_linked_url(bot.get_me().username, SO_COOL) text = "Awesome, you just accessed hidden functionality! " \ " Now let's get back to the private chat." keyboard = InlineKeyboardMarkup.from_button( InlineKeyboardButton(text='Continue here!', url=url)) update.message.reply_text(text, reply_markup=keyboard)
def handle_confirm(update, context): # re.match... podcast = None update.callback_query.edit_message_text( text="接下来请发送一张截图,用来证明您的主播身份。\n\n(如:播客音频的后台管理界面、第三方平台的官方认证主页等等)", reply_markup=InlineKeyboardMarkup.from_button( InlineKeyboardButton("直接通过其他官方渠道联系我", callback_data=f'direct_contact_{podcast}'))) return PHOTO
def start_create_spree(update, context): text = 'A Spree has 3 essential fields:\nName, Minimum Free Shipping Amount, Current Amount\n\nAll 3 fields must be entered when creating your new Spree.' button = InlineKeyboardButton(text='Okay got it!', callback_data=str(CREATE_SPREE_MENU)) keyboard = InlineKeyboardMarkup.from_button(button) update.callback_query.edit_message_text(text=text, reply_markup=keyboard) return CREATING_SPREE
def open_bot(update, context): x = update.message.from_user.id print(x) bot = context.bot url = helpers.create_deep_linked_url(bot.get_me().username, SO_COOL) keyboard = InlineKeyboardMarkup.from_button( InlineKeyboardButton(text='Get Resource here!', url=url)) #context.bot.sendMessage(chat_id=update.message.chat.id,text =" Hello",reply_markup=keyboard) update.message.reply_text("Hello", reply_markup=keyboard)
async def test_webhook_arbitrary_callback_data(self, monkeypatch, updater, invalid_data, chat_id): """Here we only test one simple setup. telegram.ext.ExtBot.insert_callback_data is tested extensively in test_bot.py in conjunction with get_updates.""" updater.bot.arbitrary_callback_data = True async def return_true(*args, **kwargs): return True try: monkeypatch.setattr(updater.bot, "set_webhook", return_true) monkeypatch.setattr(updater.bot, "delete_webhook", return_true) ip = "127.0.0.1" port = randrange(1024, 49152) # Select random port async with updater: await updater.start_webhook(ip, port, url_path="TOKEN") # Now, we send an update to the server reply_markup = InlineKeyboardMarkup.from_button( InlineKeyboardButton(text="text", callback_data="callback_data")) if not invalid_data: reply_markup = updater.bot.callback_data_cache.process_keyboard( reply_markup) update = make_message_update( message="test_webhook_arbitrary_callback_data", message_factory=make_message, reply_markup=reply_markup, user=updater.bot.bot, ) await send_webhook_message(ip, port, update.to_json(), "TOKEN") received_update = await updater.update_queue.get() assert received_update.update_id == update.update_id message_dict = update.message.to_dict() received_dict = received_update.message.to_dict() message_dict.pop("reply_markup") received_dict.pop("reply_markup") assert message_dict == received_dict button = received_update.message.reply_markup.inline_keyboard[ 0][0] if invalid_data: assert isinstance(button.callback_data, InvalidCallbackData) else: assert button.callback_data == "callback_data" await updater.stop() finally: updater.bot.arbitrary_callback_data = False updater.bot.callback_data_cache.clear_callback_data() updater.bot.callback_data_cache.clear_callback_queries()