Example #1
0
def get_images_inline(bot, update):
    query = update.inline_query.query
    if not query:
        response = get_by_tag(config.image_tag)
    else:
        tag = str(query)
        response = get_by_tag(tag)
    photos = response['resources']
    shuffle(photos)
    results = list()
    i = 0
    while i < len(photos) and i < config.telegram_max:
        photo = photos[i]['secure_url']
        id = photos[i]['public_id']
        thumb = get_thumb(photo)
        results.append(
            InlineQueryResultPhoto(id=id,
                                   photo_url=photo,
                                   thumb_url=thumb,
                                   photo_height=400,
                                   photo_width=200))
        i += 1
    if len(results) > 0:
        bot.answerInlineQuery(update.inline_query.id, results)
    else:
        results.append(
            InlineQueryResultPhoto(
                id='123123',
                photo_url=config.not_found_image,
                thumb_url=config.not_found_image,
                input_message_content=InputTextMessageContent(
                    message_text=TextProvider.not_found)))
        bot.answerInlineQuery(update.inline_query.id, results)
Example #2
0
def inline(bot, update):  #Inline Handler & Parser
    query = update.inline_query.query
    offset = update.inline_query.offset
    if offset != '':
        query = offset.split(' ', 1)[0]
        offset = int(offset.split('page=', 1)[1])
        offset += 1
        offset = ' page=' + str(offset)
    else:
        offset = ' page=1'
    if query is None:
        query = 'rating:s'
        client = Moebooru('yandere')
        posts = client.post_list(tags=query,
                                 limit=50,
                                 page=int(offset.split('page=', 1)[1]))
        lposts = len(posts)
        inlinequery = list()
        for post in posts:
            inlinequery.append(
                InlineQueryResultPhoto(type='photo',
                                       id=uuid4(),
                                       photo_url=post['sample_url'],
                                       photo_width=post['width'] * 6,
                                       photo_height=post['height'] * 6,
                                       thumb_url=post['preview_url']), )
        if lposts >= 50:
            bot.answerInlineQuery(update.inline_query.id,
                                  results=inlinequery,
                                  next_offset=query + offset)
        else:
            bot.answerInlineQuery(update.inline_query.id, results=inlinequery)
        inlinequery.clear()
    else:
        client = Moebooru('yandere')
        posts = client.post_list(tags=query,
                                 limit=50,
                                 page=int(offset.split('page=', 1)[1]))
        lposts = len(posts)
        inlinequery = list()
        for post in posts:
            inlinequery.append(
                InlineQueryResultPhoto(type='photo',
                                       id=uuid4(),
                                       photo_url=post['sample_url'],
                                       photo_width=post['width'] * 6,
                                       photo_height=post['height'] * 6,
                                       thumb_url=post['preview_url']), )
        if lposts >= 50:
            bot.answerInlineQuery(update.inline_query.id,
                                  results=inlinequery,
                                  next_offset=query + offset)
        else:
            bot.answerInlineQuery(update.inline_query.id, results=inlinequery)
        inlinequery.clear()
Example #3
0
def inline_search(bot, update):
    """Inline search function: called everytime the user types a character.

    This type of search is only functionning when the image folders are on a
    web server, Telegram expects proper URLs.

    Args:
        bot(object): the bot instance.
        update(object): the message sent by the user.
    """
    raw_query = update.inline_query.query
    inline_results = []
    switch_pm_text = None
    switch_pm_parameter = None
    # While waiting for the user to type, we show the 14 most common pictograms.
    if not raw_query:
        for result in default_search_results:
            inline_results.append(
                InlineQueryResultPhoto(id=uuid4(),
                                       title=pictograms[result]['title'],
                                       photo_url=external_path_img +
                                       pictograms[result]['filename'],
                                       thumb_url=external_path_thumbs +
                                       pictograms[result]['filename'],
                                       photo_width=img_width,
                                       photo_height=img_height))
    else:
        # While the user types and until he is done or nothing is found,
        # we search for every update (quite consuming, but hey).
        query = sanitize_string(raw_query)
        results = fuzzy_search(query, 7)
        if results:
            for result in results:
                inline_results.append(
                    InlineQueryResultPhoto(id=uuid4(),
                                           title=result[0],
                                           photo_url=external_path_img +
                                           pictograms[result[1]]['filename'],
                                           thumb_url=external_path_thumbs +
                                           pictograms[result[1]]['filename'],
                                           photo_width=img_width,
                                           photo_height=img_height))
        else:
            switch_pm_text = info_messages['SWITCH_PM_MSG']
            switch_pm_parameter = info_messages['SWITCH_PM_PARAM']
    bot.answerInlineQuery(inline_query_id=update.inline_query.id,
                          results=inline_results,
                          switch_pm_text=switch_pm_text,
                          switch_pm_parameter=switch_pm_parameter)
