Пример #1
0
def handle(msg):
    print(msg)
    if telepot.flavor(msg) == "chat":
        content_type, chat_type, chat_id = telepot.glance(msg)
        if content_type == 'text':
            logic(msg['text'], chat_id, chat_type)
    elif telepot.flavor(msg) == "callback_query":
        callback_id, chat_id, data, msg_id = msg['id'], msg['from']['id'], msg['data'], msg["message"]["message_id"]
Пример #2
0
def handle(msg):
    flavor = telepot.flavor(msg)

    # normal message
    if flavor == 'normal':
        content_type, chat_type, chat_id = telepot.glance(msg)
        print 'Normal Message:', content_type, chat_type, chat_id,
        content = msg['text']
        if containsKeyword(content):
            bot.sendMessage(chat_id, content)
            responseImg = random.choice(os.listdir("./Images/"))
            responsefile = open("./Images/" + responseImg, 'rb')
            bot.sendPhoto(chat_id, responsefile)
            # Do your stuff according to `content_type` ...

    # inline query - need `/setinline`
    elif flavor == 'inline_query':
        query_id, from_id, query_string = telepot.glance(msg, flavor=flavor)
        print 'Inline Query:', query_id, from_id, query_string

        # Compose your own answers
        articles = [{'type': 'article',
                     'id': 'abc', 'title': 'ABC', 'message_text': 'Good morning'}]

        bot.answerInlineQuery(query_id, articles)

    # chosen inline result - need `/setinlinefeedback`
    elif flavor == 'chosen_inline_result':
        result_id, from_id, query_string = telepot.glance(msg, flavor=flavor)
        print 'Chosen Inline Result:', result_id, from_id, query_string

        # Remember the chosen answer to do better next time

    else:
        raise telepot.BadFlavor(msg)
Пример #3
0
def see_every_content_types(msg):
    global expected_content_type, content_type_iterator

    flavor = telepot.flavor(msg)

    if flavor == "normal":
        content_type, chat_type, chat_id = telepot.glance2(msg)
        from_id = msg["from"]["id"]

        if chat_id != USER_ID and from_id != USER_ID:
            print "Unauthorized user:"******"Message")
        try:
            if content_type == expected_content_type:
                expected_content_type = content_type_iterator.next()
                bot.sendMessage(chat_id, "Please give me a %s." % expected_content_type)
            else:
                bot.sendMessage(
                    chat_id,
                    "It is not a %s. Please give me a %s, please." % (expected_content_type, expected_content_type),
                )
        except StopIteration:
            # reply to sender because I am kicked from group already
            bot.sendMessage(from_id, "Thank you. I am done.")

    else:
        raise telepot.BadFlavor(msg)
Пример #4
0
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    if content_type == 'audio':
        audiofile = msg['audio']
        fileid = audiofile['file_id']
        flavor = telepot.flavor(msg)
        summary = telepot.glance(msg, flavor=flavor)
        print(flavor, summary)
        print(fileid)
        print(bot.getFile(file_id=fileid))
        filename = bot.getFile(file_id=fileid)['file_path']
        os.system("wget https://api.telegram.org/file/bot" + TOKEN + "/" +
                  filename + " -O " + filename)
        if ".mp3" in filename:
            audio = MP3(filename)
            length = audio.info.length * 0.33
            l2 = (audio.info.length * 0.33) + 60
        if ".m4a" in filename:
            audio = MP4(filename)
            length = audio.info.length * 0.33
            l2 = (audio.info.length * 0.33) + 60
        if audio.info.length > l2:
            os.system(
                "ffmpeg -ss " + str(length) + " -t 60 -y -i " + filename +
                " -strict -2 -ac 1 -map 0:a -codec:a opus -b:a 128k -vn output.ogg"
            )
        else:
            os.system(
                "ffmpeg -ss 0 -t 60 -y -i " + filename +
                " -strict -2 -ac 1 -map 0:a -codec:a opus -b:a 128k -vn output.ogg"
            )
        sendVoice(chat_id, "output.ogg")
Пример #5
0
def see_every_content_types(msg):
    global expected_content_type, content_type_iterator

    flavor = telepot.flavor(msg)

    if flavor == 'normal':
        content_type, chat_type, chat_id = telepot.glance2(msg)
        from_id = msg['from']['id']

        if chat_id != USER_ID and from_id != USER_ID:
            print 'Unauthorized user:'******'Message')
        try:
            if content_type == expected_content_type:
                expected_content_type = content_type_iterator.next()
                bot.sendMessage(chat_id,
                                'Please give me a %s.' % expected_content_type)
            else:
                bot.sendMessage(
                    chat_id, 'It is not a %s. Please give me a %s, please.' %
                    (expected_content_type, expected_content_type))
        except StopIteration:
            # reply to sender because I am kicked from group already
            bot.sendMessage(from_id, 'Thank you. I am done.')

    else:
        raise telepot.BadFlavor(msg)
Пример #6
0
def handle(msg):
	flavor = telepot.flavor(msg)

	if flavor == 'normal':
		bot.sendMessage(chat_id,"Ok")
		print 'Normal message'

	elif flavor == 'inline_query':
		query_id, from_id, query_string = telepot.glance(msg, flavor='inline_query')
		print from_id
		if len(query_string)>=3:
			filelist=find(query_string) 

			#print filelist
			articles=[]
			id=0
			for filename in filelist:
				articles.append(InlineQueryResultArticle(id=filename, title=os.path.splitext(filename)[0], message_text=os.path.splitext(filename)[0]))
				id+=1
			
			print articles
			bot.answerInlineQuery(query_id, articles)

	elif flavor == 'chosen_inline_result':
		print  "chosen_inline_result"
		result_id, from_id, query_string = telepot.glance(msg, flavor='chosen_inline_result')
		print result_id
		print from_id
		f = open("mp3/"+ result_id, 'rb')
		#bot.sendDocument(from_id,f)
		bot.sendMessage(from_id,"Ok")
Пример #7
0
    def on_message(self, msg):
        flavor = telepot.flavor(msg)
        self._counts[flavor] += 1

        # Display message counts separated by flavors
        print(
            self.id, ':', flavor, '+1', ':', ', '.join([
                str(self._counts[f])
                for f in ['chat', 'inline_query', 'chosen_inline_result']
            ]))

        # Have to answer inline query to receive chosen result
        if flavor == 'inline_query':

            def compute_answer():
                query_id, from_id, query_string = telepot.glance(msg,
                                                                 flavor=flavor)

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

                return articles

            self._answerer.answer(msg, compute_answer)
Пример #8
0
    def on_message(self, msg):
        self._count += 1
        flavor = telepot.flavor(msg)

        print('%s %d: %d: %s: %s' %
              (type(self).__name__, self.id, self._count, flavor,
               telepot.glance(msg, flavor=flavor)))
Пример #9
0
def handle(msg):
    flavor = telepot.flavor(msg)

    summary = telepot.glance(msg, flavor=flavor)

    # we expect a file
    if summary[0] == 'document':
        file_name = msg['document']['file_name']
        if file_name[:3] != 'csv' or file_name[-3:] != 'zip':
            return

        print("Got baby feeding data file")
        file_info = bot.getFile(msg['document']['file_id'])

        url = 'https://api.telegram.org/file/bot{}/{}'.format(TOKEN, file_info['file_path'])

        resp = requests.get(url)

        with open(file_name, 'wb') as f:
            f.write(resp.content)

        extract_folder = extract_file(file_name)

        # predict(extract_folder)
        chart(extract_folder, msg['from']['id'])

        os.remove(file_name)
