Python telepot 模块,glance() 实例源码

我们从Python开源项目中,提取了以下49个代码示例,用于说明如何使用telepot.glance()

项目:grovebot    作者:mrsofia    | 项目源码 | 文件源码
def on_chat_message(msg):
    pprint(msg)
    content_type, chat_type, chat_id = telepot.glance(msg)
    # Ignore any messages received over 30s ago
    cur_time = time.time()
    if cur_time - msg.get("date") < 30:
        if content_type == 'text':
            text = msg.get("text")
            for url in URLS:
                if url in text:
                    # This means the message contains a link to some music, let's save it
                    get_fuego(msg)
                    save_link(msg)
                    break
    else:
        print("IGNORING OLD MESSAGE...")
项目:ai-mobile-robot-SRL    作者:normandipalo    | 项目源码 | 文件源码
def handle(msg):
    global look_obj
    content_type, chat_type, chat_id = telepot.glance(msg)
    print(content_type, chat_type, chat_id)

    #if content_type == 'text':
        #bot.sendMessage(chat_id, msg['text'])
    msg_txt=msg['text']
    words=msg_txt.split(' ')
    #print(words[-1])

    ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)
    request = ai.text_request()
    request.query = msg_txt
    response = request.getresponse()
    reply = response.read()
    reply = reply.decode("utf-8")
    parsed_json = json.loads(reply)
    action = parsed_json['result']['action']
    parameters = parsed_json['result']['parameters']
    response = parsed_json['result']['fulfillment']['speech']
    #return parameters, action, response
    print(action)
    print(parameters['object'])
    if action=='go_to':
      look_obj=str(parameters['object'])
      print(look_obj)
      bot.sendMessage(chat_id, ("I'll look for a " + str(parameters['object']) + "!") )

#TOKEN = sys.argv[1]  # get token from command-line
项目:TycotBot    作者:Programeiros    | 项目源码 | 文件源码
def __init__(self, msg, bot):
        self.bot = bot
        if msg.get('data'):
            self.query_id, self.from_id, self.query_data = telepot.glance(
                msg, flavor='callback_query')
            self.chat_id = msg['message']['chat']['id']
            self.chat_type = msg['message']['chat']['type']
            self.UserID = msg['from']['id']
            self.msg = msg
        else:
            self.content_type, self.chat_type, self.chat_id = telepot.glance(
                msg)
            self.msg_id = msg['message_id']

        if 'username' in msg['from']:
            self.username = msg['from']['username']
        else:
            self.username = '[Sem username]'
        self.user = msg['from']['first_name']
        self.UserID = msg['from']['id']
        self.msg = msg
项目:teleTweetBot    作者:CorunaDevelopers    | 项目源码 | 文件源码
def __handle_message(self, message):
        """
        Handles a message sent from telegram.
        :param message:
        :return:
        """
        try:
            content_type, chat_type, chat_id = telepot.glance(message)
            telegram_message = TelegramResponse(content_type, chat_type, chat_id, message)

            # TODO: Do an enum for the content types
            if content_type == 'text':
                print telegram_message.message.text
                user_id = telegram_message.message.message_from.id

                response = process_message(self.twitter_api, telegram_message)
                if response:
                    self.bot.sendMessage(user_id, response)

        except Exception as ex:
            ExceptionHandler.handle_exception(ex, False)
项目:Telyrics    作者:hamedafra    | 项目源码 | 文件源码
def on_chat_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance(msg)
        if '/start' not in msg['text']:
            search = msg['text']
        search.replace(" ", "+")
        self._results = spotify.search(q=search, type='track', limit='50')
        pages = math.ceil(len(self._results['tracks']['items']) / 3)
        inlinekeyboards = []

        if pages == 1:
            for track in self._results['tracks']['items']:
                trackname = track['artists'][0]['name'] + ' -' + ' ' + track['name']
                inlinekeyboards.append([InlineKeyboardButton(text=trackname, callback_data=track['uri'])])
                keyboard = InlineKeyboardMarkup(inline_keyboard=inlinekeyboards)
            self.print_search(keyboard, msg)
        elif pages > 1:
            for track in self._results['tracks']['items'][:3]:
                trackname = track['artists'][0]['name'] + ' -' + ' ' + track['name']
                inlinekeyboards.append([InlineKeyboardButton(text=trackname, callback_data=track['uri'])])
            current = 1
            pagekeyboard = self.get_pagination(current, pages)
            inlinekeyboards.append(pagekeyboard)
            keyboard = InlineKeyboardMarkup(inline_keyboard=inlinekeyboards)
            self.print_search(keyboard, msg)
