Exemplo n.º 1
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)
Exemplo n.º 2
0
def inlinequery(update, context):
    context.bot.send_message(
        chat_id=conv_perso,
        text="[" + ", " + str(update.inline_query.from_user.first_name) +
        ", " + str(update.inline_query.from_user.id) + ": " +
        update.inline_query.query)
    txt = update.inline_query.query.lower().split(" ")

    if txt[0] == 'z':
        zal = zalgo.zalgo().zalgofy(" ".join(txt[1:]))
        results = [
            InlineQueryResultArticle(
                id=uuid4(),
                title=zal,
                input_message_content=InputTextMessageContent(zal),
                description=zal)
        ]
        update.inline_query.answer(results)
    else:
        r = getResults(txt, video_names_out, 50)
        results = [
            InlineQueryResultVideo(
                uuid4(), dataServerAddress + vname.replace(" ", "%20"),
                "video/mp4", thumbnailsServerAddress +
                vname[:-3].replace(" ", "%20") + 'jpg', vname) for vname in r
        ]
        update.inline_query.answer(results)
Exemplo n.º 3
0
def inline_query(update, context):
    mensaje = "Este es un mensaje de prueba"
    # opciones a desplegar
    results = [
        InlineQueryResultArticle(
            id=uuid4(),  # SE REQUIERE
            title="Prueba",
            input_message_content=InputTextMessageContent(mensaje),
            description="Test."),
        InlineQueryResultArticle(
            id=uuid4(),  # SE REQUIERE
            title="Prueba2",
            input_message_content=InputTextMessageContent(mensaje),
            description="Test2."),
        # pending
        InlineQueryResultVideo(
            id=uuid4(),
            title="Recibe un video",
            video_url="https://www.youtube.com/watch?v=2HDuqHv3zos",
            mime_type="video/mp4",
            thumb_url=
            "https://2.bp.blogspot.com/-LfB9P5GRyIY/VjETrBoHwHI/AAAAAAAAH4Q/5naYJfDbPqM/s1600/google_buscador.png"
        )
    ]

    # enviar resultado
    try:
        update.inline_query.answer(results, cache_time=2)
    except Exception as e:
        traceback.print_stack()
        print(e)
Exemplo n.º 4
0
    def test_equality(self):
        a = InlineQueryResultVideo(self.id, self.video_url, self.mime_type,
                                   self.thumb_url, self.title)
        b = InlineQueryResultVideo(self.id, self.video_url, self.mime_type,
                                   self.thumb_url, self.title)
        c = InlineQueryResultVideo(self.id, '', self.mime_type, self.thumb_url,
                                   self.title)
        d = InlineQueryResultVideo('', self.video_url, self.mime_type,
                                   self.thumb_url, self.title)
        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)
Exemplo n.º 5
0
def inline_query_result_video():
    return InlineQueryResultVideo(
        TestInlineQueryResultVideo.id,
        TestInlineQueryResultVideo.video_url,
        TestInlineQueryResultVideo.mime_type,
        TestInlineQueryResultVideo.thumb_url,
        TestInlineQueryResultVideo.title,
        video_width=TestInlineQueryResultVideo.video_width,
        video_height=TestInlineQueryResultVideo.video_height,
        video_duration=TestInlineQueryResultVideo.video_duration,
        caption=TestInlineQueryResultVideo.caption,
        description=TestInlineQueryResultVideo.description,
        input_message_content=TestInlineQueryResultVideo.input_message_content,
        reply_markup=TestInlineQueryResultVideo.reply_markup)
Exemplo n.º 6
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))
Exemplo n.º 7
0
def search(bot, update):
    query = update.inline_query.query
    if not query:
        return
    results = list()
    ret = search_video(query)
    if not ret:
        return
    for video in ret[:9]:
        results.append(
            InlineQueryResultVideo(
                video_url=video['arcurl'],
                mime_type="text/html",
                id=video['id'],
                thumb_url="http:" + video['pic'],
                title=clear_title(video['title']),
                parse_mode=telegram.ParseMode.HTML,
                input_message_content=InputTextMessageContent(video['arcurl']),
            ))
    bot.answer_inline_query(update.inline_query.id, results)
