Python telepot.glance() Examples

The following are 30 code examples of telepot.glance(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module telepot , or try the search function .
Example #1
Source File: skeleton_route.py    From telepot with MIT License 6 votes vote down vote up
def on_callback_query(msg):
    query_id, from_id, data = telepot.glance(msg, flavor='callback_query')
    print('Callback query:', query_id, from_id, data)

    if data == 'notification':
        bot.answerCallbackQuery(query_id, text='Notification at top of screen')
    elif data == 'alert':
        bot.answerCallbackQuery(query_id, text='Alert!', show_alert=True)
    elif data == 'edit':
        global message_with_inline_keyboard

        if message_with_inline_keyboard:
            msg_idf = telepot.message_identifier(message_with_inline_keyboard)
            bot.editMessageText(msg_idf, 'NEW MESSAGE HERE!!!!!')
        else:
            bot.answerCallbackQuery(query_id, text='No previous message to edit') 
Example #2
Source File: bot.py    From spntaBot with GNU General Public License v3.0 6 votes vote down vote up
def on_callback_query(message):
    try:
        if not 'game_short_name' in message:
            query_id, from_id, data = telepot.glance(message, flavor='callback_query')
            for plugin in plugins:
                if 'callback' in plugin:
                    for pattern in plugin['callback_patterns']:
                        if re.search(pattern, data, re.IGNORECASE | re.MULTILINE):
                            matches = re.findall(pattern, data, re.IGNORECASE)
                            return_value = yield from plugin['callback'](message, matches[0],
                                                                     message['message']['chat']['id'])
                            if return_value:
                                yield from sender(return_value)
                            break
    except Exception as e:
        print(e) 
Example #3
Source File: quiza.py    From telepot with MIT License 6 votes vote down vote up
def on_chat_message(self, msg):
        content_type, chat_type, chat_id = glance(msg)
        await self.sender.sendMessage(
            'Press START to do some math ...',
            reply_markup=InlineKeyboardMarkup(
                inline_keyboard=[[
                    InlineKeyboardButton(text='START', callback_data='start'),
                ]]
            )
        )
        self.close()  # let Quizzer take over 
Example #4
Source File: payment.py    From telepot with MIT License 6 votes vote down vote up
def send_invoice(seed_tuple):
    msg = seed_tuple[1]

    content_type, chat_type, chat_id = telepot.glance(msg)

    if content_type == 'text':
        sent = bot.sendInvoice(
                   chat_id, "Nick's Hand Cream", "Keep a man's hand like a woman's",
                   payload='a-string-identifying-related-payment-messages-tuvwxyz',
                   provider_token=PAYMENT_PROVIDER_TOKEN,
                   start_parameter='abc',
                   currency='HKD', prices=[
                       LabeledPrice(label='One Case', amount=987),
                       LabeledPrice(label='Package', amount=12)],
                   need_shipping_address=True, is_flexible=True)  # required for shipping query

        print('Invoice sent:')
        pprint(sent) 
Example #5
Source File: instagram.py    From Siarobo with MIT License 6 votes vote down vote up
def inline(message, matches, chat_id, step):
    query_id, from_id, query = telepot.glance(message, flavor='inline_query')
    response = requests.get(query)
    soup = BeautifulSoup(response.text, "html.parser")
    image = soup.find("meta", {"property": "og:image"})
    video = soup.find("meta", {"property": "og:video"})
    if video:
        width = soup.find("meta", {"property": "og:video:width"})
        height = soup.find("meta", {"property": "og:video:height"})
        return [InlineQueryResultVideo(
            id=str(uuid.uuid4()), description='Instagram Video', title="Instagram Video", mime_type="video/mp4",
            thumb_url=image['content'], video_url=video['content'], video_width=int(width['content']),
            video_height=int(height['content']))]
    elif image:
        return [InlineQueryResultPhoto(
            id=str(uuid.uuid4()), title="Instagram Photo",
            photo_url=image['content'], photo_width=300, photo_height=300,
            thumb_url=image['content'])]
    else:
        return [InlineQueryResultArticle(
            id=str(uuid.uuid4()), title='Error', description="Not Found",
            input_message_content=InputTextMessageContent(message_text="Error\nNot Found", parse_mode="Markdown"),
            thumb_url="http://siyanew.com/bots/custom.jpg")] 
Example #6
Source File: bot.py    From spntaBot with GNU General Public License v3.0 6 votes vote down vote up
def on_inline_query(message):
    query_id, from_id, query = telepot.glance(message, flavor='inline_query')
    global plugins

    @asyncio.coroutine
    def get_inline():
        for plugin in plugins:
            if 'inline_query' in plugin:
                for pattern in plugin['inline_patterns']:
                    if re.search(pattern, query, re.IGNORECASE | re.MULTILINE):
                        matches = re.findall(pattern, query, re.IGNORECASE)
                        return_values = yield from plugin['inline_query'](message, matches[0], from_id, 0)
                        if return_values:
                            return {'results': return_values, 'cache_time': 0}
                        break
        return []

    try:
        answerer.answer(message, get_inline)

    except:
        pass 
Example #7
Source File: emodi.py    From telepot with MIT License 6 votes vote down vote up
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    m = telepot.namedtuple.Message(**msg)

    if chat_id < 0:
        # group message
        print 'Received a %s from %s, by %s' % (content_type, m.chat, m.from_)
    else:
        # private message
        print 'Received a %s from %s' % (content_type, m.chat)  # m.chat == m.from_

    if content_type == 'text':
        reply = ''

        # For long messages, only return the first 10 characters.
        if len(msg['text']) > 10:
            reply = u'First 10 characters:\n'

        # Length-checking and substring-extraction may work differently
        # depending on Python versions and platforms. See above.

        reply += msg['text'][:10].encode('unicode-escape').decode('ascii')
        bot.sendMessage(chat_id, reply) 
Example #8
Source File: bot.py    From Siarobo with MIT License 6 votes vote down vote up
def on_inline_query(message):
    query_id, from_id, query = telepot.glance(message, flavor='inline_query')
    global plugins

    @asyncio.coroutine
    def get_inline():
        for plugin in plugins:
            if 'inline_query' in plugin:
                for pattern in plugin['inline_patterns']:
                    if re.search(pattern, query, re.IGNORECASE|re.MULTILINE):
                        matches = re.findall(pattern, query, re.IGNORECASE)
                        return_values = yield from plugin['inline_query'](message, matches[0], from_id, 0)
                        if return_values:
                            return {'results': return_values, 'cache_time': 0}
                        break
        return []
    try:
        answerer.answer(message, get_inline)

    except:
        pass 
Example #9
Source File: skeletona_route.py    From telepot with MIT License 6 votes vote down vote up
def on_callback_query(msg):
    query_id, from_id, data = telepot.glance(msg, flavor='callback_query')
    print('Callback query:', query_id, from_id, data)

    if data == 'notification':
        await bot.answerCallbackQuery(query_id, text='Notification at top of screen')
    elif data == 'alert':
        await bot.answerCallbackQuery(query_id, text='Alert!', show_alert=True)
    elif data == 'edit':
        global message_with_inline_keyboard

        if message_with_inline_keyboard:
            msg_idf = telepot.message_identifier(message_with_inline_keyboard)
            await bot.editMessageText(msg_idf, 'NEW MESSAGE HERE!!!!!')
        else:
            await bot.answerCallbackQuery(query_id, text='No previous message to edit') 
Example #10
Source File: paymenta.py    From telepot with MIT License 6 votes vote down vote up
def send_invoice(seed_tuple):
    msg = seed_tuple[1]

    content_type, chat_type, chat_id = telepot.glance(msg)

    if content_type == 'text':
        sent = await bot.sendInvoice(
                   chat_id, "Nick's Hand Cream", "Keep a man's hand like a woman's",
                   payload='a-string-identifying-related-payment-messages-tuvwxyz',
                   provider_token=PAYMENT_PROVIDER_TOKEN,
                   start_parameter='abc',
                   currency='HKD', prices=[
                       LabeledPrice(label='One Case', amount=987),
                       LabeledPrice(label='Package', amount=12)],
                   need_shipping_address=True, is_flexible=True)  # required for shipping query

        print('Invoice sent:')
        pprint(sent) 
Example #11
Source File: quiz.py    From telepot with MIT License 6 votes vote down vote up
def on_chat_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance(msg)
        self.sender.sendMessage(
            'Press START to do some math ...',
            reply_markup=InlineKeyboardMarkup(
                inline_keyboard=[[
                    InlineKeyboardButton(text='START', callback_data='start'),
                ]]
            )
        )
        self.close()  # let Quizzer take over 
Example #12
Source File: main_app.py    From pockebot with MIT License 6 votes vote down vote up
def on_callback_query(self, msg):
        query_id, self.request_chat_id, query_data = telepot.glance(msg, flavor='callback_query')
        self.mongo.chat_id = self.request_chat_id
        self.store_contacts(msg)
        self.known_user = self.is_user_known()
        self.__debug_print('>')
        self.__debug_print('> callback')
        self.__debug_print(msg)
        to_send_msg, keyboard = self.process_command(query_data)

        if to_send_msg is None:
            await self._editor.editMessageReplyMarkup(reply_markup=keyboard)
            self.waiting_for_menu_action = True
        else:
            await self._cancel_last()
            sent = await self.sender.sendMessage(to_send_msg, reply_markup=keyboard, parse_mode='Markdown')
            self._editor = telepot.aio.helper.Editor(self.bot, sent)
            self._edit_msg_ident = telepot.message_identifier(sent)
            self.waiting_for_menu_action = False 
Example #13
Source File: flask_deeplinking.py    From telepot with MIT License 6 votes vote down vote up
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    print 'Chat Message:', content_type, chat_type, chat_id

    if content_type == 'text':
        text = msg['text']
        print 'Text:', text

        if text.startswith('/start'):
            try:
                command, payload = text.split(' ')

                print 'Payload:', payload
                print 'User ID:', key_id_map[payload]
                print 'chat_id:', chat_id

            except ValueError:
                print 'No payload, or more than one chunk of payload'

            except KeyError:
                print 'Invalid key, no corresponding User ID' 
Example #14
Source File: telegram_bot.py    From Python-Automation-Cookbook with MIT License 6 votes vote down vote up
def on_chat_message(self, msg):
        # If the data sent is not test, return an error
        content_type, chat_type, chat_id = telepot.glance(msg)

        if content_type != 'text':
            self.sender.sendMessage("I don't understand you. "
                                    "Please type 'help' for options")
            return

        # Make the commands case insensitive
        command = msg['text'].lower()
        if command not in COMMANDS:
            self.sender.sendMessage("I don't understand you. "
                                    "Please type 'help' for options")
            return

        message = COMMANDS[command]()
        self.sender.sendMessage(message) 
Example #15
Source File: telegram_bot_custom_keyboard.py    From Python-Automation-Cookbook with MIT License 6 votes vote down vote up
def on_chat_message(self, msg):
        # If the data sent is not test, return an error
        content_type, chat_type, chat_id = telepot.glance(msg)

        if content_type != 'text':
            self.sender.sendMessage("I don't understand you. "
                                    "Please type 'help' for options",
                                    reply_markup=KEYBOARD)
            return

        # Make the commands case insensitive
        command = msg['text'].lower()
        if command not in COMMANDS:
            self.sender.sendMessage("I don't understand you. "
                                    "Please type 'help' for options",
                                    reply_markup=KEYBOARD)
            return

        message = COMMANDS[command]()
        self.sender.sendMessage(message, reply_markup=KEYBOARD) 
Example #16
Source File: guessa.py    From telepot with MIT License 6 votes vote down vote up
def on_chat_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance(msg)

        if content_type != 'text':
            await self.sender.sendMessage('Give me a number, please.')
            return

        try:
           guess = int(msg['text'])
        except ValueError:
            await self.sender.sendMessage('Give me a number, please.')
            return

        # check the guess against the answer ...
        if guess != self._answer:
            # give a descriptive hint
            hint = self._hint(self._answer, guess)
            await self.sender.sendMessage(hint)
        else:
            await self.sender.sendMessage('Correct!')
            self.close() 
Example #17
Source File: guess.py    From telepot with MIT License 6 votes vote down vote up
def on_chat_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance(msg)

        if content_type != 'text':
            self.sender.sendMessage('Give me a number, please.')
            return

        try:
           guess = int(msg['text'])
        except ValueError:
            self.sender.sendMessage('Give me a number, please.')
            return

        # check the guess against the answer ...
        if guess != self._answer:
            # give a descriptive hint
            hint = self._hint(self._answer, guess)
            self.sender.sendMessage(hint)
        else:
            self.sender.sendMessage('Correct!')
            self.close() 
Example #18
Source File: chatboxa_nodb.py    From telepot with MIT License 5 votes vote down vote up
def on_chat_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance(msg)

        if content_type != 'text':
            await self.sender.sendMessage("I don't understand")
            return

        command = msg['text'].strip().lower()

        # Tells who has sent you how many messages
        if command == '/unread':
            results = self._store.unread_per_chat()

            lines = []
            for r in results:
                n = 'ID: %d\n%d unread' % r
                lines.append(n)

            if not len(lines):
                await self.sender.sendMessage('No unread messages')
            else:
                await self.sender.sendMessage('\n'.join(lines))

        # read next sender's messages
        elif command == '/next':
            results = self._store.unread_per_chat()

            if not len(results):
                await self.sender.sendMessage('No unread messages')
                return

            chat_id = results[0][0]
            unread_messages = self._store.pull(chat_id)

            await self.sender.sendMessage('From ID: %d' % chat_id)
            await self._read_messages(unread_messages)

        else:
            await self.sender.sendMessage("I don't understand") 
Example #19
Source File: datecalc.py    From telepot with MIT License 5 votes vote down vote up
def on_callback_query(self, msg):
        if 'inline_message_id' in msg:
            inline_message_id = msg['inline_message_id']
            ballot = self._ballots[inline_message_id]

            query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')
            if from_id in ballot:
                self.bot.answerCallbackQuery(query_id, text='You have already voted %s' % ballot[from_id])
            else:
                self.bot.answerCallbackQuery(query_id, text='Ok')
                ballot[from_id] = query_data 
Example #20
Source File: lover.py    From telepot with MIT License 5 votes vote down vote up
def on_callback_query(self, msg):
        query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')

        if query_data == 'yes':
            self._cancel_last()
            self.sender.sendMessage('Thank you!')
            self.close()
        else:
            self.bot.answerCallbackQuery(query_id, text='Ok. But I am going to keep asking.')
            self._cancel_last()
            self._propose() 
Example #21
Source File: skeleton_route.py    From telepot with MIT License 5 votes vote down vote up
def on_inline_query(msg):
    def compute():
        query_id, from_id, query_string = telepot.glance(msg, flavor='inline_query')
        print('%s: Computing for: %s' % (threading.current_thread().name, query_string))

        articles = [InlineQueryResultArticle(
                        id='abcde', title='Telegram', input_message_content=InputTextMessageContent(message_text='Telegram is a messaging app')),
                    dict(type='article',
                        id='fghij', title='Google', input_message_content=dict(message_text='Google is a search engine'))]

        photo1_url = 'https://core.telegram.org/file/811140934/1/tbDSLHSaijc/fdcc7b6d5fb3354adf'
        photo2_url = 'https://www.telegram.org/img/t_logo.png'
        photos = [InlineQueryResultPhoto(
                      id='12345', photo_url=photo1_url, thumb_url=photo1_url),
                  dict(type='photo',
                      id='67890', photo_url=photo2_url, thumb_url=photo2_url)]

        result_type = query_string[-1:].lower()

        if result_type == 'a':
            return articles
        elif result_type == 'p':
            return photos
        else:
            results = articles if random.randint(0,1) else photos
            if result_type == 'b':
                return dict(results=results, switch_pm_text='Back to Bot', switch_pm_parameter='Optional_start_parameter')
            else:
                return dict(results=results)

    answerer.answer(msg, compute) 
Example #22
Source File: skeleton_route.py    From telepot with MIT License 5 votes vote down vote up
def on_chosen_inline_result(msg):
    result_id, from_id, query_string = telepot.glance(msg, flavor='chosen_inline_result')
    print('Chosen Inline Result:', result_id, from_id, query_string) 
Example #23
Source File: flask_skeleton.py    From telepot with MIT License 5 votes vote down vote up
def on_chosen_inline_result(msg):
    result_id, from_id, query_string = telepot.glance(msg, flavor='chosen_inline_result')
    print('Chosen Inline Result:', result_id, from_id, query_string) 
Example #24
Source File: lovera.py    From telepot with MIT License 5 votes vote down vote up
def on_callback_query(self, msg):
        query_id, from_id, query_data = glance(msg, flavor='callback_query')

        if query_data == 'yes':
            await self._cancel_last()
            await self.sender.sendMessage('Thank you!')
            self.close()
        else:
            await self.bot.answerCallbackQuery(query_id, text='Ok. But I am going to keep asking.')
            await self._cancel_last()
            await self._propose() 
Example #25
Source File: votea.py    From telepot with MIT License 5 votes vote down vote up
def on_callback_query(self, msg):
        query_id, from_id, query_data = glance(msg, flavor='callback_query')

        if from_id in self._ballot_box:
            await self.bot.answerCallbackQuery(query_id, text='You have already voted %s' % self._ballot_box[from_id])
        else:
            await self.bot.answerCallbackQuery(query_id, text='Ok')
            self._ballot_box[from_id] = query_data

        # Announce results if everyone has voted.
        if len(self._ballot_box) >= self._member_count:
            result = self._count_votes()
            await self._close_ballot()
            await self.sender.sendMessage('Everyone has voted:\nYes: %d\nNo: %d\nSilent: %d' % result) 
Example #26
Source File: quiz.py    From telepot with MIT License 5 votes vote down vote up
def on_callback_query(self, msg):
        query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')

        if query_data != 'start':
            self._score[self._answer == int(query_data)] += 1

        self._answer = self._show_next_question() 
Example #27
Source File: inlinea.py    From telepot with MIT License 5 votes vote down vote up
def on_chosen_inline_result(self, msg):
        from pprint import pprint
        pprint(msg)
        result_id, from_id, query_string = telepot.glance(msg, flavor='chosen_inline_result')
        print(self.id, ':', 'Chosen Inline Result:', result_id, from_id, query_string) 
Example #28
Source File: inlinea.py    From telepot with MIT License 5 votes vote down vote up
def on_inline_query(self, msg):
        def compute_answer():
            query_id, from_id, query_string = telepot.glance(msg, flavor='inline_query')
            print(self.id, ':', 'Inline Query:', query_id, from_id, query_string)

            articles = [{'type': 'article',
                             'id': 'abc', 'title': query_string, 'message_text': query_string}]

            return articles

        self.answerer.answer(msg, compute_answer) 
Example #29
Source File: inline.py    From telepot with MIT License 5 votes vote down vote up
def on_chosen_inline_result(self, msg):
        from pprint import pprint
        pprint(msg)
        result_id, from_id, query_string = telepot.glance(msg, flavor='chosen_inline_result')
        print(self.id, ':', 'Chosen Inline Result:', result_id, from_id, query_string) 
Example #30
Source File: aiohttp_skeletona.py    From telepot with MIT License 5 votes vote down vote up
def on_callback_query(msg):
    query_id, from_id, data = telepot.glance(msg, flavor='callback_query')
    print('Callback query:', query_id, from_id, data)

# need `/setinline`