项目:Surrender-Bot    作者:Radeox    | 项目源码 | 文件源码
def handle(msg):
    """
    This function handle all messages incoming from users
    """

    content_type, chat_type, chat_id = telepot.glance(msg)
    command_input = msg['text']

    if command_input == '/start':
        # Check if already registred
        if register_user(chat_id):
            bot.sendMessage(chat_id, start_msg)
            feed = feedparser.parse(feed_url)

            # Send all news from older to newest
            for entry in reversed(feed.entries):
                msg = entry.title + '\n' + entry.link
                bot.sendMessage(chat_id, msg)

    if command_input == '/stop':
        bot.sendMessage(chat_id, stop_msg)
        remove_user(chat_id)
项目:pitalk    作者:samar-agrawal    | 项目源码 | 文件源码
def on_chat_message(self, msg):
        '''process and response message'''

        ntuple = Message(**msg)

        if telepot.glance(msg)[0] == 'text':

            if any(q in ntuple.text for q in ACTION_DICT.keys()):
                response = perform_action(ntuple.text, ntuple.from_.id)
            else:
                response = KERNEL.respond(ntuple.text)

        #if not response:
            #response = self.sender.sendMessage(
               # chat_id, 'I do not understand your last message.', reply_to_message_id=msg_id)
        self.sender.sendMessage(response)
项目:ifictionbot    作者:ykrivopalov    | 项目源码 | 文件源码
def on_message(self, msg):
        debug('MainDialog on_message')
        content_type = telepot.glance(msg)[0]
        if content_type != 'text':
            return

        text = msg['text']
        if text == self._GAMES_DB:
            return DIALOG_BROWSING, {}
        elif text == self._RECENTLY_PLAYED:
            return DIALOG_LAST_PLAYED, {}
        elif text == self._HOWTO:
            await self._sender.sendMessage(HELP_MESSAGE, parse_mode='Markdown')
        else:
            await self._sender.sendMessage('Choose section', reply_markup=self._KEYBOARD)

        return DIALOG_MAIN, {}
项目:ifictionbot    作者:ykrivopalov    | 项目源码 | 文件源码
def on_message(self, msg):
        debug('BrowsingDialog on_message %s', msg)
        content_type = telepot.glance(msg)[0]
        if content_type != 'text':
            return DIALOG_BROWSING, {}

        text = msg['text']
        if text == self._FORWARD:
            items = self._iterator.next()
        elif text == self._BACKWARD:
            items = self._iterator.prev()
        elif text == self._CANCEL:
            return DIALOG_MAIN, {}
        elif text.startswith('/'):
            return DIALOG_GAME, {'game': text[1:]}
        else:
            items = self._iterator.get_page()

        msg = self._make_items_list(items)
        await self._sender.sendMessage(msg, reply_markup=self._make_keyboard())
        return DIALOG_BROWSING, {}
项目:ifictionbot    作者:ykrivopalov    | 项目源码 | 文件源码
def on_message(self, msg):
        debug('GameDialog on_message')
        content_type = telepot.glance(msg)[0]
        if content_type != 'text':
            return

        text = msg['text']
        if text.startswith('/command'):
            text = text[9:]
        elif text.startswith('/c'):
            text = text[3:]

        if text.lower() in ['save', 'restore', 'quit', 'q']:
            await self._sender.sendMessage('This command currently unsupported',
                                           reply_markup=self._KEYBOARD)
            return DIALOG_GAME, {}
        elif text == self._RETURN:
            return DIALOG_MAIN, {}
        elif not text:
            return DIALOG_GAME, {}
        else:
            await self._game.command(text)
            return DIALOG_GAME, {}