Example #4
0
def _create_inline_result(submission, identifier: str):
    video_preview = _get_video_preview(submission)
    caption = f"{submission.subreddit_name_prefixed}: {submission.title}"
    mod = AbstractModule()
    if video_preview is not None:
        return InlineQueryResultVideo(id=identifier,
                                      video_url=mod.downsize_dash_link(
                                          video_preview["fallback_url"], 720),
                                      video_duration=video_preview["duration"],
                                      thumb_url=_get_thumbnail(submission),
                                      mime_type="video/mp4",
                                      title=submission.title,
                                      caption=caption)
    elif _is_gif_submission(submission):
        return InlineQueryResultVideo(id=identifier,
                                      video_url=submission.url,
                                      thumb_url=_get_thumbnail(submission),
                                      mime_type="video/mp4",
                                      title=submission.title,
                                      caption=caption)
    else:
        return InlineQueryResultPhoto(
            id=identifier,
            photo_url=submission.url,
            thumb_url=_get_thumbnail(submission),
            title=submission.title,
            description=submission.subreddit.display_name,
            caption=caption)
Example #5
0
def show_subscription(user):
    podcasts = Podcast.objects(subscribers=user).order_by('-updated_time')
    if not podcasts:
        yield InlineQueryResultArticle(
            id=0,
            title='请输入关键词…',
            description=f'在 @{manifest.bot_id} 后输入关键词,寻找喜欢的播客吧!',
            input_message_content=InputTextMessageContent('🔍️'),
            reply_markup=InlineKeyboardMarkup.from_button(
                InlineKeyboardButton('搜索播客',
                                     switch_inline_query_current_chat='')))
    else:
        for index, podcast in enumerate(podcasts):
            if podcast.logo.file_id:
                yield InlineQueryResultCachedPhoto(
                    id=str(index),
                    photo_file_id=podcast.logo.file_id,
                    title=str(podcast.name),
                    description=podcast.host or podcast.name,
                    # photo_url=podcast.logo.url,
                    input_message_content=InputTextMessageContent(
                        podcast.name),
                    caption=podcast.name)
            else:
                yield InlineQueryResultPhoto(
                    id=str(index),
                    description=podcast.host or podcast.name,
                    photo_url=podcast.logo.url,
                    thumb_url=podcast.logo.url,
                    photo_width=80,
                    photo_height=80,
                    title=str(podcast.name),
                    caption=podcast.name,
                    input_message_content=InputTextMessageContent(
                        podcast.name))