Пример #10
0
    def on_chat_message(self, msg):

        try:
            flavor = telepot.flavor(msg)

            # inline query test code...
            # Have to answer inline query to receive chosen result
            log.info('flavor : %s', flavor)
            if flavor == 'inline_query':
                log.info('inline query!!')
                query_id, from_id, query_string = telepot.glance(msg,
                                                                 flavor=flavor)
                log.info('Inline Query: id:%s, from:%d, msg:%s', query_id,
                         from_id, query_string)

                articles = [{
                    'type': 'article',
                    'id': 'abc',
                    'title': 'ABC',
                    'message_text': 'Good morning'
                }]
                self.bot.answerInlineQuery(query_id, articles)
                return

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

            log.info("ContentType : '%s'", content_type)
            log.info("chat_type : '%s'", chat_type)
            log.info("chat_id : %d", chat_id)

            # Message to Log Write
            self.PrintMsg(msg)

            # Valid User Check
            if not chat_id in self.valid_user:
                log.info("Invalid user : %d", chat_id)
                return

            log.debug("chat_type:'%s'", chat_type)
            if chat_type == 'group':
                groupMsg = self.group_command_handler(unicode(msg['text']),
                                                      chat_id)
                log.info("Group Message : %s", groupMsg)
                return

            if content_type is 'text':
                self.command_handler(unicode(msg['text']), chat_id)
                log.info(msg['text'])
                return

            if content_type is 'document':
                file_name = msg['document']['file_name']
                file_id = msg['document']['file_id']
                file_ext = os.path.splitext(file_name)
                file_type = msg['document']['mime_type']
                self.file_handler(file_name, file_id, file_ext[1], file_type,
                                  chat_id)
                return
        except Exception, e:
            log.error(e, exc_info=True)
Пример #11
0
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)
    path = '/home/alman/telegram_bot'
    url = re.findall(
        'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',
        input_text)
    url = str(url)
    url = url.replace('[', '')
    url = url.replace("'", '')
    url = url.replace(']', '')
    print(url)
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])
        bot.getUpdates
        files = os.listdir(path)
        for file in files:
            if ".mp3" in file:
                url = "https://api.telegram.org/bot%s/sendAudio" % (TOKEN)
                files = {'audio': open(file, 'rb')}
                data = {'chat_id': chat_id}
                r = requests.post(url, files=files, data=data)
                print(r.status_code, r.reason, r.content)
                os.remove(file)
Пример #12
0
def answer(msg):
    flavor = telepot.flavor(msg)

    if flavor == 'inline_query':
        query_id, from_id, query = telepot.glance2(msg, flavor=flavor)

        if from_id != USER_ID:
            print 'Unauthorized user:'******'InlineQuery')
        
        articles = [InlineQueryResultArticle(
                       id='abc', title='HK', message_text='Hong Kong', url='https://www.google.com', hide_url=True),
                   InlineQueryResultArticle(
                       id='def', title='SZ', message_text='Shenzhen', url='https://www.yahoo.com')]

        photos = [InlineQueryResultPhoto(
                      id='123', photo_url='https://core.telegram.org/file/811140934/1/tbDSLHSaijc/fdcc7b6d5fb3354adf', thumb_url='https://core.telegram.org/file/811140934/1/tbDSLHSaijc/fdcc7b6d5fb3354adf'),
                  {'type': 'photo',
                      'id': '345', 'photo_url': 'https://core.telegram.org/file/811140184/1/5YJxx-rostA/ad3f74094485fb97bd', 'thumb_url': 'https://core.telegram.org/file/811140184/1/5YJxx-rostA/ad3f74094485fb97bd', 'caption': 'Caption', 'title': 'Title', 'message_text': 'Message Text'}]
        """"           
        gifs = [InlineQueryResultGif(
                    id='ghi', gif_url='http://www.animalstown.com/animals/g/gnu/coloring-pages/gnu-color-page-6.gif', thumb_url='http://www.animalstown.com/animals/g/gnu/coloring-pages/gnu-color-page-6.gif'),
                {'type': 'gif',
                    'id': 'jkl', 'gif_url': 'http://img2.colorirgratis.com/gnu-na-savana-africana_49d5b597bc78d-p.gif', 'thumb_url': 'http://img2.colorirgratis.com/gnu-na-savana-africana_49d5b597bc78d-p.gif'}]
        """
#                   InlineQueryResultVideo(
#                       id='jkl', video_url='', mime_type='')

        results = random.choice([articles, photos])

        bot.answerInlineQuery(query_id, results, cache_time=20, is_personal=True, next_offset='5')
    else:
        raise telepot.BadFlavor(msg)
Пример #13
0
def callback_function(msg):
    flavor = telepot.flavor(msg)
    if flavor == 'callback_query':
        print "callback!!"
    elif flavor == 'chat':
        print "normal message"
        return
Пример #14
0
def handle(msg):
    flavor = telepot.flavor(msg)

    # a normal message
    if flavor == 'normal':
        content_type, chat_type, chat_id = telepot.glance2(msg)
        print content_type, chat_type, chat_id

        # Do your stuff according to `content_type` ...

    # an inline query - only AFTER `/setinline` has been done for the bot.
    elif flavor == 'inline_query':
        query_id, from_id, query_string = telepot.glance2(msg, flavor=flavor)
        print 'Inline Query:', query_id, from_id, query_string

        # Compose your own answers
        articles = [{'type': 'article',
                        'id': 'abc', 'title': 'ABC', 'message_text': 'Good morning'}]

        bot.answerInlineQuery(query_id, articles)

    # a chosen inline result - only AFTER `/setinlinefeedback` has been done for the bot.
    elif flavor == 'chosen_inline_result':
        result_id, from_id, query_string = telepot.glance2(msg, flavor=flavor)
        print 'Chosen Inline Result:', result_id, from_id, query_string

        # Remember the chosen answer to do better next time

    else:
        raise telepot.BadFlavor(msg)
Пример #15
0
def handle(msg):
    flavor = telepot.flavor(msg)

    # normal message
    if flavor == 'normal':
        content_type, chat_type, chat_id = telepot.glance(msg)
        print 'Normal Message:', content_type, chat_type, chat_id

        # Do your stuff according to `content_type` ...

    # inline query - need `/setinline`
    elif flavor == 'inline_query':
        query_id, from_id, query_string = telepot.glance(msg, flavor=flavor)
        print 'Inline Query:', query_id, from_id, query_string

        # Compose your own answers
        articles = [{
            'type': 'article',
            'id': 'abc',
            'title': 'ABC',
            'message_text': 'Good morning'
        }]

        bot.answerInlineQuery(query_id, articles)

    # chosen inline result - need `/setinlinefeedback`
    elif flavor == 'chosen_inline_result':
        result_id, from_id, query_string = telepot.glance(msg, flavor=flavor)
        print 'Chosen Inline Result:', result_id, from_id, query_string

        # Remember the chosen answer to do better next time

    else:
        raise telepot.BadFlavor(msg)
