Exemplo n.º 1
0
def inline_rate(bot, update):
    query = update.inline_query.query
    query_list = query.split(" ")

    results = list()

    parser_classes = utils.get_parser_classes()
    parsers = [parser(cache=default_cache) for parser in parser_classes]

    for parser in parsers:
        # Best exchange rate in inline mode
        # TODO: write wrapper function to handle inputs like this one
        if len(query_list) == 2 and "best" in query_list:
            # TODO: this feature is experimental and
            # not-optimized at all, it is SLOW
            # Mutating original list is not a great ideas
            temp_list = query_list[:]
            temp_list.remove("best")
            currency = temp_list[0]
            if currency.upper() not in parser.allowed_currencies:
                continue
            best = utils.get_best_currencies(currency)
            buy_msg = _("Buy {}: <b>{}</b> - {}")
            buy_msg = buy_msg.format(best["buy"][1].iso, best["buy"][0],
                                     best["buy"][1].buy)
            # TODO: add allignment
            sell_msg = _("Sell {}: <b>{}</b> - {}")
            sell_msg = sell_msg.format(best["sell"][1].iso, best["sell"][0],
                                       best["sell"][1].sell)
            msg = "\n".join([buy_msg, sell_msg])

            res = telegram.InputTextMessageContent(
                msg, parse_mode=telegram.ParseMode.HTML)
            result = telegram.InlineQueryResultArticle(
                id=uuid.uuid4(),
                title=_("Best rate"),
                input_message_content=res)

            bot.answerInlineQuery(update.inline_query.id, [result])
            return
        if query.upper() not in parser.allowed_currencies:
            continue
        cur_value = cache_proxy.get_currency(parser, query.upper())
        bank_name = parser.name
        text = "{}\n<b>{}</b>: {}".format(bank_name, query.upper(),
                                          cur_value.sell)
        mes_content = telegram.InputTextMessageContent(
            text, parse_mode=telegram.ParseMode.HTML)

        result = telegram.InlineQueryResultArticle(
            id=uuid.uuid4(),
            title=parser.name,
            input_message_content=mes_content)
        results.append(result)

    bot.answerInlineQuery(update.inline_query.id, results)
Exemplo n.º 2
0
 def handle_inline(self, bot, context: Context):
     query = context.query
     if context.update.inline_query.offset != "":
         offset = int(context.update.inline_query.offset)
     else:
         offset = 0
     try:
         res: octobot.Catalog = self.function(query, offset, 50, bot,
                                              context)
     except CatalogCantGoDeeper:
         return
     if res is None:
         return
     inline_res = []
     for item in res:
         if item.photo is not None:
             if item.parse_mode is None or item.parse_mode.lower(
             ) != "html":
                 item.parse_mode = 'html'
                 item.text = html.escape(item.text)
             text = add_photo_to_text(item.text, item.photo)
             res_kwargs = dict(id=item.item_id,
                               photo_url=item.photo[0].url,
                               photo_width=item.photo[0].width,
                               photo_height=item.photo[0].height,
                               thumb_url=item.photo[-1].url,
                               title=item.title,
                               description=item.description,
                               reply_markup=item.reply_markup)
             if res.photo_primary:
                 res_kwargs['caption'] = text
                 res_kwargs['parse_mode'] = item.parse_mode
             else:
                 res_kwargs[
                     'input_message_content'] = telegram.InputTextMessageContent(
                         text, parse_mode=item.parse_mode)
             if isinstance(item, octobot.CatalogKeyPhoto):
                 inline_res.append(
                     telegram.InlineQueryResultPhoto(**res_kwargs))
             else:
                 inline_res.append(
                     telegram.InlineQueryResultArticle(**res_kwargs))
         else:
             inline_res.append(
                 telegram.InlineQueryResultArticle(
                     item.item_id,
                     title=item.title,
                     description=item.description,
                     input_message_content=telegram.InputTextMessageContent(
                         item.text, parse_mode=item.parse_mode)))
     context.update.inline_query.answer(
         inline_res,
         cache_time=(360 if Settings.production else 0),
         next_offset=res.next_offset)
Exemplo n.º 3
0
def handle_inline_spoiler(update: tg.Update, context: tg_ext.CallbackContext):
    query = update.inline_query.query

    if (len(query) < 1):
        return

    quotes = [
        "That's not a prediction. That's a Spoiler...",
        "Spoiler, we die in the end...",
        "Is it a Spoiler? I don't know... Im not a car guy.",
        "How do I Spoil?", "Random quote? Nope - just a Spoiler.",
        "Experience is a gread Spoiler of pleasures.",
        "You see, but you do not observe. The Spoiler is clear.",
        "Chewbacca dies, but the real Spoiler is below.",
        "Spoiler ahead, everyone aboard!", "Spoiler warning"
    ]

    results = [
        tg.InlineQueryResultArticle(
            id=uuid.uuid4(),
            title="Send",
            input_message_content=tg.InputTextMessageContent(
                message_text=random.choice(quotes)),
            reply_markup=tg.InlineKeyboardMarkup(inline_keyboard=[[
                tg.InlineKeyboardButton(text='Show me', callback_data=query)
            ]]))
    ]
    update.inline_query.answer(results=results)
    def test_equality(self):
        a = telegram.InlineQueryResultVenue(self._id, self.longitude,
                                            self.latitude, self.title,
                                            self._address)
        b = telegram.InlineQueryResultVenue(self._id, self.longitude,
                                            self.latitude, self.title,
                                            self._address)
        c = telegram.InlineQueryResultVenue(self._id, "", self.latitude,
                                            self.title, self._address)
        d = telegram.InlineQueryResultVenue("", self.longitude, self.latitude,
                                            self.title, self._address)
        e = telegram.InlineQueryResultArticle(self._id, "", "")

        self.assertEqual(a, b)
        self.assertEqual(hash(a), hash(b))
        self.assertIsNot(a, b)

        self.assertEqual(a, c)
        self.assertEqual(hash(a), hash(c))

        self.assertNotEqual(a, d)
        self.assertNotEqual(hash(a), hash(d))

        self.assertNotEqual(a, e)
        self.assertNotEqual(hash(a), hash(e))
