Пример #1
0
def inline_tablas(bot, update):
    logging.debug("%s %s" % (bot, update))
    query = update.inline_query.query
    max_range = 25
    results = []

    if len(__TABLAS_JSON["tablas"]) < 25:
        max_range = len(__TABLAS_JSON["tablas"])

    if len(query) > 2:
        count = 0
        for i in __TABLAS_JSON["tablas"]:
            if re.search(query.lower(), i["name"].lower()):
                count = count + 1
                results.append(
                    InlineQueryResultCachedPhoto(
                        id=uuid4(),
                        photo_file_id=i["file_id"],
                        title=i["name"],
                        caption="@ProfesorDumbledoreBot {}".format(i["name"])))

            if count == max_range:
                update.inline_query.answer(results=results, cache_time=0)
                return

        for i in __TABLAS_JSON["tablas"]:
            count = count + 1
            in_keywords = False
            for k in i["keywords"]:
                if re.search(query.lower(), k.lower()):
                    results.append(
                        InlineQueryResultCachedPhoto(
                            id=uuid4(),
                            photo_file_id=i["file_id"],
                            title=i["name"],
                            caption="@ProfesorDumbledoreBot {}".format(
                                i["name"])))
                    break

        update.inline_query.answer(results=results, cache_time=0)

    else:
        for i in range(max_range):
            results.append(
                InlineQueryResultCachedPhoto(
                    id=uuid4(),
                    photo_file_id=__TABLAS_JSON["tablas"][i]["file_id"],
                    title=__TABLAS_JSON["tablas"][i]["name"],
                    caption="@ProfesorDumbledoreBot {}".format(
                        __TABLAS_JSON["tablas"][i]["name"])))

        update.inline_query.answer(results=results, cache_time=0)
Пример #2
0
def get_list_items_by_type(nt_list: NotetonList,
                           user: NotetonUser) -> List[InlineQueryResult]:
    items = NotetonUsersManager.get_items_of_list(user.id, nt_list)
    answer_items = []
    for item in items:
        id_ = item.id
        item_ = None
        if nt_list.type == NotetonList.TYPE_ARTICLE:
            ans_text = InputTextMessageContent(item.text)
            item_ = InlineQueryResultArticle(id=id_,
                                             title=item.text,
                                             input_message_content=ans_text)
        elif nt_list.type == NotetonList.TYPE_IMAGE:
            item_ = InlineQueryResultCachedPhoto(id=id_,
                                                 photo_file_id=item.file_id)
        elif nt_list.type == NotetonList.TYPE_STICKER:
            item_ = InlineQueryResultCachedSticker(
                id=id_, sticker_file_id=item.file_id)
        elif nt_list.type == NotetonList.TYPE_GIF:
            item_ = InlineQueryResultCachedGif(id=id_,
                                               gif_file_id=item.file_id)
        elif nt_list.type == NotetonList.TYPE_AUDIO:
            item_ = InlineQueryResultCachedAudio(id=id_,
                                                 audio_file_id=item.file_id)
        elif nt_list.type == NotetonList.TYPE_DOCUMENT:
            item_ = InlineQueryResultCachedDocument(
                id=id_, title=item.title, document_file_id=item.file_id)
        if item_:
            answer_items.append(item_)
    return answer_items
Пример #3
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))
    def uploadImage(self, image, expression, caption, code_in_caption):
        attempts = 0
        errorMessage = None

        while attempts < 3:
            try:
                latex_picture_id = self._bot.sendPhoto(self._devnullChatId,
                                                       image).photo[0].file_id
                self.logger.debug("Image successfully uploaded for %s",
                                  expression)

                return InlineQueryResultCachedPhoto(
                    0,
                    photo_file_id=latex_picture_id,
                    caption=caption,
                    parse_mode=ParseMode.MARKDOWN
                    if not code_in_caption else None)
            except TelegramError as err:
                errorMessage = self._resourceManager.getString(
                    "telegram_error") + str(err)
                self.logger.warn(errorMessage)
                attempts += 1

        return InlineQueryResultArticle(0, errorMessage,
                                        InputTextMessageContent(expression))
