def inline_caps(bot, update): query = bot.update.inline_query.query results = list() results.append(InlineQueryResultArticle(query.upper(), 'Caps', query.upper())) bots.answerInlineQuery(update.inline_query.id, results)
def spb(query: str, update: Update, context: CallbackContext) -> None: """Handle the inline query.""" query = update.inline_query.query user_id = update.effective_user.id try: search = query.split(" ", 1)[1] except IndexError: search = user_id if search: srdata = search else: srdata = user_id url = f"https://api.intellivoid.net/spamprotection/v1/lookup?query={srdata}" r = requests.get(url) a = r.json() response = a["success"] if response is True: date = a["results"]["last_updated"] stats = f"*◢ Intellivoid• SpamProtection Info*:\n" stats += f' • *Updated on*: `{datetime.fromtimestamp(date).strftime("%Y-%m-%d %I:%M:%S %p")}`\n' if a["results"]["attributes"]["is_potential_spammer"] is True: stats += f" • *User*: `USERxSPAM`\n" elif a["results"]["attributes"]["is_operator"] is True: stats += f" • *User*: `USERxOPERATOR`\n" elif a["results"]["attributes"]["is_agent"] is True: stats += f" • *User*: `USERxAGENT`\n" elif a["results"]["attributes"]["is_whitelisted"] is True: stats += f" • *User*: `USERxWHITELISTED`\n" stats += f' • *Type*: `{a["results"]["entity_type"]}`\n' stats += ( f' • *Language*: `{a["results"]["language_prediction"]["language"]}`\n' ) stats += f' • *Language Probability*: `{a["results"]["language_prediction"]["probability"]}`\n' stats += f"*Spam Prediction*:\n" stats += f' • *Ham Prediction*: `{a["results"]["spam_prediction"]["ham_prediction"]}`\n' stats += f' • *Spam Prediction*: `{a["results"]["spam_prediction"]["spam_prediction"]}`\n' stats += f'*Blacklisted*: `{a["results"]["attributes"]["is_blacklisted"]}`\n' if a["results"]["attributes"]["is_blacklisted"] is True: stats += ( f' • *Reason*: `{a["results"]["attributes"]["blacklist_reason"]}`\n' ) stats += f' • *Flag*: `{a["results"]["attributes"]["blacklist_flag"]}`\n' stats += f'*PTID*:\n`{a["results"]["private_telegram_id"]}`\n' else: stats = "`cannot reach SpamProtection API`" results = [ InlineQueryResultArticle( id=str(uuid4()), title=f"SpamProtection API info of {srdata}", input_message_content=InputTextMessageContent( stats, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True), ), ] update.inline_query.answer(results, cache_time=5)
def handle_inlinerequest(update, context): # Handle any inline requests to this bot query = update.inline_query sender_id = query.from_user.id database = sqlite3.connect("data/user_links") cursor = database.cursor() # Inline requests can only be started by admins, check this cursor.execute('''SELECT admin FROM users WHERE telegram_id=?''', (sender_id, )) isAdmin = cursor.fetchone() if isAdmin is None: return isAdmin = isAdmin[0] results = list() input = query.query.split(" ") if input[0] == "link" and isAdmin and len( input ) >= 2: # Link the recipient of the message to the specified mete account (Needs to be confirmed by recipient) mete_id = int(input[1]) # Get a list of all users (list[dict()]) mete_user_list = json.loads( requests.get(f"{BASE_URL}/api/v1/users.json").text) valid_user = False for user in mete_user_list: if user['id'] == mete_id: mete_name = user['name'] valid_user = True break if not valid_user: return cursor.execute('''SELECT id FROM users WHERE mete_id=?''', (mete_id, )) if not (cursor.fetchone() is None): # The user is already linked - print a helpful error message output = "This Telegram account is already linked to the Mete account *{}*_(id: {})_. 😔".format( mete_name, mete_id) kb_link = [[ InlineKeyboardButton("Sorry...", callback_data="cancel") ]] kb_link_markup = InlineKeyboardMarkup(kb_link) results.append( InlineQueryResultArticle( id="0", title="User already linked!", input_message_content=InputTextMessageContent( output, parse_mode=ParseMode.MARKDOWN), reply_markup=kb_link_markup)) else: # User is not linked yet - send link request buttons output = "Press 'Link accounts' to link your Telegram account to the Mete account *{}*_(id: {})_.".format( mete_name, mete_id) kb_link = [[ InlineKeyboardButton("Link accounts", callback_data="link/" + str(mete_id)) ], [InlineKeyboardButton("Cancel", callback_data="cancel")]] kb_link_markup = InlineKeyboardMarkup(kb_link) results.append( InlineQueryResultArticle( id="0", title="Send link request", input_message_content=InputTextMessageContent( output, parse_mode=ParseMode.MARKDOWN), reply_markup=kb_link_markup)) elif input[ 0] == "promote" and isAdmin: # Promote the recipient of the message to be an administrator (Needs to be confirmed by recipient) output = "Press 'Become administrator' to become a Chaosdorf-Mete administrator." kb_admin_requests = [[ InlineKeyboardButton("Become administrator", callback_data="promote") ], [InlineKeyboardButton("Cancel", callback_data="cancel")]] kb_admin_requests_markup = InlineKeyboardMarkup(kb_admin_requests) results.append( InlineQueryResultArticle( id="0", title="Send promotion request", input_message_content=InputTextMessageContent(output), reply_markup=kb_admin_requests_markup)) else: results.append( InlineQueryResultArticle( id="0", title="Send drink buttons", input_message_content=InputTextMessageContent( "Please press one of the buttons below to buy a drink."), reply_markup=getDrinkInlineKeyboardMarkup())) context.bot.answer_inline_query(query.id, results, cache_time=0) cursor.close()
def inlinequery(update, context): """Handle the inline query.""" user_id = str(update.inline_query.from_user.id) user: User = User.get(telegram_id=user_id) if not user or not user.spotify: update.inline_query.answer( [], switch_pm_text="Login with Spotify", switch_pm_parameter="spotify_log_in", cache_time=0, ) return status = user.spotify.status song = status.song if not song: logging.warning("no song found") logging.info("{} - {}".format(song.artist, song.name)) thumb = song.thumbnail results = [ InlineQueryResultArticle( id=uuid4(), title="{} - {}".format(song.artist, song.name), url=song.url, thumb_url=thumb.url, thumb_width=thumb.width, thumb_height=thumb.height, input_message_content=InputTextMessageContent( "🎵 [{}]({}) by {}".format(escape_markdown(song.name), song.url, escape_markdown(song.artist)), parse_mode=ParseMode.MARKDOWN, ), reply_markup=InlineKeyboardMarkup(inline_keyboard=[[ Button(text="Open on Spotify", url=song.url), Button(text="Add to queue", callback_data="queue;" + song.id), ]]), ) ] if status.context: thumb = status.context.thumbnail if status.context.type == "album": title = "{} - {}".format(status.context.artist, status.context.name) message_content = "🎧 [{}]({}) by {}".format( escape_markdown(status.context.name), status.context.url, escape_markdown(status.context.artist), ) else: title = status.context.name message_content = "🎧 [{}]({})".format( escape_markdown(status.context.name), status.context.url) results.append( InlineQueryResultArticle( id=uuid4(), title=title, url=status.context.url, description=status.context.type, thumb_url=thumb.url, thumb_width=thumb.width, thumb_height=thumb.height, input_message_content=InputTextMessageContent( message_content, parse_mode=ParseMode.MARKDOWN, ), reply_markup=InlineKeyboardMarkup(inline_keyboard=[[ Button(text="Open on Spotify", url=status.context.url), ]]), )) update.inline_query.answer(results, cache_time=0)
def show_episodes(podcast, index): buttons = [ InlineKeyboardButton("订阅列表", switch_inline_query_current_chat=""), InlineKeyboardButton( "单集列表", switch_inline_query_current_chat=f"{podcast.name}#") ] if index: if re.match(r'^-?[0-9]*$', index): index = int(index) if abs(index) <= len(podcast.episodes): if index >= 0: index = -index episodes = podcast.episodes[max(index - 3, -len(podcast.episodes) ):min(index + 2, -1)] else: index = abs(index + 1) episodes = podcast.episodes[ max(index - 3, 0):min(index + 2, len(podcast.episodes))] else: yield InlineQueryResultArticle( id=0, title='超出检索范围', input_message_content=InputTextMessageContent(':('), # !!如果 podcast.episodes.count() == 1 description=f"请输入 1 ~ {len(podcast.episodes)} 之间的数字", ) return else: episodes = Episode.objects( Q(from_podcast=podcast) & Q(title__icontains=index) ).order_by('-published_time') or Episode.objects( Q(from_podcast=podcast) & Q(summary__icontains=index)).order_by('-published_time') if not episodes: yield InlineQueryResultArticle( id=0, title='没有找到相关的节目', input_message_content=InputTextMessageContent(':('), description=f"换个关键词试试", ) return else: episodes = podcast.episodes for index, episode in enumerate(episodes): if episode.file_id: yield InlineQueryResultCachedAudio( id=index, audio_file_id=episode.file_id, reply_markup=InlineKeyboardMarkup.from_row(buttons), input_message_content=InputTextMessageContent(( f"[{SPEAKER_MARK}]({podcast.logo.url}) *{podcast.name}* #{len(podcast.episodes)-index}" )), ) else: yield InlineQueryResultArticle( id=index, title=episode.title, input_message_content=InputTextMessageContent(( f"[{SPEAKER_MARK}]({podcast.logo.url}) *{podcast.name}* #{len(podcast.episodes)-index}" )), reply_markup=InlineKeyboardMarkup.from_row(buttons), description= f"{datetime.timedelta(seconds=episode.duration) or podcast.name}\n{episode.subtitle}", thumb_url=episode.logo.url, thumb_width=80, thumb_height=80)
def generate_multi_currency_list(query): # Build the message that is sent when the user chooses to send the list. coins = initialize_multicurrency_query(query) prices = "***Selected Cryptocurrency Prices***\n\n" capitalizations = "***Selected Cryptocurrency Market Capitalizations***\n\n" changes = "***Selected Cryptocurrency 24 Hour Percent Change Values***\n\n" for x in range(0, len(coins)): prices += "***" + coins[x].name + ":*** $" + coins[x].price_USD + "\n" capitalizations += "***" + coins[x].name + ":*** $" + coins[ x].marketCap + "\n" changes += "***" + coins[x].name + ":*** " + coins[ x].percentChange + "%\n" # Add the "Prices", "Market Capitalizations", and "Percent Change Values" options that are displayed at the top if coins: results = [ # Prices InlineQueryResultArticle( id=uuid4(), title=('Prices'), description='Tap to send.', thumb_url="https://imgur.com/7RCGCoc.png", input_message_content=InputTextMessageContent( prices, ParseMode.MARKDOWN)), # Market Capitalizations InlineQueryResultArticle( id=uuid4(), title=('Market Capitalizations'), description='Tap to send.', thumb_url="https://i.imgur.com/UMczLVP.png", input_message_content=InputTextMessageContent( capitalizations, ParseMode.MARKDOWN)), # Percent Change Values InlineQueryResultArticle( id=uuid4(), title=('Percent Change Values'), description='Tap to send.', thumb_url=("https://imgur.com/iAoXFQc.png"), input_message_content=InputTextMessageContent( changes, ParseMode.MARKDOWN)), ] # Cryptora allows users to put up to 10 coins in a multi-currency query. if len(coins) > 10: length = 10 else: length = len(coins) # Add each individual coin to the list. for x in range(0, length): results.append( InlineQueryResultArticle( id=uuid4(), description=("$" + coins[x].price_USD), thumb_url=coins[x].imageURL, title=(coins[x].name), input_message_content=InputTextMessageContent(coins[x].summary, \ ParseMode.MARKDOWN)), ) return results
def spb(query: str, update: Update, context: CallbackContext) -> None: """Handle the inline query.""" query = update.inline_query.query user_id = update.effective_user.id srdata = None apst = requests.get( f'https://api.intellivoid.net/spamprotection/v1/lookup?query={context.bot.username}' ) api_status = apst.status_code if (api_status != 200): stats = f"API RETURNED {api_status}" else: try: search = query.split(" ", 1)[1] except IndexError: search = user_id srdata = search or user_id url = f"https://api.intellivoid.net/spamprotection/v1/lookup?query={srdata}" r = requests.get(url) a = r.json() response = a["success"] if response is True: date = a["results"]["last_updated"] stats = '*◢ Intellivoid• SpamProtection Info*:\n' stats += f' • *Updated on*: `{datetime.fromtimestamp(date).strftime("%Y-%m-%d %I:%M:%S %p")}`\n' if a["results"]["attributes"]["is_potential_spammer"] is True: stats += ' • *User*: `USERxSPAM`\n' elif a["results"]["attributes"]["is_operator"] is True: stats += ' • *User*: `USERxOPERATOR`\n' elif a["results"]["attributes"]["is_agent"] is True: stats += ' • *User*: `USERxAGENT`\n' elif a["results"]["attributes"]["is_whitelisted"] is True: stats += ' • *User*: `USERxWHITELISTED`\n' stats += f' • *Type*: `{a["results"]["entity_type"]}`\n' stats += ( f' • *Language*: `{a["results"]["language_prediction"]["language"]}`\n' ) stats += f' • *Language Probability*: `{a["results"]["language_prediction"]["probability"]}`\n' stats += '*Spam Prediction*:\n' stats += f' • *Ham Prediction*: `{a["results"]["spam_prediction"]["ham_prediction"]}`\n' stats += f' • *Spam Prediction*: `{a["results"]["spam_prediction"]["spam_prediction"]}`\n' stats += f'*Blacklisted*: `{a["results"]["attributes"]["is_blacklisted"]}`\n' if a["results"]["attributes"]["is_blacklisted"] is True: stats += ( f' • *Reason*: `{a["results"]["attributes"]["blacklist_reason"]}`\n' ) stats += f' • *Flag*: `{a["results"]["attributes"]["blacklist_flag"]}`\n' stats += f'*PTID*:\n`{a["results"]["private_telegram_id"]}`\n' else: stats = "`cannot reach SpamProtection API`" kb = InlineKeyboardMarkup([[ InlineKeyboardButton(text="Report Error", url='https://t.me/zerounions'), InlineKeyboardButton( text="Search again", switch_inline_query_current_chat=".spb ", ), ]]) a = "the entity was not found" results = [ InlineQueryResultArticle( id=str(uuid4()), title=f"SpamProtection API info of {srdata or a}", input_message_content=InputTextMessageContent( stats, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True), reply_markup=kb), ] update.inline_query.answer(results, cache_time=5)
def inline_handle(bot: Bot, update: Update): query = update.inline_query.query args = query.split(" ")[1:] user = update.inline_query.from_user result = [] # Handle normal commands support modloader_response = MODLOADER.handle_inline(update) if modloader_response: for command in modloader_response: reply = command[0](bot, update, user, args) if reply is None: return if not isinstance(reply, core.message): reply = core.message.from_old_format(reply) if reply.parse_mode: result.append( InlineQueryResultArticle( id=uuid4(), title=command[1], description=re.sub(cleanr, "", reply.text.split("\n")[0]), input_message_content=InputTextMessageContent( reply.text, parse_mode=reply.parse_mode), reply_markup=reply.inline_keyboard)) elif reply.photo: if isinstance(reply.photo, str): result.append( InlineQueryResultPhoto( photo_url=reply.photo, thumb_url=reply.photo, id=uuid4(), reply_markup=reply.inline_keyboard, caption=reply.text)) else: pic = bot.sendPhoto(chat_id=settings.CHANNEL, photo=reply.photo) pic = pic.photo[0].file_id result.append( InlineQueryResultCachedPhoto( photo_file_id=pic, caption=reply.text, id=uuid4(), reply_markup=reply.inline_keyboard)) elif reply.voice: result.append( InlineQueryResultArticle( id=uuid4(), title="Unsupported content", description= "It is impossible to send non-hosted voice right now, due to Telegram limitations", input_message_content=InputTextMessageContent( "It is impossible to send non-hosted voice right now, due to Telegram limitations" ), )) elif not reply.text == "": result.append( InlineQueryResultArticle( id=uuid4(), title=command[1], description=reply.text.split("\n")[0], input_message_content=InputTextMessageContent( reply.text), reply_markup=reply.inline_keyboard)) else: result.append( InlineQueryResultArticle( id=uuid4(), title="Unsupported content", description="This command doesnt work in inline mode.", input_message_content=InputTextMessageContent( "This command doesnt work in inline mode."), )) # Handle custom inline commands modloader_response = MODLOADER.handle_inline_custom(update) for resp in modloader_response: result += resp(bot, query) result = result[:49] try: update.inline_query.answer(results=result, switch_pm_text="List commands", switch_pm_parameter="help", cache_time=1) except Exception as e: LOGGER.critical(str(e)) return True
def inline_query(bot, update): word = update.inline_query.query results = list() if len(word) >= 1: with connection.cursor() as cursor: sql = "select * from CantonDict where word=%s limit 1" cursor.execute(sql, (word[0])) result = cursor.fetchone() if result: canton_dict = CantonDict(result) else: canton_dict = CantonDict(word[0]) with connection.cursor() as cursor: sql = "INSERT INTO `CantonDict`" \ " (`word`, `url`,`examples`,`brief_explains`,`audios`" \ ",`cangjie_pattern`,`char_can_notes`,`eng_meanings`,`word_example`,`homonyms`)" \ " VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)" cursor.execute( sql, (word[0], canton_dict.url, str( canton_dict.examples).replace("[", "").replace( "]", ""), str(canton_dict.brief_explains).replace( "[", "").replace("]", ""), str(canton_dict.audios).replace("[", "").replace( "]", ""), canton_dict.cangjie_pattern, str(canton_dict.char_can_notes).replace("[", "").replace( "]", ""), canton_dict.eng_meanings, str(canton_dict.word_example).replace("[", "").replace( "]", ""), str(canton_dict.homonyms).replace( "[", "").replace("]", ""))) connection.commit() if len(canton_dict.audios) == len(canton_dict.char_can_notes): for index in range(len(canton_dict.audios)): both = canton_dict.char_can_notes[ index] and canton_dict.examples[index] results.append( InlineQueryResultAudio( id=uuid4(), title="「{0}」讀音:{1},{2}".format( word[0], canton_dict.char_can_notes[index], canton_dict.examples[index]) if both else "「{0}」讀音:{1}{2}".format( word[0], canton_dict.char_can_notes[index], canton_dict.examples[index]), audio_url= 'http://humanum.arts.cuhk.edu.hk/Lexis/lexi-mf/{0}'. format(canton_dict.audios[index]))) if canton_dict.word_example: example_line = list() empty = True for example in canton_dict.examples: example_line.append(example.replace("'", "").strip()) if example.replace("'", "").strip(): empty = False if len(example_line) > 0 and not empty: results.append( InlineQueryResultArticle( id=uuid4(), title="「{0}」例子".format(word[0]), input_message_content=InputTextMessageContent( "「{0}」例子\n{1}".format(word[0], "\n".join(example_line))))) if canton_dict.brief_explains: is_str = type(canton_dict.brief_explains) is str results.append( InlineQueryResultArticle( id=uuid4(), title="「{0}」略說".format(word[0]), input_message_content=InputTextMessageContent( "「{0}」{1}".format( word[0], ast.literal_eval( canton_dict.brief_explains. replace('\\\\', '\\')).decode()) if is_str else canton_dict.brief_explains[0].decode('utf8')))) if canton_dict.eng_meanings: results.append( InlineQueryResultArticle( id=uuid4(), title="「{0}」English meaning".format(word[0]), input_message_content=InputTextMessageContent( "「{0}」English meaning\n{1}".format( word[0], canton_dict.eng_meanings)))) if len(canton_dict.audios) == len(canton_dict.homonyms): for index in range(len(canton_dict.audios)): results.append( InlineQueryResultArticle( id=uuid4(), title="「{0}」({1})同音字".format( word[0], canton_dict.audios[index][6:-4]), input_message_content=InputTextMessageContent( "「{0}」{1} 同音字\n{2}".format( word[0], canton_dict.audios[index][6:-4], canton_dict.homonyms[index])))) if canton_dict.cangjie_pattern: results.append( InlineQueryResultArticle( id=uuid4(), title="「{0}」倉頡碼".format(word[0]), input_message_content=InputTextMessageContent( "「{0}」倉頡碼:{1}".format(word[0], canton_dict.cangjie_pattern)))) if canton_dict.url: results.append( InlineQueryResultArticle( id=uuid4(), title="「{0}」更多".format(word[0]), input_message_content=InputTextMessageContent( canton_dict.url))) update.inline_query.answer(results)
def inline_caps(update, context): query = update.inline_query.query results = list() if query.lower() == '' or query.lower().strip() == 'help': results.append( InlineQueryResultArticle( id=uuid4(), title='How to use me to make a request:', input_message_content=InputTextMessageContent( """Type r,BookName(s),AuthorName,AmazonLink(for audible/KU),Language Tags(if any)""", parse_mode='HTML'), description= 'Type r, BookName(s), AuthorName, AmazonLink(for audible/KU), Language Tags(if any)', )) #Individual rules if query.lower().strip() == '1': results = list() results.append( InlineQueryResultArticle( id=uuid4(), title= '1. Before You Request -> 1.1. Verify the name and author of the ebook/audiobook...', input_message_content=InputTextMessageContent( """<b>1. Before You Request</b> 1.1. Verify the name and author of the ebook/audiobook and that the book has been released in the particular format in which you want(ebook/audiobook).""", parse_mode='HTML'))) results.append( InlineQueryResultArticle( id=uuid4(), title='1.2. If you want a book series or multiple books...', input_message_content=InputTextMessageContent( """ 1.2. If you want a <i>book series or multiple books</i> then individually request each one with correct names of the titles.""", parse_mode='HTML'))) results.append( InlineQueryResultArticle( id=uuid4(), title='1.3. Only request for ebooks which are preferably on...', input_message_content=InputTextMessageContent( """ 1.3. Only request for ebooks which are preferably on <i>Amazon</i> and audiobooks that are on <i>Audible</i>.""", parse_mode='HTML'))) results.append( InlineQueryResultArticle( id=uuid4(), title='1.4. DON\'T request for books that are...', input_message_content=InputTextMessageContent( """ 1.4. <b>DON'T</b> request for books that are; 1.4.1. Available only in <i>paperback/hardcover</i>. 1.4.2. <a href="https://t.me/BookCrushGroup/165744">Academic textbooks</a>. 1.4.3. In <a href="https://t.me/BookCrushGroup/141180">DMCA list</a>""", parse_mode='HTML', disable_web_page_preview=True))) results.append( InlineQueryResultArticle( id=uuid4(), title='1.5. DON\'T be choosy about...', input_message_content=InputTextMessageContent( """ 1.5. <b>DON'T</b> be choosy about ebook formats or narrators for audiobooks.""", parse_mode='HTML'))) results.append( InlineQueryResultArticle( id=uuid4(), title='1.6. DON\'T just send links or covers...', input_message_content=InputTextMessageContent( """ 1.6. <b>DON'T</b> just send links or covers of books that you want. Instead be a good lad and follow the request format.""", parse_mode='HTML'))) results.append( InlineQueryResultArticle( id=uuid4(), title='1.7. Search before requesting...', input_message_content=InputTextMessageContent( """ 1.7. Click on the 🔍 icon in the top right and search if that ebook/audiobook has been shared already in the group. Follow this tutorial on how to search in the group.""", parse_mode='HTML'))) if query.lower().strip() == '2': results = list() results.append( InlineQueryResultArticle( id=uuid4(), title= '2. Request Format -> 2.1. If that book has not been shared before, request using...', input_message_content=InputTextMessageContent( """<b>2. Request Format</b> 2.1. If that book has not been shared before, request using the following format: <code>#request Book's name Author's name #ebook or #audiobook</code> [Amazon link to audiobook/KU book, if applicable]""", parse_mode='HTML'))) results.append( InlineQueryResultArticle( id=uuid4(), title='2.2.1. ebook example', input_message_content=InputTextMessageContent( """ 2.2.1. ebooks: <code>#request Sapiens: A Brief History of Humankind Yuval Noah Harari #ebook</code>""", parse_mode='HTML'))) results.append( InlineQueryResultArticle( id=uuid4(), title='2.2.2. Audible Audiobook example', input_message_content=InputTextMessageContent( """ 2.2.2. Audible Audiobooks: <code>#request Dark Matter Blake Crouch #audiobook https://www.audible.in/pd/Dark-Matter-Audiobook/B07B7BFH4M</code>""", parse_mode='HTML', disable_web_page_preview=True))) results.append( InlineQueryResultArticle( id=uuid4(), title='2.2.3. Kindle Unlimited book example', input_message_content=InputTextMessageContent( """ 2.2.3. Kindle Unlimited(KU) books: <code>#request Harry Potter and the Chamber of Secrets J.K. Rowling #KU https://www.amazon.in/Harry-Potter-Chamber-Secrets-Rowling-ebook/dp/B019PIOJY0</code>""", parse_mode='HTML', disable_web_page_preview=True))) if query.lower().strip() == '3': results.append( InlineQueryResultArticle( id=uuid4(), title='3. Hashtags', input_message_content=InputTextMessageContent( """<b>3. Hashtags</b> Include appropriate hashtags in your requests which will help us track them better: 3.1. For languages other than English, Use <code>#Hindi</code>, <code>#Marathi</code>, <code>#Spanish</code> and so on. 3.2. For Kindle Unlimited - <code>#KU</code> ; Audible Audiobooks - <code>#audiobook</code> or #audible (provide their links as well).""", parse_mode='HTML'), description='Hashtags to include in your request')) if query.lower().strip() == '4': results.append( InlineQueryResultArticle( id=uuid4(), title='4. Request Limits', input_message_content=InputTextMessageContent( """<b>4. Request Limits</b> 4.1. <b>DON'T</b> request for more than 3 books(ebooks+audiobooks) in a day. Exceeding it will trigger @ShiiinaBot to delete your request and you will have to wait for 24 hours to request again. Deleting and re-requesting if you made any mistake in your original request will not reset the count, instead learn how to Edit your message. 4.2. <b>Hoarding</b> books(even within request limit) is strictly not tolerated. Request only what you want to read/listen in the near future.""", parse_mode='HTML'), description='How many can you request per day?')) if query.lower().strip() == '5': results = list() results.append( InlineQueryResultArticle( id=uuid4(), title= '5. After you request -> 5.1. Sit back and wait, DON\'T tag or PM admins...', input_message_content=InputTextMessageContent( """<b>5. After You Request</b> 5.1. Sit back and wait, DON'T tag or PM admins. """, parse_mode='HTML'))) results.append( InlineQueryResultArticle( id=uuid4(), title='5.2. Asking Updates', input_message_content=InputTextMessageContent( """ 5.2. <b>DON'T</b> ask for updates on the book before 48 hours. You will receive an @ notification from a contributor or BookCrush Buddy when it is fulfilled.""", parse_mode='HTML'))) results.append( InlineQueryResultArticle( id=uuid4(), title='5.3. Wait 48 Hours', input_message_content=InputTextMessageContent( """ 5.3. If your request is not fulfilled, repost after <b>48 hours</b>. Subsequent reminders should also be spaced out 48 hours between each one.""", parse_mode='HTML'))) results.append( InlineQueryResultArticle( id=uuid4(), title='5.4. DON\'T ask for specific format', input_message_content=InputTextMessageContent( """ 5.4. After you get the book, <b>DON'T</b> be lazy and ask us for a specific format like pdf, epub etc. Convert it yourself online(@SmartConverter_bot or @cloud_convert_bot). """, parse_mode='HTML'))) if query.lower().strip() == '6': results = list() results.append( InlineQueryResultArticle( id=uuid4(), title='6. Communication -> 6.1. Use English at all times....', input_message_content=InputTextMessageContent( """<b>6. Communication</b> 6.1. Use English at all times. """, parse_mode='HTML'))) results.append( InlineQueryResultArticle( id=uuid4(), title='6.2. Asking Updates', input_message_content=InputTextMessageContent( """ 6.2. Refrain from any off-topic chatter.""", parse_mode='HTML'))) results.append( InlineQueryResultArticle( id=uuid4(), title='6.3. Wait 48 Hours', input_message_content=InputTextMessageContent( """ 6.3. <b>DON'T</b> PM any group member without permission.""", parse_mode='HTML'))) results.append( InlineQueryResultArticle( id=uuid4(), title='6.4. DON\'T ask for specific format', input_message_content=InputTextMessageContent( """ 6.4. <b>DON'T</b> spam with gifs/stickers, promotional messages or channel/group invites(t.me links) either in group or in PM. """, parse_mode='HTML'))) if query.lower().strip() == '7': results.append( InlineQueryResultArticle( id=uuid4(), title='7. Disallowed Names/Usernames', input_message_content=InputTextMessageContent( """<b>7. Disallowed Names/Usernames</b> 7.1. Names/Usernames containing single letter/double letters, NSFW words, Just emojis, special characters, punctuation marks or Annoying Unicode/RTL characters which mess up the Telegram UI. <i>Anyone violating this rule will be muted until the username no longer violates any of the above conditions. Message any admin to be un-muted once you comply with the name rule.</i>""", parse_mode='HTML'), )) if query.lower().strip() == '8': results = list() results.append( InlineQueryResultArticle( id=uuid4(), title= '8. What will get you muted/kicked/(f)banned? -> 8.1. Violating any of the....', input_message_content=InputTextMessageContent( """<b>8. What will get you muted/kicked/(f)banned?</b> 8.1. <b>Violating</b> any of the above rules(1-7) will be first met with a friendly notice, repeated violations will each lead to a warning and 5 such warnings to getting muted forever.""", parse_mode='HTML'))) results.append( InlineQueryResultArticle( id=uuid4(), title='8.2. Abuse', input_message_content=InputTextMessageContent( """ 8.2. <b>Abusing</b> members/admins in PM will directly lead to getting fedbanned in all BookCrush groups.""", parse_mode='HTML'))) results.append( InlineQueryResultArticle( id=uuid4(), title='8.3. Hoarding', input_message_content=InputTextMessageContent( """ 8.3. <b>Hoarding</b> books without considering the time and effort of admins/contributors that goes into ripping ebooks/audiobooks. Such violators will be tracked and muted/banned accordingly.""", parse_mode='HTML'))) results.append( InlineQueryResultArticle( id=uuid4(), title='8.4. Alt IDs', input_message_content=InputTextMessageContent( """ 8.4. <b>Having</b> one or more Alternate IDs so as to bypass the request limit. """, parse_mode='HTML'))) #END of individual rules #Full group rules if query.lower().startswith('grouprules'): results.append( InlineQueryResultArticle( id=uuid4(), title='BookCrush:Requests', input_message_content=InputTextMessageContent( "https://telegra.ph/BookCrushRequests-Group-Rules-12-03", disable_web_page_preview=False), description='Complete Rules of the Group', thumb_url='https://telegra.ph/file/c20df171f38eda7ad316f.png', thumb_width=30, thumb_height=30)) #context.bot.answer_inline_query(update.inline_query.id, results) #results = list() results.append( InlineQueryResultArticle( id=uuid4(), title='1. Before You Request', input_message_content=InputTextMessageContent( """<b>1. Before You Request</b> 1.1. Verify the name and author of the ebook/audiobook and that the book has been released in the particular format in which you want(ebook/audiobook). 1.2. If you want a <i>book series or multiple books</i> then individually request each one with correct names of the titles. 1.3. Only request for ebooks which are preferably on <i>Amazon</i> and audiobooks that are on <i>Audible</i>. 1.4. <b>DON'T</b> request for books that are; 1.4.1. Available only in <i>paperback/hardcover</i>. 1.4.2. <a href="https://t.me/BookCrushGroup/165744">Academic textbooks</a>. 1.4.3. In <a href="https://t.me/BookCrushGroup/141180">DMCA list</a>. 1.5. <b>DON'T</b> be choosy about ebook formats or narrators for audiobooks. 1.6. <b>DON'T</b> just send links or covers of books that you want. Instead be a good lad and follow the request format. 1.7. Click on the 🔍 icon in the top right and search if that ebook/audiobook has been shared already in the group. Follow this tutorial on how to search in the group.""", parse_mode='HTML'), description='What you need to remember before requesting?')) results.append( InlineQueryResultArticle( id=uuid4(), title='2. Request Format', input_message_content=InputTextMessageContent( """<b>2. Request Format</b> 2.1. If that book has not been shared before, request using the following format: <code>#request Book's name Author's name #ebook or #audiobook</code> [Amazon link to audiobook/KU book, if applicable] 2.2. Examples 2.2.1. ebooks: <code>#request Sapiens: A Brief History of Humankind Yuval Noah Harari #ebook</code> 2.2.2. Audible Audiobooks: <code>#request Dark Matter Blake Crouch #audiobook https://www.audible.in/pd/Dark-Matter-Audiobook/B07B7BFH4M</code> 2.2.3. Kindle Unlimited(KU) books: <code>#request Harry Potter and the Chamber of Secrets J.K. Rowling #KU https://www.amazon.in/Harry-Potter-Chamber-Secrets-Rowling-ebook/dp/B019PIOJY0</code>""", parse_mode='HTML'))) results.append( InlineQueryResultArticle( id=uuid4(), title='3. Hashtags', input_message_content=InputTextMessageContent( """<b>3. Hashtags</b> Include appropriate hashtags in your requests which will help us track them better: 3.1. For languages other than English, Use <code>#Hindi</code>, <code>#Marathi</code>, <code>#Spanish</code> and so on. 3.2. For Kindle Unlimited - <code>#KU</code> ; Audible Audiobooks - <code>#audiobook</code> or #audible (provide their links as well).""", parse_mode='HTML'), description='Hashtags to include in your request')) results.append( InlineQueryResultArticle( id=uuid4(), title='4. Request Limits', input_message_content=InputTextMessageContent( """<b>4. Request Limits</b> 4.1. <b>DON'T</b> request for more than 3 books(ebooks+audiobooks) in a day. Exceeding it will trigger @ShiiinaBot to delete your request and you will have to wait for 24 hours to request again. Deleting and re-requesting if you made any mistake in your original request will not reset the count, instead learn how to Edit your message. 4.2. <b>Hoarding</b> books(even within request limit) is strictly not tolerated. Request only what you want to read/listen in the near future.""", parse_mode='HTML'), description='How many can you request per day?')) results.append( InlineQueryResultArticle( id=uuid4(), title='5. After You Request', input_message_content=InputTextMessageContent( """<b>5. After You Request</b> 5.1. Sit back and wait, DON'T tag or PM admins. 5.2. <b>DON'T</b> ask for updates on the book before 48 hours. You will receive an @ notification from a contributor or BookCrush Buddy when it is fulfilled. 5.3. If your request is not fulfilled, repost after <b>48 hours</b>. Subsequent reminders should also be spaced out 48 hours between each one. 5.4. After you get the book, <b>DON'T</b> be lazy and ask us for a specific format like pdf, epub etc. Convert it yourself online(@SmartConverter_bot or @cloud_convert_bot). """, parse_mode='HTML'), description='What you need to do after you request?')) results.append( InlineQueryResultArticle( id=uuid4(), title='6. Communication', input_message_content=InputTextMessageContent( """<b>6. Communication</b> 6.1. Use English at all times. 6.2. Refrain from any off-topic chatter. 6.3. <b>DON'T</b> PM any group member without permission. 6.4. <b>DON'T</b> spam with gifs/stickers, promotional messages or channel/group invites(t.me links) either in group or in PM.""", parse_mode='HTML'), description='Etiquette for communicating in the group')) results.append( InlineQueryResultArticle( id=uuid4(), title='7. Disallowed Names/Usernames', input_message_content=InputTextMessageContent( """<b>7. Disallowed Names/Usernames</b> 7.1. Names/Usernames containing single letter/double letters, NSFW words, Just emojis, special characters, punctuation marks or Annoying Unicode/RTL characters which mess up the Telegram UI. <i>Anyone violating this rule will be muted until the username no longer violates any of the above conditions. Message any admin to be un-muted once you comply with the name rule.</i>""", parse_mode='HTML'), )) results.append( InlineQueryResultArticle( id=uuid4(), title='8. What will get you muted/kicked/(f)banned?', input_message_content=InputTextMessageContent( """<b>8. What will get you muted/kicked/(f)banned?</b> 8.1. <b>Violating</b> any of the above rules(1-7) will be first met with a friendly notice, repeated violations will each lead to a warning and 5 such warnings to getting muted forever. 8.2. <b>Abusing</b> members/admins in PM will directly lead to getting fedbanned in all BookCrush groups. 8.3. <b>Hoarding</b> books without considering the time and effort of admins/contributors that goes into ripping ebooks/audiobooks. Such violators will be tracked and muted/banned accordingly. 8.4. <b>Having</b> one or more Alternate IDs so as to bypass the request limit.""", parse_mode='HTML'), description='Things you shouldn\'t do to be a good member')) from telegram import InlineKeyboardButton, InlineKeyboardMarkup #requesting using the bot if query.lower().strip().startswith('r'): origquery = query request = query.split(',', 4) fullrequest = '' for req in request: if (req == 'r'): continue #if(req.isspace()): # continue; fullrequest = fullrequest + req.strip( ) + """\n""" #if req.startswith('http') else fullrequest + req.strip().title() + """\n""" results = list() keyboard = [[ InlineKeyboardButton("Repost/Edit", switch_inline_query_current_chat=origquery), #], #[ InlineKeyboardButton("New Request", switch_inline_query_current_chat=''), ]] markup = InlineKeyboardMarkup(keyboard) try: results.append( InlineQueryResultArticle( id=uuid4(), title='Request ebook: ' + request[1].strip().title() + ' ; ' + request[2].strip().title(), input_message_content=InputTextMessageContent( """#request\n""" + fullrequest.strip() + """\n#ebook""", parse_mode='HTML', disable_web_page_preview=True), reply_markup=markup, description='Request an ebook', thumb_url= 'https://telegra.ph/file/f9bc07b2d216238b2a910.png', thumb_width=30, thumb_height=30)) except: #results = list() results.append( InlineQueryResultArticle( id=uuid4(), title='Author Name Missing!', input_message_content=InputTextMessageContent( """<i>Author Name Missing!\nTry again...\nType r, BookName(s), AuthorName, Language Tags(if any)</i>""", parse_mode='HTML'), description= 'Type r, BookName(s), AuthorName, Language Tags(if any)', thumb_url= 'https://telegra.ph/file/f9bc07b2d216238b2a910.png', thumb_width=30, thumb_height=30)) #print(fullrequest) try: results.append( InlineQueryResultArticle( id=uuid4(), title='Request audiobook: ' + request[1].strip().title() + ' ; ' + request[2].strip().title() + ' ; ' + request[3].strip(), input_message_content=InputTextMessageContent( """#request\n""" + fullrequest.strip() + """\n#audiobook""", parse_mode='HTML', disable_web_page_preview=True), reply_markup=markup, description='Request an Audible Audiobook', thumb_url= 'https://telegra.ph/file/f91a6a03e5592573a6ff4.jpg', thumb_width=30, thumb_height=30)) except: #results = list() results.append( InlineQueryResultArticle( id=uuid4(), title='Audible Link Missing!', input_message_content=InputTextMessageContent( """<i>Audible Link Missing!\nTry again...\nType r, BookName(s), AuthorName, AudibleLink, Language Tags(if any)</i>""", parse_mode='HTML'), description= 'Type r, BookName(s), AuthorName, AudibleLink, Language Tags(if any)', thumb_url= 'https://telegra.ph/file/f91a6a03e5592573a6ff4.jpg', thumb_width=30, thumb_height=30)) try: print("link is" + request[3]) results.append( InlineQueryResultArticle( id=uuid4(), title='Request KU book: ' + request[1].strip().title() + ' ; ' + request[2].strip().title() + ' ; ' + request[3].strip(), input_message_content=InputTextMessageContent( """#request\n""" + fullrequest.strip() + """\n#KU""", parse_mode='HTML', disable_web_page_preview=True), reply_markup=markup, description='Request a Kindle Unlimited ebook', thumb_url= 'https://telegra.ph/file/31bdcc94a29e964acc5d9.png', thumb_width=30, thumb_height=30)) except: #results = list() results.append( InlineQueryResultArticle( id=uuid4(), title='KU Link Missing!', input_message_content=InputTextMessageContent( """<i>KU Link Missing!\nTry again...\nType r, BookName(s), AuthorName, Amazon KU Link, Language Tags(if any)</i>""", parse_mode='HTML'), description= 'Type r, BookName(s), AuthorName, Amazon KU Link, Language Tags(if any)', thumb_url= 'https://telegra.ph/file/31bdcc94a29e964acc5d9.png', thumb_width=30, thumb_height=30)) #request format if query.lower() == 'format': results = list() results.append( InlineQueryResultArticle( id=uuid4(), title='Request Format', input_message_content=InputTextMessageContent( """<code>#request Book's name Author's name #ebook or #audiobook [Amazon link to audiobook/KU book, if applicable]</code>""", parse_mode='HTML'), )) #bookcrushpress rules if query.lower() == 'press': results = list() results.append( InlineQueryResultArticle( id=uuid4(), title='BookCrushPress Rules', input_message_content=InputTextMessageContent( """https://telegra.ph/BookCrush-Press-Group-Rules-12-05""", parse_mode='HTML'), thumb_url='https://telegra.ph/file/9cc715bb08a9ce45c0ef6.png', thumb_width=30, thumb_height=30)) context.bot.answer_inline_query(update.inline_query.id, results)
from telegram import InputTextMessageContent, InlineQueryResultArticle connection_error_message = InputTextMessageContent(message_text='Network error.') connection_error_response = InlineQueryResultArticle( id='networkerror', title='No response from Gelbooru', description='Please try again a little later.', input_message_content=connection_error_message) value_error_message = InputTextMessageContent(message_text='No results found with those tags.') value_error_response = InlineQueryResultArticle( id='noresults', title='No results found', description='Please try different tags.', input_message_content=value_error_message)
from telegram import InlineQueryResultArticle, InputTextMessageContent from uuid import uuid4 inline_welp_message = '''Hello There.\n @PruRobot ket <http status code>\n @PruRobot dogge <http status code>\n Kode l1nk : https://github.com/prkprime/PruRobot ''' inline_welp = InlineQueryResultArticle( id=uuid4(), title='Click here for Welp', input_message_content=InputTextMessageContent(message_text=inline_welp_message), )
def inlineparse(update, context): inline_query = update.inline_query query = inline_query.query helpmsg = [ InlineQueryResultArticle( id=uuid4(), title="帮助", description="将 Bot 添加到群组可以自动匹配消息, Inline 模式只可发单张图。", reply_markup=sourcecodemarkup, input_message_content=InputTextMessageContent( "欢迎使用 @bilifeedbot 的 Inline 模式来转发动态,您也可以将 Bot 添加到群组自动匹配消息。"), ) ] if not query: inline_query.answer(helpmsg) return try: url = re.search(regex, query).group(0) except AttributeError: inline_query.answer(helpmsg) return logger.info(f"Inline: {url}") f = asyncio.run(feedparser(url)) if not f: logger.warning("解析错误!") return if not f.mediaurls: results = [ InlineQueryResultArticle( id=uuid4(), title=f.user, description=f.content, reply_markup=origin_link(f.url), input_message_content=InputTextMessageContent( captions(f), parse_mode=ParseMode.MARKDOWN_V2, disable_web_page_preview=True, ), ) ] else: if f.mediatype == "video": results = [ InlineQueryResultVideo( id=uuid4(), caption=captions(f), title=f.user, description=f.content, mime_type="video/mp4", parse_mode=ParseMode.MARKDOWN_V2, reply_markup=origin_link(f.url), thumb_url=f.mediathumb, video_url=f.mediaurls[0], ) ] if f.mediatype == "audio": results = [ InlineQueryResultAudio( id=uuid4(), caption=captions(f), title=f.mediatitle, description=f.content, audio_duration=f.mediaduration, audio_url=f.mediaurls[0], parse_mode=ParseMode.MARKDOWN_V2, performer=f.user, reply_markup=origin_link(f.url), thumb_url=f.mediathumb, ) ] else: results = [ InlineQueryResultGif( id=uuid4(), caption=captions(f), title=f"{f.user}: {f.content}", gif_url=img, parse_mode=ParseMode.MARKDOWN_V2, reply_markup=origin_link(f.url), thumb_url=img, ) if ".gif" in img else InlineQueryResultPhoto( id=uuid4(), caption=captions(f), title=f.user, description=f.content, parse_mode=ParseMode.MARKDOWN_V2, photo_url=img + "@1280w.jpg", reply_markup=origin_link(f.url), thumb_url=img + "@512w_512h.jpg", ) for img in f.mediaurls ] if len(results) == 1: results.extend(helpmsg) inline_query.answer(results)
def inline_caps(bot, update): user_id = update.inline_query.from_user.id args = helper_global.value(str(user_id) + "_status", "0,0") params = args.split(",") channel_id = int(params[0]) msg_id = int(params[1]) if channel_id == 0: bot.answer_inline_query(update.inline_query.id, []) return config = helper_database.get_channel_config(channel_id) if config is None: bot.answer_inline_query(update.inline_query.id, []) return channel_lang = config[1] recent = config[3] query = update.inline_query.query if len(query.strip()) == 0: bot.answer_inline_query(update.inline_query.id, [], switch_pm_text=helper_global.value( "reply_prompt", "comment here first", lang=channel_lang), switch_pm_parameter="0", cache_time=0, is_personal=True) return records = helper_database.get_recent_records(channel_id, msg_id, recent, 0) results = [] for idx, record in enumerate(records): name = record[3] content = record[5] msg_user_id = record[8] row_id = int(record[11]) results.append( InlineQueryResultArticle( id=idx, title=name, description=re.sub("<.*?>", "", content).replace('<', '<').replace('>', '>'), input_message_content=InputTextMessageContent( message_text=query.replace('<', '<').replace('>', '>'), parse_mode='HTML'), reply_markup=InlineKeyboardMarkup([[ InlineKeyboardButton(helper_global.value( "reply_to", "Reply to: ", lang=channel_lang) + name, callback_data="notify,%d,%d,%d" % (channel_id, msg_id, row_id)) ]]))) bot.answer_inline_query(update.inline_query.id, results, switch_pm_text=helper_global.value( "reply_prompt", "comment here first", lang=channel_lang), switch_pm_parameter="0", cache_time=0, is_personal=True)
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() offset = update.inline_query.offset if offset == '': offset = 0 else: offset = int(offset) 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()) \ .limit(10) \ .offset(offset) \ .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()) \ .limit(10) \ .offset(offset) \ .all() # Try to find polls that are shared by external people via uuid if len(polls) == 0 and len(query) == 36: try: poll_uuid = uuid.UUID(query) polls = session.query(Poll) \ .filter(Poll.uuid == poll_uuid) \ .all() except ValueError: pass 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, user=user, inline_query=True) keyboard = InlineKeyboardMarkup([[ InlineKeyboardButton('Please ignore this', callback_data='100:0:0') ]]) content = InputTextMessageContent( text, parse_mode='markdown', disable_web_page_preview=True, ) description = poll.description[: 100] if poll.description is not None else None results.append( InlineQueryResultArticle( poll.id, poll.name, description=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', next_offset=str(offset + 10), )
def inlinequery(bot, update): """Handle the inline query.""" query = update.inline_query.query results = [] if (not query): update.inline_query.answer(results) return zalgo_res = zalgo_txt(query) results.append( InlineQueryResultArticle( id=uuid4(), title= "Zalgo (Z̙͑͘a̵̺̳̫̅́́͋l̝̠͑̃͘͢ǵ̨͎̰͈͂͆̑ơ̳͚̳͒ W̹͛͝a̛͙̫̤͌ṋ͖̙̇ͧ̊͜ t͙ͮ̀̈́ͣ͞ͅsͭ̐ͥ͢͜ Ÿ̶͈́ͣ͋o̡͖̜͓͆̿ų̜͍͎͛͌̏ͨ)", description=zalgo_res, input_message_content=InputTextMessageContent( message_text=zalgo_res))) up_and_down_res = upper_and_lower(query) results.append( InlineQueryResultArticle(id=uuid4(), title="Up and Down (bRoKeN cApSlOcK)", description=up_and_down_res, input_message_content=InputTextMessageContent( message_text=up_and_down_res))) # InlineQueryResultArticle( # id=uuid4(), # title="Binary", # description="0s and 1s", # input_message_content=InputTextMessageContent( # message_text=binary(query))), double_struck_res = double_struck(query) results.append( InlineQueryResultArticle(id=uuid4(), title="Double Struck (𝔽𝕒𝕟𝕔𝕪)", description=double_struck_res, input_message_content=InputTextMessageContent( message_text=double_struck_res))) cursive_res = cursive(query) results.append( InlineQueryResultArticle(id=uuid4(), title="Cursive (𝓐𝓵𝓼𝓸 𝓯𝓪𝓷𝓬𝔂)", description=cursive_res, input_message_content=InputTextMessageContent( message_text=cursive_res))) spaced_res = spaced(query) results.append( InlineQueryResultArticle(id=uuid4(), title="Spaced (S P A C E D)", description=spaced_res, input_message_content=InputTextMessageContent( message_text=spaced_res))) circled_res = circled(query) results.append( InlineQueryResultArticle(id=uuid4(), title="Circled (Ⓒⓘⓡⓒⓛⓔⓢ)", description=circled_res, input_message_content=InputTextMessageContent( message_text=circled_res))) negative_circled_res = negative_circled(query) results.append( InlineQueryResultArticle(id=uuid4(), title="Filled Circled (🅒🅘🅡🅒🅛🅔🅢 🅑🅤🅣 🅕🅘🅛🅛🅔🅓)", description=negative_circled_res, input_message_content=InputTextMessageContent( message_text=negative_circled_res))) parenthesis_res = parenthesis(query) results.append( InlineQueryResultArticle(id=uuid4(), title="Parenthesis [🄟⒜⒭⒠⒩⒯⒣⒠⒮⒤⒮]", description=parenthesis_res, input_message_content=InputTextMessageContent( message_text=parenthesis_res))) fraktur_res = fraktur(query) results.append( InlineQueryResultArticle(id=uuid4(), title="Gothic (𝔊𝔬𝔱𝔥𝔦𝔠)", description=fraktur_res, input_message_content=InputTextMessageContent( message_text=fraktur_res))) leet_res = leet(query) results.append( InlineQueryResultArticle(id=uuid4(), title="Leet Speak (1337, y0!)", description=leet_res, input_message_content=InputTextMessageContent( message_text=leet_res))) large_res = large(query) results.append( InlineQueryResultArticle(id=uuid4(), title="Full-width (BIG!)", description=large_res, input_message_content=InputTextMessageContent( message_text=large_res))) reverse_res = reverse(query) results.append( InlineQueryResultArticle(id=uuid4(), title="Reversed (desreveR)", description=reverse_res, input_message_content=InputTextMessageContent( message_text=reverse_res))) morse_code_res = morse_code(query) results.append( InlineQueryResultArticle(id=uuid4(), title="Morse Code (-- --- .-. ... .)", description=morse_code_res, input_message_content=InputTextMessageContent( message_text=morse_code_res))) strikethrough_res = strikethrough(query) results.append( InlineQueryResultArticle( id=uuid4(), title="Strikethrough (̶̶S̶t̶r̶i̶k̶e̶t̶h̶r̶o̶u̶g̶h̶)", description=strikethrough_res, input_message_content=InputTextMessageContent( message_text=strikethrough_res))) small_caps_res = small_caps(query) results.append( InlineQueryResultArticle(id=uuid4(), title="Small Caps (sᴍᴀʟʟ)", description=small_caps_res, input_message_content=InputTextMessageContent( message_text=small_caps_res))) superscript_res = superscript(query) results.append( InlineQueryResultArticle(id=uuid4(), title="Superscript (Superˢᶜʳᶦᵖᵗ)", description=superscript_res, input_message_content=InputTextMessageContent( message_text=superscript_res))) underline_res = underline(query) results.append( InlineQueryResultArticle(id=uuid4(), title="Underline (U̲n̲d̲e̲r̲l̲i̲n̲e̲)", description=underline_res, input_message_content=InputTextMessageContent( message_text=underline_res))) # InlineQueryResultArticle( # id=uuid4(), # title="Bold", # description="*text*", # input_message_content=InputTextMessageContent( # message_text="*{}*".format(query), # parse_mode=ParseMode.MARKDOWN)), # InlineQueryResultArticle( # id=uuid4(), # title="Italic", # description="_text_", # input_message_content=InputTextMessageContent( # message_text="_{}_".format(query), # parse_mode=ParseMode.MARKDOWN)), # InlineQueryResultArticle( # id=uuid4(), # title="Monospace", # description="```text```", # input_message_content=InputTextMessageContent( # message_text="```{}```".format(query), # parse_mode=ParseMode.MARKDOWN)), cebolinha_res = cebolinha(query) results.append( InlineQueryResultArticle(id=uuid4(), title="Cebolinha (Troque seu R por um L)", description=cebolinha_res, input_message_content=InputTextMessageContent( message_text=cebolinha_res))) update.inline_query.answer(results)
def search(update, context): infos_user = update.effective_user chat_id = infos_user.id infos_query = update.inline_query query_string = infos_query.query query_id = infos_query.id if not authorized(chat_id): return try: tongue = infos_user.language_code except AttributeError: tongue = "en" init_user(chat_id, tongue) if ".chart." == query_string: search1 = request(api_chart).json() result = [ InlineQueryResultArticle( id=a["link"], title=a["title"], description=( "Artist: {}\nAlbum: {}".format( a["artist"]["name"], a["album"]["title"] ) ), thumb_url=a["album"]["cover_big"], input_message_content=InputTextMessageContent(a["link"]), ) for a in search1["tracks"]["data"] ] result += [ InlineQueryResultArticle( id="https://www.deezer.com/album/%d" % a["id"], title="%s (Album)" % a["title"], description=( "Artist: {}\nPosition: {}".format( a["artist"]["name"], a["position"] ) ), thumb_url=a["cover_big"], input_message_content=InputTextMessageContent( "https://www.deezer.com/album/%d" % a["id"] ), ) for a in search1["albums"]["data"] ] result += [ InlineQueryResultArticle( id=a["link"], title=a["name"], description="Position: %d" % a["position"], thumb_url=a["picture_big"], input_message_content=InputTextMessageContent(a["link"]), ) for a in search1["artists"]["data"] ] result += [ InlineQueryResultArticle( id=a["link"], title=a["title"], description=( "N° tracks: {}\nUser: {}".format(a["nb_tracks"], a["user"]["name"]) ), thumb_url=a["picture_big"], input_message_content=InputTextMessageContent(a["link"]), ) for a in search1["playlists"]["data"] ] else: query_string = query_string.replace("#", "") search = query_string method = "" if "alb:" in query_string or "art:" in query_string or "pla:" in query_string: search = query_string.split(query_string[:4])[-1] if "alb:" in query_string: method = "album" elif "art:" in query_string: method = "artist" elif "pla:" in query_string: method = "playlist" search1 = request(api_type1.format(method, search)).json() try: if search1["error"]: return except KeyError: pass if "alb:" in query_string: result = [ InlineQueryResultArticle( id=a["link"], title=a["title"], description=( "Artist: {}\nTracks: {}".format( a["artist"]["name"], a["nb_tracks"] ) ), thumb_url=a["cover_big"], input_message_content=InputTextMessageContent(a["link"]), ) for a in search1["data"] ] elif "art:" in query_string: result = [ InlineQueryResultArticle( id=a["link"], title=a["name"], description=( "Albums: {}\nFollowers: {}".format( a["nb_album"], a["nb_fan"] ) ), thumb_url=a["picture_big"], input_message_content=InputTextMessageContent(a["link"]), ) for a in search1["data"] ] elif "pla:" in query_string: result = [ InlineQueryResultArticle( id=a["link"], title=a["title"], description=( "N° tracks: {}\nUser: {}".format( a["nb_tracks"], a["user"]["name"] ) ), thumb_url=a["picture_big"], input_message_content=InputTextMessageContent(a["link"]), ) for a in search1["data"] ] else: if "lbl:" in query_string or "trk:" in query_string: search = query_string.split(query_string[:4])[-1] if "lbl:" in query_string: method = "label" elif "trk:" in query_string: method = "track" search1 = request(api_type2.format(method, search)).json() try: if search1["error"]: return except KeyError: pass result = [ InlineQueryResultArticle( id=a["link"], title=a["title"], description=( "Artist: {}\nAlbum: {}".format( a["artist"]["name"], a["album"]["title"] ) ), thumb_url=a["album"]["cover_big"], input_message_content=InputTextMessageContent(a["link"]), ) for a in search1["data"] ] already = [] for a in search1["data"]: ids = a["album"]["id"] if not ids in already: result += [ InlineQueryResultArticle( id=ids, title="%s (Album)" % a["album"]["title"], description=a["artist"]["name"], thumb_url=a["album"]["cover_big"], input_message_content=InputTextMessageContent( "https://www.deezer.com/album/%d" % a["album"]["id"] ), ) ] already.append(ids) try: bot.answerInlineQuery(query_id, result) except (error.BadRequest, error.TimedOut): pass
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() offset = update.inline_query.offset if offset == "": offset = 0 elif offset == "Done": update.inline_query.answer( [], cache_time=0, is_personal=True, ) return else: offset = int(offset) 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()).limit(10).offset(offset).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()).limit(10).offset(offset).all()) # Try to find polls that are shared by external people via uuid if len(polls) == 0 and len(query) == 36: try: poll_uuid = uuid.UUID(query) poll = (session.query(Poll).filter( Poll.uuid == poll_uuid).offset(offset).one_or_none()) if poll is not None: # Check if sharin is enabled # If not, check if the owner issued the query if not poll.allow_sharing and user != poll.user: polls = [] else: polls = [poll] except ValueError: pass if len(polls) == 0: update.inline_query.answer( [], cache_time=0, is_personal=True, ) else: results = [] for poll in polls: inline_reference_count = 0 for reference in poll.references: if reference.type == ReferenceType.inline.name: inline_reference_count += 1 max_share_amount = config["telegram"]["max_inline_shares"] if inline_reference_count > max_share_amount: text = i18n.t("poll.shared_too_often", locale=poll.locale, amount=max_share_amount) results.append( InlineQueryResultArticle( uuid.uuid4(), poll.name, description=text, input_message_content=InputTextMessageContent(text), )) continue text = i18n.t("poll.please_wait", locale=poll.locale) keyboard = InlineKeyboardMarkup([[ InlineKeyboardButton("Please ignore this", callback_data="100:0:0") ]]) content = InputTextMessageContent( text, parse_mode="markdown", disable_web_page_preview=True, ) description = (poll.description[:100] if poll.description is not None else None) results.append( InlineQueryResultArticle( poll.id, poll.name, description=description, input_message_content=content, reply_markup=keyboard, )) if len(polls) < 10: offset = "Done" else: offset + 10 update.inline_query.answer( results, cache_time=0, is_personal=True, next_offset=str(offset), )
def inlineinfo(query: str, update: Update, context: CallbackContext) -> None: """Handle the inline query.""" bot = context.bot query = update.inline_query.query log.info(query) user_id = update.effective_user.id try: search = query.split(" ", 1)[1] except IndexError: search = user_id try: user = bot.get_chat(int(search)) except (BadRequest, ValueError): user = bot.get_chat(user_id) chat = update.effective_chat sql.update_user(user.id, user.username) text = (f"<b>Information:</b>\n" f"• ID: <code>{user.id}</code>\n" f"• First Name: {html.escape(user.first_name)}") if user.last_name: text += f"\n• Last Name: {html.escape(user.last_name)}" if user.username: text += f"\n• Username: @{html.escape(user.username)}" text += f"\n• Permanent user link: {mention_html(user.id, 'link')}" nation_level_present = False if user.id == OWNER_ID: text += '\n\nThis person is my owner' nation_level_present = True elif user.id in DEV_USERS: text += '\n\nThis Person is a part of Eagle Union' nation_level_present = True elif user.id in SUDO_USERS: text += '\n\nThe Nation level of this person is Royal' nation_level_present = True elif user.id in SUPPORT_USERS: text += '\n\nThe Nation level of this person is Sakura' nation_level_present = True elif user.id in SARDEGNA_USERS: text += '\n\nThe Nation level of this person is Sardegna' nation_level_present = True elif user.id in WHITELIST_USERS: text += '\n\nThe Nation level of this person is Neptunia' nation_level_present = True if nation_level_present: text += ' [<a href="https://t.me/{}?start=nations">?</a>]'.format( bot.username) try: spamwtc = sw.get_ban(int(user.id)) if spamwtc: text += "<b>\n\n• SpamWatched:\n</b> Yes" text += f"\n• Reason: <pre>{spamwtc.reason}</pre>" text += "\n• Appeal at @SpamWatchSupport" else: text += "<b>\n\n• SpamWatched:</b> No" except: pass # don't crash if api is down somehow... apst = requests.get( f'https://api.intellivoid.net/spamprotection/v1/lookup?query={context.bot.username}' ) api_status = apst.status_code if (api_status == 200): try: status = client.raw_output(int(user.id)) # ptid = status["results"]["private_telegram_id"] op = status.get("results").get("attributes").get("is_operator") ag = status.get("results").get("attributes").get("is_agent") wl = status.get("results").get("attributes").get("is_whitelisted") ps = status.get("results").get("attributes").get( "is_potential_spammer") sp = status.get("results").get("spam_prediction").get( "spam_prediction") hamp = status.get("results").get("spam_prediction").get( "ham_prediction") blc = status.get("results").get("attributes").get("is_blacklisted") blres = status.get("results").get("attributes").get( "blacklist_reason") text += "\n\n<b>SpamProtection:</b>" # text += f"<b>\n• Private Telegram ID:</b> <code>{ptid}</code>\n" text += f"<b>\n• Operator:</b> <code>{op}</code>\n" text += f"<b>• Agent:</b> <code>{ag}</code>\n" text += f"<b>• Whitelisted:</b> <code>{wl}</code>\n" text += f"<b>• Spam/Ham Prediction:</b> <code>{round((sp / hamp * 100), 3)}%</code>\n" text += f"<b>• Potential Spammer:</b> <code>{ps}</code>\n" text += f"<b>• Blacklisted:</b> <code>{blc}</code>\n" text += f"<b>• Blacklist Reason:</b> <code>{blres}</code>\n" except HostDownError: text += "\n\n<b>SpamProtection:</b>" text += "\nCan't connect to Intellivoid SpamProtection API\n" else: text += "\n\n<b>SpamProtection:</b>" text += f"\n<code>API RETURNED: {api_status}</code>\n" num_chats = sql.get_user_num_chats(user.id) text += f"\n• Chat count: <code>{num_chats}</code>" kb = InlineKeyboardMarkup([[ InlineKeyboardButton(text="Report Error", url='https://t.me/zerounions'), InlineKeyboardButton( text="Search again", switch_inline_query_current_chat=".info ", ), ]]) results = [ InlineQueryResultArticle( id=str(uuid4()), title=f"User info of {html.escape(user.first_name)}", input_message_content=InputTextMessageContent( text, parse_mode=ParseMode.HTML, disable_web_page_preview=True), reply_markup=kb), ] update.inline_query.answer(results, cache_time=5)
def get_help_messages(): results = [ InlineQueryResultArticle( id=uuid4(), title=("Retrieve cryptocurrency prices"), description=('"BTC", "bitcoin"'), thumb_url="https://imgur.com/joQ2gGR.png", input_message_content=InputTextMessageContent(\ "To get information about a cryptocurrency, just type " \ + "the name or the shorthand abbreviation. For example, " \ + "if you want to see information about Ethereum, you " \ + "can just type `ethereum` or `ETH` (case does not " \ + "matter), and Cryptora will get up to the moment " \ + "information about Ethereum for you. \n\nYou can " \ + "also type the name of your cryptocurrency, followed " \ + "by a date in MM/DD/YYYY format (or Month Day, Year " \ + "format) to get historical pricing. Alternatively, " \ + "you can type relative dates too – so typing " \ + "`bitcoin 2 weeks ago` will get you the price of " \ + "Bitcoin two weeks ago.", ParseMode.MARKDOWN)), InlineQueryResultArticle( id=uuid4(), title=("Convert between cryptocurrencies and U.S. dollars"), description=('"$2000 BTC", "50 BTC"'), thumb_url="https://imgur.com/8XwhAWO.png", input_message_content=InputTextMessageContent("Cryptora " \ + "can convert cryptocurrency values to U.S. dollars. Just " \ + "type in a cryptocurrency value – for instance, `50 ETH` " \ + "– to see the USD value of 50 ETH. " \ + "\n\nYou can also type in a U.S. dollar amount and follow " \ + "that with a cryptocurrency to convert from dollars to a " \ + "cryptocurrency. For example, `$50 ETH` will retrieve the " \ + "quantity of Ethereum that $50 will get you.", ParseMode.MARKDOWN)), InlineQueryResultArticle( id=uuid4(), title=("Read the latest cryptocurrency headlines"), description=('"news"'), thumb_url="https://imgur.com/FUX10Vi.png", input_message_content=InputTextMessageContent("You can type " \ + "`news` to get the ten latest headlines from CoinDesk.com " \ + "in-line. Tap a link to send to your chat.", ParseMode.MARKDOWN)), InlineQueryResultArticle( id=uuid4(), title=("See the top cryptocurrencies"), thumb_url="https://imgur.com/g6YajTp.png", description=('"top"'), input_message_content=InputTextMessageContent("Type `top` " \ + "to see the top 50 cryptocurrencies, ranked by " \ + "their market capitalization. If you'd like to see " \ + "a specific number of cryptocurrencies, you can type " \ + "`top x` (where x ≤ 50) – so typing `top 20` will display " \ + "the top 20 cryptocurrencies.", ParseMode.MARKDOWN)), InlineQueryResultArticle( id=uuid4(), title=("See real-time trading prices on GDAX"), thumb_url="https://imgur.com/Eyh7KSb.png", description='"gdax"', input_message_content=InputTextMessageContent("Need more up-to-the-minute " \ + "prices than the standard cryptocurrency lookup? Cryptora can retrieve " \ + "the prices of bitcoin, litecoin, and ethereum on GDAX. Just type " \ + "`gdax` to get the prices in-line.", ParseMode.MARKDOWN)), InlineQueryResultArticle( id=uuid4(), title=("See global stats"), thumb_url="https://imgur.com/MyjXCmb.png", description='"global"', input_message_content=InputTextMessageContent("Type 'global' to" \ + "see a variety of up-to-the-minute global statistics." ,\ ParseMode.MARKDOWN)), InlineQueryResultArticle( id=uuid4(), title=("Compare multiple cryptocurrencies"), thumb_url="https://imgur.com/Gbnrtod.png", description='"btc, ltc, eth, dash, iota, ripple"', input_message_content=InputTextMessageContent("You can " \ + "search for multiple cryptocurrencies in a single "\ + "query by typing a selection of cryptocurrencies " \ + "(either their name, their symbol, or you can even " \ + "mix it up), separated by commas. For example, you " \ + "can type `btc, ethereum, omg, xrb, monero, ripple` to send the " \ + "prices, market capitalizations, or percent change " \ + "values of Bitcoin, Ethereum, OmiseGO, RaiBlocks, " \ + "Monero, and Ripple in one message.", ParseMode.MARKDOWN)), ] return results
def media_query(query: str, update: Update, context: CallbackContext) -> None: """ Handle anime inline query. """ results: List = [] try: results: List = [] r = requests.post('https://graphql.anilist.co', data=json.dumps({ 'query': MEDIA_QUERY, 'variables': { 'search': query } }), headers={ 'Content-Type': 'application/json', 'Accept': 'application/json' }) res = r.json() data = res['data']['Page']['media'] res = data for data in res: title_en = data["title"].get("english") or "N/A" title_ja = data["title"].get("romaji") or "N/A" format = data.get("format") or "N/A" type = data.get("type") or "N/A" bannerimg = data.get( "bannerImage" ) or "https://telegra.ph/file/cc83a0b7102ad1d7b1cb3.jpg" try: des = data.get("description").replace("<br>", "").replace("</br>", "") description = des.replace("<i>", "").replace("</i>", "") or "N/A" except AttributeError: description = data.get("description") try: description = html.escape(description) except AttributeError: description = description or "N/A" if len((str(description))) > 700: description = description[0:700] + "....." avgsc = data.get("averageScore") or "N/A" status = data.get("status") or "N/A" genres = data.get("genres") or "N/A" genres = ", ".join(genres) img = f"https://img.anili.st/media/{data['id']}" or "https://telegra.ph/file/cc83a0b7102ad1d7b1cb3.jpg" aurl = data.get("siteUrl") kb = InlineKeyboardMarkup([ [ InlineKeyboardButton( text="Read More", url=aurl, ), InlineKeyboardButton( text="Search again", switch_inline_query_current_chat=".anilist ", ), ], ]) txt = f"<b>{title_en} | {title_ja}</b>\n" txt += f"<b>Format</b>: <code>{format}</code>\n" txt += f"<b>Type</b>: <code>{type}</code>\n" txt += f"<b>Average Score</b>: <code>{avgsc}</code>\n" txt += f"<b>Status</b>: <code>{status}</code>\n" txt += f"<b>Genres</b>: <code>{genres}</code>\n" txt += f"<b>Description</b>: <code>{description}</code>\n" txt += f"<a href='{img}'>­</a>" results.append( InlineQueryResultArticle( id=str(uuid4()), title=f"{title_en} | {title_ja} | {format}", thumb_url=img, description=f"{description}", input_message_content=InputTextMessageContent( txt, parse_mode=ParseMode.HTML, disable_web_page_preview=False), reply_markup=kb)) except Exception as e: kb = InlineKeyboardMarkup([ [ InlineKeyboardButton( text="Report error", url="t.me/zerounions", ), InlineKeyboardButton( text="Search again", switch_inline_query_current_chat=".anilist ", ), ], ]) results.append( InlineQueryResultArticle( id=str(uuid4()), title=f"Media {query} not found", input_message_content=InputTextMessageContent( f"Media {query} not found due to {e}", parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True), reply_markup=kb)) update.inline_query.answer(results, cache_time=5)
def inlinequery(update, context): """Handles the inline query.""" query = update.inline_query.query buttons = [[ InlineKeyboardButton(text="Search Again", switch_inline_query_current_chat="") ]] if len(query) == 0: results = [ InlineQueryResultArticle( id=uuid4(), title="Search any keyword", input_message_content=InputTextMessageContent( f"*Search any torrent\nExample : *`Avengers`\n\n{FOOTER_TEXT}", parse_mode="Markdown"), reply_markup=InlineKeyboardMarkup(buttons)) ] context.bot.answer_inline_query(update.inline_query.id, results=results) return print(len(query)) torrent = torrent_search(query) results = [] if torrent == None: results.append( InlineQueryResultArticle( id=uuid4(), title="Search any keyword", input_message_content=InputTextMessageContent( f"*Search any torrent\nExample : *`Avengers`\n\n{FOOTER_TEXT}", parse_mode="Markdown"), reply_markup=InlineKeyboardMarkup(buttons))) context.bot.answer_inline_query(update.inline_query.id, results=results) return if len(torrent) == 0: results.append( InlineQueryResultArticle( id=uuid4(), title="404 Not Found", input_message_content=InputTextMessageContent( f"*f**k there is no results for your query {query}*\n\n{FOOTER_TEXT}", parse_mode="Markdown"), reply_markup=InlineKeyboardMarkup(buttons))) context.bot.answer_inline_query(update.inline_query.id, results=results) return for response in torrent[:15]: name = response.get("name") age = response.get("age") leechers = response.get("leecher") magnet_link = response.get("magnet") seeders = response.get("seeder") size = response.get("size") type_of_file = response.get("type") site = response.get("site") torrent_url = response.get("url") results.append( InlineQueryResultArticle( id=uuid4(), title=name, input_message_content=InputTextMessageContent( f"*Name : {name}\nSize : {size}\nAge : {age}\nLeechers : {leechers}\nNo: of seeds : {seeders}\nType of File : {type_of_file}\nTorrent Url : {torrent_url}*\n\n*Magnet Link : *`{magnet_link}`\n\n*Powered by {site} website*\n\n{FOOTER_TEXT}", parse_mode="Markdown"), reply_markup=InlineKeyboardMarkup(buttons))) context.bot.answer_inline_query(update.inline_query.id, results=results)
def inline_query_callback(update: Update, context: CallbackContext, chat_info: dict): query = update.inline_query.query if not query: logging.info("inline_request empty query") last_requests = get_last_request(update.effective_user.id) results = [] for r in last_requests: if not r.from_currency.is_active or not r.to_currency.is_active: continue try: price_request_result = convert( PriceRequest( amount=None, currency=r.from_currency.code, to_currency=r.to_currency.code, parser_name="InlineQuery", )) except NoRatesException: continue title = InlineFormatPriceRequestResult(price_request_result, chat_info["locale"]).get() text_to = FormatPriceRequestResult(price_request_result, chat_info["locale"]).get() ident = ( f"{r.from_currency.code}{r.to_currency.code}" f"{price_request_result.rate}{price_request_result.last_trade_at}" ) results.append( InlineQueryResultArticle( id=ident, title=title, input_message_content=InputTextMessageContent( text_to, disable_web_page_preview=True, parse_mode=ParseMode.MARKDOWN, ), )) write_request_log.delay( chat_id=update.effective_user.id, msg="", created_at=datetime.now(), tag="Inline All", ) else: tag = "" try: price_request = start_parse( query, chat_info["chat_id"], chat_info["locale"], chat_info["default_currency"], chat_info["default_currency_position"], ) logging.info(f"inline_request: {query} -> {price_request}") tag = price_request.parser_name price_request_result = convert(price_request) logging.info(f"inline_request: {price_request_result}") title = InlineFormatPriceRequestResult(price_request_result, chat_info["locale"]).get() text_to = FormatPriceRequestResult(price_request_result, chat_info["locale"]).get() ident = ( f"{price_request.currency}|{price_request.to_currency}|" f"{price_request_result.rate}|{price_request_result.last_trade_at}" ) results = [ InlineQueryResultArticle( id=ident, title=title, input_message_content=InputTextMessageContent( text_to, disable_web_page_preview=True, parse_mode=ParseMode.MARKDOWN, ), ) ] except (ValidationException, ConverterException): logging.info(f"inline_request unrecognized: {query}") results = [] finally: if len(query) <= settings.MAX_LEN_MSG_REQUESTS_LOG: write_request_log.delay( chat_id=update.effective_user.id, msg=query, created_at=datetime.now(), tag=f"Inline {tag}" if tag else "Inline", ) update.inline_query.answer(results)
def inlinequery(bot, update): results = list() results.clear() link = '' # inline mode for zero character if len(update.inline_query.query) <= 5: results.clear() results.append( InlineQueryResultArticle( id=uuid4(), title=" ▶️ Retwittgram", description="type tweet link", url="https://twitter.com/user/status/9876543210", thumb_url=logo_address, input_message_content=InputTextMessageContent( " ♻️ @retwitgrambot sends your tweet beautifully "))) # inline mode in normal case else: link = re.search('(?P<url>https?://[^\s]+)', update.inline_query.query).group('url').split('?')[0] extend(link) pure_text = re.sub(r"http\S+", '', tweet.full_text) if extend_status: kb = [[ InlineKeyboardButton(text='🔗', url=link), InlineKeyboardButton(text='ℹ️', callback_data=link), InlineKeyboardButton(text='🔀', switch_inline_query=link) ]] if tweet.is_quote_status: response = pure_text + '\n\n' + ' 💬' + ' ' + \ tweet.quoted_status['user']['name'] + ' : ' + \ tweet.quoted_status['full_text'] + ' \n\n 👤 <a href=\"' + \ link + '\">' + tweet.user.name + '</a>' else: response = tweet.full_text + ' \n\n 👤 <a href=\"' + link + \ '\">' + tweet.user.name + '</a>' results.append( InlineQueryResultArticle( id=uuid4(), title=tweet.user.name, description=pure_text, reply_markup=InlineKeyboardMarkup( kb, resize_keyboard=True), input_message_content=InputTextMessageContent( response, parse_mode=ParseMode.HTML))) update.inline_query.answer(results) if 'media' in tweet.entities: if (tweet.entities['media'][0]['type'] == 'photo' and not tweet.extended_entities['media'][0]['type'] == 'video'): response = '<a href=\"' + \ tweet.entities['media'][0]['media_url_https'] + \ '\">‍</a> ' + pure_text + ' \n\n 👤 ' + \ tweet.user.name + '\n ' + \ tweet.entities['media'][0]['url'] results.append( InlineQueryResultArticle( id=uuid4(), title=tweet.user.name, description=tweet.full_text, url=link, thumb_url=tweet.entities['media'][0]['url'], reply_markup=InlineKeyboardMarkup( kb, resize_keyboard=True), input_message_content=InputTextMessageContent( response, parse_mode=ParseMode.HTML))) update.inline_query.answer(results) if tweet.extended_entities['media'][0]['video_info'][ 'variants'][0]['content_type'] == 'video/mp4': response = '<a href=\"' + \ tweet.extended_entities['media'][0]['video_info']['variants'][0]['url'] + \ '\">‍</a> ' + pure_text + ' \n\n 👤 ' + \ tweet.user.name + '\n ' +\ tweet.entities['media'][0]['url'] results.append( InlineQueryResultArticle( id=uuid4(), title=tweet.user.name, description=tweet.full_text, url=link, thumb_url=tweet.entities['media'][0]['url'], reply_markup=InlineKeyboardMarkup( kb, resize_keyboard=True), input_message_content=InputTextMessageContent( response, parse_mode=ParseMode.HTML))) update.inline_query.answer(results) elif tweet.extended_entities['media'][0]['video_info'][ 'variants'][1]['content_type'] == 'video/mp4': response = '<a href=\"' + \ tweet.extended_entities['media'][0]['video_info']['variants'][1]['url'] + \ '\">‍</a> ' + pure_text + ' \n\n 👤 ' + \ tweet.user.name + '\n ' +\ tweet.entities['media'][0]['url'] results.append( InlineQueryResultArticle( id=uuid4(), title=tweet.user.name, description=tweet.full_text, url=link, thumb_url=tweet.entities['media'][0]['url'], reply_markup=InlineKeyboardMarkup( kb, resize_keyboard=True), input_message_content=InputTextMessageContent( response, parse_mode=ParseMode.HTML))) update.inline_query.answer(results) if not extend_status: results.append( InlineQueryResultArticle( id=uuid4(), title=" ▶️ Retwittgram", description="❌", url="https://twitter.com/user/status/9876543210", thumb_url=logo_address, input_message_content=InputTextMessageContent( " ♻️ @retwitgrambot sends your tweet beautifully "))) update.inline_query.answer(results)
def search_podcast(user, keywords): searched_results = search_itunes(keywords) if not searched_results: podcasts = Podcast.objects( Q(name__icontains=keywords) & Q(subscribers=user)) if not podcasts: yield InlineQueryResultArticle( id='0', title="没有找到相关的播客 :(", description="换个关键词试试", input_message_content=InputTextMessageContent(":("), reply_markup=InlineKeyboardMarkup.from_button( InlineKeyboardButton( '返回搜索', switch_inline_query_current_chat=keywords))) else: yield InlineQueryResultArticle( id='0', title="没有找到相关的播客 :(", description="以下是在订阅列表中搜索到的结果:", input_message_content=InputTextMessageContent(":("), reply_markup=InlineKeyboardMarkup.from_button( InlineKeyboardButton( '返回搜索', switch_inline_query_current_chat=keywords))) for index, podcast in enumerate(podcasts): if podcast.logo.file_id: yield InlineQueryResultCachedPhoto( id=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=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)) else: for result in searched_results: name = re.sub(r"[_*`]", ' ', result['collectionName']) host = re.sub(r"[_*`]", ' ', result['artistName']) feed = result.get('feedUrl') or '(此播客没有提供订阅源)' thumbnail_small = result.get('artworkUrl60') # 如果不在 机器人主页,则: # [InlineKeyboardButton('前 往 B O T', url = f"https://t.me/{manifest.bot_id}")], yield InlineQueryResultArticle( id=result['collectionId'], title=name, input_message_content=InputTextMessageContent(feed, parse_mode=None), description=host, thumb_url=thumbnail_small or None, thumb_height=60, thumb_width=60)
def inlinequery(update, context): # get entered text message query = update.inline_query.query.strip() if len(query) < 2 or len(query) > 40: update.inline_query.answer([ InlineQueryResultArticle( id=uuid4(), title="Not enough arguments", description="Text must be between 2 and 40 characters long.", thumb_url= "https://cdn.pixabay.com/photo/2013/07/12/18/09/help-153094__340.png", input_message_content=InputTextMessageContent( "Usage: @isgonebot <overlay text>\n\nText must be between 2 and 40 characters long.", parse_mode=ParseMode.MARKDOWN)) ]) return # generate query results results = [ InlineQueryResultVideo( id=uuid4(), title="🦀🦀 PAPAJ IS GONE 🦀🦀", description=query, thumb_url=f"{BASE_URL}/thumb/papaj.jpg?t={time.time()}", video_url= f"{BASE_URL}/video/{parse.quote_plus(query)}.mp4?style=papaj&font=comicsans&color=white&size=52&filter=classic&t={time.time()}", mime_type="video/mp4"), InlineQueryResultVideo( id=uuid4(), title="🦀🦀 DESPACITO IS GONE 🦀🦀", description=query, thumb_url=f"{BASE_URL}/thumb/classic.jpg?t={time.time()}", video_url= f"{BASE_URL}/video/{parse.quote_plus(query)}.mp4?style=classic&font=raleway&color=white&size=52&filter=classic&t={time.time()}", mime_type="video/mp4"), InlineQueryResultVideo( id=uuid4(), title="🦀🦀 KEBAB IS GONE 🦀🦀", description=query, thumb_url=f"{BASE_URL}/thumb/kebab.jpg?t={time.time()}", video_url= f"{BASE_URL}/video/{parse.quote_plus(query)}.mp4?style=kebab&font=impact&color=white&size=48&filter=snapchat&t={time.time()}", mime_type="video/mp4"), InlineQueryResultVideo( id=uuid4(), title="🦀🦀 STONOGA IS GONE 🦀🦀", description=query, thumb_url=f"{BASE_URL}/thumb/stonoga.jpg?t={time.time()}", video_url= f"{BASE_URL}/video/{parse.quote_plus(query)}.mp4?style=stonoga&font=timesnewroman&color=white&size=48&filter=topbottom&t={time.time()}", mime_type="video/mp4"), InlineQueryResultVideo( id=uuid4(), title="🦀🦀 FICHTL IS GONE 🦀🦀", description=query, thumb_url=f"{BASE_URL}/thumb/woodys.jpg?t={time.time()}", video_url= f"{BASE_URL}/video/{parse.quote_plus(query)}.mp4?style=woodys&font=potsdam&color=white&size=52&filter=classic&t={time.time()}", mime_type="video/mp4"), InlineQueryResultVideo( id=uuid4(), title="🦀🦀 RONNIE FERRARI IS GONE 🦀🦀", description=query, thumb_url=f"{BASE_URL}/thumb/onabytakchciala.jpg?t={time.time()}", video_url= f"{BASE_URL}/video/{parse.quote_plus(query)}.mp4?style=onabytakchciala&font=comicsans&color=white&size=52&filter=snapchat&t={time.time()}", mime_type="video/mp4"), InlineQueryResultVideo( id=uuid4(), title="🦀🦀 BAG RAIDERS IS GONE 🦀🦀", description=query, thumb_url=f"{BASE_URL}/thumb/shootingstars.jpg?t={time.time()}", video_url= f"{BASE_URL}/video/{parse.quote_plus(query)}.mp4?style=shootingstars&font=spacemono&color=white&size=52&filter=simple&t={time.time()}", mime_type="video/mp4"), InlineQueryResultArticle( id=uuid4(), title="Bot made by @divadsn", description="Check out my source code on GitHub!", thumb_url= "https://avatars2.githubusercontent.com/u/28547847?s=460&v=4", input_message_content=InputTextMessageContent( "https://github.com/divadsn/crabrave-telegram-bot\n\nDonate me via PayPal: https://paypal.me/divadsn", parse_mode=ParseMode.MARKDOWN)) ] update.inline_query.answer(results)
def inlineinfo(query: str, update: Update, context: CallbackContext) -> None: """Handle the inline query.""" bot = context.bot query = update.inline_query.query log.info(query) user_id = update.effective_user.id try: search = query.split(" ", 1)[1] except IndexError: search = user_id try: user = bot.get_chat(int(search)) except (BadRequest, ValueError): user = bot.get_chat(user_id) chat = update.effective_chat sql.update_user(user.id, user.username) text = (f"<b>General:</b>\n" f"ID: <code>{user.id}</code>\n" f"First Name: {html.escape(user.first_name)}") if user.last_name: text += f"\nLast Name: {html.escape(user.last_name)}" if user.username: text += f"\nUsername: @{html.escape(user.username)}" text += f"\nPermanent user link: {mention_html(user.id, 'link')}" try: spamwtc = sw.get_ban(int(user.id)) if spamwtc: text += "<b>\n\nSpamWatch:\n</b>" text += "<b>This person is banned in Spamwatch!</b>" text += f"\nReason: <pre>{spamwtc.reason}</pre>" text += "\nAppeal at @SpamWatchSupport" else: text += "<b>\n\nSpamWatch:</b>\n Not banned" except: pass # don't crash if api is down somehow... try: status = client.raw_output(int(user.id)) ptid = status["results"]["private_telegram_id"] op = status["results"]["attributes"]["is_operator"] ag = status["results"]["attributes"]["is_agent"] wl = status["results"]["attributes"]["is_whitelisted"] ps = status["results"]["attributes"]["is_potential_spammer"] sp = status["results"]["spam_prediction"]["spam_prediction"] hamp = status["results"]["spam_prediction"]["ham_prediction"] blc = status["results"]["attributes"]["is_blacklisted"] if blc: blres = status["results"]["attributes"]["blacklist_reason"] else: blres = None text += "\n\n<b>SpamProtection:</b>" text += f"<b>\nPrivate Telegram ID:</b> <code>{ptid}</code>\n" text += f"<b>Operator:</b> <code>{op}</code>\n" text += f"<b>Agent:</b> <code>{ag}</code>\n" text += f"<b>Whitelisted:</b> <code>{wl}</code>\n" text += f"<b>Spam Prediction:</b> <code>{sp}</code>\n" text += f"<b>Ham Prediction:</b> <code>{hamp}</code>\n" text += f"<b>Potential Spammer:</b> <code>{ps}</code>\n" text += f"<b>Blacklisted:</b> <code>{blc}</code>\n" text += f"<b>Blacklist Reason:</b> <code>{blres}</code>\n" except HostDownError: text += "\n\n<b>SpamProtection:</b>" text += "\nCan't connect to Intellivoid SpamProtection API\n" nation_level_present = False num_chats = sql.get_user_num_chats(user.id) text += f"\nChat count: <code>{num_chats}</code>" if user.id == OWNER_ID: text += f"\nThis person is my owner" nation_level_present = True elif user.id in DEV_USERS: text += f"\nThis Person is a part of Eagle Union" nation_level_present = True elif user.id in SUDO_USERS: text += f"\nThe Nation level of this person is Royal" nation_level_present = True elif user.id in SUPPORT_USERS: text += f"\nThe Nation level of this person is Sakura" nation_level_present = True elif user.id in SARDEGNA_USERS: text += f"\nThe Nation level of this person is Sardegna" nation_level_present = True elif user.id in WHITELIST_USERS: text += f"\nThe Nation level of this person is Neptunia" nation_level_present = True if nation_level_present: text += ' [<a href="https://t.me/{}?start=nations">?</a>]'.format( bot.username) results = [ InlineQueryResultArticle( id=str(uuid4()), title=f"User info of {html.escape(user.first_name)}", input_message_content=InputTextMessageContent( text, parse_mode=ParseMode.HTML, disable_web_page_preview=True), ), ] update.inline_query.answer(results, cache_time=5)
def inline_query(update, context): """Handle the inline query.""" global sprinter, sprinter_ls query = update.inline_query.query user_id = update.message.from_user['id'] state = conversation_state.get(user_id) logging.debug("Query: " + query) # Inline 1 Shows current markets if state is State.WAIT_INLINE_1: conversation_state[user_id] = State.WAIT_INLINE_2 logging.debug("Inline 1") results = [] data = ing_sprinters.database() with open('database.pkl', 'rb') as file: try: data = pickle.load(file) titles = data['markets'] except EOFError: return None for item in titles: if item.lower().startswith(query.lower()): results.append( InlineQueryResultArticle( id=uuid4(), title=item, input_message_content=InputTextMessageContent( '/market ' + item))) if item in query: conversation_state[user_id] = State.WAIT_INLINE_1 sprinter = item # Inline 2 Shows sprinter types if state is State.WAIT_INLINE_2: conversation_state[user_id] = State.WAIT_INLINE_3 logging.debug("Inline 2") results = [] for item in ['Long', 'Short']: output = sprinter + ' ' + item # Sprinter + Long/Short results.append( InlineQueryResultArticle( id=uuid4(), title=item, input_message_content=InputTextMessageContent('/market ' + sprinter))) if item.lower() in query.lower(): sprinter_ls = output # Inline 3 Shows current sprinters if state is State.WAIT_INLINE_3: del conversation_state[user_id] logging.debug("Inline 3") results = [] query_short = query.lower().replace( sprinter_ls.lower() + ' ', '') # Remove first two inlines from query # Extract numbers from the shortened query query_nr = re.findall(r'\d*\,?\d+', query_short) sprinters = ing_sprinters.sprinter_list( sprinter_ls) # Retreive list of sprinters for key, value in sprinters.items(): key_nr = re.findall(r'\d*\,?\d+', key) # If sprinter (key), isin (value) or number (inside key) match if key.lower().startswith(query_short) \ or value.lower().startswith(query_short) \ or (key_nr[-1].startswith(query_nr[-1])): output = sprinter + ' ' + value # Sprinter + Long/Short + isin results.append( InlineQueryResultArticle( id=uuid4(), title=key, input_message_content=InputTextMessageContent('/ing ' + output))) # Reset inlines if (sprinter not in query): logging.debug("Reset") results = [] del conversation_state[user_id] if update.inline_query.offset == "": offset = 0 else: offset = int(update.inline_query.offset) update.inline_query.answer(results=results[offset:offset + 50], next_offset=str(offset + 50))
def in_line_query(self, update, context): self.hits += 1 query = update.inline_query.query logger.debug('Inline mode activated.') results = [] x = 0 # counter, unique id for match in self.game_list: output = '' if query.lower() in match['game'].lower( ): # compares input with matchname or team name output += ("\n\nMatch: " + match['game'] + '\n') output += ("Time: " + match['time'] + '\n\n\n') for i in range(0, min(len(match['links']), 8)): output += ("Stream Name: " + match['links'][i]['name'] + '\n') output += ("Stream Link: " + match['links'][i]['link'] + '\n\n') if (len(match['links'])) == 0: output += 'No streaming links found for this match.\n\n' results.append( InlineQueryResultArticle( id=x, title=(match['game']), input_message_content=InputTextMessageContent(output))) x += 1 if results == []: for match in self.game_list: output = '' output += ("\n\nMatch: " + match['game'] + '\n') output += ("Time: " + match['time'] + '\n\n\n') for i in range(0, min(len(match['links']), 8)): output += ("Stream Name: " + match['links'][i]['name'] + '\n') output += ("Stream Link: " + match['links'][i]['link'] + '\n\n') if (len(match['links'])) == 0: output += 'No streaming links found for this match.\n\n' results.append( InlineQueryResultArticle( id=x, title=(match['game']), input_message_content=InputTextMessageContent(output))) x += 1 if results == []: output = '' output += ('No matches are currently being broadcasted.') output += ( '\nStreaming links usually appear 30 minutes before a game.') results.append( InlineQueryResultArticle( id=x, title=('No matches are currently being broadcasted.'), input_message_content=InputTextMessageContent(output))) update.inline_query.answer(results)
def botHook(): bot = telegram.Bot(TOKEN) update = telegram.update.Update.de_json(request.json, bot) if update.inline_query is not None and update.inline_query.query: # We've got an inline query tlkz = tsr.search_talkz(update.inline_query.query, 50) results = [] for t in tlkz: txt = '' if t[0] != -500: txt = t[1] # results.append(InlineQueryResultArticle(id = uuid4(), title = '(' + str(t[0]) + ') ' + t[2], input_message_content = InputTextMessageContent(txt), description = t[1])) results.append( InlineQueryResultArticle( id=uuid4(), title=txt, input_message_content=InputTextMessageContent(txt))) bot.answerInlineQuery(update.inline_query.id, results) return 'OK' if update.message is not None: # We've got a message global mAdd global command_message # global tstconf # logger.info('message: ' + update.message.text) if users.add_user(update.message.from_user.id, update.message.from_user.username, 'U', dt.date(1901, 1, 1), 'Added ' + dt.datetime.now().isoformat()): bot.sendMessage(chat_id=PAPAID, text='добавил копа. ' + update.message.from_user.username + ' (' + str(update.message.from_user.id) + ')') if update.message.location is not None: locz.add_loc(update.message) #logger.info('location %s, %s', update.message.location.longitude, update.message.location.latitude) return 'OK' if update.message.text == '/listusers': command_message = update.message if not users.usertype_is(update.message.from_user.id, 'O'): bot.sendMessage(chat_id=update.message.chat_id, text='Иди нухай, коп') return 'Access denied' bot.sendMessage(chat_id=update.message.chat_id, text=users.list_userz()) return 'OK' if isinstance(update.message.text, str): mtext = update.message.text command = mtext.split()[0] user_name = "" if len(mtext.split()) > 1: user_name = mtext.split()[1] if command == '/makeowner': if not (update.message.from_user.id == PAPAID): bot.sendMessage(chat_id=update.message.chat_id, text='иди нухай, коп. ты непапа') return 'Access denied' if users.change_attr(user_name, 'utype', 'O'): bot.sendMessage(chat_id=update.message.chat_id, text=users.str_user( users.find_user('uname', user_name))) return 'OK' else: bot.sendMessage(chat_id=update.message.chat_id, text='нету такого копа') return 'OK' if command == '/makemoder': if not (users.usertype_is(update.message.from_user.id, 'O') or update.message.from_user.id == PAPAID): bot.sendMessage(chat_id=update.message.chat_id, text='иди нухай, коп') return 'Access denied' if users.change_attr(user_name, 'utype', 'M'): bot.sendMessage(chat_id=update.message.chat_id, text=users.str_user( users.find_user('uname', user_name))) return 'OK' else: bot.sendMessage(chat_id=update.message.chat_id, text='нету такого копа') return 'OK' if command == '/makeuser': if not (users.usertype_is(update.message.from_user.id, 'O') or update.message.from_user.id == PAPAID): bot.sendMessage(chat_id=update.message.chat_id, text='иди нухай, коп') return 'Access denied' if users.change_attr(user_name, 'utype', 'U'): bot.sendMessage(chat_id=update.message.chat_id, text=users.str_user( users.find_user('uname', user_name))) return 'OK' else: bot.sendMessage(chat_id=update.message.chat_id, text='нету такого копа') return 'OK' if command == '/set': user_attr = mtext.split()[2] user_value = mtext[len(mtext.split()[0]) + len(mtext.split()[1]) + len(mtext.split()[2]) + 3:] if not (users.usertype_is(update.message.from_user.id, 'O') or update.message.from_user.id == PAPAID): bot.sendMessage(chat_id=update.message.chat_id, text='иди нухай, коп') return 'Access denied' if users.find_user('uname', user_name) is None: bot.sendMessage(chat_id=update.message.chat_id, text='нету такого копа') return 'Not found' if users.change_attr(user_name, user_attr, user_value): bot.sendMessage(chat_id=update.message.chat_id, text=users.str_user( users.find_user('uname', user_name))) return 'OK' else: bot.sendMessage(chat_id=update.message.chat_id, text='хуйню сказал, папаша') return 'Error' if update.message.text == '/add': command_message = update.message u = users.find_user('uid', update.message.from_user.id) if u is None or not (u['utype'] == 'O' or u['utype'] == 'M'): bot.sendMessage(chat_id=update.message.chat_id, text='иди нухай, коп') return 'Access denied' bot.sendMessage( chat_id=update.message.chat_id, text='Пезди давай. Но токо больше 10 букв и ченть новенькое') mAdd = True return 'OK' if update.message.text == '/del': command_message = update.message u = users.find_user('uid', update.message.from_user.id) if u is None or not (u['utype'] == 'O' or u['utype'] == 'M'): bot.sendMessage(chat_id=update.message.chat_id, text='иди нухай, коп') return 'Access denied' if tsr.last_message[0] == -1: bot.sendMessage(chat_id=update.message.chat_id, text='нехуя удалять') return 'OK' keyboard = [[ InlineKeyboardButton('удалить впезду "' + tsr.last_message[1] + '"', callback_data=tsr.last_message[0]) ], [InlineKeyboardButton("или нуево нахуй", callback_data=-1)]] reply_markup = InlineKeyboardMarkup(keyboard) update.message.reply_text('Ну чо, ', reply_markup=reply_markup) return 'OK' if mAdd: mAdd = False res = tsr.add_talk(update.message.text) if res[0]: bot.sendMessage(chat_id=update.message.chat_id, text='зопомнел') logger.info('ADDTALK. User:%s in chat:%s added talk:%s', update.message.from_user, update.message.chat, update.message.text) else: if res[1]: txt = 'уже есть такая хуета: ' + res[1] else: txt = 'хуйню сказал, папаша' bot.sendMessage(chat_id=update.message.chat_id, text=txt) return 'OK' bot_called = False if update.message.text is not None: bot_called = (update.message.text.partition(' ')[0] in bot_aliases) if bot_called: message_text = update.message.text.partition(' ')[2] if message_text == 'локи': logger.info('локи') logger.debug('локи') lres = locz.select_locz(update.message.chat_id, update.message.from_user.id) if lres[0] == '|': bot.sendMessage( chat_id=update.message.chat_id, text= "http://maps.googleapis.com/maps/api/staticmap?size=800x800&path={0}" .format(lres[1:])) else: bot.sendMessage(chat_id=update.message.chat_id, text=lres) return 'OK' else: message_text = update.message.text if update.message.chat.type == 'private' or tsr.can_talk( update.message.chat.id) or (tsr.can_answer( update.message.chat.id) and bot_called): if message_text == '': bot.sendMessage(chat_id=update.message.chat_id, text='чево?') else: bot.sendMessage(chat_id=update.message.chat_id, text=tsr.search_talk(message_text)) return 'OK' if update.callback_query is not None: # We've got a callback query query = update.callback_query ndx = int(query.data) if ndx == -1: bot.edit_message_text(text='ну ок', chat_id=query.message.chat_id, message_id=query.message.message_id) else: tsr.last_message = (-1, '') res = tsr.del_talk(ndx) bot.edit_message_text(text='удалил "' + res + '"', chat_id=query.message.chat_id, message_id=query.message.message_id) logger.info( 'DELTALK. User:%s in chat:%s deleted talkid:%s talk:%s', command_message.from_user, query.message.chat, ndx, res) return 'OK'