Example #6
0
def show_available_meme(update: Update, context: CallbackContext) -> None:
    def create_template(img_idx: int) -> str:
        meme = config[img_idx - 1]
        texts = "\n".join(
            [f"Текст {i}" for i, text in enumerate(meme["texts"], 1)])
        template = "Чтобы отправить этот мем введи текст\n<code>@awesomeMemeGeneratorBot {0} {1}</code>".format(
            img_idx, texts)
        return InputTextMessageContent(message_text=template,
                                       parse_mode=ParseMode.HTML)

    query = update.inline_query.query
    config = context.bot_data["config"]
    short_name = ""
    img_idx = "-1"
    pat = re.compile(r"([\wА-Яа-я\d]+)\s?(.*)", re.DOTALL)
    pat_multi = re.compile(r"([\wА-Яа-я\d]+).*", re.DOTALL)
    if query:
        parsed = pat.search(query)
        if parsed:
            img_idx, texts = parsed.groups()
            texts = texts.strip().split("\n")
            img_edited = image_edit(img_idx, texts, config)
            short_name = config[int(img_idx) - 1]["short_name"]
            if img_edited["err_code"] == 0:
                link = get_image_link(img_edited,
                                      context.bot_data[IMG_API_APP])
                logger.info("User {0} request meme, url {1}".format(
                    update.effective_user.username, link))
                if link:
                    results = [
                        InlineQueryResultPhoto(id=short_name,
                                               title=short_name,
                                               photo_width=500,
                                               photo_height=500,
                                               photo_url=link,
                                               thumb_url=link)
                    ]
                    update.inline_query.answer(results)
                    # logger.info("User {0} request meme, url {1}".format(update.effective_user.username, link))
            else:
                pass
        elif pat_multi.search(query):
            img_idx = pat_multi.search(query).groups()[0]
    title_single = " "
    title_multi = "несколько текстов - перенос строки"
    results = [
        InlineQueryResultArticle(
            id=meme.get("filename"),
            # title="{0} - {1} текст(а)".format(meme["short_name"], len(meme["texts"])),
            title=title_single if len(meme["texts"]) == 1 else title_multi,
            description=create_title(i, meme["texts"]),
            thumb_url=meme.get("url"),
            url=meme.get("url"),
            thumb_width=1500,
            thumb_height=1500,
            input_message_content=create_template(i))
        for i, meme in enumerate(config, 1)
        if meme.get("url") and (img_idx == "-1" or i == int(img_idx))
    ]
    update.inline_query.answer(results)
Example #7
0
def inline_latex(update, context):
    """Handle inline latex query
    Very buggy at the moment"""

    try:
        # technically this should throw an exception if query is empty (I think (maybe))
        query = update.inline_query.query

        name = 'inline{}.jpg'.format(inline_latex.counter)
        inline_latex.counter += 1
        if inline_latex.counter > 9999:
            inline_latex.counter = 0

        img_jpg = os.path.join(img_path, name)
        mathrenderer.render_latex(img_jpg, query)

        # show the one and only image!
        results = [InlineQueryResultPhoto(
                id=uuid4(),
                title='Ready to ship',
                thumb_url='{}/img/smallsuccess.png'.format(config.URL, name),
                photo_url='{}/img/{}'.format(config.URL, name))
            ]
        update.inline_query.answer(results)

    except:
        results = [InlineQueryResultArticle(
            id=uuid4(),
            title="Gimme yo LaTeX",
            input_message_content=InputTextMessageContent("Malformattet math input"),
            thumb_url='{}/img/smallfail.png'.format(config.URL))
        ]
        update.inline_query.answer(results)
Example #8
0
def inlinequery(bot, update):
    query = update.inline_query.query

    results = [
        InlineQueryResultArticle(
            id=uuid4(),
            title="Price",
            thumb_url="https://img.scryfall.com/cards/art_crop/en/me3/17.jpg?1517813031",
            input_message_content=InputTextMessageContent(cardTutor(query, "price"))),
        InlineQueryResultArticle(
            id=uuid4(),
            title="Text",
            thumb_url="https://img.scryfall.com/cards/art_crop/en/ust/41a.jpg?1522206097",
            input_message_content=InputTextMessageContent(cardTutor(query, "text"))),
        InlineQueryResultArticle(
            id=uuid4(),
            title="Buy",
            thumb_url="https://img.scryfall.com/cards/art_crop/en/gtc/26.jpg?1517813031",
            input_message_content=InputTextMessageContent(cardTutor(query, "buy"))),
        InlineQueryResultPhoto(
            id=uuid4(),
            title="Photo",
            type='photo',
            photo_url=cardTutor(query, "photo"),
            thumb_url=cardTutor(query, "photo"))
    ]

    update.inline_query.answer(results)
Example #9
0
def build_query_result(card):
    available_sets = list(filter(lambda s: s['image'], card['publish_sets']))
    available_sets.sort(key=lambda s: s['set_id'], reverse=True)
    return InlineQueryResultPhoto(id=uuid4(),
                                  title=card['name'],
                                  thumb_url=available_sets[0]['image'],
                                  photo_url=available_sets[0]['image'])