Пример #5
0
def inlinenow(update, context):
    'inline implementation of notplaying() function along with exception handeling for new users'
    try: 
        uid = update.inline_query.from_user.id
        authtoken = list(sql.get_user(uid)[0])[2]
    except: 
        update.inline_query.answer(
            results=[], 
            switch_pm_text='Connect your Spotify account.',
            switch_pm_parameter='link', 
            cache_time=0
        )
        return
    try: 
        data = {
            'grant_type':'refresh_token',
            'refresh_token':authtoken,
            'redirect_uri':redirect_uri,
            'client_id':client_id,
            'client_secret':client_secret
        }
        token = requests.post('https://accounts.spotify.com/api/token', data=data).json()
    except:
        update.inline_query.answer(
            results=[], 
            switch_pm_text="Something's wrong. Lets fix it.", 
            switch_pm_parameter='relink', 
            cache_time=0
        )
        return
    try: 
        headers = {
            'Accept':'application/json', 
            'Content-Type':'application/json', 
            'Authorization':'Bearer '+token['access_token']
        }
        r = requests.get('https://api.spotify.com/v1/me/player/currently-playing', headers=headers).json()
        if   r['currently_playing_type'] == 'ad': 
            update.inline_query.answer([], switch_pm_text="You're listening to annoying ads.", switch_pm_parameter='ads', cache_time=0)
        elif r['currently_playing_type'] == 'track':
            button = InlineKeyboardButton(text="Play on Spotify", url=r['item']['external_urls']['spotify'])
            image   = getpic(r, uid, context)
            dump    = context.bot.send_photo(dumpchannel, photo=image)
            photo   = dump['photo'][1]['file_id']
            dump.delete()
            update.inline_query.answer(
                [
                    InlineQueryResultCachedPhoto(
                        id=uuid4(),
                        photo_file_id=photo,
                        reply_markup=InlineKeyboardMarkup([[button]])
                    )
                ], cache_time=0
            )
        else: 
            update.inline_query.answer([], switch_pm_text="Not sure what you're listening to.", switch_pm_parameter='notsure', cache_time=0)
    except Exception as e: 
        print(e)
        update.inline_query.answer([], switch_pm_text="You're not listening to anything.", switch_pm_parameter='notlistening', cache_time=0)
Пример #6
0
def photo_inline_result(doc: Document) -> InlineQueryResultCachedPhoto:
    content = doc.content
    return InlineQueryResultCachedPhoto(
        id=doc.internal_id,
        photo_file_id=content['best_photo'],
        title=doc.keywords,
        caption=content.get('caption'),
    )
Пример #7
0
    def send_qr(qr):
        photo_info = bot.send_photo(update.inline_query.from_user.id,
                                    photo=qr,
                                    caption=name)

        results.append(
            InlineQueryResultCachedPhoto(
                id=uuid4(), photo_file_id=photo_info.photo[0].file_id))

        update.inline_query.answer(results)
Пример #8
0
    def test_equality(self):
        a = InlineQueryResultCachedPhoto(self.id, self.photo_file_id)
        b = InlineQueryResultCachedPhoto(self.id, self.photo_file_id)
        c = InlineQueryResultCachedPhoto(self.id, '')
        d = InlineQueryResultCachedPhoto('', self.photo_file_id)
        e = InlineQueryResultCachedVoice(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)
Пример #9
0
def inline_query_result_cached_photo():
    return InlineQueryResultCachedPhoto(
        TestInlineQueryResultCachedPhoto.id,
        TestInlineQueryResultCachedPhoto.photo_file_id,
        title=TestInlineQueryResultCachedPhoto.title,
        description=TestInlineQueryResultCachedPhoto.description,
        caption=TestInlineQueryResultCachedPhoto.caption,
        input_message_content=TestInlineQueryResultCachedPhoto.
        input_message_content,
        reply_markup=TestInlineQueryResultCachedPhoto.reply_markup)