项目:Tele_Genesys    作者:mthbernardes    | 项目源码 | 文件源码
def handle_message(msg):
    user_id = msg['from']['id']
    nome = msg['from']['first_name']
    try:
        sobrenome = msg['from']['last_name']
    except:
        sobrenome = ''
    username = msg['from']['username']
    hostname = subprocess.check_output(['hostname']).lower()
    content_type, chat_type, chat_id = telepot.glance(msg)
    if username in admins:
        if content_type is 'document':
            bot.downloadFile(msg['document']['file_id'], msg['document']['file_name'])

        elif content_type is 'text':
            command = msg['text'].lower()
            actions(user_id,command,hostname)
    else:
        bot.sendMessage(user_id, 'Desculpe '+nome+' '+sobrenome+' nao tenho permissao para falar com voce!')
项目:AssemblyBot    作者:mbikovitsky    | 项目源码 | 文件源码
def on_chat_message(self, message):
        try:
            content_type, chat_type, chat_id = telepot.glance(message)

            if content_type in self.UNRECOGNIZED_CONTENT_TYPES:
                raise BotException("Message content not understood.")

            message_text = message["text"]

            if self._is_command(message_text):
                result = self._process_command_text(message["text"])
            else:
                result = self._process_query_text(message["text"])
            await self._send_reply(message, result)
        except Exception as e:
            try:
                exception_string = str(e)
            except:
                exception_string = "Unprintable exception."
            finally:
                error_message = "ERROR: " + exception_string
                await self._send_reply(message,
                                       self._format_as_html(error_message))
项目:AssemblyBot    作者:mbikovitsky    | 项目源码 | 文件源码
def on_inline_query(self, message):
        query_id, from_id, query_string = telepot.glance(message,
                                                         flavor="inline_query")

        def _compute_answer():
            result = self._process_query_text(query_string)

            return [
                {
                    "type": "article",
                    "id": self._generate_random_id(),
                    "title": "0xDEADBEEF",
                    "input_message_content": {
                        "message_text": result,
                        "parse_mode": "HTML"
                    }
                }
            ]

        self._answerer.answer(message, _compute_answer)
项目:RandTalkBot    作者:quasiyoke    | 项目源码 | 文件源码
def __init__(self, message_json):
        try:
            content_type, chat_type, chat_id = telepot.glance(message_json)
        except KeyError:
            raise UnsupportedContentError()
        if 'forward_from' in message_json:
            raise UnsupportedContentError()
        self.is_reply = 'reply_to_message' in message_json
        self.text = message_json.get('text')
        self.type = content_type
        self.command = None
        self.command_args = None
        try:
            init_method = getattr(self, '_init_' + content_type)
        except AttributeError:
            raise UnsupportedContentError()
        init_method(message_json)
项目:RandTalkBot    作者:quasiyoke    | 项目源码 | 文件源码
def on_inline_query(self, query):
        query_id, from_id, query_string = telepot.glance(query, flavor='inline_query')
        LOGGER.debug('Inline query from %d: \"%s\"', self._stranger.id, query_string)
        response = [{
            'type': 'article',
            'id': 'invitation_link',
            'title': _('Rand Talk Invitation Link'),
            'description': _('The more friends\'ll use your link -- the faster the search will be'),
            'thumb_url': 'http://randtalk.ml/static/img/logo-500x500.png',
            'message_text': (
                _('Do you want to talk with somebody, practice in foreign languages or you just want '
                    'to have some fun? Rand Talk will help you! It\'s a bot matching you with '
                    'a random stranger of desired sex speaking on your language. {0}'),
                self._stranger.get_invitation_link(),
                ),
            'parse_mode': 'Markdown',
            }]
        await self._sender.answer_inline_query(query_id, response)
项目:telegram-control-torrent    作者:seungjuchoi    | 项目源码 | 文件源码
def on_chat_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance(msg)
        # Check ID
        if not chat_id in VALID_USERS:
            print("Permission Denied")
            return

        if content_type is 'text':
            self.handle_command(msg['text'])
            return

        if content_type is 'document':
            file_name = msg['document']['file_name']
            if file_name[-3:] == 'smi':
                file_id = msg['document']['file_id']
                self.handle_smifile(file_id, file_name)
                return
            if file_name[-7:] == 'torrent':
                file_id = msg['document']['file_id']
                self.handle_seedfile(file_id, file_name)
                return
            self.sender.sendMessage('Invalid File')
            return

        self.sender.sendMessage('Invalid File')