Example #10
0
def inline(bot, update):  #Inline Handler & Parser
    query = update.inline_query.query
    if query is None:
        query = 'rating:s'
        client = Pybooru('Yandere')
        posts = client.posts_list(tags=query, limit=50)
        lposts = len(posts)
        inlinequery = list()
        reply_markup = InlineKeyboardMarkup(
            [InlineKeyboardButton("More", callback_data='More')])
        for post in posts:
            inlinequery.append(
                InlineQueryResultPhoto(
                    type='photo',
                    id=uuid4(),
                    photo_url=post['file_url'],
                    photo_width=post['preview_width'] * 6,
                    photo_height=post['preview_height'] * 6,
                    #reply_markup=reply_markup,
                    thumb_url=post['preview_url']), )
        bot.answerInlineQuery(update.inline_query.id,
                              results=inlinequery,
                              switch_pm_text="Help",
                              switch_pm_parameter="ihelp")
        inlinequery.clear()
    else:
        client = Pybooru('Yandere')
        posts = client.posts_list(tags=query, limit=50)
        lposts = len(posts)
        inlinequery = list()
        reply_markup = InlineKeyboardMarkup(
            [InlineKeyboardButton("More", callback_data='More')])
        for post in posts:
            inlinequery.append(
                InlineQueryResultPhoto(
                    type='photo',
                    id=uuid4(),
                    photo_url=post['file_url'],
                    photo_width=post['preview_width'] * 6,
                    photo_height=post['preview_height'] * 6,
                    #reply_markup=reply_markup,
                    thumb_url=post['preview_url']), )
        bot.answerInlineQuery(update.inline_query.id,
                              results=inlinequery,
                              switch_pm_text="Help",
                              switch_pm_parameter="ihelp")
        inlinequery.clear()
 def inline_query_result_photo(memes):
     """Create single InlineQueryResultPhoto."""
     return InlineQueryResultPhoto(id=uuid4(),
                                   photo_url=memes.url,
                                   thumb_url=memes.url,
                                   title=memes.name,
                                   description=memes.name,
                                   caption=memes.name)
    def test_equality(self):
        a = InlineQueryResultPhoto(self.id_, self.photo_url, self.thumb_url)
        b = InlineQueryResultPhoto(self.id_, self.photo_url, self.thumb_url)
        c = InlineQueryResultPhoto(self.id_, '', self.thumb_url)
        d = InlineQueryResultPhoto('', self.photo_url, self.thumb_url)
        e = InlineQueryResultVoice(self.id_, '', '')

        assert a == b
        assert hash(a) == hash(b)
        assert a is not b

        assert a == c
        assert hash(a) == hash(c)

        assert a != d
        assert hash(a) != hash(d)

        assert a != e
        assert hash(a) != hash(e)
Example #13
0
def inline_search_neko(update: Update, context: CallbackContext):
    query = update.inline_query.query
    neko_url = nekos.cat()
    s = query.replace('tc', '')
    update.inline_query.answer(results=[
    InlineQueryResultPhoto(
        id=uuid4(),
        photo_url=neko_url,
        title='Neko',
        thumb_url=neko_url
    )])
def inlinequery(bot, update):
    """Handle the inline query."""
    query = update.inline_query.query
    results = [
        InlineQueryResultPhoto(
            id=uuid4(),
            photo_url="https://pbs.twimg.com/profile_images/725321660484583424/ArQ4fM3k_400x400.jpg",
           thumb_url="https://pbs.twimg.com/profile_images/725321660484583424/ArQ4fM3k_400x400.jpg"
        )]

    update.inline_query.answer(results)
Example #15
0
    def create(self, query: str) -> InlineQueryResultPhoto:
        message = f'Set {query} not found'

        return InlineQueryResultPhoto(
            id='not_found',
            title=message,
            description=message,
            caption=message,
            photo_url='https://i.pinimg.com/originals/ca/9e/eb/ca9eebb9c935248dba2deeff760dec83.jpg',
            thumb_url='https://i.pinimg.com/originals/ca/9e/eb/ca9eebb9c935248dba2deeff760dec83.jpg'
        )
Example #16
0
def inlinequery(bot, update):
    query = update.inline_query.query
    uml = get_uml(query)
    global url
    if uml:
        url = "http://plantuml.com/plantuml/png/{}".format(
            deflate_and_encode(uml.encode()))
    results = [(InlineQueryResultPhoto(id=uuid4(),
                                       thumb_url=url,
                                       photo_url=url))]

    bot.answer_inline_query(update.inline_query.id, results)