def build_kwargs(signature: inspect.Signature,
                 default_kwargs,
                 dfv: Any = DEFAULT_NONE):
    kws = {}
    for name, param in signature.parameters.items():
        # For required params we need to pass something
        if param.default is inspect.Parameter.empty:
            # Some special casing
            if name == "permissions":
                kws[name] = ChatPermissions()
            elif name in ["prices", "commands", "errors"]:
                kws[name] = []
            elif name == "media":
                media = InputMediaPhoto("media", parse_mode=dfv)
                if "list" in str(param.annotation).lower():
                    kws[name] = [media]
                else:
                    kws[name] = media
            elif name == "results":
                itmc = InputTextMessageContent("text",
                                               parse_mode=dfv,
                                               disable_web_page_preview=dfv)
                kws[name] = [
                    InlineQueryResultArticle("id",
                                             "title",
                                             input_message_content=itmc),
                    InlineQueryResultCachedPhoto("id",
                                                 "photo_file_id",
                                                 parse_mode=dfv,
                                                 input_message_content=itmc),
                ]
            elif name == "ok":
                kws["ok"] = False
                kws["error_message"] = "error"
            else:
                kws[name] = True
        # pass values for params that can have defaults only if we don't want to use the
        # standard default
        elif name in default_kwargs:
            if dfv != DEFAULT_NONE:
                kws[name] = dfv
        # Some special casing for methods that have "exactly one of the optionals" type args
        elif name in ["location", "contact", "venue", "inline_message_id"]:
            kws[name] = True
        elif name == "until_date":
            if dfv == "non-None-value":
                # Europe/Berlin
                kws[name] = pytz.timezone("Europe/Berlin").localize(
                    datetime.datetime(2000, 1, 1, 0))
            else:
                # UTC
                kws[name] = datetime.datetime(2000, 1, 1, 0)
    return kws
Пример #11
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)
Пример #12
0
 def get_picture(self, update, query):
     logger.info('input query ' + query)
     results = []
     if query != '':
         name = update.inline_query.from_user['username']
         meme_path = generate_image(query, '{0}{1}'.format(name, 'IMG'))
         msg = self.updater.bot.send_photo(chat_id=CHANEL_ID,
                                           photo=open(meme_path, "rb"))
         file_id = msg.photo[0].file_id
         self.updater.bot.delete_message(chat_id=CHANEL_ID,
                                         message_id=msg.message_id)
         results.append(
             InlineQueryResultCachedPhoto(id=uuid4(),
                                          photo_file_id=file_id))
     return results
Пример #13
0
def inline_handler(update, context):
    stage = 10

    results = [
        InlineQueryResultCachedPhoto(
            id=uuid.uuid4(),
            photo_file_id=hang_pictures[stage],
            caption="Нажми кнопку чтобы начать новую игру ⬇️",
            reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("Начать игру!", callback_data="new_game")]]),
        )
    ]

    try:
        res = update.inline_query.answer(results, cache_time=1, is_personal=True)
    except BadRequest as e:
        __upload_pic(stage, context.bot)
        res = update.inline_query.answer(results, cache_time=1, is_personal=True)

    print(f"inline_handler answer result: {res}")
Пример #14
0
 def _entity_to_inline_query_result(self, entity: Image):
     """
     Creates a telegram inline query result object for the given entity
     :param entity: the entity to use
     :return: inline result object
     """
     telegram_file_ids_for_current_bot = self.find_telegram_file_ids_for_current_bot(self.bot.token, entity)
     if len(telegram_file_ids_for_current_bot) > 0:
         return InlineQueryResultCachedPhoto(
             id=entity.image_hash,
             photo_file_id=str(telegram_file_ids_for_current_bot[0].id),
         )
     else:
         return InlineQueryResultPhoto(
             id=entity.image_hash,
             photo_url=entity.url,
             thumb_url=entity.url,
             photo_height=50,
             photo_width=50
         )
