Beispiel #1
0
def inlinequery(bot, update):
    query = update.inline_query.query

    res = list()
    
    if len(query) < 3: 
        bot.answerInlineQuery(update.inline_query.id, results=res)
        return

    print(query)
    subreddit = None

    try: 
        subreddit = reddit.get_subreddit(query)
        subreddit.fullname
    except:
        logger.warning('invalid subreddit: %s' % query)
        bot.answerInlineQuery(update.inline_query.id, results=res)
        return

    submissions = subreddit.get_hot(limit=25)

    for sub in submissions:
        offset = sub.name
        link_url = sub.url

        try:
            if 'imgur' in sub.url:
                m = re.search('imgur\.com\/(\w*)', sub.url)
                # geen albums (imgur.com/a/)
                if len(m.group(1) > 2):
                    link_url = 'https://i.imgur.com/' + m.group(1) + '.jpg'
        except:
            # voor het geval dat
            pass

        message = '<strong>{title}</strong> \n <a href="{url}">link</a> | <a href="https://www.reddit.com/r/{subreddit}">/r/{subreddit}</a> | <a href="{link}">permalink</a>'.format(title=html.escape(sub.title), url=html.escape(link_url), subreddit=sub.subreddit, link=sub.permalink)

        qwe = InlineQueryResultArticle(
            id=uuid4(),
            title=sub.title,
            input_message_content=InputTextMessageContent(message, parse_mode=ParseMode.HTML)
            )

        thumbnail = ''

        if hasattr(sub, 'preview'): 
            thumbnail = sub.preview['images'][0]['source']['url']
        
        try:
            if sub.secure_media != None:
                thumbnail = sub.secure_media['oembed']['thumbnail_url']
        except:
            # jammer
            pass

        qwe.thumb_url = thumbnail
        res.append(qwe)

    bot.answerInlineQuery(update.inline_query.id, results=res, cache_time=CACHE_TIME)
Beispiel #2
0
def inline_genverde(bot, update):
    query = update.inline_query.query
    results = list()

    results.append(InlineQueryResultArticle(
        id=uuid4(),
        title="Genverde",
        description="Genverde el desde en keddese",
        input_message_content=InputTextMessageContent(genverde(query))))

    update.inline_query.answer(results)
def inline_caps(update, context):
    query = update.inline_query.query
    if not query:
        return
    results = list()
    results.append(
        InlineQueryResultArticle(
            id='1',
            title='Weather',
            input_message_content=InputTextMessageContent("Get weather info")
        )
    )
    results.append(
        InlineQueryResultArticle(
            id='2',
            title='Covid',
            input_message_content=InputTextMessageContent("Get covid info")
        )
    )
    context.bot.answer_inline_query(update.inline_query.id, results)
Beispiel #4
0
def inlinequery(update, context):
    if update.inline_query.query != "":
        res = getResult(update.inline_query.query.split(),
                        update.inline_query.from_user.language_code)
        update.inline_query.answer([
            InlineQueryResultArticle(
                id=uuid4(),
                title="🍪 Choose your fighter",
                input_message_content=InputTextMessageContent(res))
        ],
                                   cache_time=1)
Beispiel #5
0
def inlinequery(bot, update):
    """Handle the inline query."""
    query = update.inline_query.query
    results = [
        InlineQueryResultArticle(id=uuid4(),
                                 title="Caps",
                                 input_message_content=InputTextMessageContent(query.upper())),
        InlineQueryResultArticle(id=uuid4(),
                                 title="Bold",
                                 input_message_content=InputTextMessageContent(
                                     "*{}*".format(escape_markdown(query)),
                                     parse_mode=ParseMode.MARKDOWN)),
        InlineQueryResultArticle(id=uuid4(),
                                 title="Italic",
                                 input_message_content=InputTextMessageContent(
                                     "_{}_".format(escape_markdown(query)),
                                     parse_mode=ParseMode.MARKDOWN))
    ]

    update.inline_query.answer(results)
Beispiel #6
0
def inlinequery(update, context):
    """Handle the inline query."""
    draw = csm.spin()
    results = [
        InlineQueryResultArticle(
            id=uuid4(),
            title="Take me for a spin!",
            input_message_content=InputTextMessageContent(draw))
    ]

    update.inline_query.answer(results, cache_time=0)