项目:matrigram    作者:GalPressman    | 项目源码 | 文件源码
def do_leave(self, msg, match):
        query_id, _, _ = telepot.glance(msg, flavor='callback_query')
        chat_id = msg['message']['chat']['id']
        room_name = match.group('room')
        client = self._get_client(chat_id)

        prev_focus_room = client.get_focus_room_alias()
        client.leave_room(room_name)
        self.sendMessage(chat_id, 'Left {}'.format(room_name))
        curr_focus_room = client.get_focus_room_alias()

        if curr_focus_room != prev_focus_room and curr_focus_room is not None:
            self.sendMessage(chat_id,
                             'You are now participating in: {}'.format(
                                 client.get_focus_room_alias()))

        self.answerCallbackQuery(query_id, 'Done!')
项目:Siarobo    作者:siyanew    | 项目源码 | 文件源码
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
项目:Siarobo    作者:siyanew    | 项目源码 | 文件源码
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")]
项目:katcr    作者:XayOn    | 项目源码 | 文件源码
def on_chat_message(self, msg):
        """Answer only chat messages."""
        if msg['text'] == "/start":
            return

        chat_id = telepot.glance(msg)[2]

        for engine in (self.katcr, self.thepiratebay):
            res = tuple(engine.search(msg['text'], 1))
            if res:
                break

        keyboard = InlineKeyboardMarkup(inline_keyboard=list(
            [InlineKeyboardButton(text=k, callback_data=str(r))]
            for r, (k, _, _) in enumerate(res)))

        self.responses[chat_id] = {r: (k, v) for r, (k, _, v)
                                   in enumerate(res)}
        self.sendMessage(chat_id, "Results for: {}".format(msg['text']),
                         reply_markup=keyboard, parse_mode="html")
项目:surveillancebot    作者:ola-ct    | 项目源码 | 文件源码
def on_callback_query(self, msg):
        global alerting_on, snapshooter, snapshot_queue
        query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')
        if verbose:
            print('Callback Query:', query_id, from_id, query_data)
        if cameras.get(query_data):
            bot.answerCallbackQuery(query_id,
                                    text='Schnappschuss von deiner Kamera "{}"'.format(query_data))
            snapshot_queue.put({'cameras': [cameras[query_data]],
                                'chat_id': from_id,
                                'callback': lambda: self.send_snapshot_menu()})
        elif query_data == 'disable':
            alerting_on = False
            self.bot.answerCallbackQuery(query_id, text='Alarme wurden ausgeschaltet.')
            self.send_main_menu()
        elif query_data == 'enable':
            alerting_on = True
            self.bot.answerCallbackQuery(query_id, text='Alarme wurden eingeschaltet.')
            self.send_main_menu()
        elif query_data == 'snapshot':
            self.bot.answerCallbackQuery(query_id)
            self.send_snapshot_menu()
项目:pockebot    作者:Fillll    | 项目源码 | 文件源码
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
项目:progrobot    作者:petr-kalinin    | 项目源码 | 文件源码
def on_chat_message(self, msg):
        try:
            #print("In on_chat_message")
            content_type, chat_type, chat_id = telepot.glance(msg)
            print('Chat:', content_type, chat_type, chat_id)
            pprint(msg)
            requests.insert({"request": msg, "time": datetime.now().isoformat()})

            answer = process_command(self.state, msg["text"], msg)
            self.sender.sendMessage(parse_mode="HTML", **answer)
        except Exception as e:
            traceback.print_exc()
            print("Error: " + str(e))
            self.sender.sendMessage("Error: " + str(e))
项目:progrobot    作者:petr-kalinin    | 项目源码 | 文件源码
def on_callback_query(self, msg):
        try:
            #print("In on_callback_query")
            query_id, from_id, data = telepot.glance(msg, flavor='callback_query')
            print('Callback query:', query_id, from_id, data)            
            pprint(msg)
            requests.insert({"request": msg, "time": datetime.now().isoformat()})

            answer = process_command(self.state, msg["data"], msg)
            self.sender.sendMessage(parse_mode="HTML", **answer)
        except Exception as e:
            traceback.print_exc()
            print("Error: " + str(e))
            self.sender.sendMessage("Error: " + str(e))
项目:progrobot    作者:petr-kalinin    | 项目源码 | 文件源码
def on_inline_query(self, msg):
        query_id, from_id, query_string = telepot.glance(msg, flavor='inline_query')
        #print(self.id, ':', 'Inline Query:', query_id, from_id, query_string)

        def compute_answer():
            ir = InlineReference()
            result = ir.search_inline(query_string)
            #print("Inline result: ", result)
            return result

        self._answerer.answer(msg, compute_answer)