Пример #15
0
def inline_query(bot, update):
    query = update.inline_query.query
    telegram_id = update.inline_query.from_user.id
    results = []
    for media in find_random_media(count=7):
        if media.media_type == 'img':
            results.append(
                InlineQueryResultCachedPhoto(
                    type='photo',
                    id=uuid.uuid4(),
                    photo_file_id=media.telegram_file_id))
        elif media.media_type == 'animation':
            results.append(
                InlineQueryResultCachedMpeg4Gif(
                    type='mpeg4_gif',
                    id=uuid.uuid4(),
                    mpeg4_file_id=media.telegram_file_id))

    update.inline_query.answer(results, next_offset=7, cache_time=0)
    save_inline_query(query, telegram_id)
Пример #16
0
def inline_find_post(update: Update, context: CallbackContext) -> None:
    query = update.inline_query.query

    if not query.startswith('#'):
        update.inline_query.answer([],
                                   switch_pm_text='Create new quiz post',
                                   switch_pm_parameter='_')
        return

    post_id = query[1:]
    LOGGER.info(f"Inline query with id {post_id}")

    try:
        post = db.models.find_post(post_id)
    except:
        LOGGER.error(f"Error looking for ID {post_id} in inline query")
        return

    content = postutils.get_content_description(post)
    markup = InlineKeyboardMarkup(
        postutils.get_post_keyboard(post['buttons'], post_id))

    result = None
    if postutils.post_type(post) == 'text':
        result = InlineQueryResultArticle(
            id=post_id,
            title="New post",
            description=f"Create new post with {content}",
            input_message_content=InputTextMessageContent(post['text']),
            reply_markup=markup)

    elif postutils.post_type(post) == 'photo':
        result = InlineQueryResultCachedPhoto(
            id=post_id,
            photo_file_id=post['photo'],
            title="New post",
            description=f"Create new post with {content}",
            reply_markup=markup)

    update.inline_query.answer([result])
Пример #17
0
def handle_publishing_options(update: Update, _: CallbackContext):
    user: TGUser = update.effective_user

    try:
        msg, buttons = get_msg_and_buttons(user, update.inline_query.query)
    except ValueError:
        return

    reply_markup = make_reactions_keyboard(buttons or ['-'])
    msg_type = get_message_type(msg)
    config = {
        'id': str(uuid4()),
        'title': msg.text_markdown or msg.caption_markdown
        or "Message to publish.",
        'text': msg.text_markdown,
        'caption': msg.caption_markdown,
        'parse_mode': ParseMode.MARKDOWN,
        'reply_markup': reply_markup,
        # types
        'photo_file_id': msg.photo and msg.photo[0].file_id,
        'video_file_id': msg.video and msg.video.file_id,
        'mpeg4_file_id': msg.animation and msg.animation.file_id,
    }
    if msg_type == 'photo':
        qr = InlineQueryResultCachedPhoto(**config)
    elif msg_type == 'video':
        qr = InlineQueryResultCachedVideo(**config)
    elif msg_type == 'animation':
        qr = InlineQueryResultCachedMpeg4Gif(**config)
    elif msg_type in ('text', 'link'):
        qr = InlineQueryResultArticle(
            input_message_content=InputTextMessageContent(
                msg.text_markdown,
                parse_mode=ParseMode.MARKDOWN,
            ),
            **config,
        )
    else:
        return
    update.inline_query.answer([qr], cache_time=0, is_personal=True)
Пример #18
0
 def send_inline_image(update: Update, _: CallbackContext, file_id: str):
     result = [
         InlineQueryResultCachedPhoto(id=str(uuid4()),
                                      photo_file_id=file_id)
     ]
     update.inline_query.answer(result, cache_time=0)