Exemplo n.º 5
0
				def makeres(gt):
					gameid = str(uuid.uuid4().hex)[:8]
					butts = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(text = "Join", switch_inline_query_current_chat = "join " + gameid)]])
					return telegram.InlineQueryResultArticle(id= str(gt) + "_" + str(gameid),
						title= "Create new *" + str(gt) + "*",
						reply_markup = butts,
						input_message_content = telegram.InputTextMessageContent(message_text="Play a game of *" + gt + "* with me!",
							parse_mode="Markdown"))
Exemplo n.º 6
0
 def to_result(self):
     return t.InlineQueryResultArticle(
         id=uuid4(),
         title=self.title,
         input_message_content=t.InputTextMessageContent(
             self.text, 'HTML'
         ),
     )
Exemplo n.º 7
0
 def strikethrough():
     text = strike_text(query)
     desc = text
     results.append(
         tg.InlineQueryResultArticle(
             id=uuid4(),
             title='Strikethrough',
             description=desc,
             input_message_content=tg.InputTextMessageContent(
                 text, parse_mode=tg.ParseMode.MARKDOWN)))
Exemplo n.º 8
0
 def add_inline_result(self):
     result = telegram.InlineQueryResultArticle(
         id=uuid4(),
         title=self.inline_title,
         input_message_content=telegram.InputTextMessageContent(
             self.message),
         reply_markup=telegram.InlineKeyboardMarkup(self.keyboard),
         url="",
         description="")
     self.inline_results.append(result)
Exemplo n.º 9
0
 def vaporwave():
     text = ''
     for i in list(query):
         text += chr(0xFEE0 + ord(i))
     desc = text
     results.append(
         tg.InlineQueryResultArticle(
             id=uuid4(),
             # seriously, if this is overused, it should be removed # IGNORE THIS LINE
             title='Vaporwave',
             description=desc,
             input_message_content=tg.InputTextMessageContent(text)))
Exemplo n.º 10
0
 def markdown_prev():
     text = query
     desc = text
     results.append(
         tg.InlineQueryResultArticle(
             id=uuid4(),
             title='Markdown (Preview)',
             description=desc,
             input_message_content=tg.InputTextMessageContent(
                 text,
                 parse_mode=tg.ParseMode.MARKDOWN,
                 disable_web_page_preview=False)))
Exemplo n.º 11
0
def inlineR(update, context):
    query = update.inline_query.query
    results = []
    try:
        images = subredditImg(query, count=40)
    except Exception:
        results.append(
            tg.InlineQueryResultArticle(0, "No",
                                        tg.InputTextMessageContent("No!")))
    else:
        if len(images) == 0:
            results.append(tg.InlineQueryResultArticle(
                0,
                "No",
                "No!",
            ))
        else:
            for img in images:
                results.append(tg.InlineQueryResultPhoto(img, img, img))
    finally:
        update.inline_query.answer(results)
Exemplo n.º 12
0
 def subs():
     subs_used = sub_all.findall(query)  # list of subs used in query
     text = query
     desc = ', '.join(subs_used)
     for sub in subs_used:
         text = subs_re[sub].sub(subs_dict[sub], text, count=1)
     if subs_used:
         results.append(
             tg.InlineQueryResultArticle(
                 id=uuid4(),
                 title='xxSubs',
                 # desc is all instances that were substituted
                 description=desc,
                 input_message_content=tg.InputTextMessageContent(text)))
     else:
         results.append(
             tg.InlineQueryResultArticle(
                 id=uuid4(),
                 title='/subs',
                 # desc is all instances that were substituted
                 description='Gives a list of substitutions.',
                 input_message_content=tg.InputTextMessageContent('/subs')))