Пример #16
0
def see_every_content_types(msg):
    global expected_content_type, content_type_iterator

    flavor = telepot.flavor(msg)
    
    if flavor == 'normal':
        content_type, chat_type, chat_id = telepot.glance(msg)
        from_id = msg['from']['id']

        if chat_id != USER_ID and from_id != USER_ID:
            print 'Unauthorized user:'******'Message')
        try:
            if content_type == expected_content_type:
                expected_content_type = content_type_iterator.next()
                bot.sendMessage(chat_id, 'Please give me a %s.' % expected_content_type)
            else:
                bot.sendMessage(chat_id, 'It is not a %s. Please give me a %s, please.' % (expected_content_type, expected_content_type))
        except StopIteration:
            # reply to sender because I am kicked from group already
            bot.sendMessage(from_id, 'Thank you. I am done.')

    else:
        raise telepot.BadFlavor(msg)
Пример #17
0
def process_msg(msg):
    flavor = telepot.flavor(msg)
    if flavor == 'callback_query':
        process_callback(msg)
    elif flavor == 'chat' and is_start_cmd(msg):
        chat_id = msg['chat']['id']
        bot.sendMessage(chat_id, START_MSG, reply_markup=get_days_keyboard())
Пример #18
0
    def handle(self, msg):
        flavor = telepot.flavor(msg)

        # normal message
        if flavor == 'normal':
            content_type, chat_type, chat_id = telepot.glance2(msg)
            print('Normal Message:', content_type, chat_type, chat_id)

            # Do your stuff according to `content_type` ...

        # inline query - need `/setinline`
        elif flavor == 'inline_query':
            query_id, from_id, query_string = telepot.glance2(msg, flavor=flavor)
            print('Inline Query:', query_id, from_id, query_string)

            # Compose your own answers
            articles = [{'type': 'article',
                            'id': 'abc', 'title': 'ABC', 'message_text': 'Good morning'}]

            bot.answerInlineQuery(query_id, articles)

        # chosen inline result - need `/setinlinefeedback`
        elif flavor == 'chosen_inline_result':
            result_id, from_id, query_string = telepot.glance2(msg, flavor=flavor)
            print('Chosen Inline Result:', result_id, from_id, query_string)

            # Remember the chosen answer to do better next time

        else:
            raise telepot.BadFlavor(msg)
Пример #19
0
def handle(msg):

    txt = str(msg['text']).lower().replace(';', ' ')
    print str(msg)

    if txt.startswith("snap"):
        cmd.runAndReturn(cmd.getCommand(txt.split(' ')[0]))
        sendImage()
        return

    elif cmd.getCommand(txt):
        print "Nao conheco a palavra " + str(cmd.getCommand(
            txt)) + " envie ajuda para conhecer os comando possiveis"
        if len(txt.split(' ')) > 1:
            bot.sendMessage(
                msg['from']['id'],
                cmd.runAndReturn(
                    cmd.getCommand(txt.split(' ')[0]) + ' ' +
                    txt.split(' ')[1]))
        else:
            bot.sendMessage(msg['from']['id'],
                            cmd.runAndReturn(cmd.getCommand(txt)))

    else:
        print "Comando nao encontrado: " + str(txt)
        bot.sendMessage(msg['from']['id'],
                        "Comando nao encontrado " + str(txt))

    flavor = telepot.flavor(msg)
    summary = telepot.glance(msg, flavor=flavor)
    print flavor, summary
Пример #20
0
def handle(msg):
    flavor = telepot.flavor(msg)

    # normal message
    if flavor == "normal":
        content_type, chat_type, chat_id = telepot.glance(msg)
        print "Normal Message:", content_type, chat_type, chat_id

        # Do your stuff according to `content_type` ...

    # inline query - need `/setinline`
    elif flavor == "inline_query":
        query_id, from_id, query_string = telepot.glance(msg, flavor=flavor)
        print "Inline Query:", query_id, from_id, query_string

        # Compose your own answers
        articles = [{"type": "article", "id": "abc", "title": "ABC", "message_text": "Good morning"}]

        bot.answerInlineQuery(query_id, articles)

    # chosen inline result - need `/setinlinefeedback`
    elif flavor == "chosen_inline_result":
        result_id, from_id, query_string = telepot.glance(msg, flavor=flavor)
        print "Chosen Inline Result:", result_id, from_id, query_string

        # Remember the chosen answer to do better next time

    else:
        raise telepot.BadFlavor(msg)
Пример #21
0
def handle_msg(msg):
    flavor = telepot.flavor(msg)
    # print(flavor)
    pprint(msg)
    if flavor == "normal":
        content_type, chat_type, chat_id = telepot.glance(msg, flavor)
        if content_type != "text":
            return
        msgText = msg["text"].strip()
        for plugin in arconfig.plugins:
            scan = scanRegex(plugin.regex, msgText)
            if scan is not None:
                ans = plugin.handler(bot, scan, msg, flavor)
                if ans is not None:
                    bot.sendMessage(chat_id, ans, reply_to_message_id=msg["message_id"], parse_mode="Markdown",
                                    disable_web_page_preview=False)
                    # print(content_type, chat_type, chat_id)

    elif flavor == "inline_query":
        query_id, from_id, query_string = telepot.glance(msg, flavor)
        for plugin in arconfig.plugins:
            groups = scanRegex(plugin.regexInline, query_string)
            if groups:
                ans = plugin.handler(bot, groups, msg, flavor)
                if ans is not None:
                    bot.answerInlineQuery(query_id, ans)
Пример #22
0
    def handle(self, msg):
        flavor = telepot.flavor(msg)
        if flavor != "chat":
            return

        text, chat_id = None, None

        try:
            content_type, chat_type, chat_id = telepot.glance(msg)
            text = msg['text']
        except:
            return
        else:
            if content_type != "text":
                return

        if text == '/start':
            show_keyboard = {'keyboard': [['/server', '/password']]}
            bot.sendMessage(chat_id, 'Server or Password? http://www.vpnbook.com/#pptpvpn', reply_markup=show_keyboard)

        elif text == '/server':
            for server in SERVERS:
                bot.sendMessage(chat_id, server)

        elif text == '/password':
            with urllib.request.urlopen("http://www.vpnbook.com") as url:
            	html = str(url.read())
            
            pwd = self.find_between(html, "Password: "******"</strong>")
            bot.sendMessage(chat_id, pwd)
Пример #23
0
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    flavor = telepot.flavor(msg)
    print(content_type, chat_type, chat_id, flavor)
    text = msg['text']
    print('\n* Question:', text, ' *')
    if (content_type == 'text'):
        atts = []
        atts = text.split()
        init = atts[0]
        if (init == '/start'):
            answer = initMessage()
        else:
            answer = ''
            op = validateMessage(chat_id, init)

        if (atts[0] == '/start'):
            answer = initMessage()
        elif (atts[0] == 'conv' or atts[0] == 'Conv'):
            answer = base_conv.main(atts[1], int(atts[2]), int(atts[3]))
        elif (atts[0] == 'clima' or atts[0] == 'Clima'):
            answer = weatherMod.getWeather(atts[1])
        elif (atts[0] == 'hora' or atts[0] == 'Hora'):
            answer = timeMod.getCoord(atts[1])
        elif (atts[0] == 'help' or atts[0] == 'Help'):
            answer = helpPage.getHelp(atts[1])


#=====================================================================#

        print('\n*Reply:', answer, '*\n')
        bot.sendMessage(chat_id, answer)
        print('=========================')
Пример #24
0
async def handle(msg):
    flavor = telepot.flavor(msg)
    content_type, chat_type, chat_id = telepot.glance(msg, flavor=flavor)
    print("content_type: {}, chat_type: {}, chat_id: {}, flavor {}".format(
        content_type, chat_type, chat_id, flavor))
    if content_type == 'text':
        await bot.sendMessage(chat_id, msg['text'])