Пример #19
0
def inline_query(bot, update):
    query = update.inline_query.query
    if re.match(r'^show \d+ \d+$', query):
        if not get_whisper(query.split()[1], query.split()[2]):
            bot.answerInlineQuery(
                update.inline_query.id,
                results=[
                    InlineQueryResultArticle(
                        id=update.inline_query.id + 'notf',
                        title='Photo not found',
                        input_message_content=InputTextMessageContent(
                            'ماكو هيج صورة'))
                ],
                cache_time=0)
            return

        sender_id, receiver, message_id, chat_id = get_whisper(
            query.split()[1],
            query.split()[2])
        receiver = receiver.lower()
        if str(update.inline_query.from_user.id) == str(sender_id) or str(
                update.inline_query.from_user.username).lower() == str(
                    receiver).lower():
            bot.answerInlineQuery(
                update.inline_query.id,
                results=[],
                switch_pm_text='Show Photo 👳‍♀®',
                switch_pm_parameter='{0[1]}_{0[2]}show'.format(
                    query.strip().split()),
                cache_time=0)
            return
        else:
            bot.answerInlineQuery(
                update.inline_query.id,
                results=[
                    InlineQueryResultArticle(
                        id=update.inline_query.id + 'wuser',
                        title='This whisper wasn\'t meant for you',
                        input_message_content=InputTextMessageContent('لتدود'))
                ],
                cache_time=0)
            return

    if not re.match(r'^@[0-9a-zA-Z_]+( \d+ \d+_)?$', query):
        bot.answerInlineQuery(
            update.inline_query.id,
            results=[
                InlineQueryResultArticle(
                    id=update.inline_query.id + 'wformat',
                    title='Write the username',
                    input_message_content=InputTextMessageContent('اكتب عدل'))
            ],
            cache_time=0)
        return
    results_ = []

    if query.endswith('_'):
        if str(update.inline_query.from_user.id) in to_be_whispers:
            sender_id = update.inline_query.from_user.id
            receiver, message_id, chat_id, file_id = to_be_whispers[str(
                sender_id)]
            receiver = receiver.lower()
            results_.append(
                InlineQueryResultCachedPhoto(
                    id=update.inline_query.id + 'photo',
                    photo_file_id=file_id,
                    title='Whisper photo to {}'.format(query.split()[0]),
                    input_message_content=InputTextMessageContent(
                        'Photo whisper to ' + query.split()[0].lower()),
                    reply_markup=InlineKeyboardMarkup([[
                        InlineKeyboardButton(
                            'Show Photo',
                            switch_inline_query_current_chat='show {} {}'.
                            format(message_id, chat_id))
                    ]])))
        bot.answerInlineQuery(
            update.inline_query.id,
            results=results_,
            switch_pm_text='👳‍♀® Whisper a new photo to {} ..'.format(
                query.split()[0]),
            switch_pm_parameter=query.split()[0][1:],
            cache_time=0)
        return
    else:
        bot.answerInlineQuery(
            update.inline_query.id,
            results=[],
            switch_pm_text='👳‍♀® Whisper a new photo to {} ..'.format(
                query.lower()),
            switch_pm_parameter=query.split()[0][1:],
            cache_time=0)
Пример #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 = []
    # 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