Exemplo n.º 13
0
    def vortaro():
        nonlocal query
        nonlocal results
        if query:
            if query.startswith('v: '):
                query = query[3:]
                matches = search_espdic(query)

            if 'matches' in locals():
                exact, fuzzy = matches
                matches = exact + fuzzy
                matches = matches[:tg.constants.MAX_INLINE_QUERY_RESULTS]

                # reset results to only show dictionary entries
                results = list()

                for match in matches:
                    results.append(
                        tg.InlineQueryResultArticle(
                            id=uuid4(),
                            title=match['eo'],
                            description=match['en'],
                            input_message_content=tg.InputTextMessageContent(
                                '*{}*: _{}_'.format(match['eo'], match['en']),
                                parse_mode=tg.ParseMode.MARKDOWN)))
        if not 'matches' in locals() or not matches:
            usage = [
                'Por serĉi la Esperanto-angla vortaro: `v: <vorto>`',
                'To search the Esperanto-English dictionary: `v: <vorto>`',
                'Iksa sistemo uzeblas. / X-system is usable.',
            ]
            results.append(
                tg.InlineQueryResultArticle(
                    id=uuid4(),
                    title='Vortaro / Dictionary',
                    description='v: <vorto | word>',
                    input_message_content=tg.InputTextMessageContent(
                        '\n'.join(usage), parse_mode=tg.ParseMode.MARKDOWN)))
Exemplo n.º 14
0
    def test_equality(self):
        a = telegram.InlineQueryResultArticle(self._id, self.title,
                                              self.input_message_content)
        b = telegram.InlineQueryResultArticle(self._id, self.title,
                                              self.input_message_content)
        c = telegram.InlineQueryResultArticle(self._id, "",
                                              self.input_message_content)
        d = telegram.InlineQueryResultArticle("", self.title,
                                              self.input_message_content)
        e = telegram.InlineQueryResultAudio(self._id, "", "")

        self.assertEqual(a, b)
        self.assertEqual(hash(a), hash(b))
        self.assertIsNot(a, b)

        self.assertEqual(a, c)
        self.assertEqual(hash(a), hash(c))

        self.assertNotEqual(a, d)
        self.assertNotEqual(hash(a), hash(d))

        self.assertNotEqual(a, e)
        self.assertNotEqual(hash(a), hash(e))
Exemplo n.º 15
0
 def generate_inline_answer(self, text):
     "Generates inline 'buttons' via so-called article buttons."
     ret = []
     # generated text - everything for the two variants
     msgs = (self.convert(text), self.convert_no_spaces(text))
     for t, d, m, i in zip(self.titles, self.descs, msgs, self.imgs):
         # first we indicate we use markdown in message that will be sent
         r = telegram.InputTextMessageContent(m, parse_mode="Markdown")
         # then we generate result with that message and strings set above
         result = telegram.InlineQueryResultArticle(id=t,
                                                    title=t,
                                                    description=d,
                                                    input_message_content=r,
                                                    thumb_url=i)
         ret.append(result)
     return ret
Exemplo n.º 16
0
def get_inline_query_definition_result(
    definition: complete_definition.CompleteDefinition
) -> telegram.InlineQueryResultArticle:
    reply_markup = telegram.InlineKeyboardMarkup(
        definition.inline_keyboard_buttons)

    return telegram.InlineQueryResultArticle(
        id=str(uuid.uuid4()),
        title=definition.title,
        thumb_url=constants.DEX_THUMBNAIL_URL,
        url=definition.url,
        hide_url=True,
        reply_markup=reply_markup,
        input_message_content=telegram.InputTextMessageContent(
            message_text=definition.html,
            parse_mode=telegram.ParseMode.HTML,
            disable_web_page_preview=True))
Exemplo n.º 17
0
def handle_inline_query(update: tg.Update, context: tg_ext.CallbackContext):
    from bot.inline import CallbackCommands
    query = update.inline_query.query
    results = [
        tg.InlineQueryResultArticle(
            id=uuid.uuid4(),
            title="Send",
            input_message_content=tg.InputTextMessageContent(
                message_text='Spoiler'),
            reply_markup=tg.InlineKeyboardMarkup(inline_keyboard=[[
                tg.InlineKeyboardButton(
                    text='Show',
                    callback_data=json.dumps(
                        [CallbackCommands.DISPLAY_SPOILER, query]))
            ]]))
    ]
    update.inline_query.answer(results=results)
Exemplo n.º 18
0
def inline_query_handler(bot, update):
    query = update.inline_query.query
    inline_query_id = update.inline_query.id

    if len(query) < 3:
        bot.answerInlineQuery(inline_query_id, [])
        return

    query_result = table.scan(
        FilterExpression=Attr('first_name').contains(query.upper())
        | Attr('last_name').contains(query.upper()))['Items']
    query_articles = list(
        map(
            lambda x: telegram.InlineQueryResultArticle(
                x['username'], '%s %s' %
                (x['first_name'] or '', x['last_name'] or ''),
                telegram.InputTextMessageContent('%s %s' % (x['first_name'], x[
                    'last_name']))), query_result))
    bot.answerInlineQuery(inline_query_id, query_articles)
    def test_equality(self):
        a = telegram.InlineQueryResultAudio(self._id, self.audio_url,
                                            self.title)
        b = telegram.InlineQueryResultAudio(self._id, self.title, self.title)
        c = telegram.InlineQueryResultAudio(self._id, "", self.title)
        d = telegram.InlineQueryResultAudio("", self.audio_url, self.title)
        e = telegram.InlineQueryResultArticle(self._id, "", "")

        self.assertEqual(a, b)
        self.assertEqual(hash(a), hash(b))
        self.assertIsNot(a, b)

        self.assertEqual(a, c)
        self.assertEqual(hash(a), hash(c))

        self.assertNotEqual(a, d)
        self.assertNotEqual(hash(a), hash(d))

        self.assertNotEqual(a, e)
        self.assertNotEqual(hash(a), hash(e))