Beispiel #7
0
def create_result_article_chart_artist(datas):
    results = [
        InlineQueryResultArticle(
            id=data['id'],
            title=data['name'],
            input_message_content=InputTextMessageContent(data['link']),
            description=f"Position: {data['position']}",
            thumb_url=data['picture_big']) for data in datas
    ]

    return results
Beispiel #8
0
def new_bots_article():
    from components.explore import _new_bots_text
    msg_text = messages.PROMOTION_MESSAGE + '\n\n' + _new_bots_text()
    return InlineQueryResultArticle(
        id=uuid4(),
        title='🆕 New Bots',
        input_message_content=InputTextMessageContent(message_text=msg_text,
                                                      parse_mode="Markdown"),
        description='Bots added since the last update',
        # thumb_url='http://www.colorcombos.com/images/colors/FF0000.png',
    )
Beispiel #9
0
def inlinequery(_bot, update):
    random_hankpun = random.choice(hankpuns)
    results = [
        InlineQueryResultArticle(id=uuid4(),
                                 title="Hank Johnson says: ",
                                 description=random_hankpun['pun'],
                                 input_message_content=InputTextMessageContent(
                                     random_hankpun['pun']),
                                 thumb_url=puns_thumb)
    ]
    update.inline_query.answer(results)
Beispiel #10
0
def get_inline_results(bot, update):
    query = update.inline_query.query
    results = list()

    results.append(InlineQueryResultArticle(id='1000',
                                            title="Book 1",
                                            description='Description of this book, author ...',
                                            thumb_url='https://fakeimg.pl/100/?text=book%201',
                                            input_message_content=InputTextMessageContent(
                                                'chosen book:')))

    results.append(InlineQueryResultArticle(id='1001',
                                            title="Book 2",
                                            description='Description of the book, author...',
                                            thumb_url='https://fakeimg.pl/300/?text=book%202',
                                            input_message_content=InputTextMessageContent(
                                                'chosen book:')
                                            ))

    update.inline_query.answer(results)
Beispiel #11
0
def query_too_short_article():
    txt = '[I am a stupid, crazy fool.](https://www.youtube.com/watch?v=DLzxrzFCyOs)'
    return InlineQueryResultArticle(
        id=uuid4(),
        title=util.action_hint(
            'Your search term must be at least {} characters long.'.format(
                SEARCH_QUERY_MIN_LENGTH)),
        input_message_content=InputTextMessageContent(
            message_text=txt,
            parse_mode="Markdown",
            disable_web_page_preview=True))
Beispiel #12
0
 def inline_query(self, _, update):
     query = update.inline_query.query
     results = [
         InlineQueryResultArticle(
             id=uuid4(),
             title='format',
             input_message_content=InputTextMessageContent(
                 self.state.formatter.format(query),
                 parse_mode=ParseMode.HTML))
     ]
     update.inline_query.answer(results)
Beispiel #13
0
def on_inline(bot, update):
    query = update.inline_query.query
    results = [
        InlineQueryResultArticle(id=uuid4(),
                                 title='italic',
                                 input_message_content=InputTextMessageContent(
                                     message_text=to_italic(query),
                                     parse_mode='HTML')),
        InlineQueryResultArticle(id=uuid4(),
                                 title='bold',
                                 input_message_content=InputTextMessageContent(
                                     message_text=to_bold(query),
                                     parse_mode='HTML')),
        InlineQueryResultArticle(id=uuid4(),
                                 title='pOèRo',
                                 input_message_content=InputTextMessageContent(
                                     message_text=to_poero(query),
                                     parse_mode='HTML'))
    ]
    update.inline_query.answer(results)
Beispiel #14
0
def inline_query_received(bot, update):
    # get query
    query = update.inline_query
    user_id = query.from_user.id
    results = None

    # check if file_id is provided
    if query.query.lower() not in ('', 'share'):
        try:
            file = bot.get_file(query.query)

            # set id to preferred langs order
            id = int(get_message(user_id, "order"))

            title = get_message(user_id, "your_sticker")
            desc = get_message(user_id, "forward_desc")
            caption = "@EzStickerBot"
            results = [
                InlineQueryResultCachedDocument(id,
                                                title,
                                                file.file_id,
                                                description=desc,
                                                caption=caption)
            ]
        except TelegramError:
            pass

    if results is None:
        # build InlineQueryResultArticle arguments individually
        title = get_message(user_id, "share")
        description = get_message(user_id, "share_desc")
        thumb_url = "https://i.imgur.com/wKPBstd.jpg"
        markup = InlineKeyboardMarkup([[
            InlineKeyboardButton(text=get_message(user_id,
                                                  "make_sticker_button"),
                                 url="https://t.me/EzStickerBot")
        ]])
        input_message_content = InputTextMessageContent(get_message(
            user_id, "share_text"),
                                                        parse_mode='Markdown')

        # set id to preferred langs order
        id = int(get_message(user_id, "order"))

        results = [
            InlineQueryResultArticle(
                id=id,
                title=title,
                description=description,
                thumb_url=thumb_url,
                reply_markup=markup,
                input_message_content=input_message_content)
        ]
    query.answer(results=results, cache_time=60, is_personal=True)