Пример #21
0
def inlinequery(update, context):
    """Handle the inline query."""

    ###
    # https://python-telegram-bot.readthedocs.io/en/stable/telegram.inlinequery.html
    ##
    # There is pretty much no info except the sender in update. context is also useless. So we can't get the replied-to file.
    ###
    def ans_text(text: str = "", cache_time=1):  # "To undo the folded lie,"
        if not text:
            return
        update.inline_query.answer(
            [
                InlineQueryResultArticle(
                    id=uuid4(),
                    title=text,
                    input_message_content=InputTextMessageContent(
                        text, disable_web_page_preview=False),
                )
            ],
            cache_time=cache_time,
            is_personal=True,
        )

    if not isAdmin(update, admins=graylist):
        ans_text(
            """Defenceless under the night
Our world in stupor lies;
Yet, dotted everywhere,
Ironic points of light
Flash out wherever the Just
Exchange their messages:
May I, composed like them
Of Eros and of dust,
Beleaguered by the same
Negation and despair,
Show an affirming flame.
    - Auden""",
            cache_time=86400,
        )
        return

    with lock_inline:
        query = update.inline_query.query
        m = PDI.match(query)
        if m:
            c_id = m.group(1)
            c_kind = m.group(2) or ""
            print(f"Download ID: {c_id} {c_kind}")
            result = None
            if c_kind == "":
                result = InlineQueryResultCachedDocument(id=uuid4(),
                                                         title=str(c_id),
                                                         document_file_id=c_id)
            elif c_kind.startswith("vid"):
                result = InlineQueryResultCachedVideo(id=uuid4(),
                                                      title=str(c_id),
                                                      video_file_id=c_id)
            elif c_kind == "photo":
                result = InlineQueryResultCachedPhoto(id=uuid4(),
                                                      title=str(c_id),
                                                      photo_file_id=c_id)
            elif c_kind == "gif":
                result = InlineQueryResultCachedMpeg4Gif(id=uuid4(),
                                                         title=str(c_id),
                                                         mpeg4_file_id=c_id)
            if result:
                try:
                    update.inline_query.answer([result],
                                               cache_time=1,
                                               is_personal=True)
                except:
                    ans_text(traceback.format_exc())
            else:
                ans_text(f"Invalid kind: {c_kind}")
            return
        command = ""
        cache_time = 1
        is_personal = True
        no_match = True
        m = PC_KITSU.match(query)
        if m:
            no_match = False
            arg = zq(str(m.group(1)))
            if not arg:
                ans_text()
                return
            command = f"kitsu-getall {arg}"
            cache_time = 86400
            is_personal = False
        m = PC_GOO.match(query)
        if m:
            no_match = False
            mode = str(m.group(1))
            arg = zq(str(m.group(2)))
            if not arg:
                ans_text()
                return
            if mode == "g":
                command = f"jigoo {arg}"
            elif mode == "as":
                command = f"jias {arg}"
            else:  # 'd'
                command = f"search_json_ddg=y jigoo {arg}"
            is_personal = False
        if no_match:
            if not isAdmin(update):
                ans_text("""The enlightenment driven away,
The habit-forming pain,
Mismanagement and grief:
We must suffer them all again. - Auden""")
                return
            if query == ".x":
                bsh.restart()
                cache.clear()
                ans_text("Restarted")
                return
            m = PAF.match(query)
            if m == None:
                ans_text()
                return
            command = m.group(2)
            if m.group(1) == "n":
                # embed()
                command = "noglob " + command
        if not command:
            ans_text()
            return
        print(f"Inline command accepted: {command}")
        results = get_results(command)
        update.inline_query.answer(results,
                                   cache_time=cache_time,
                                   is_personal=is_personal)