Exemplo n.º 20
0
def inlineQuery(update):
    projectId = update.inline_query.query
    print(projectId)
    response = requests.get("https://chamranteam.ir/api/project_name/{}".format(projectId))
    if response.status_code == 200:
        projectInfo = response.json()
        if projectInfo['creator_photo'] is not "None":
            projectInfo['creator_photo'] = "https://chamranteam.ir" + projectInfo['creator_photo']
        query = update.inline_query.query
        results = [
            telegram.InlineQueryResultArticle(
                id=uuid4(),
                title=projectInfo['creator'],
                description=projectInfo['project_name'],
                thumb_url=projectInfo['creator_photo'],
                input_message_content=telegram.InputTextMessageContent(
                    projectInfo['project_name'])),]
        update.inline_query.answer(results, cache_time=15)
    else:
        print(response.json())
    return
Exemplo n.º 21
0
    def test_equality(self):
        a = telegram.InlineQueryResultGif(self._id, self.gif_url,
                                          self.thumb_url)
        b = telegram.InlineQueryResultGif(self._id, self.gif_url,
                                          self.thumb_url)
        c = telegram.InlineQueryResultGif(self._id, "", self.thumb_url)
        d = telegram.InlineQueryResultGif("", self.gif_url, self.thumb_url)
        e = telegram.InlineQueryResultArticle(self._id, "", "")

        self.assertEqual(a, b)
        self.assertEqual(hash(a), hash(b))
        self.assertIsNot(a, b)

        self.assertEqual(a, c)
        self.assertEqual(hash(a), hash(c))

        self.assertNotEqual(a, d)
        self.assertNotEqual(hash(a), hash(d))

        self.assertNotEqual(a, e)
        self.assertNotEqual(hash(a), hash(e))
    def test_equality(self):
        a = telegram.InlineQueryResultContact(self._id, self.phone_number,
                                              self.first_name)
        b = telegram.InlineQueryResultContact(self._id, self.phone_number,
                                              self.first_name)
        c = telegram.InlineQueryResultContact(self._id, "", self.first_name)
        d = telegram.InlineQueryResultContact("", self.phone_number,
                                              self.first_name)
        e = telegram.InlineQueryResultArticle(self._id, "", "")

        self.assertEqual(a, b)
        self.assertEqual(hash(a), hash(b))
        self.assertIsNot(a, b)

        self.assertEqual(a, c)
        self.assertEqual(hash(a), hash(c))

        self.assertNotEqual(a, d)
        self.assertNotEqual(hash(a), hash(d))

        self.assertNotEqual(a, e)
        self.assertNotEqual(hash(a), hash(e))
Exemplo n.º 23
0
def conv_search(in_state, query_text, bot, update, send_message=True):
    """ For conversations: Search message handler.
    """
    if query_text == None:
        query_text = update.message.text
    logger.info("User %s: %s", update.effective_user.username, query_text)
    message_back, definition = query_jisho(query_text)
    if in_state == RECORDING:
        recording = chat_recordings.get(update.effective_user.username)
        if recording == None:
            update.message.reply_text(
                "Warning: your recording got reset, probably because idle time was too long."
            )
            recording = []
            chat_recordings[update.effective_user.username] = recording
        if definition != None:
            recording.append(definition)
        message_back += '\nRecorded ' + str(len(recording)) + ' items.'

    # TODO(philhu): Use our own models.
    answer = None
    if definition != None:
        answer = telegram.InlineQueryResultArticle(
            input_message_content=telegram.InputTextMessageContent(
                message_text=message_back,
                parse_mode=telegram.ParseMode.MARKDOWN,
                disable_web_page_preview=True),
            id=uuid4(),
            title=render_word(definition) + ' (' + render_reading(definition) +
            ')')

    if send_message:
        bot.send_message(chat_id=update.message.chat_id,
                         text=message_back,
                         parse_mode=telegram.ParseMode.MARKDOWN,
                         disable_web_page_preview=True)
    return answer
Exemplo n.º 24
0
def chInQuery(bot, update):
    print("--> Inline query received\n")
    query = update.inline_query.query
    fEx = 0
    results = list()

    if ("/" in query):
        results.append(
            tg.InlineQueryResultArticle(
                id=uuid4(),
                title="help",
                input_message_content=tg.InputTextMessageContent("/help"),
                description="Prints out help message"))

        results.append(
            tg.InlineQueryResultArticle(
                id=uuid4(),
                title="start",
                input_message_content=tg.InputTextMessageContent("/start"),
                description="Start the security monitoring"))

        results.append(
            tg.InlineQueryResultArticle(
                id=uuid4(),
                title="stop",
                input_message_content=tg.InputTextMessageContent("/stop"),
                description="Stop the security monitoring"))

        results.append(
            tg.InlineQueryResultArticle(
                id=uuid4(),
                title="log",
                input_message_content=tg.InputTextMessageContent("/log"),
                description="Print out last 10 events"))

        results.append(
            tg.InlineQueryResultArticle(
                id=uuid4(),
                title="list",
                input_message_content=tg.InputTextMessageContent("/list"),
                description="List triggered sensors within 5 mins"))

        results.append(
            tg.InlineQueryResultArticle(
                id=uuid4(),
                title="test",
                input_message_content=tg.InputTextMessageContent("/test"),
                description="Dummy command for comm debug"))

        if (query in cmdString):
            fEx = 1
    else:
        results.append(
            tg.InlineQueryResultArticle(
                id=uuid4(),
                title="ERROR!",
                input_message_content=tg.InputTextMessageContent(query),
                description="Command unknown"))
        fEx = 0

    if (fEx == 1):
        globals()['b' + query.replace('/', '')](bot, update)
    else:
        pass

    bot.answerInlineQuery(update.inline_query.id, results=results)