Beispiel #15
0
def inlinequery(update, context):
    query = update.inline_query.query
    print(query)
    results = [
        InlineQueryResultArticle(
            id=uuid4(),
            title="summarize: " + query,
            input_message_content=InputTextMessageContent(
                query + "\n" + return_summary(query)[:1024 - len(query) - 2]))
    ]
    update.inline_query.answer(results)
Beispiel #16
0
def article_mapper(audio):
    return InlineQueryResultArticle(
        id=str(uuid4()),
        thumb_url=audio.get('cover_url_small') or audio.get('cover'),
        hide_url=True,
        url=audio['download'],
        title=audio["title"],
        description="Artist: {}\n{}".format(audio['artist'],
                                            album_or_duration(audio)),
        audio_duration=audio["duration"],
        input_message_content=InputTextMessageContent(audio['download']))
Beispiel #17
0
def inlinequery(bot, update):
    results = list()

    results.append(
        InlineQueryResultArticle(id=uuid4(),
                                 title='Create Tic-Tac-Toe 3x3 round.',
                                 input_message_content=InputTextMessageContent(
                                     'Tic-Tac-Toe round created!'),
                                 reply_markup=get_initial_keyboard()))

    bot.answerInlineQuery(update.inline_query.id, results=results)
def new_secret_santa(bot, update):
    query = update.inline_query.query
    results = [
        InlineQueryResultArticle(
            id=uuid4(),
            title=">> Crear Nuevo Amigo Invisible <<",
            input_message_content=InputTextMessageContent(
                "Amigo invisible\nNo hay nadie apuntado. Se el primero!"),
            reply_markup=buttons_open)
    ]
    bot.answerInlineQuery(update.inline_query.id, results=results)
Beispiel #19
0
def add_other_cards(player, results, game):
    """Add hand cards when choosing colors"""

    results.append(
        InlineQueryResultArticle("hand",
                                 title=_("Card (tap for game state):",
                                         "Cards (tap for game state):",
                                         len(player.cards)),
                                 description=', '.join(
                                     [repr(card) for card in player.cards]),
                                 input_message_content=game_info(game)))
Beispiel #20
0
def inline(update: Update, context: CallbackContext):
    results = [
        InlineQueryResultArticle(
            id="id",
            title=" f",
            input_message_content=InputTextMessageContent(" f"))
    ]
    update.inline_query.answer(  # I have found a bug in python_telegram_bot API. answer method raises and exception when there's no results
        results,
        switch_pm_text="Your json was sent to pm",
        switch_pm_parameter="start")
Beispiel #21
0
def inline_caps(update, context):
    query = update.inline_query.query
    if not query:
        return
    results = list()
    results.append(
        InlineQueryResultArticle(id=query.upper(),
                                 title='Caps',
                                 input_message_content=InputTextMessageContent(
                                     query.upper())))
    context.bot.answer_inline_query(update.inline_query.id, results)
def inline_query_result_article():
    return InlineQueryResultArticle(TestInlineQueryResultArticle.id,
                                    TestInlineQueryResultArticle.title,
                                    input_message_content=TestInlineQueryResultArticle.input_message_content,
                                    reply_markup=TestInlineQueryResultArticle.reply_markup,
                                    url=TestInlineQueryResultArticle.url,
                                    hide_url=TestInlineQueryResultArticle.hide_url,
                                    description=TestInlineQueryResultArticle.description,
                                    thumb_url=TestInlineQueryResultArticle.thumb_url,
                                    thumb_height=TestInlineQueryResultArticle.thumb_height,
                                    thumb_width=TestInlineQueryResultArticle.thumb_width)