项目:progrobot    作者:petr-kalinin    | 项目源码 | 文件源码
def on_chosen_inline_result(self, 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)
项目:skybeard-2    作者:LanceMaverick    | 项目源码 | 文件源码
def on_callback_query(self, msg):
        query_id, from_id, query_data = glance(msg, flavor='callback_query')

        try:
            data = self.deserialize(query_data)
        except ThatsNotMineException:
            return

        await self.bot.editMessageText(
            telepot.origin_identifier(msg),
            text="Selected option: {}".format(data),
            reply_markup=self.keyboard)
项目:SmartSlam    作者:Oneiroe    | 项目源码 | 文件源码
def on_callback(msg):
    """  Reaction to an interaction with an InLineKeyboard """
    query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')
    logging.info('Got Callback Query:' + str(query_id) + ' Command:' + query_data + ' From ChatID:' + str(from_id))

    # SWITCH/CASE to identify the call and respond consequently
    if query_data == '/rectify':
        options = [i.split('% ')[1] for i in
                   msg['message']['text'].split('\n')[msg['message']['text'].split('\n').index('DETAILS: ') + 1:]]
        options_buttons = [[InlineKeyboardButton(text=i, callback_data='/rectify_' + i)] for i in options]
        options_buttons.append([InlineKeyboardButton(text='<< Go back', callback_data='/back')])
        keyboard = InlineKeyboardMarkup(
            inline_keyboard=options_buttons)
        bot.editMessageReplyMarkup((from_id, msg['message']['message_id']), reply_markup=keyboard)
    elif '/rectify_' in query_data:
        rectified_classification = query_data[len('/rectify_'):]
        new = msg['message']['text'].split('\n')
        new[2] = 'UPDATED: ' + rectified_classification
        new_message = ''.join('%s\n' % i for i in new)

        sample_name = new[1][6:] + '.wav'
        db_save_access(os.path.join(data['db_path'], 'smartSlamDB.sqlite'),
                       os.path.join(data['db_path'], 'Samples', sample_name),
                       rectified_classification)

        keyboard = InlineKeyboardMarkup(
            inline_keyboard=[[InlineKeyboardButton(text='Rectify classification?', callback_data='/rectify')]]
        )
        bot.editMessageText((from_id, msg['message']['message_id']), new_message, reply_markup=keyboard)

    elif query_data == '/back':
        keyboard = InlineKeyboardMarkup(
            inline_keyboard=[[InlineKeyboardButton(text='Rectify classification?', callback_data='/rectify')]]
        )
        bot.editMessageReplyMarkup((from_id, msg['message']['message_id']), reply_markup=keyboard)
项目:telegramBots    作者:medialab-prado    | 项目源码 | 文件源码
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    print(content_type, chat_type, chat_id)

    if content_type == 'text':
        #bot.sendMessage(chat_id, msg)
        bot.sendMessage(6579175, numero_view)
    if content_type == 'new_chat_member':
        bot.sendMessage(chat_id, "wellcome to this awesome group!")
    if content_type == 'left_chat_member':
        bot.sendMessage(chat_id, "Sayonara baby")
项目:telegramBots    作者:medialab-prado    | 项目源码 | 文件源码
def on_voice_msg(msg):
    query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')
    print('Callback Query:', query_id, from_id, query_data)

    bot.answerCallbackQuery(query_id, text='Calling....')
项目:telegramBots    作者:medialab-prado    | 项目源码 | 文件源码
def on_callback_query(msg):
    query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')
    print('Callback Query:', query_id, from_id, query_data)

    bot.answerCallbackQuery(query_id, text='Calling....')
项目:CosciaPolloBot    作者:Porchetta    | 项目源码 | 文件源码
def handle(msg):
  global found
  content_type, chat_type, chat_id = telepot.glance(msg)

  chat_id = msg['chat']['id']
  command_input = msg['text']

  pattern = 'pollo|polli|pollastrello|pollastrella'

  cp = re.findall(pattern, command_input.lower())
  if cp:
      bot.sendPhoto(chat_id, found[randint(0,len(found))])