Exemplo n.º 25
0
    def handle_inline_query(self, update):
        m = self.parse_cmd_comment(update.inline_query.query)
        if m:
            reviewed_user_id, comment = m
            userinfo = Userinfo(reviewed_user_id)

            update.inline_query.answer(results=[
                telegram.InlineQueryResultArticle(
                    id='comment',
                    title='向{}留言'.format(userinfo.full_name),
                    description='{},留言內容為「{}」'.format(
                        userinfo.format_full_raw(), comment),
                    input_message_content=telegram.InputTextMessageContent(
                        message_text=update.inline_query.query, ))
            ])
            return

        reviewed_user_id = self.parse_cmd_reanswer(update.inline_query.query)
        if reviewed_user_id:
            userinfo = Userinfo(reviewed_user_id)

            update.inline_query.answer(results=[
                telegram.InlineQueryResultArticle(
                    id='reanswer',
                    title='要求{}重新作答'.format(userinfo.full_name),
                    description='{}'.format(userinfo.format_full_raw()),
                    input_message_content=telegram.InputTextMessageContent(
                        message_text=update.inline_query.query, ))
            ])
            return

        reviewed_user_id = self.parse_cmd_approve(update.inline_query.query)
        if reviewed_user_id:
            userinfo = Userinfo(reviewed_user_id)

            update.inline_query.answer(results=[
                telegram.InlineQueryResultArticle(
                    id='approve',
                    title='批准{}的申請'.format(userinfo.full_name),
                    description='{}'.format(userinfo.format_full_raw()),
                    input_message_content=telegram.InputTextMessageContent(
                        message_text=update.inline_query.query, ))
            ])
            return

        reviewed_user_id = self.parse_cmd_reject(update.inline_query.query)
        if reviewed_user_id:
            userinfo = Userinfo(reviewed_user_id)

            update.inline_query.answer(results=[
                telegram.InlineQueryResultArticle(
                    id='reject',
                    title='拒絕{}的申請'.format(userinfo.full_name),
                    description='{}'.format(userinfo.format_full_raw()),
                    input_message_content=telegram.InputTextMessageContent(
                        message_text=update.inline_query.query, ))
            ])
            return

        if update.inline_query.query:
            update.inline_query.answer(results=[
                telegram.InlineQueryResultArticle(
                    id='unknown',
                    title=update.inline_query.query,
                    input_message_content=telegram.InputTextMessageContent(
                        message_text=update.inline_query.query, ))
            ])
            return