Exemplo n.º 8
0
def add_inlinequery(tweet_data: dict):
    """Adds an appropriate InlineQueryResult* for each type of tweet."""
    if 'video_url' in tweet_data:  # Video -
        tweet_data['mime_type'] = 'video/mp4' if 'application/x' in tweet_data['mime_type'] else tweet_data['mime_type']
        return InlineQueryResultVideo(**tweet_data)

    if 'images' not in tweet_data:  # Article -
        return InlineArticle(**{
            'input_message_content': InpTxtMsg(tweet_data.pop('caption'), entities=tweet_data.pop('caption_entities'),
                                               disable_web_page_preview=True),
            **tweet_data})

    # Photo -
    images = tweet_data.pop('images')
    tweet_data['thumb_url'] = images[0]['photo_url']  # Keep thumb photo same as actual photo (instead of user dp)

    if len(images) > 1:  # Display buttons if more than 1 image is found
        buttons = [[InlineKeyboardButton(text='Next Photo', callback_data=f"{tweet_data['tweet_id']}_next_1")]]
        tweet_data['reply_markup'] = InlineKeyboardMarkup(buttons)

    data = {**images[0], **tweet_data}
    return InlineQueryResultPhoto(**data)
Exemplo n.º 9
0
def get_results(command: str, json_mode: bool = True):
    cwd = dl_base + "Inline " + str(uuid4()) + "/"
    Path(cwd).mkdir(parents=True, exist_ok=True)
    res = z(
        """
    if cd {cwd} ; then
        {command:e}
    else
        echo Inline Query: cd failed >&2
    fi
    """,
        fork=True,
    )  # @design We might want to add a timeout here. We also need a file cacher ... Easier yet, just cache the results array and reset it using our 'x' command
    out = res.outerr
    if WHITESPACE.match(out):
        out = f"The process exited {res.retcode}."
    out_j = None
    results = []
    if json_mode:
        try:
            out_j = json.loads(res.out)
        except:
            pass
    if out_j and not isinstance(out_j, str) and isinstance(out_j, Iterable):
        print(res.err)
        if True:
            for item in out_j:
                if isinstance(item, dict):
                    tlg_title = item.get("tlg_title", "")
                    tlg_preview = bool(item.get("tlg_preview", "y"))
                    tlg_video = item.get("tlg_video", "")
                    # Mime type of the content of video url, “text/html” or “video/mp4”.
                    tlg_video_mime = item.get("tlg_video_mime", "video/mp4")
                    tlg_img = item.get("tlg_img", "")
                    tlg_img_thumb = item.get("tlg_img_thumb", "") or tlg_img
                    tlg_content = item.get("tlg_content",
                                           item.get("caption", ""))
                    tlg_parsemode = item.get("tlg_parsemode", "").lower()
                    pm = DEFAULT_NONE
                    if tlg_parsemode == "md2":
                        pm = ParseMode.MARKDOWN_V2
                    elif tlg_parsemode == "md":
                        pm = ParseMode.MARKDOWN
                    elif tlg_parsemode == "html":
                        pm = ParseMode.HTML
                    print(f"Parse mode: {pm}, preview: {tlg_preview}")
                    if tlg_img:
                        # There is a bug that makes, e.g., `@spiritwellbot kitsu-getall moon 2 fin` show only two returned results, even though we return 10 results. Idk what's the cause.
                        print(
                            f"tlg_img found: {tlg_title}: {tlg_img} , {tlg_img_thumb}"
                        )
                        results.append(
                            InlineQueryResultPhoto(
                                id=uuid4(),
                                photo_url=tlg_img,
                                thumb_url=tlg_img_thumb,
                                title=f"{tlg_title}",
                                caption=tlg_content[:MEDIA_MAX_LENGTH],
                                parse_mode=pm,
                            ))
                    elif tlg_video:
                        # test @spiritwellbot ec '[{"tlg_title":"f","tlg_video":"https://files.lilf.ir/tmp/Tokyo%20Ghoul%20AMV%20-%20Run-rVed44_uz8s.mp4"}]' fin
                        print(f"tlg_video found: {tlg_title}: {tlg_video}")
                        results.append(
                            InlineQueryResultVideo(
                                id=uuid4(),
                                video_url=tlg_video,
                                mime_type=tlg_video_mime,
                                # To bypass telegram.error.BadRequest: Video_thumb_url_empty
                                thumb_url=
                                (tlg_img_thumb or
                                 "https://media.kitsu.io/anime/cover_images/3936/original.jpg?1597696323"
                                 ),
                                title=f"{tlg_title}",
                                caption=tlg_content[:MEDIA_MAX_LENGTH],
                                parse_mode=pm,
                            ))
                    elif tlg_title:
                        print(f"tlg_title found: {tlg_title}")
                        results.append(
                            InlineQueryResultArticle(
                                id=uuid4(),
                                title=tlg_title,
                                thumb_url=tlg_img_thumb,
                                input_message_content=InputTextMessageContent(
                                    tlg_content[:MAX_LENGTH],
                                    disable_web_page_preview=(not tlg_preview),
                                    parse_mode=pm,
                                ),
                            ))
                    # @design We can add an else clause and go to the normal (json-less) mode below
    else:
        results = [
            InlineQueryResultArticle(
                id=uuid4(),
                # Telegram truncates itself, so this is redundant.
                title=out[:150],
                input_message_content=InputTextMessageContent(
                    out[:MAX_LENGTH], disable_web_page_preview=False),
            )
        ]
        files = list(Path(cwd).glob("*"))
        files.sort()
        for f in files:
            if not f.is_dir():
                file_add = f.absolute()
                base_name = str(os.path.basename(file_add))
                ext = f.suffix
                file = open(file_add, "rb")
                uploaded_file = updater.bot.send_document(tmp_chat, file)
                file.close()
                if uploaded_file.document:
                    # print(f"File ID: {uploaded_file.document.file_id}")
                    results.append(
                        InlineQueryResultCachedDocument(
                            id=uuid4(),
                            title=base_name,
                            document_file_id=uploaded_file.document.file_id,
                        ))
                else:
                    print("BUG?: Uploaded file had no document!")

    z("command rm -r {cwd}")
    print(f"len(results): {len(results)}")
    return results