Пример #25
0
    def post(self, request, token):

        try:
            raw = request.body.decode('utf8')
            logging.debug('Telegram raw data %s' % raw)
            update = json.loads(raw)
            if 'message' in update:
                data = message = update['message']
            elif 'callback_query' in update:
                data = update['callback_query']
                message = data['message']
            else:
                logging.error('Can not recognize update {}', update)
                raise TypeError('Not supported')

            current_user = get_telegram_from_seed(message)
            sender = Sender('telegram', current_user.user_id)
            bot = Bot(current_user, sender)
        except (TypeError, ValueError) as e:
            logging.exception("Can not decode message")
            return HttpResponse('Error')

        if token != settings.TELEGRAM_BOT_TOKEN:
            sender = Sender('telegram', current_user.user_id)
            sender.sendMessage('Our bot migrated to @{}'.format(
                settings.TELEGRAM_BOT_NAME),
                               token=token)
            return HttpResponse('ok')

        try:
            flavor = telepot.flavor(data)
            if flavor == 'chat':
                text = message.get('text', '') or message.get(
                    'contact', {}).get('phone_number')
                if not text:
                    return HttpResponse('ok')

                bot.on_chat_message(text)
            elif flavor == 'callback_query':
                msg_id = (data['from']['id'], data['message']['message_id'])
                query_id, from_id, query_data = telepot.glance(
                    data, flavor='callback_query')
                sender.msg_id = msg_id
                sender.query_id = query_id

                data = json.loads(query_data) if query_data else None
                if not data:
                    return HttpResponse('ok')

                bot.on_callback(data)
        except Exception:
            logging.exception('Error on handling bot message')
            try:
                sender.sendMessage('❌❌❌❌❌ Internal error',
                                   reply_markup=bot.get_menu())
            except Exception:
                logging.exception('Error on handling bot message error')

        return HttpResponse('ok')
Пример #26
0
 async def on_chat_message(self, msg):
     flavor = telepot.flavor(msg)
     content_type, chat_type, chat_id = telepot.glance(msg, flavor=flavor)
     print(
         "content_type: {}, chat_type: {}, chat_id: {}, flavor: {}".format(
             content_type, chat_type, chat_id, flavor))
     if content_type == 'text':
         await self.sender.sendMessage(msg['text'])
Пример #27
0
def handle(msg):
    # pprint(msg)

    if telepot.flavor(msg) == 'chat':
        content_type, chat_type, chat_id = telepot.glance(msg)
        # print(content_type, chat_type, chat_id, sep=" ")
        # text
        # private  私人的
        # 用户id 591197749
        if msg['text'] == '/food':
            bot.sendMessage(chat_id, 'hamburger')
        elif msg['text'] == '/drink':
            bot.sendMessage(chat_id, 'coke zero')
        elif msg['text'] == '/start1':  # custom keyboard
            keyboard1 = [['McFlurry'], ['Nugget'], ['Coke'], ['Fries']]

            mark_up = ReplyKeyboardMarkup(keyboard=keyboard1,
                                          one_time_keyboard=True)

            text = 'What would you like to order?'

            bot.sendMessage(chat_id, text, reply_markup=mark_up)
        elif msg['text'] == '/start2':  # inline keyboard
            # menu = ['Nugget', 'McFlurry', 'Coke', 'Fries']
            menu = [('McFlurry', 'McFlurry'), ('Nugget', 'Nugget'),
                    ('Coke', 'Coke'), ('Fries', 'Fries')]
            kb = []
            for t in menu:
                kb.append(
                    [InlineKeyboardButton(text=t[0], callback_data=t[1])])
            mark_up = InlineKeyboardMarkup(inline_keyboard=kb,
                                           one_time_keyboard=True)
            bot.sendMessage(chat_id,
                            'What would you like to order?',
                            reply_markup=mark_up)

            # print(msg)

        else:
            bot.sendMessage(chat_id, msg['text'])
    elif telepot.flavor(msg) == 'callback_query':
        query_id, from_id, query_data = telepot.glance(msg,
                                                       flavor='callback_query')
        bot.answerCallbackQuery(query_id, text='Sold out!')
        bot.answerCallbackQuery(query_id, text='You have ordered' + query_data)
Пример #28
0
def handle(msg):
    flavor = telepot.flavor(msg)

    summary = telepot.glance(msg, flavor=flavor)
    print(flavor, summary)

    chat_id = msg['chat']['id']
    command = msg['text']
    bot.sendMessage(chat_id, "haha")
Пример #29
0
    def __init__(self, seed_tuple, timeout, flavors='all'):
        bot, initial_msg, seed = seed_tuple
        super(UserHandler, self).__init__(bot, seed, initial_msg['from']['id'])
        self.listener.set_options(timeout=timeout)

        if flavors == 'all':
            self.listener.capture(from__id=self.user_id)
        else:
            self.listener.capture(_=lambda msg: telepot.flavor(msg) in flavors, from__id=self.user_id)
Пример #30
0
def handle(msg):

    print("Got message: " + str(msg))
    flavor = telepot.flavor(msg)

    # The message is chat. Easy enough.
    if flavor == "chat":
        # Get the Message Content Information from the Message.
        content_type, chat_type, chat_id = telepot.glance(msg)

        # This message is a chat event (sent by a user).
        if content_type == 'text':
            # Is this a command?
            if AwooUtils.isCommand(msg):
                # Parse some information from the message, and get it ready.
                cmd, params = AwooUtils.parseCommand(msg['text'])
                user_id = AwooUtils.getUserID(msg)
                username = AwooUtils.getUsername(msg)

                # Create the Arguments packet. Commands may pick and choose what parameters
                # they want to use from this.
                args = {'chat_id': chat_id,
                        'params': params,
                        'user_id': user_id,
                        'chat_type': chat_type,
                        'username': username,
                        'message': msg}
                try:
                    # Run a command from the CommandManager, if it exists
                    COMMANDS.execute(BOT, cmd, args)

                except Exception:
                    e = sys.exc_info()[0]
                    # Report the fact that the command failed to run, and notify the Developers.
                    BOT.sendMessage(chat_id,
                                    "[Error] Could not run command. The developers have been notified and are being beaten savagely for their mistake.")
                    for i in SUPERUSERS:
                        BOT.sendMessage(i,
                                        r"\[DEV] Internal Error. Trace:\n\n```" + traceback.format_exc(e) + "```",
                                        "Markdown")
                    # Print the stack trace.
                    traceback.print_exc()

        # A new Chat Member has been added!
        elif content_type == 'new_chat_member':
            AwooChat.newUserWatchdog(msg, chat_id)
            
        elif content_type == 'left_chat_member':
            if msg['left_chat_participant']['id'] == AwooUtils.getBotID():
                # Debug
                for i in SUPERUSERS:
                    BOT.sendMessage(i, "WolfBot was kicked from chat " + str(msg['chat']['title']))
                PREFS.purgeChat(msg['chat']['id'])

        # Check if the title exists.
        elif content_type == 'new_chat_title':
            AwooChat.titleWatchdog(msg)