Exemplo n.º 26
0
    def reply(self,
              text,
              photo_url=None,
              reply_to_previous=False,
              reply_markup=None,
              parse_mode=None,
              no_preview=False,
              title=None,
              to_pm=False,
              failed=False,
              editable=True,
              inline_description=None,
              photo_primary=False):
        """
        Replies to a message/shows a popup in inline keyboard/sends out inline query result

        :param text: Text to send
        :type text: :class:`str`
        :param photo_url: Photo URLs, with best quality descending to worst
        :type photo_url: :class:`list`, optional
        :param reply_to_previous: If bot should reply to reply of trigger message, defaults to False. *We need to go deeper*
        :type reply_to_previous: :class:`bool`, optional
        :param reply_markup: Telegram reply markup
        :type reply_markup: :class:`telegram.ReplyMarkup`, optional
        :param parse_mode: Parse mode of messages. Become 'html' if photo_url is passed. Available values are `markdown`, `html` and None
        :type parse_mode: :class:`str`, optional
        :param no_preview: Should the webpage preview be disabled. Defaults to `False`, becomes `False` if `photo_url` is passed
        :type no_preview: :class:`bool`, optional
        :param title: Title of message for inline mode, defaults to first line of `text`
        :type title: :class:`str`, optional
        :param to_pm: If message should be sent into user PM
        :type to_pm: :class:`bool`
        :param failed: Pass :obj:`True` if command failed to execute. defaults to :obj:`False`
        :type failed: :class:`bool`, optional
        :param editable: Pass :obj:`False` if you want your command NOT to be editable, defaults to :obj:`True`
        :type editable: :class:`bool`, optional
        :param inline_description: Description for inline mode, optional, defaults to first 400 symbols of `text`
        :type inline_description: :class:`str`
        """
        reply_markup, kbd_id = rebuild_inline_markup(reply_markup, self)
        if photo_url and not photo_primary:
            if parse_mode is None or parse_mode.lower() != "html":
                parse_mode = "html"
                text = html.escape(text)
            text = add_photo_to_text(text, photo_url)
        if title is None:
            title = self.text[:20]
        if self.update_type == UpdateType.message or to_pm:
            if reply_to_previous and (self.update.message.reply_to_message
                                      is not None):
                target_msg: telegram.Message = self.update.message.reply_to_message
            else:
                target_msg: telegram.Message = self.update.message
            kwargs = dict(chat_id=target_msg.chat_id,
                          parse_mode=parse_mode,
                          reply_markup=reply_markup,
                          disable_web_page_preview=no_preview,
                          reply_to_message_id=target_msg.message_id)
            if to_pm:
                kwargs["chat_id"] = self.user.id
                del kwargs["reply_to_message_id"]
            if photo_url and photo_primary:
                try:
                    message = self.bot.send_photo(caption=text,
                                                  photo=photo_url[0],
                                                  **kwargs)
                except telegram.error.TelegramError:
                    if parse_mode.lower() != 'html':
                        text = html.escape(text)
                    text = f'<b><a href="{photo_url[0]}">Link to image</a></b>\n\n' + text
                    message = self.bot.send_photo(caption=text,
                                                  photo=Settings.no_image,
                                                  **kwargs)
            else:
                message = self.bot.send_message(text=text, **kwargs)

            if octobot.Database.redis is not None and editable:
                octobot.Database.redis.set(
                    octobot.utils.generate_edit_id(self.update.message),
                    message.message_id)
                octobot.Database.redis.expire(
                    octobot.utils.generate_edit_id(self.update.message), 30)
            self.edit_tgt = message.message_id
            return message
        elif self.update_type == UpdateType.edited_message and octobot.Database.redis is not None:
            return self.edit(text=text,
                             photo_url=photo_url,
                             reply_markup=reply_markup,
                             parse_mode=parse_mode)
        elif self.update_type == UpdateType.inline_query:
            inline_content = telegram.InputTextMessageContent(
                text,
                parse_mode=parse_mode,
                disable_web_page_preview=no_preview)
            result = telegram.InlineQueryResultArticle(
                self.update.inline_query.query,
                title=title,
                description=cleanhtml(text)[:500]
                if inline_description is None else inline_description,
                input_message_content=inline_content,
                reply_markup=reply_markup,
                thumb_url=photo_url)
            self.update.inline_query.answer(
                [result], cache_time=(360 if Settings.production else 0))
        elif self.update_type == UpdateType.button_press:
            self.update.callback_query.answer(text)
Exemplo n.º 27
0
def parseInlineQuery(bot, update):
    q = update.inline_query.query

    # actual inline query results to present to the user
    results = []

    if q.lower() == 'gen':
        # if it's simply 'gen', we fill our results with a generated SIGARETTO
        restext = gen.generate()
        results.append(
            telegram.InlineQueryResultArticle(
                type='article',
                id=uuid.uuid4(),
                thumb_url=utils.thumbnail(),
                thumb_width=AVATAR_SIZE,
                thumb_height=AVATAR_SIZE,
                title='SIGARETTO #GENERATED',
                description=restext[:200],
                input_message_content=telegram.InputTextMessageContent(
                    message_text=restext, parse_mode=None)))

    else:
        # we have to search
        # search results:
        res = []

        # try to detect if user asked for a SIGA id or a regex search (starting with "-r ")
        asked_siga = parseSigaNumber(q)
        if asked_siga:
            # yes, pick it
            res = [getS(sl, asked_siga)]
        elif q.startswith('-r '):
            # no, but a regex search is invoked
            q = q[3:]
            res = regexSearch(q, sl)
        else:
            # neither special case is required, normal search
            res = normalSearch(q, sl)

        # search completed, we now have all matching results in res, which may or may not be empty
        if not res:
            # empty, send bogus SIGA
            restext = random.choice(notfound.notfound)
            if "%s" in restext:
                restext = restext % q
            results.append(
                telegram.InlineQueryResultArticle(
                    type='article',
                    id=uuid.uuid4(),
                    thumb_url=utils.thumbnail(),
                    thumb_width=AVATAR_SIZE,
                    thumb_height=AVATAR_SIZE,
                    title='SIGARETTO #NOT_FOUND',
                    description=restext[:200],
                    input_message_content=telegram.InputTextMessageContent(
                        message_text=restext, parse_mode=None)))

        else:
            # non-empty, build list of actual results
            for i in res:
                restext = i['text']
                sid = i['id']
                authorid = i['authorid']

                # if sid in img_cache:
                #     results.append(telegram.InlineQueryResultPhoto(
                #         type='photo',
                #         id=sid,
                #         photo_url=img_url(sid),
                #         thumb_url=utils.thumbnail(authorid),
                #         title='SIGARETTO #%d' % sid,
                #         description=restext[:200],
                #         caption=restext[:200],
                #         photo_file_id=img_cache[sid],
                #     ))
                # elif sid in audio_cache:
                #     results.append(telegram.InlineQueryResultAudio(
                #         type='audio',
                #         id=sid,
                #         audio_url=audio_url(sid),
                #         title='SIGARETTO #%d' % sid,
                #         caption=restext[:200]
                #         # to be completed with other parameters
                #     ))

                fulltext = restext
                if sid in videos:
                    fulltext = restext + "\n\n" + videos[sid]
                results.append(
                    telegram.InlineQueryResultArticle(
                        type='article',
                        id=sid,
                        thumb_url=utils.thumbnail(authorid),
                        thumb_width=AVATAR_SIZE,
                        thumb_height=AVATAR_SIZE,
                        title='SIGARETTO #%d' % sid,
                        description=restext[:200],
                        input_message_content=telegram.InputTextMessageContent(
                            message_text=fulltext, parse_mode=None)))

    # all cases examined, we now have a results array and can answer the query
    bot.answerInlineQuery(update.inline_query.id, results, cache_time=0)

    logger.info(update)