Exemplo n.º 10
0
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)
Exemplo n.º 11
0
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)
Exemplo n.º 12
0
 def answer_results(f: feed, fallback: bool = False):
     if not f.mediaurls:
         results = [
             InlineQueryResultArticle(
                 id=str(uuid4()),
                 title=f.user,
                 description=f.content,
                 reply_markup=origin_link(f.url),
                 input_message_content=InputTextMessageContent(
                     captions(f, fallback),
                     parse_mode=None
                     if fallback else ParseMode.MARKDOWN_V2,
                 ),
             )
         ]
     else:
         if f.mediatype == "video":
             results = [
                 InlineQueryResultVideo(
                     id=str(uuid4()),
                     caption=captions(f, fallback),
                     title=f.user,
                     description=f.content,
                     mime_type="video/mp4",
                     parse_mode=None
                     if fallback else 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=str(uuid4()),
                     caption=captions(f, fallback),
                     title=f.mediatitle,
                     description=f.content,
                     audio_duration=f.mediaduration,
                     audio_url=f.mediaurls[0],
                     parse_mode=None
                     if fallback else ParseMode.MARKDOWN_V2,
                     performer=f.user,
                     reply_markup=origin_link(f.url),
                     thumb_url=f.mediathumb,
                 )
             ]
         else:
             results = [
                 InlineQueryResultGif(
                     id=str(uuid4()),
                     caption=captions(f, fallback),
                     title=f"{f.user}: {f.content}",
                     gif_url=img,
                     parse_mode=None
                     if fallback else ParseMode.MARKDOWN_V2,
                     reply_markup=origin_link(f.url),
                     thumb_url=img,
                 ) if ".gif" in img else InlineQueryResultPhoto(
                     id=str(uuid4()),
                     caption=captions(f, fallback),
                     title=f.user,
                     description=f.content,
                     parse_mode=None
                     if fallback else 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
             ]
             results.extend(helpmsg)
     inline_query.answer(results)