Пример #31
0
    def handle(self, msg):

        if 'migrate_to_chat_id' in msg:
            yield from self.onSupergroupUpgradeCallback(self, msg)

        else:
            flavor = telepot.flavor(msg)

            if flavor == "chat":  # chat message
                content_type, chat_type, chat_id = telepot.glance(msg)
                if content_type == 'text':
                    if TelegramBot.is_command(msg):  # bot command
                        cmd, params = TelegramBot.parse_command(msg['text'])
                        user_id = TelegramBot.get_user_id(msg)
                        args = {'params': params, 'user_id': user_id, 'chat_type': chat_type}
                        if cmd in self.commands:
                            yield from self.commands[cmd](self, chat_id, args)
                        else:
                            if self.config['be_quiet']:
                                pass
                            else:
                                comebacks = [
                                    'Can\'t toast that: {cmd}',
                                ]
                                shuffle(comebacks)
                                yield from self.sendMessage(chat_id, comebacks[0].format(cmd=cmd))

                    else:  # plain text message
                        yield from self.onMessageCallback(self, chat_id, msg)

                elif content_type == 'location':
                    yield from self.onLocationShareCallback(self, chat_id, msg)

                elif content_type == 'new_chat_member':
                    yield from self.onUserJoinCallback(self, chat_id, msg)

                elif content_type == 'left_chat_member':
                    yield from self.onUserLeaveCallback(self, chat_id, msg)

                elif content_type == 'photo':
                    yield from self.onPhotoCallback(self, chat_id, msg)

                elif content_type == 'sticker':
                    if 'enable_sticker_sync' in tg_bot.ho_bot.config.get_by_path(['telesync']):
                        if tg_bot.ho_bot.config.get_by_path(['telesync'])['enable_sticker_sync']:
                            yield from self.onStickerCallback(self, chat_id, msg)

            elif flavor == "inline_query":  # inline query e.g. "@gif cute panda"
                query_id, from_id, query_string = telepot.glance(msg, flavor=flavor)
                print("inline_query")

            elif flavor == "chosen_inline_result":
                result_id, from_id, query_string = telepot.glance(msg, flavor=flavor)
                print("chosen_inline_result")

            else:
                raise telepot.BadFlavor(msg)
Пример #32
0
def handle(msg):
    if telepot.flavor(msg) == 'callback_query':
        logger.info("Callback query processing:")
        logger.info(msg)
        logger.info(' by ' + str(msg['from']['id']))
        user = User.objects.get(telegram_id=msg['from']['id'])
        callbacks[msg['data'].split('_')[0]].handle(msg, user)
    elif telepot.flavor(msg) == 'chat' and telepot.glance(msg)[0] == 'text':
        content_type, chat_type, chat_id = telepot.glance(msg)
        logger.info("Message processing:")
        logger.info(msg)
        logger.info(content_type + ' by ' + str(msg['from']['id']))
        try:
            user = User.objects.get(telegram_id=msg['from']['id'])
        except User.DoesNotExist:
            User.create(telegram_id=msg['from']['id'])
        else:
            user.get_state().handle(user, msg['text'])
Пример #33
0
    def __init__(self, seed_tuple, timeout, flavors='all'):
        bot, initial_msg, seed = seed_tuple
        super(UserHandler, self).__init__(bot, seed, initial_msg['from']['id'])
        self.listener.set_options(timeout=timeout)

        if flavors == 'all':
            self.listener.capture(from__id=self.user_id)
        else:
            self.listener.capture(_=lambda msg: telepot.flavor(msg) in flavors, from__id=self.user_id)
Пример #34
0
    def handle(self, msg):

        if 'migrate_to_chat_id' in msg:
            yield from self.onSupergroupUpgradeCallback(self, msg)

        else:
            flavor = telepot.flavor(msg)

            if flavor == "chat":  # chat message
                content_type, chat_type, chat_id = telepot.glance(msg)
                if content_type == 'text':
                    if TelegramBot.is_command(msg):  # bot command
                        cmd, params = TelegramBot.parse_command(msg['text'])
                        user_id = TelegramBot.get_user_id(msg)
                        args = {'params': params, 'user_id': user_id, 'chat_type': chat_type}
                        if cmd in self.commands:
                            yield from self.commands[cmd](self, chat_id, args)
                        else:
                            if self.config['be_quiet']:
                                pass
                            else:
                                yield from self.sendMessage(chat_id, "Unknown command: {cmd}".format(cmd=cmd))

                    elif TelegramBot.is_blacklisted_word(self, msg['text']):
                        pass

                    else:  # plain text message
                        yield from self.onMessageCallback(self, chat_id, msg)

                elif content_type == 'location':
                    yield from self.onLocationShareCallback(self, chat_id, msg)

                elif content_type == 'new_chat_member':
                    yield from self.onUserJoinCallback(self, chat_id, msg)

                elif content_type == 'left_chat_member':
                    yield from self.onUserLeaveCallback(self, chat_id, msg)

                elif content_type == 'photo':
                    yield from self.onPhotoCallback(self, chat_id, msg)

                elif content_type == 'sticker':
                    if 'enable_sticker_sync' in tg_bot.ho_bot.config.get_by_path(['telesync']):
                        if tg_bot.ho_bot.config.get_by_path(['telesync'])['enable_sticker_sync']:
                            yield from self.onStickerCallback(self, chat_id, msg)

            elif flavor == "inline_query":  # inline query e.g. "@gif cute panda"
                query_id, from_id, query_string = telepot.glance(msg, flavor=flavor)
                print("inline_query")

            elif flavor == "chosen_inline_result":
                result_id, from_id, query_string = telepot.glance(msg, flavor=flavor)
                print("chosen_inline_result")

            else:
                raise telepot.BadFlavor(msg)
 def handle(self, msg):
     try:
         my_logger.debug("COMMAND: " + str(msg))
         flavor = telepot.flavor(msg)
         if flavor == 'chat':
             content_type, chat_type, chat_id = telepot.glance(msg)
             my_logger.info("Chat message: " + content_type + " - Type: " + chat_type + " - ID: " + str(chat_id) + " - Command: " + msg['text'])
             # verifico se l'utente da cui ho ricevuto il comando è censito
             user_exist = False
             for u in MyIPCameraBot_config.users:
                 if u is None:
                     break
                 if u['telegram_id'] == str(chat_id):
                     user_exist = True
                     my_logger.debug("Check userID " + u['telegram_id'] + ": user exist...")
             # se l'utente non è censito, abortisco
             # questo controllo è per evitare che le risposte dei messaggi
             # vadano a richiedenti non abilitati
             if user_exist == False:
                 my_logger.info("User NOT exist!!!")
                 return None
             # seleziono il tipo di comando da elaborare
             if msg['text'] == '/help':
                 self.__comm_help(chat_id)
             elif msg['text'] == '/start':
                 self.__comm_help(chat_id)
             elif msg['text'] == '/jpg':
                 self.__comm_jpg(chat_id)
             elif msg['text'] == '/status':
                 self.__comm_status(chat_id)
             elif msg['text'] == '/motion':
                 self.__comm_motion(chat_id)
             elif msg['text'] == 'Motion Detection OFF':
                 self.__comm_motion_detection(chat_id, msg["from"]["first_name"], 0)
             elif msg['text'] == 'Motion Detection ON':
                 self.__comm_motion_detection(chat_id, msg["from"]["first_name"], 1)
             elif msg['text'] == '/night':
                 self.__comm_night(chat_id)
             elif msg['text'] == 'IR Automatic':
                 self.__comm_night_IR(chat_id, 0)
             elif msg['text'] == 'IR On':
                 self.__comm_night_IR(chat_id, 2)
             elif msg['text'] == 'IR Off':
                 self.__comm_night_IR(chat_id, 3)
             elif msg['text'] == '/rep':
                 self.__comm_rep(chat_id)
             elif msg['text'] == 'Clear repository':
                 self.__comm_rep_clear(chat_id)
             elif msg['text'] == 'Cancel':
                 self.__comm_rep_cancel(chat_id)
             else:
                 self.__comm_nonCapisco(chat_id)
         else:
             raise telepot.BadFlavor(msg)
     except:
         my_logger.exception("Unable to parse command: " + str(sys.exc_info()[0]))