Exemplo n.º 28
0
def inline_query(bot, update):
    query = update.inline_query.query
    results = []
    user_id = str(update.inline_query.from_user.id)
    first_name = update.inline_query.from_user.first_name

    if not query:
        results.append(
            telegram.InlineQueryResultArticle(
                id="commands",
                title="Commands",
                input_message_content=telegram.InputTextMessageContent((
                    "Type @hkobservatory_bot + one of the following:\n"
                    "topics;\ntellme + topic;\nsubscribe + topic;\nunsubscribe + topic;\nenglish;\n繁體中文;\n简体中文;"
                )),
                description="List of available commands"))
    else:
        if query.lower() in "topics":
            results.append(
                telegram.InlineQueryResultArticle(
                    id="topics",
                    title="Topics",
                    input_message_content=telegram.InputTextMessageContent(
                        get_topics()),
                    description="List of available topics"))
        if query.lower() in "tellme current":
            results.append(
                telegram.InlineQueryResultArticle(
                    id="tellme_current",
                    title="Current Weather",
                    input_message_content=telegram.InputTextMessageContent(
                        get_feed_message(user_id, "current")),
                    description="Current weather from the HK Observatory"))
        if query.lower() in "tellme warning":
            results.append(
                telegram.InlineQueryResultArticle(
                    id="tellme_warning",
                    title="Warning",
                    input_message_content=telegram.InputTextMessageContent(
                        get_feed_message(user_id, "warning")),
                    description="Warnings in force"))
        if query.lower() in "subscribe current":
            results.append(
                telegram.InlineQueryResultArticle(
                    id="sub_current",
                    title="Subscribe Current",
                    input_message_content=telegram.InputTextMessageContent(
                        first_name + " has subscribed to: Current"),
                    description="Subscribe to current to receive updates"))
        if query.lower() in "subscribe warning":
            results.append(
                telegram.InlineQueryResultArticle(
                    id="sub_warning",
                    title="Subscribe Warning",
                    input_message_content=telegram.InputTextMessageContent(
                        first_name + " has subscribed to: Warning"),
                    description="Subscribe to warning to receive updates"))
        if query.lower() in "unsubscribe current":
            results.append(
                telegram.InlineQueryResultArticle(
                    id="unsub_current",
                    title="Unsubscribe Current",
                    input_message_content=telegram.InputTextMessageContent(
                        first_name + " has unsubscribed from: Current"),
                    description=
                    "Unsubscribe from current to stop receiving updates"))
        if query.lower() in "unsubscribe warning":
            results.append(
                telegram.InlineQueryResultArticle(
                    id="unsub_warning",
                    title="Unsubscribe Warning",
                    input_message_content=telegram.InputTextMessageContent(
                        first_name + " has unsubscribed from: Warning"),
                    description=
                    "Unsubscribe from warning to stop receiving updates"))
        if query.lower() in "english":
            results.append(
                telegram.InlineQueryResultArticle(
                    id="lang_english",
                    title="English",
                    input_message_content=telegram.InputTextMessageContent(
                        first_name + "\'s language changed to English"),
                    description="Select English as topic information language")
            )
        if query in "繁體中文":
            results.append(
                telegram.InlineQueryResultArticle(
                    id="lang_traditional",
                    title="繁體中文",
                    input_message_content=telegram.InputTextMessageContent(
                        first_name + "\'s language changed to 繁體中文"),
                    description="Select 繁體中文 as topic information language"))
        if query in "简体中文":
            results.append(
                telegram.InlineQueryResultArticle(
                    id="lang_simplified",
                    title="简体中文",
                    input_message_content=telegram.InputTextMessageContent(
                        first_name + "\'s language changed to 简体中文"),
                    description="Select 简体中文 as topic information language"))
    bot.answerInlineQuery(update.inline_query.id, results, cache_time=0)