项目:ChatAchievementsBot    作者:cherya    | 项目源码 | 文件源码
def handle_message(msg):
    flavor = telepot.flavor(msg)
    content_type, chat_type, chat_id = telepot.glance(msg, flavor=flavor)
    if len(chats) == 0 or chat_id in chats:
        # just save every message
        database.connect()
        message = Messages.create(id=msg['message_id'], message=msg, chat_id=chat_id, content_type=content_type)
        message.save()
        database.close()
        pprint(msg)


# TODO: handle message edit
项目:lelerax    作者:luizperes    | 项目源码 | 文件源码
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)

    if content_type == 'text':
        checkMsg(chat_id, msg['text'], msg['message_id'])
项目:grovebot    作者:mrsofia    | 项目源码 | 文件源码
def on_callback_query(msg):
    query_id, from_id, data = telepot.glance(msg, flavor='callback_query')
    print('Callback query:', query_id, from_id, data)
    add_fuego(query_id, data, from_id, msg)
项目:telegram-bot    作者:botshala    | 项目源码 | 文件源码
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    input_text = msg['text']
    flavor = telepot.flavor(msg)
    summary = telepot.glance(msg, flavor=flavor)
    print(flavor, summary)

    if input_text.startswith("https://"):
        cmd = 'youtube-dl --extract-audio --audio-format mp3 \
            --output "audio.%%(ext)s" %summary'%(input_text)
        os.system(cmd)
        sendAudio(chat_id,'audio.mp3')
    else:
        bot.sendMessage(chat_id,input_text)
项目:ifictionbot    作者:ykrivopalov    | 项目源码 | 文件源码
def on_message(self, msg):
        content_type = telepot.glance(msg)[0]
        if content_type != 'text':
            return

        text = msg['text']
        debug('LastPlayedDialog on_message %s', text)
        if text == self._CANCEL:
            return DIALOG_MAIN, {}
        elif text.startswith('/'):
            return DIALOG_GAME, {'game': text[1:]}
        else:
            await self._send_last_played_games()
            return DIALOG_LAST_PLAYED, {}
项目:ifictionbot    作者:ykrivopalov    | 项目源码 | 文件源码
def open(self, msg, dummy_seed):
        try:
            info('chat %s: open', self._chat_id)
            self._registry.register(self._chat_id, self)

            content_type = telepot.glance(msg)[0]
            if content_type == 'text' and msg['text'] == '/start':
                self._state['current'] = DIALOG_MAIN

            await self._dialogs[self._state['current']].start()
            return False  # process initial message
        except Exception as e:
            error('chat %s: open error %s', self._chat_id, e)
            raise
项目:RandTalkBot    作者:quasiyoke    | 项目源码 | 文件源码
def on_chat_message(self, message_json):
        content_type, chat_type, chat_id = telepot.glance(message_json)

        if chat_type != 'private':
            return

        try:
            message = Message(message_json)
        except UnsupportedContentError:
            await self._sender.send_notification(_('Messages of this type aren\'t supported.'))
            return

        if message.command:
            if (await self._stranger_setup_wizard.handle_command(message)):
                return
            try:
                await self.handle_command(message)
            except UnknownCommandError as e:
                await self._sender.send_notification(
                    _('Unknown command. Look /help for the full list of commands.'),
                    )
        elif not (await self._stranger_setup_wizard.handle(message)):
            try:
                await self._stranger.send_to_partner(message)
            except MissingPartnerError:
                pass
            except StrangerError:
                await self._sender.send_notification(_('Messages of this type aren\'t supported.'))
            except TelegramError:
                LOGGER.warning(
                    'Send message. Can\'t send to partned: %d -> %d',
                    self._stranger.id,
                    self._stranger.get_partner().id,
                    )
                await self._sender.send_notification(
                    _('Your partner has blocked me! How did you do that?!'),
                    )
                await self._stranger.end_talk()
项目:matrigram    作者:GalPressman    | 项目源码 | 文件源码
def on_chat_message(self, msg):
        """Main entry point.

        This function is our main entry point to the bot.
        Messages will be routed according to their content type.

        Args:
            msg: The message object received from telegram user.
        """
        content_type, _, _ = telepot.glance(msg)
        logger.debug('content type: %s', content_type)
        self.content_type_routes[content_type](msg)