Пример #36
0
    def handler(self, msg):
        flav = telepot.flavor(msg)

        if flav is 'chat':
            self.command_router.route(msg)
        elif flav is 'callback_query':
            self.__callbackQueryCmd(msg)
            self.bot.answerCallbackQuery(msg['id'])
        else:
            print("Default")
Пример #37
0
def handle(msg):
    flavor = telepot.flavor(msg)

    if flavor == 'inline_query':
        # Just dump inline query to answerer
        answerer.answer(msg)

    elif flavor == 'chosen_inline_result':
        result_id, from_id, query_string = telepot.glance(msg, flavor=flavor)
        print('Chosen Inline Result:', result_id, from_id, query_string)
Пример #38
0
 async 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)
Пример #39
0
    def on_message(self, msg):
        flavor = telepot.flavor(msg)

        if flavor == 'inline_query':
            # Just dump inline query to answerer
            self._answerer.answer(msg)

        elif flavor == 'chosen_inline_result':
            result_id, from_id, query_string = telepot.glance(msg, flavor=flavor)
            print(self.id, ':', 'Chosen Inline Result:', result_id, from_id, query_string)
Пример #40
0
def handle(msg):
    flavor = telepot.flavor(msg)

    if flavor == 'inline_query':
        # Just dump inline query to answerer
        answerer.answer(msg)

    elif flavor == 'chosen_inline_result':
        result_id, from_id, query_string = telepot.glance(msg, flavor=flavor)
        print('Chosen Inline Result:', result_id, from_id, query_string)
Пример #41
0
    def on_message(self, msg):
        self._count += 1
        flavor = telepot.flavor(msg)

        print "%s %d: %d: %s: %s" % (
            type(self).__name__,
            self.id,
            self._count,
            flavor,
            telepot.glance2(msg, flavor=flavor),
        )
Пример #42
0
def flow(msg):
    flavor = telepot.flavor(msg)
    logger.info(f'Flavor: {flavor} - Message: {msg}')

    if flavor == 'chat':
        if msg['text'].startswith('/'):  # Check if it is a command
            process_cmd(msg)
        else:
            process_text(msg)
    elif flavor == 'callback_query':
        process_callback(msg)
Пример #43
0
def answer(msg):
    flavor = telepot.flavor(msg)

    if flavor == "inline_query":
        query_id, from_id, query = telepot.glance2(msg, flavor=flavor)

        if from_id != USER_ID:
            print "Unauthorized user:"******"InlineQuery")

        articles = [
            InlineQueryResultArticle(
                id="abc", title="HK", message_text="Hong Kong", url="https://www.google.com", hide_url=True
            ),
            {"type": "article", "id": "def", "title": "SZ", "message_text": "Shenzhen", "url": "https://www.yahoo.com"},
        ]

        photos = [
            InlineQueryResultPhoto(
                id="123",
                photo_url="https://core.telegram.org/file/811140934/1/tbDSLHSaijc/fdcc7b6d5fb3354adf",
                thumb_url="https://core.telegram.org/file/811140934/1/tbDSLHSaijc/fdcc7b6d5fb3354adf",
            ),
            {
                "type": "photo",
                "id": "345",
                "photo_url": "https://core.telegram.org/file/811140184/1/5YJxx-rostA/ad3f74094485fb97bd",
                "thumb_url": "https://core.telegram.org/file/811140184/1/5YJxx-rostA/ad3f74094485fb97bd",
                "caption": "Caption",
                "title": "Title",
                "message_text": "Message Text",
            },
        ]

        results = random.choice([articles, photos])

        bot.answerInlineQuery(query_id, results)

    elif flavor == "chosen_inline_result":
        result_id, from_id, query = telepot.glance2(msg, flavor=flavor)

        if from_id != USER_ID:
            print "Unauthorized user:"******"ChosenInlineResult")

        print "Chosen inline query:"
        pprint.pprint(msg)

    else:
        raise telepot.BadFlavor(msg)
Пример #44
0
def handle(blob):
	flavor = telepot.flavor(blob)
	if flavor == 'chat':
		content_type, chat_type, chat_id = telepot.glance(blob)
		print (content_type, chat_type, chat_id)
		if content_type == 'text':
			smartReply(blob['text'], blob['from']['id'])
	elif flavor == 'inline_query':
		query_id, from_id, query_string = telepot.glance(blob, flavor='inline_query')
		print ('Inline query:', query_id, from_id, query_string)
	pprint(blob)
Пример #45
0
def handle(msg):
    flavor = telepot.flavor(msg)
    chat_id = msg['chat']['id']
    command = msg['text']
    sender = msg['from']
    msg_date = msg['date']
    actual_date = time.time()

    summary = telepot.glance(msg, flavor=flavor)

    if command.lower().startswith('/pokemap'):
        if command.count(' ') >= 1:
            # printing info
            print('Sender: ', sender)
            print('Command: ', command)
            print('Msg date: ', msg_date)
            print('Act date: ', actual_date)
            if msg_date+1 > actual_date:
                # saving the location into a variable
                locTemp = command.split(' ', 1)
                location = locTemp[1]
                # running the shell command
                os.system('python PokemonGo-Map-develop/runserver.py -a ptc -u %s -p %s -l "%s" -st %s -H %s -P %s >mapstd.txt 2>maperr.txt &' % (USER, PASS, location, STEP, HOST, PORT))
                # let the map load a minute
                bot.sendMessage(chat_id, 'Wait a minute...')
                time.sleep(60)
                # initializing the page
                driver = webdriver.PhantomJS()
                driver.set_window_size(1024, 1024)
                driver.get('http://%s:%s' % (HOST, PORT))
                # let the page load
                time.sleep(5)
                # save a screenshot
                driver.save_screenshot('loc.png')
                # kill the map
                os.system('pkill -f runserver.py')
                os.system('pkill -f node')
                os.system('pkill -f phantomjs')
                # send the screenshot
                bot.sendChatAction(chat_id, 'upload_photo')
                bot.sendPhoto(chat_id, open('loc.png', 'rb'), caption=location)
            else:
                bot.sendMessage(chat_id, 'I\'m now avaiable')
        else:
            bot.sendMessage(chat_id, 'Correct syntax is "/pokemap location"')

    elif command.lower().startswith('/start'):
        bot.sendMessage(chat_id, 'Hi!')

    elif command.lower().startswith('/help'):
        bot.sendMessage(chat_id,    'To get the map of a location with nearby Pokémon, just type\n' \
                                    '/pokemap followed by the desired location\n\n' \
                                    'Sources can be found here https://github.com/robbcocco/PokemonGo-Map-forTelegram', disable_web_page_preview=True)