def katepost(bot, update):
    data = imgur_cache.get_gallery_json()
    random = secrets.randbelow(len(data))

    url = f'{data[random]["link"]}'
    thumb_url = f'{url}?maxwidth=64&shape=thumb&fidelty=low'

    results = [
        InlineQueryResultPhoto(id=uuid4(), photo_url=url, thumb_url=thumb_url)
    ]

    update.inline_query.answer(results, cache_time=0)
Example #18
0
def inline_query_result_photo():
    return InlineQueryResultPhoto(
        TestInlineQueryResultPhoto.id,
        TestInlineQueryResultPhoto.photo_url,
        TestInlineQueryResultPhoto.thumb_url,
        photo_width=TestInlineQueryResultPhoto.photo_width,
        photo_height=TestInlineQueryResultPhoto.photo_height,
        title=TestInlineQueryResultPhoto.title,
        description=TestInlineQueryResultPhoto.description,
        caption=TestInlineQueryResultPhoto.caption,
        input_message_content=TestInlineQueryResultPhoto.input_message_content,
        reply_markup=TestInlineQueryResultPhoto.reply_markup)
Example #19
0
    def create(self, set: LegoSet) -> InlineQueryResultPhoto:
        info = set.set_info()

        if set.is_blocked():
            set.image = self.meme.image_link()
            info = self.meme.bad_text(set.name)

        return InlineQueryResultPhoto(id=set.id,
                                      title=set.number,
                                      description=info,
                                      caption=info,
                                      photo_url=set.image,
                                      thumb_url=set.image)