Beispiel #23
0
def search_sticker_sets(session, update, user, query, tags, nsfw, furry,
                        offset, inline_query, inline_query_request):
    """Query sticker sets."""
    # Get all matching stickers
    matching_sticker_sets, duration = get_matching_sticker_sets(
        session, user, query, tags, nsfw, furry, offset)

    # Calculate the next offset. 'done' means there are no more results.
    next_offset = get_next_set_offset(inline_query, matching_sticker_sets,
                                      offset)

    inline_query_request.duration = duration
    inline_query_request.next_offset = next_offset.split(
        ':', 1)[1] if next_offset != 'done' else next_offset

    # Stuff for debugging, since I need that all the time
    if False:
        import pprint
        pprint.pprint('\n\nNext: ')  # noqa
        pprint.pprint(offset)  # noqa
        pprint.pprint(matching_sticker_sets)  # noqa

    # Create a result list of max 50 cached sticker objects
    results = []
    for sticker_set in matching_sticker_sets:
        sticker_set = sticker_set[0]
        url = f'https://telegram.me/addstickers/{sticker_set.name}'
        input_message_content = InputTextMessageContent(url)
        results.append(
            InlineQueryResultArticle(
                f'{inline_query.id}:{sticker_set.name}',
                title=sticker_set.title,
                description=sticker_set.name,
                url=url,
                input_message_content=input_message_content))

        for index in range(0, 5):
            if index < len(sticker_set.stickers):
                file_id = sticker_set.stickers[index].file_id
                results.append(
                    InlineQueryResultCachedSticker(
                        f'{inline_query.id}:{file_id}',
                        sticker_file_id=file_id))

    call_tg_func(update.inline_query,
                 'answer',
                 args=[results],
                 kwargs={
                     'next_offset': next_offset,
                     'cache_time': 1,
                     'is_personal': True,
                     'switch_pm_text': 'Maybe tag some stickers :)?',
                     'switch_pm_parameter': 'inline',
                 })
def main(req: func.HttpRequest) -> func.HttpResponse:
    logger = logging.getLogger('Reddit')
    logger.setLevel(logging.INFO)
    sh = logging.StreamHandler()
    sh.setLevel(logging.INFO)
    logger.addHandler(sh)

    req_body = req.get_body()
    logger.info(req_body)
    bot = telegram.Bot('botid:sec-ret')

    update = telegram.Update.de_json(json.loads(req_body), bot)

    if update.inline_query is not None:
        query = update.inline_query.query
        results = [
            InlineQueryResultArticle(
                id=uuid4(),
                title="Days",
                input_message_content=InputTextMessageContent(
                    "{} days".format(query))),
            InlineQueryResultArticle(
                id=uuid4(),
                title="Minutes",
                input_message_content=InputTextMessageContent(
                    "{} minutes".format(query)))
        ]

        update.inline_query.answer(results, cache_time=0, is_personal=True)
        return func.HttpResponse(f"Hello!")

    chat_id = update.message.chat.id
    text = update.message.text

    if text == '/start':
        text = """Hello, human! I am an reddit embedder bot. Just provide me reddit url and I'll try to get media content and embed it to the telegram message!"""
    else:
        text = process_message(update.message.text)

    bot.sendMessage(chat_id=chat_id, text=text)
    return func.HttpResponse(f"Hello!")
Beispiel #25
0
def inline_place(bot, update):
    query = update.inline_query.query
    help = 'Scrivi il nome di una città per cercare solo gli eventi in quella città.\nPuoi anche cercare in una intera regione!\nOppure puoi cercare nei dintorni di una città scrivendo "dintorni" dopo il nome della città'
    if not query or len(query) == 0:
        return
    else:
        if query == 'help':
            results = [
                InlineQueryResultArticle(
                    id=uuid4(),
                    title=help,
                    input_message_content=InputTextMessageContent(
                        "Un attimo, sto usando @cercaEventi_bot"))
            ]
            update.inline_query.answer(results)
            return
        p = Parser(query)
        events = p.getEvents()
        if len(events) > 0:
            results = [
                InlineQueryResultArticle(
                    id=uuid4(),
                    title=event['name'],
                    input_message_content=InputTextMessageContent(
                        "{}\n<b>{}</b>\n<b>{}</b>\n{}".format(
                            event['name'], event['date'], event['place'],
                            event['link']),
                        parse_mode='HTML'),
                    thumb_url=event['img'],
                    description="{}\n{}".format(event['date'], event['place']))
                for event in events
            ]
        else:
            results = [
                InlineQueryResultArticle(
                    id=uuid4(),
                    title='Nessun evento trovato per {}'.format(query),
                    input_message_content=InputTextMessageContent(
                        'Nessun evento trovato per {}'.format(query)))
            ]
        update.inline_query.answer(results)