Пример #46
0
    def handle(self, msg):
        flavor = telepot.flavor(msg)

        msg_type, chat_type, chat_id = telepot.glance(msg, flavor=flavor)

        if msg_type == "text":
            commands = self.parse_commands(msg)
            if commands:
                for command in commands:
                    self.handle_command(chat_id, command)
            else:
                print json.dumps(msg)
Пример #47
0
    def on_chat_message(self, msg):

        try:
            flavor = telepot.flavor(msg)

            # inline query test code...
            # Have to answer inline query to receive chosen result
            log.info('flavor : %s', flavor)
            if flavor == 'inline_query':
                log.info('inline query!!')
                query_id, from_id, query_string = telepot.glance(msg, flavor=flavor)
                log.info('Inline Query: id:%s, from:%d, msg:%s', query_id, from_id, query_string)

                articles = [{'type': 'article',
                                 'id': 'abc', 'title': 'ABC', 'message_text': 'Good morning'}]
                self.bot.answerInlineQuery(query_id, articles)
                return

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

            log.info("ContentType : '%s'", content_type)
            log.info("chat_type : '%s'", chat_type)
            log.info("chat_id : %d", chat_id)

            # Message to Log Write
            self.PrintMsg(msg)

            # Valid User Check
            if not chat_id in self.valid_user:
                log.info("Invalid user : %d", chat_id)
                return

            log.debug("chat_type:'%s'", chat_type)
            if chat_type == 'group':
                groupMsg = self.group_command_handler(unicode(msg['text']), chat_id)
                log.info("Group Message : %s", groupMsg)
                return


            if content_type is 'text':
                self.command_handler(unicode(msg['text']), chat_id)
                log.info(msg['text'])
                return

            if content_type is 'document':
                file_name = msg['document']['file_name']
                file_id = msg['document']['file_id']
                file_ext = os.path.splitext(file_name)
                file_type = msg['document']['mime_type']
                self.file_handler(file_name, file_id, file_ext[1], file_type, chat_id)
                return
        except Exception, e:
            log.error(e, exc_info=True)
Пример #48
0
    async def display(self, reply, data, msg):
        keyboard = []
        next_page = data and data.get('next_page') or None
        previous_page = data and data.get('prev_page') or None
        image = data and data.get('image') or None

        if previous_page:
            keyboard.append(
                InlineKeyboardButton(text='prev {}'.format(previous_page),
                                     callback_data='previous'))
        if next_page:
            keyboard.append(
                InlineKeyboardButton(text='next {}'.format(next_page),
                                     callback_data='next'))
        if data.get('result'):
            keyboard.append(
                InlineKeyboardButton(text='view', callback_data='image'))
            keyboard.append(
                InlineKeyboardButton(
                    text='delete', callback_data='this_is_delete_intent_key'))
        if image:
            await self.bot.sendPhoto(msg['message']['chat']['id'], image)
            return data

        markup = keyboard and InlineKeyboardMarkup(
            inline_keyboard=[keyboard]) or None
        if telepot.flavor(msg) == 'callback_query' and not image:
            c, m = msg['message']['chat']['id'], msg['message']['message_id']
            try:
                await self.bot.editMessageText((c, m),
                                               reply,
                                               reply_markup=markup,
                                               parse_mode='HTML')
            except Exception as e:
                print(e)
            return data

        content_type, chat_type, chat_id = telepot.glance(msg)
        last_id = data.get('last_query_id')
        last_markup = data.get('last_query_markup')
        pages = next_page or previous_page
        if last_id and last_markup and pages:
            await self.bot.editMessageReplyMarkup((last_id[0], last_id[1]),
                                                  reply_markup=None)
        # response = await self.bot.sendMessage(chat_id, reply, reply_markup=markup)
        response = await self.bot.sendMessage(chat_id,
                                              reply,
                                              reply_markup=markup,
                                              parse_mode='HTML')
        data['last_query_id'] = [chat_id, response['message_id']]
        data['last_query_markup'] = markup and True or False
        return data
Пример #49
0
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)
Пример #50
0
def handle(msg):
    global users
    load_users()
    try:
        f = telepot.flavor(msg)
        if f == "chat":
            chat_handle(msg)
        if f == "callback_query":
            callback_handle(msg)
        if f == "inline_query":
            inline_handle(msg)
    finally:
        save_users()
Пример #51
0
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)
Пример #52
0
    def handle(self, msg):
        flavor = telepot.flavor(msg)

        # a normal message
        if flavor == 'normal':
            content_type, chat_type, chat_id = telepot.glance2(msg)
            print(content_type, chat_type, chat_id)

            # Do your stuff according to `content_type` ...

        # an inline query - possible only AFTER `/setinline` has been done for the bot.
        elif flavor == 'inline_query':
            query_id, from_id, query_string = telepot.glance2(msg, flavor=flavor)
            print(query_id, from_id, query_string)
Пример #53
0
    def on_message(self, msg):
        flavor = telepot.flavor(msg)
        self._counts[flavor] += 1

        print(self.id, ':', self._counts)

        # Have to answer inline query to receive chosen result
        if flavor == 'inline_query':
            query_id, from_id, query_string = telepot.glance(msg, flavor=flavor)

            articles = [{'type': 'article',
                             'id': 'abc', 'title': 'ABC', 'message_text': 'Good morning'}]

            self.bot.answerInlineQuery(query_id, articles)
Пример #54
0
    def handle(self, msg):
        flavor = telepot.flavor(msg)
        msg_text = ""
        articles = [{'type': 'article',
                    'id': 'abc', 'title': 'ABC', 'message_text': 'Good morning'}]

        # normal message
        if flavor == 'normal':
            content_type, chat_type, chat_id = telepot.glance(msg)
            try:
#                msg_data = json.loads(msg)
                if (len(msg)):
                    msg_text = msg["text"]
                    cmdArray = string.rsplit(msg_text,' ')
                    command = cmdArray[0]
                    if (len(command)):
                        print ("command: "+command)
                        if (command == "/getdevvals"):
                            ssn_cmd = '===ssn10001000502003b{"ssn":{"v":1,"obj":1,"cmd":"getdevvals", "data": {"g":1}}}968f'
                            self.sendSsnCommand(msg = ssn_cmd, obj_id = 1)
 
            except Exception as ex:
                print("Cannot decode JSON object, msg={}: {}".format(msg,ex))

            print('Normal Message:', content_type, chat_type, chat_id)
	    self.bot.sendMessage(chat_id, msg_text)
#        show_keyboard = {'keyboard': [['Yes','No'], ['Maybe','Maybe not']]}
#        bot.sendMessage('-123873656', 'This is a custom keyboard', reply_markup=show_keyboard)

        # inline query - need `/setinline`
        elif flavor == 'inline_query':
            query_id, from_id, query_string = telepot.glance(msg, flavor=flavor)
            print('Inline Query:', query_id, from_id, query_string)
            self.bot.answerInlineQuery(query_id, articles)

    # Do your stuff according to `content_type` ...
        # chosen inline result - need `/setinlinefeedback`
        elif flavor == 'chosen_inline_result':
            result_id, from_id, query_string = telepot.glance(msg, flavor=flavor)
            print('Chosen Inline Result:', result_id, from_id, query_string)

        # Remember the chosen answer to do better next time

        else:
            raise telepot.BadFlavor(msg)

        # Compose your own answers

        print (msg)