项目:matrigram    作者:GalPressman    | 项目源码 | 文件源码
def do_change_focus(self, msg, match):
        query_id, _, _ = telepot.glance(msg, flavor='callback_query')
        chat_id = msg['message']['chat']['id']
        room_name = match.group('room')

        self.sendChatAction(chat_id, 'typing')
        client = self._get_client(chat_id)

        client.set_focus_room(room_name)
        self.sendMessage(chat_id, 'You are now participating in {}'.format(room_name))
        self.sendMessage(chat_id, '{} Room history:'.format(room_name))
        client.backfill_previous_messages()

        self.answerCallbackQuery(query_id, 'Done!')
项目:matrigram    作者:GalPressman    | 项目源码 | 文件源码
def do_join(self, msg, match):
        query_id, _, _ = telepot.glance(msg, flavor='callback_query')
        chat_id = msg['message']['chat']['id']
        room_name = match.group('room')

        self.sendChatAction(chat_id, 'typing')
        client = self._get_client(chat_id)

        ret = client.join_room(room_name)
        if not ret:
            self.answerCallbackQuery(query_id, 'Can\'t join room')
        else:
            self.answerCallbackQuery(query_id, 'Joined {}'.format(room_name))
项目:matrigram    作者:GalPressman    | 项目源码 | 文件源码
def do_nop(self, msg, _):
        query_id, _, _ = telepot.glance(msg, flavor='callback_query')
        chat_id = msg['message']['chat']['id']

        self.sendChatAction(chat_id, 'typing')
        self.answerCallbackQuery(query_id, 'OK Boss!')
项目:dotabuff-telegram-bot    作者:vaskinyy    | 项目源码 | 文件源码
def on_inline_query(self, msg):
        query_id, from_id, query_string = telepot.glance(msg, flavor='inline_query')
        print(self.id, ':', 'Inline Query:', query_id, from_id, query_string)

        def compute_answer():
            players = self.query.get_players(query_string)
            articles = []
            for player in players:
                article = player.telegram_article
                articles.append(article)

            return articles

        self._answerer.answer(msg, compute_answer)
项目:dotabuff-telegram-bot    作者:vaskinyy    | 项目源码 | 文件源码
def on_chosen_inline_result(self, 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)
项目:inlinelatex    作者:bmagyarkuti    | 项目源码 | 文件源码
def handle(self, msg):
        flavor = telepot.flavor(msg)
        if flavor == 'normal':
            content_type, chat_type, chat_id = telepot.glance(msg, flavor)
            server_logger.info("Normal %s message, %s." % (content_type, chat_id))
            await bot.sendMessage(int(chat_id), "I'm an inline bot. You cannot speak to me directly")
        elif flavor == 'inline_query':
            msg_id, from_id, query_string = telepot.glance(msg, flavor='inline_query')
            server_logger.info("Inline equation, %s : %s" % (from_id, query_string))
            answerer.answer(msg)
项目:telebot    作者:hack-ghost    | 项目源码 | 文件源码
def handle(self, msg):
        content_type, chat_type, chat_id = glance(msg)

        if content_type == "text":
            return await self.text_router.route(msg)
项目:friday-bot    作者:dhruvramdev    | 项目源码 | 文件源码
def handle(msg):
    sender_id = msg['chat']['id']
    msg_recieved = msg['text']
    content_type, chat_type, chat_id = telepot.glance(msg)
项目:friday-bot    作者:dhruvramdev    | 项目源码 | 文件源码
def on_callback_query(msg):
    query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')
    print('Callback Query:', query_id, from_id, query_data)
    if query_data == "newsMore":
        bot.answerCallbackQuery(query_id, text='Loading More News')
        response = getNews()
        for i in range(1):
            number = random.randint(2, len(response))
            bot.sendMessage(from_id, response[number])

        keyboardNews = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text='More News', callback_data="newsMore")]
        ])
        bot.sendMessage(from_id, 'Load More', reply_markup=keyboardNews)

    else:
        type_of_link = query_data.split(' ')[-1]
        link = query_data.split(' ')[0]

        mapping = {
            'song' : download_send_audio,
            'video' : download_send_video, 
            'lyrics' : download_send_lyrics
        }


        if type_of_link not in mapping :
            bot.sendMessage(from_id, 'Cant Download This One, Try Others')
        else:
            bot.sendMessage(from_id, 'Got Your Request! \n Sending...')
            mapping[type_of_link](from_id, link)