Beispiel #26
0
def show_subscription(subscription, current_page):
    subscription_count = len(subscription)
    results_per_page = constants.MAX_INLINE_QUERY_RESULTS
    no_more_subscription = subscription_count <= results_per_page * (
        current_page - 1)

    if no_more_subscription:
        results = [
            InlineQueryResultArticle(
                id="-1",
                title="没有更多的订阅了 :(",
                description="前往搜索播客",
                input_message_content=InputTextMessageContent("/search"))
        ]
    else:
        print(subscription.values())
        results = [
            InlineQueryResultArticle(
                id=index,
                title=feed.podcast.name,
                input_message_content=InputTextMessageContent(
                    (f"[📻️]({feed.podcast.logo_url})  *{feed.podcast.name}*\n"
                     f"{feed.podcast.host}\n\n"
                     f"{feed.podcast.email}")),
                reply_markup=InlineKeyboardMarkup.from_column([
                    InlineKeyboardButton(
                        "查 看 单 集",
                        switch_inline_query_current_chat=
                        f"episodes {feed.podcast.name} page 1"),
                    InlineKeyboardButton("关      于", url=feed.podcast.website)
                ]),
                description=feed.podcast.host,
                thumb_url=feed.podcast.logo_url,
                thumb_width=30,
                thumb_height=30) for index, feed in enumerate(
                    list(subscription.values())[results_per_page *
                                                (current_page -
                                                 1):results_per_page *
                                                current_page])
        ]
    return results
Beispiel #27
0
def inlinequeries(update, context):
    """Handle the inline query."""
    query = update.inline_query.query
    results = [
        InlineQueryResultArticle(id=uuid4(),
                                 title="current_weather",
                                 input_message_content=InputTextMessageContent(
                                     get_current_weather_inline(query))),
        InlineQueryResultArticle(id=uuid4(),
                                 title="Bold",
                                 input_message_content=InputTextMessageContent(
                                     "*{}*".format(escape_markdown(query)),
                                     parse_mode=ParseMode.MARKDOWN)),
        InlineQueryResultArticle(id=uuid4(),
                                 title="Italic",
                                 input_message_content=InputTextMessageContent(
                                     "_{}_".format(escape_markdown(query)),
                                     parse_mode=ParseMode.MARKDOWN))
    ]

    update.inline_query.answer(results)
Beispiel #28
0
    def inlinequery(self, bot, update):
        query = update.inline_query.query
        results = list()
        chat_id = update.inline_query.from_user.id

        resp = self.get_resp_for_idle_text(query, chat_id=chat_id)
        results.append(
            InlineQueryResultArticle(
                id=uuid4(),
                title=resp,
                input_message_content=InputTextMessageContent(resp)))
        update.inline_query.answer(results)
Beispiel #29
0
def inline_get_info(bot, update):
    query = update.inline_query.query
    if not query:
        return
    results = list()
    results.append(
        InlineQueryResultArticle(id=query.upper(),
                                 title='Check phone',
                                 input_message_content=InputTextMessageContent(
                                     get_phone_info(query),
                                     parse_mode="Markdown")))
    bot.answer_inline_query(update.inline_query.id, results)
Beispiel #30
0
 def inline_help(r):
     text = '\n'.join(help_text)
     desc = 'Don\'t know how this works? Click here!'
     r.append(
         InlineQueryResultArticle(
             id=uuid4(),
             title='Help and Usage',
             description=desc,
             input_message_content=InputTextMessageContent(
                 text,
                 parse_mode=ParseMode.MARKDOWN,
                 disable_web_page_preview=True)))
Beispiel #31
0
 def inline_error(r):
     text = 'This message should not appear.'
     desc = text
     r.append(
         InlineQueryResultArticle(
             id=uuid4(),
             title='Error',
             description=desc,
             input_message_content=InputTextMessageContent(
                 text,
                 parse_mode=ParseMode.HTML,
             )))