Пример #55
0
def handle(msg):
    flavor = telepot.flavor(msg)
    # normal message
    if flavor == 'normal':
        content_type, chat_type, chat_id = telepot.glance2(msg)
        print('Normal Message:', content_type, chat_type, chat_id)
        command = msg['text']
        if command == '/start':
        	start(chat_id)
        elif command == '/eagles':
        	news_command_handler(chat_id, 'eagles')
        elif command == '/flyers':
        	news_command_handler(chat_id, 'flyers')
        elif command == '/sixers':
        	news_command_handler(chat_id, 'sixers')
        elif command == '/phillies':
        	news_command_handler(chat_id, 'phillies')
        elif command == '/help':
        	help(chat_id)
        elif command == '/settings':
        	settings(chat_id)
        else:
        	unknown(chat_id)

        return('Message sent')

        # Do your stuff according to `content_type` ...

    # inline query - need `/setinline`
    elif flavor == 'inline_query':
        query_id, from_id, query_string = telepot.glance2(msg, flavor=flavor)
        print('Inline Query:', query_id, from_id, query_string)

        # Compose your own answers
        articles = [{'type': 'article',
                        'id': 'abc', 'title': 'ABC', 'message_text': 'Good morning'}]

        bot.answerInlineQuery(query_id, articles)

    # chosen inline result - need `/setinlinefeedback`
    elif flavor == 'chosen_inline_result':
        result_id, from_id, query_string = telepot.glance2(msg, flavor=flavor)
        print('Chosen Inline Result:', result_id, from_id, query_string)

        # Remember the chosen answer to do better next time

    else:
        raise telepot.BadFlavor(msg)
Пример #56
0
    def handle(self, msg):

        if "migrate_to_chat_id" in msg:
            yield from self.onSupergroupUpgradeCallback(self, msg)

        else:
            flavor = telepot.flavor(msg)

            if flavor == "chat":  # chat message
                content_type, chat_type, chat_id = telepot.glance(msg)
                if content_type == "text":
                    if TelegramBot.is_command(msg):  # bot command
                        cmd, params = TelegramBot.parse_command(msg["text"])
                        user_id = TelegramBot.get_user_id(msg)
                        args = {"params": params, "user_id": user_id, "chat_type": chat_type}
                        if cmd in self.commands:
                            yield from self.commands[cmd](self, chat_id, args, cmd)
                        else:
                            if self.config["be_quiet"]:
                                pass
                            else:
                                yield from self.sendMessage(chat_id, "Unknown command: {cmd}".format(cmd=cmd))

                    else:  # plain text message
                        yield from self.onMessageCallback(self, chat_id, msg)

                elif content_type == "location":
                    yield from self.onLocationShareCallback(self, chat_id, msg)

                elif content_type == "new_chat_member":
                    yield from self.onUserJoinCallback(self, chat_id, msg)

                elif content_type == "left_chat_member":
                    yield from self.onUserLeaveCallback(self, chat_id, msg)

                elif content_type == "photo":
                    yield from self.onPhotoCallback(self, chat_id, msg)

            elif flavor == "inline_query":  # inline query e.g. "@gif cute panda"
                query_id, from_id, query_string = telepot.glance(msg, flavor=flavor)
                print("inline_query")

            elif flavor == "chosen_inline_result":
                result_id, from_id, query_string = telepot.glance(msg, flavor=flavor)
                print("chosen_inline_result")

            else:
                raise telepot.BadFlavor(msg)
Пример #57
0
def handle(msg):
    actual_date = time.time()
    flavor = telepot.flavor(msg)
    chat_id = msg['chat']['id']
    command = msg['text']
    sender = msg['from']
    msg_date = msg['date']

    summary = telepot.glance(msg, flavor=flavor)

    if command.lower().startswith('/pokemap'):
        if command.count(' ') >= 1:
            # print info
            print('Sender: ', sender)
            print('Command: ', command)
            print('Msg date: ', msg_date)
            print('Act date: ', actual_date)
            # avoid old messages
            if actual_date-msg_date < 3:
                # save the location into a variable
                locTemp = command.split(' ', 1)
                location = locTemp[1]
                # run the shell command
                #os.system('python2.7 PokemonGo-Map-develop/runserver.py -a ptc -u %s -p %s -l "%s" -st %s -H %s -P %s >mapstd.txt 2>maperr.txt &' % (USER, PASS, location, STEP, HOST, PORT))
                os.system('python2.7 PokemonGo-Map-1.0/example.py -a ptc -u %s -p %s -l "%s" -st %s -H %s -P %s >mapstd.txt 2>maperr.txt &' % (USER, PASS, location, STEP, HOST, PORT))
                # let the map load a minute
                bot.sendMessage(chat_id, 'Wait a minute...')
                time.sleep(60)
                # initialize the page
                driver = webdriver.PhantomJS()
                driver.set_window_size(1024, 1024)
                driver.get('http://%s:%s' % (HOST, PORT))
                # let the page load
                time.sleep(3)
                # save a screenshot
                driver.save_screenshot('loc.png')
                # kill the map
                #os.system('pkill -f runserver.py')
                os.system('pkill -f example.py')
                os.system('pkill -f node')
                os.system('pkill -f phantomjs')
                # send the screenshot
                bot.sendChatAction(chat_id, 'upload_photo')
                bot.sendPhoto(chat_id, open('loc.png', 'rb'), caption=location)
            else:
                bot.sendMessage(chat_id, 'I\'m now avaiable')
        else:
            bot.sendMessage(chat_id, 'Correct syntax is "/pokemap location"')
Пример #58
0
    def on_chat_message(self, msg):

        if telepot.flavor(msg) == 'chat':
            content_type, chat_type, chat_id = telepot.glance(msg)

            response = chatbot.get_response(msg['text'])

            if (len(response.text) > 1500):
                aux = response.text.split("\n")

                for tex in aux:
                    self.sender.sendMessage(tex)

            else:

                self.sender.sendMessage(response.text)
Пример #59
0
    def handle(self, msg):
        flavor = telepot.flavor(msg)

        if flavor == "normal":  # normal message
            content_type, chat_type, chat_id = telepot.glance2(msg)
            if content_type == 'text':
                if TelegramBot.is_command(msg):  # bot command
                    cmd, params = TelegramBot.parse_command(msg['text'])
                    user_id = TelegramBot.get_user_id(msg)
                    args = {
                        'params': params,
                        'user_id': user_id,
                        'chat_type': chat_type
                    }
                    if cmd in self.commands:
                        yield from self.commands[cmd](self, chat_id, args)
                    else:
                        yield from self.sendMessage(
                            chat_id, "Unknown command: {cmd}".format(cmd=cmd))

                else:  # plain text message
                    yield from self.onMessageCallback(self, chat_id, msg)

            elif content_type == 'location':
                yield from self.onLocationShareCallback(self, chat_id, msg)

            elif content_type == 'new_chat_participant':
                yield from self.onUserJoinCallback(self, chat_id, msg)

            elif content_type == 'left_chat_participant':
                yield from self.onUserLeaveCallback(self, chat_id, msg)

            elif content_type == 'photo':
                yield from self.onPhotoCallback(self, chat_id, msg)

        elif flavor == "inline_query":  # inline query e.g. "@gif cute panda"
            query_id, from_id, query_string = telepot.glance2(msg,
                                                              flavor=flavor)
            print("inline_query")

        elif flavor == "chosen_inline_result":
            result_id, from_id, query_string = telepot.glance2(msg,
                                                               flavor=flavor)
            print("chosen_inline_result")

        else:
            raise telepot.BadFlavor(msg)