Exemplo n.º 29
0
def handle_old(bot):
	global update_id
	# Request updates after the last update_id
	for update in bot.getUpdates(offset=update_id, timeout=10):
		# chat_id is required to reply to any message
		update_id = update.update_id + 1
		#print(update.message)
		print(update)
		if update.message:  # your bot can receive updates without messages
			chat_id = update.message.chat_id
			player_info[chat_id] = update.message.from_user
			# Reply to the message
			if update.message.text.startswith("/start") and len(update.message.text.split()) == 1:
				bot.send_message(chat_id = chat_id,parse_mode="Markdown", text = "Welcome!\n`/create [GAMETYPE]`\t\t-create a game\n`/join [GAMEID]`\t-join a game\n`/leave`\t\t-leave game\n\n*Available game types:*\nresistance\nticktacktoe\nrockpaperscissors")
			elif update.message.text.startswith("/join") or update.message.text.startswith("/start join"):
				if update.message.text.startswith("/start join"):
					ss = ["/join", update.message.text[len("/start join_"):]]
				else:
					ss = update.message.text.split()
				if len(ss) < 2:
					bot.send_message(chat_id = chat_id, text = "Use\n/join [GAMEID]\n to join a game")
				else:
					if chat_id in player_gameids:
						bot.send_message(chat_id = chat_id, text = "You are already in a game!")
						continue
					try:
						gameid = ss[1]
						if gameid not in games:
							bot.send_message(chat_id = chat_id, text = "That game doesn't exist")
						else:
							join_game(chat_id, gameid)
					except ValueError:
						bot.send_message(chat_id = chat_id, text = "Id not valid")
			elif update.message.text.startswith("/create"):
				if chat_id in player_gameids:
					bot.send_message(chat_id = chat_id, text = "You are already in a game!")
					continue
				ss = update.message.text.split()
				if len(ss) < 2:
					gt = my_games.game_types[my_games.DEFAULT_GAME]
				else:
					if ss[1].lower() not in my_games.game_types:
						bot.send_message(chat_id = chat_id, text = "Game type doesn't exist.")
					else:
						gt = my_games.game_types[ss[1].lower()]
				gg = gt(update_view, leave_foo, creator=chat_id, player_info=player_info)
				games[gg.id] = gg
				bot.send_message(chat_id = chat_id, text = "Created game {gameid}".format(gameid = gg.id))
				buttons = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(text = "Share", switch_inline_query = "")]])
				bot.send_message(chat_id = chat_id, text = "/join {gameid}".format(gameid = gg.id), reply_markup=buttons)
				join_game(chat_id, gg.id)
			elif update.message.text.startswith("/leave"):
				if chat_id not in player_gameids:
					bot.send_message(chat_id = chat_id, text = "You are not in a game!")
				else:
					gid = player_gameids[chat_id]
					games[gid].cancel()
					del games[gid]
				pass
		elif update.callback_query:
			#from_id = update.callback_query.from_user.id
			from_id = update.callback_query.message.chat.id
			data = update.callback_query.data
			notif = None
			if from_id in player_gameids:
				notif = games[player_gameids[from_id]].handle_action(from_id, data)
			bot.answer_callback_query(callback_query_id=update.callback_query.id, text = notif)
		elif update.inline_query:
			q = update.inline_query.query
			qid = update.inline_query.id
			fid = update.inline_query.from_user.id
			
			if q.startswith("join"):
				qs = "_".join(q.split())
				bot.answer_inline_query(inline_query_id = qid, results=[], switch_pm_text="Join game", switch_pm_parameter=qs, cache_time = 0, is_personal = True)
			elif fid not in player_info:
				bot.answer_inline_query(inline_query_id = qid, results=[], switch_pm_text="Start bot", switch_pm_parameter="start", cache_time = 0, is_personal = True)
			elif fid in player_gameids:
				gameid = player_gameids[fid]
				gt = games[gameid].type
				butts = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(text = "Join", switch_inline_query_current_chat = "join " + gameid)]])
				results = [telegram.InlineQueryResultArticle(id=hex(getrandbits(64))[2:],
					title= "*" + str(gt) + "* " + str(gameid),
					reply_markup=butts,
					input_message_content = telegram.InputTextMessageContent(message_text="Play a game of *" + gt + "* with me!",
						parse_mode="Markdown"))]
				bot.answer_inline_query(inline_query_id = qid, results=results, cache_time = 0, is_personal = True)
			else:
				def makeres(gt):
					gameid = str(uuid.uuid4().hex)[:8]
					butts = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(text = "Join", switch_inline_query_current_chat = "join " + gameid)]])
					return telegram.InlineQueryResultArticle(id= str(gt) + "_" + str(gameid),
						title= "Create new *" + str(gt) + "*",
						reply_markup = butts,
						input_message_content = telegram.InputTextMessageContent(message_text="Play a game of *" + gt + "* with me!",
							parse_mode="Markdown"))
				results = [makeres(gt) for gt in my_games.game_types.keys()]
				bot.answer_inline_query(inline_query_id = qid, results=results, cache_time = 0, is_personal = True)
		elif update.chosen_inline_result:
			rid = update.chosen_inline_result.result_id
			if "_" not in rid:
				continue
			chat_id = update.chosen_inline_result.from_user.id
			gt, gameid = rid.split("_")
			
			gg = my_games.game_types[gt](update_view, leave_foo, creator=chat_id, player_info=player_info)
			gg.id = gameid
			games[gg.id] = gg
			bot.send_message(chat_id = chat_id, text = "Created game {gameid}".format(gameid = gg.id))
			buttons = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton(text = "Share", switch_inline_query = "")]])
			bot.send_message(chat_id = chat_id, text = "/join {gameid}".format(gameid = gg.id), reply_markup=buttons)
			join_game(chat_id, gg.id)