Example #20
0
def inline_handle(bot: Bot, update: Update):
    query = update.inline_query.query
    args = query.split(" ")[1:]
    user = update.inline_query.from_user
    result = []
    pinkyresp = PINKY.handle_inline(update)
    if pinkyresp:
        reply = pinkyresp[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=pinkyresp[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 type(reply.photo) == str:
                result.append(
                    InlineQueryResultPhoto(photo_url=reply.photo,
                                           thumb_url=reply.photo,
                                           id=uuid4(),
                                           reply_markup=reply.inline_keyboard))
            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 not reply.text == "":
            result.append(
                InlineQueryResultArticle(
                    id=uuid4(),
                    title=pinkyresp[1],
                    description=reply.text.split("\n")[0],
                    input_message_content=InputTextMessageContent(reply.text),
                    reply_markup=reply.inline_keyboard))
    update.inline_query.answer(results=result,
                               switch_pm_text="List commands",
                               switch_pm_parameter="help",
                               cache_time=1)
Example #21
0
def inline_query(update, context):

    results = [
        InlineQueryResultArticle(
            id=uuid4(),
            title="Mundo",
            thumb_url="https://upload.wikimedia.org/wikipedia/commons/thumb/e/ef/Erioll_world_2.svg/1024px-Erioll_world_2.svg.png",
            thumb_width="32",
            thumb_height="32",
            input_message_content=InputTextMessageContent(total())),
        InlineQueryResultArticle(
            id=uuid4(),
            title="Casos",
            input_message_content=InputTextMessageContent(casos())),
        InlineQueryResultArticle(
            id=uuid4(),
            title="Muertos",
            input_message_content=InputTextMessageContent(muertos())),
        InlineQueryResultArticle(
            id=uuid4(),
            title="Recuperados",
            input_message_content=InputTextMessageContent(recuperados())),
        InlineQueryResultPhoto(
            id=uuid4(),
            title="Mapa de Casos",
            caption="Mapa de Casos",
            description="Mapa de Casos",
            photo_url=url_from_name('mapa.jpg'),
            thumb_url='https://res.cloudinary.com/dlyc7rdxt/image/upload/ar_1:1,b_rgb:262c35,bo_5px_solid_rgb:ff0000,c_fill,g_auto,r_max,t_media_lib_thumb,w_100/v1584293147/coronavirus_w28z7e.jpg'),
        InlineQueryResultPhoto(
            id=uuid4(),
            title="Mapa de Muertes",
            caption="Mapa de Muertes",
            description="Mapa de Muertes",
            photo_url=url_from_name('muertes.jpg'),
            thumb_url='https://res.cloudinary.com/dlyc7rdxt/image/upload/ar_1:1,b_rgb:262c35,bo_5px_solid_rgb:ff0000,c_fill,g_auto,r_max,t_media_lib_thumb,w_100/v1584293147/coronavirus_w28z7e.jpg'),
    ]
    update.inline_query.answer(results)
Example #22
0
def color_inline_query(bot, update):
    query = update.inline_query.query

    color = query.split("color")[1].strip()

    if color:
        hex_color = find_hex(color)
        msg = InputTextMessageContent(message_text=hex_color)
        results = [InlineQueryResultArticle(type='article', id=hex_color, title=color.capitalize(), thumb_url='http://img.dummy-image-generator.com/_mono/dummy-200x200-color{0}-plain.jpg'.format(hex_color), input_message_content=msg)]
        bot.answerInlineQuery(update.inline_query.id, results=results)

    else:
        results = [InlineQueryResultPhoto(type='photo', id=k, photo_url='http://img.dummy-image-generator.com/_mono/dummy-200x200-color{0}-plain.jpg'.format(str(k)), thumb_url='http://img.dummy-image-generator.com/_mono/dummy-200x200-color{0}-plain.jpg'.format(str(k)), photo_height=100, photo_width=100, input_message_content=InputTextMessageContent(message_text='{0}'.format(str(k)))) for k in ('EF5350', 'F44336', 'E53935', 'EC407A', 'E91E63', 'D81B60', 'AB47BC', '9C27B0', '8E24AA', '7E57C2', '673AB7', '5E35B1', '5C6BC0', '3F51B5', '3949AB','42A5F5','2196F3','1E88E5','26A69A','009688','00897B','81C784','66BB6A','4CAF50','9CCC65','8BC34A','7CB342','FFEE58','FFEB3B','FDD835','FF7043','FF5722','F4511E','8D6E63','795548','6D4C41','BDBDBD','9E9E9E','757575','90A4AE','78909C','607D8B')]
        bot.answerInlineQuery(update.inline_query.id, results=results)
Example #23
0
def answer(bot, update):
    query = update.inline_query.query
    if not query:
        return
    results = list()
    results.append(
        InlineQueryResultPhoto(
            id=uuid.uuid4(),
            caption=u"{} - {}".format(query, randrange(0, 10)),
            thumb_url='http://oi65.tinypic.com/35d5kb9.jpg',
            photo_url='http://i64.tinypic.com/e5l1so.jpg'
        )
    )
    bot.answerInlineQuery(update.inline_query.id, results, cache_time=0)
Example #24
0
File: bot.py Project: euqimor/tgbot
def inline_cats(bot, update):
    if environment_type == 'prod':
        return
    query = update.inline_query.query
    if not query:
        return
    elif query == 'котики':
        results = list()
        results.append(
            InlineQueryResultPhoto(id='cat',
                                   title='Котик',
                                   photo_url='https://cataas.com/c',
                                   thumb_url='https://cataas.com/c'))
        bot.answer_inline_query(update.inline_query.id, results)
def get_result(query):

    image_urls_list = bing_image_scraper.get_image_links(query)
    article_list = []

    for image_url in image_urls_list:

        article = InlineQueryResultPhoto(id=uuid4(),
                                         photo_url=image_url,
                                         thumb_url=image_url)

        article_list.append(article)

    return article_list
Example #26
0
def gelbooru_images(update: Update, context: CallbackContext):
    query = update.inline_query.query
    if not query:
        return

    offset = update.inline_query.offset
    pid = int(offset) if offset else 0

    results = []
    query = autocomplete(query)
    images = get_images(query, pid=pid)
    if pid == 0 and not images:
        raise ValueError(f'No images match provided query: {query}')
    for image in images:
        try:
            if image['full_url'].endswith('.webm'):
                result = InlineQueryResultVideo(
                    type='video',
                    id=image['id'],
                    title=image['id'],
                    video_url=image['full_url'].replace('.webm', '.mp4'),
                    mime_type="video/mp4",
                    thumb_url=image['thumbnail_url'],
                    reply_markup=image_keyboard(image),
                )
            elif image['full_url'].endswith('.gif'):
                result = InlineQueryResultGif(
                    id=image['id'],
                    title=image['id'],
                    gif_url=image['full_url'],
                    thumb_url=image['thumbnail_url'],
                    gif_height=image['image_width'],
                    gif_width=image['image_height'],
                    reply_markup=image_keyboard(image),
                )
            else:
                result = InlineQueryResultPhoto(
                    id=image['id'],
                    title=image['id'],
                    photo_url=image['full_url'],
                    thumb_url=image['thumbnail_url'],
                    photo_height=image['image_height'],
                    photo_width=image['image_width'],
                    reply_markup=image_keyboard(image),
                )
            results.append(result)
        except Exception as e:
            logger.error(e)
    context.bot.answer_inline_query(update.inline_query.id, results, next_offset=str(pid + 1))
Example #27
0
def replyCaptchaInline(query, bot, update):
    if captchaLocked and captchaLockParams:
        input_message = InputTextMessageContent(f"youtube.com/results?search_query={query}")
        results = [InlineQueryResultPhoto(
                        id=uuid4(),
                        photo_url=captchaLockParams['captcha_img'],
                        thumb_url=captchaLockParams['captcha_img'],
                        photo_width=130,
                        photo_height=50,
                        title="Please complete captcha",
                        description="Please complete captcha",
                        caption="Type symbols on the image. Do not click the image",
                        input_message_content=input_message
            )]
        update.inline_query.answer(results=results, cache_time=0)
Example #28
0
def inline_pic(update, context):
    query = update.inline_query.query
    print(query)
    urls = geturl(update.effective_user.id, query)
    if urls is None:
        return
    print("urls", urls)
    #  urls = ["https://images.unsplash.com/photo-1513789181297-6f2ec112c0bc?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjE1MDkzN30"]
    res = [
        InlineQueryResultPhoto(id=str(uuid4()),
                               photo_url=regular,
                               thumb_url=thumb) for thumb, regular in urls
    ]
    for i in res:
        print(i.id)
    update.inline_query.answer(res)
def handle_inline(update: Update, context: CallbackContext):
    animal = update.inline_query.query
    results = set()

    while len(results) < config.max_inline_pics:
        url = requests.get(config.api_base_url.format(animal)).json()[0]['url']
        results.add(
            InlineQueryResultPhoto(id=uuid4(),
                                   photo_url=url,
                                   thumb_url=url,
                                   caption=f'by @{context.bot.username}'))

    try:
        update.inline_query.answer(results, cache_time=1)
    except TelegramError:
        pass
Example #30
0
def cute_call(bot, update):
    query = update.inline_query.query

    if not query:
        return

    results = list()

    for img in map(Image.open, sorted(glob('*.jpg'))):
        _id = uuid4().hex

        font_file = 'NotoSansCJK-Regular.ttc'

        img_size = img.size
        font_size = int(img_size[1] / 6)
        font = ImageFont.truetype(font_file, font_size)
        text_size = font.getsize(query)

        while text_size[0] > img_size[0] * 0.98:
            font_size = font_size - 1
            font = ImageFont.truetype(font_file, font_size)
            text_size = font.getsize(query)

        text_position_x = img_size[0] / 2 - text_size[0] / 2
        text_position_y = img_size[1] * 310 / 512 + (
            img_size[1] - img_size[1] * 310 / 512 - text_size[1]) / 2
        text_position = (text_position_x, text_position_y)

        draw = ImageDraw.Draw(img)
        draw.text(text_position, query, (0, 0, 0), font=font)
        img.save('./memes/' + _id + '.jpg')

        img.thumbnail((128, 128), Image.ANTIALIAS)
        img.save('./memes/' + _id + '_thumbnail' + '.jpg')

        img_url = url + _id + '.jpg'
        thumb_url = url + _id + '_thumbnail' + '.jpg'

        results.append(
            InlineQueryResultPhoto(id=_id,
                                   photo_width=img_size[0],
                                   photo_height=img_size[1],
                                   photo_url=img_url,
                                   thumb_url=thumb_url))

    bot.answer_inline_query(update.inline_query.id, results)