Пример #22
0
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)
Пример #23
0
def send_compile_results(update: Update, context: CallbackContext):
    # is this an inline query or text message
    is_inline_query = update.inline_query is not None
    if (not is_inline_query and not update.effective_message):  # why is this happening?! Let me see these messages...
        context.bot.send_message(constants.RENYHP, "not inline query and not update.message:")
        inspect_update(update, context)
        return
    if (is_inline_query and not update.inline_query.query) or (not is_inline_query and not update.effective_message.text):
        return

    inline_query_results = []

    # typing...
    if not is_inline_query:
        update.effective_chat.send_action(ChatAction.TYPING)

    # compile
    filename, output, error = lilypond.lilypond_compile(update, context)

    # send text
    if is_inline_query:
        inline_query_results.append(
            InlineQueryResultArticle(uuid4(), "Source code", InputTextMessageContent(update.inline_query.query)))

    if error:
        result = secure_send(context.bot, constants.DEV_NULL if is_inline_query else update.effective_chat.id, error,
                             f"{constants.USER_FILES_DIR}/{filename}.log", is_inline_query)
        if result is not None:
            inline_query_results.append(result)

    if output:  # I want to know if that happens...
        error = f"ERROR\n\n{error}"
        output = f"OUTPUT\n\n{output}"
        secure_send(context.bot, constants.RENYHP, error, f"{constants.ERROR_FILES_DIR}/{filename}.error", False)
        secure_send(context.bot, constants.RENYHP, output, f"{constants.ERROR_FILES_DIR}/{filename}.output", False)
        shutil.copy(f"{constants.USER_FILES_DIR}/{filename}.ly", f"{constants.ERROR_FILES_DIR}/{filename}.ly")

    successfully_compiled = False

    # send png's
    for png_file in glob.glob(f"{constants.USER_FILES_DIR}/{filename}*.png"):
        successfully_compiled = True  # yay compiled
        if not is_inline_query:
            update.effective_chat.send_action(ChatAction.UPLOAD_PHOTO)
        lilypond.add_padding(png_file)
        if is_inline_query:
            with open(png_file, "rb") as file:
                file_id = context.bot.send_photo(constants.DEV_NULL, file).photo[0].file_id
            inline_query_results.append(InlineQueryResultCachedPhoto(uuid4(), file_id))
        else:
            with open(png_file, "rb") as file:
                try:
                    update.effective_message.reply_photo(file)
                except TelegramError:
                    try:
                        update.effective_message.reply_document(file)
                    except BadRequest as badreq:
                        context.dispatcher.dispatch_error(update, badreq)
                        inspect_update(update, context)
                        stat = os.stat(png_file)
                        context.bot.send_message(constants.RENYHP,
                                                 f"glob:\n{glob.glob(f'{constants.USER_FILES_DIR}/{filename}*')}\n\n"
                                                 f"offending: {png_file}\n"
                                                 f"file size: {stat.st_size} B")
                        context.bot.send_message(constants.RENYHP,
                                                 "<code>" + str(stat) + "</code>", ParseMode.HTML)
                        shutil.copy(png_file, f"{constants.ERROR_FILES_DIR}/{filename}.png")

    # send midi's
    for midi_file in glob.glob(f"{constants.USER_FILES_DIR}/{filename}*.midi"):
        successfully_compiled = True
        if is_inline_query:
            with open(midi_file, "rb") as file:
                file_id = context.bot.send_document(constants.DEV_NULL, file).document.file_id
            inline_query_results.append(InlineQueryResultCachedDocument(uuid4(), "MIDI output", file_id))
        else:
            update.effective_chat.send_action(ChatAction.UPLOAD_AUDIO)
            # convert to mp3
            mp3_file = midi_file.rstrip("midi") + "mp3"
            process = subprocess.run(f"timidity {midi_file} -Ow -o - | "
                                     f"ffmpeg -i - -ar 44100 -ac 2 -q:a 2 {mp3_file}",
                                     stderr=subprocess.PIPE, stdout=subprocess.PIPE, errors='replace', shell=True)
            if process.returncode != 0:
                context.bot.send_message(constants.RENYHP, f"{midi_file} error.\n"
                                                           f"ffmpeg return code: {process.returncode}")
                secure_send(context.bot, constants.RENYHP,
                            process.stderr, f"{constants.ERROR_FILES_DIR}/{filename}.midi.error", False)
                secure_send(context.bot, constants.RENYHP,
                            process.stdout, f"{constants.ERROR_FILES_DIR}/{filename}.midi.output", False)
                shutil.copy(midi_file, midi_file.replace(constants.USER_FILES_DIR, constants.ERROR_FILES_DIR))
                file_to_send = midi_file
            else:
                file_to_send = mp3_file
            with open(file_to_send, "rb") as file:
                try:
                    if file_to_send.endswith("mp3"):
                        update.effective_message.reply_audio(file)
                    else:
                        raise TelegramError
                except TelegramError:
                    update.effective_message.reply_document(file)

    if is_inline_query:
        update.inline_query.answer(inline_query_results)

    if successfully_compiled and update.effective_user.id != constants.RENYHP:
        monitor.successful_compilations += 1