Ejemplo n.º 1
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)
Ejemplo n.º 2
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)
Ejemplo n.º 3
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)
Ejemplo n.º 4
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")
Ejemplo n.º 5
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)
Ejemplo n.º 6
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)
Ejemplo n.º 7
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)
Ejemplo n.º 8
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)
Ejemplo n.º 9
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)
Ejemplo n.º 10
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)
Ejemplo n.º 11
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)
Ejemplo n.º 12
0
            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
Ejemplo n.º 13
0
    def on_message(self, msg):
        flavor = telepot.flavor(msg)

        if flavor == 'inline_query':
            query_id, from_id, query_string = telepot.glance(msg, flavor=flavor)
            print(self.id, ':', 'Inline Query:', query_id, from_id, query_string)

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

            self.bot.answerInlineQuery(query_id, articles)
            print(self.id, ':', 'Answers sent.')

        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)
Ejemplo n.º 14
0
def on_chat_message(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    print('Chat:', content_type, chat_type, chat_id)

    if content_type != 'text':
        return

    command = msg['text'][-1:].lower()

    if command == 'c':
        markup = ReplyKeyboardMarkup(keyboard=[
                     ['Plain text', KeyboardButton(text='Text only')],
                     [dict(text='Phone', request_contact=True), KeyboardButton(text='Location', request_location=True)],
                 ])
        yield from bot.sendMessage(chat_id, 'Custom keyboard with various buttons', reply_markup=markup)
    elif command == 'i':
        markup = InlineKeyboardMarkup(inline_keyboard=[
                     [dict(text='Telegram URL', url='https://core.telegram.org/')],
                     [InlineKeyboardButton(text='Callback - show notification', callback_data='notification')],
                     [dict(text='Callback - show alert', callback_data='alert')],
                     [InlineKeyboardButton(text='Callback - edit message', callback_data='edit')],
                     [dict(text='Switch to using bot inline', switch_inline_query='initial query')],
                 ])

        global message_with_inline_keyboard
        message_with_inline_keyboard = yield from bot.sendMessage(chat_id, 'Inline keyboard with various buttons', reply_markup=markup)
    elif command == 'h':
        markup = ReplyKeyboardHide()
        yield from bot.sendMessage(chat_id, 'Hide custom keyboard', reply_markup=markup)
    elif command == 'f':
        markup = ForceReply()
        yield from bot.sendMessage(chat_id, 'Force reply', reply_markup=markup)
Ejemplo n.º 15
0
    def on_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance(msg)

        if hasattr(self, content_type):
            return getattr(self, content_type)(msg)

        self.unknown(msg);
Ejemplo n.º 16
0
def handle(msg):
    welcome="welcome!\nwith this bot u can downloder any yuotube video in mp3 format.\ncan u get me a youtube url and file name?"
    benvenuto = "ciao\n con questo bot puoi scaricare video da yt in formato mp3. iviami il link yt + il nome file\nNON SI ACCETTANO SPAZI!"
    content_type, chat_type, chat_id, = telepot.glance(msg)
    print (msg)

    with open('/home/makerfra/Documents/yt_bot/log/log.txt', 'w') as infile:
        infile.write(str(msg))

    if content_type == 'text':
        cmd = msg['text'].split()

        if cmd[0] == '/start':
            bot.sendMessage(chat_id, welcome)
            bot.sendMessage(chat_id, benvenuto)

        else:
            yt_opts['outtmpl'] = path + cmd[1]+".mp3"
            try:
                with yt.YoutubeDL(yt_opts) as ydl:
                    ydl.download([cmd[0]])
                    bot.sendAudio(chat_id, open(path + cmd[1]+".mp3", 'rb'))
                    print("send file...")
                    os.remove(path+cmd[1]+'.mp3')
                    print("file deleded...")
            except Exception as error:
                bot.sendMessage(chat_id, "error...")
                print(error)
Ejemplo n.º 17
0
    def compute_answer():
        query_id, from_id, query_string = telepot.glance(msg, flavor='inline_query')
        print('Computing for: %s' % query_string)

        articles = [{'type': 'article',
                         'id': 'abc', 'title': query_string, 'message_text': query_string}]
        return articles
Ejemplo n.º 18
0
    async def on_callback_query(self, msg):
        query_id, from_id, query_data = glance(msg, flavor='callback_query')

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

        self._answer = await self._show_next_question()
Ejemplo n.º 19
0
def msg_cb(self, msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    print("content_type, chat_type, chat_id", content_type, chat_type, chat_id)

    k = telegram.Keyboard()
    if content_type == 'location':
        print("location", msg['location'])
        k.hide_keyboard()
        self.bot.sendMessage(chat_id, **k.get_message_params("Got it!"))

    elif content_type == 'text' and "🏠 Go home" == msg['text']:
        k.hide_keyboard()
        self.bot.sendMessage(chat_id, **k.get_message_params('Welcome home'))

    # Youtube-dl
    #
    elif content_type == 'text' and "/youtube-dl " in msg['text']:
        tmp = re.findall(r'(http.+?)(?:s|$)', msg['text'], re.M)
        if tmp:
            telegram.send_video(chat_id, tmp[0])
            k.hide_keyboard()
            self.bot.sendMessage(chat_id, **k.get_message_params('youtube-dl'))

    elif content_type == 'text' and 'http' in msg['text']:
        tmp = re.findall(r'(http.+?)(?:s|$)', msg['text'], re.M)
        if tmp:
            url = tmp[0]
            if any([d in url for d in telegram.youtube_dl_sites]):
                k.add("🎞 /youtube-dl \n" + tmp[0])
                k.add("🏠 Go home", callback_data="home")
                self.bot.sendMessage(chat_id, **k.get_message_params('Sent'))

    """
Ejemplo n.º 20
0
def on_chat_message(msg):

    content_type, chat_type, chat_id = telepot.glance(msg)
    logging.info('content type: %s, chat type: %s, chat id: %s',
            content_type, chat_type, chat_id)

    if content_type != 'text':
        sendMessage(chat_id, "Only text!")

    rcv_msg = msg['text']
    command = rcv_msg.split(' ')

    if command[0] == '/1':
        res_list = get_apt_rent(command)
    elif command[0] == '/2':
        res_list = get_ty()
    else:
        bot_help(chat_id)
        return

    if (len(res_list) == 0):
        sendMessage(chat_id, "No result")
    else:
        for res in res_list:
            sendMessage(chat_id, res)
    return
Ejemplo n.º 21
0
        def compute_answer():
            query_id, from_id, query_string = telepot.glance(msg, flavor="inline_query")
            print(self.id, ":", "Inline Query:", query_id, from_id, query_string)

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

            return articles
Ejemplo n.º 22
0
def handle_bot_message(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    user = msg["from"]
    uid = msg["from"]["id"]
    if chat_type == 'private':
        sprint('Private message from {}({})'.format(user, uid))
        return
    if content_type == "text":
        text = msg["text"]
        sprint("Group message from {} ({}): {}".format(user, uid, text))
        send_mail(msg)
    elif content_type in ['audio', 'document', 'photo', 'sticker', 'video', 'voice']:
        with tempfile.TemporaryDirectory() as tmpdir:
            if content_type == 'photo':
                file_id = msg['photo'][-1]['file_id']
                sprint("Got Photo from {} ({}): {}".format(user, uid, file_id))
                bot.download_file(file_id, tmpdir+'/photo')
                msg["photo"] = tmpdir+'/photo'
                send_mail(msg)
            else:
                file_id = msg[content_type]['file_id']
                sprint("Got some content ({}) from {} ({}): {}".format(content_type, user, uid, file_id))
                bot.download_file(msg[content_type]['file_id'], tmpdir+'/file')
                msg[content_type] = tmpdir+'/file'
                send_mail(msg)
    elif content_type in ['new_chat_member', 'left_chat_member']:
        new_msg = {"from": msg[content_type]}
        new_msg["text"] = "*tschüss*" if content_type == 'left_chat_member' else "*hallo*"
        send_mail(new_msg)
Ejemplo n.º 23
0
def on_inline_query(msg):
    def compute():
        articles = [InlineQueryResultArticle(
                       id='abc', title='HK', input_message_content=InputTextMessageContent(message_text='Hong Kong'), url='https://www.google.com', hide_url=True),
                   {'type': 'article',
                       'id': 'def', 'title': 'SZ', 'input_message_content': {'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', 'input_message_content': {'message_text': 'Shenzhen'}}]

        games = [InlineQueryResultGame(
                    id='abc', game_short_name='sunchaser')]

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

    query_id, from_id, query = telepot.glance(msg, flavor='inline_query')

    if from_id != USER_ID:
        print('Unauthorized user:', from_id)
        return

    examine(msg, InlineQuery)
    answerer.answer(msg, compute)
Ejemplo n.º 24
0
    def compute():
        query_id, from_id, query_string = telepot.glance(msg, flavor='inline_query')
        print('Computing for: %s' % query_string)

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

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

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

        if result_type == 'a':
            return articles
        elif result_type == 'p':
            return photos
        else:
            results = articles if random.randint(0,1) else photos
            if result_type == 'b':
                return dict(results=results, switch_pm_text='Back to Bot', switch_pm_parameter='Optional start parameter')
            else:
                return dict(results=results)
Ejemplo n.º 25
0
def handle(msg):
    global last_report, report_interval

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

    # ignore non-text message
    if msg_type != 'text':
        return

    # only respond to one user
    if chat_id != USER_ID:
        return

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

    if command == '/now':
        read_send(chat_id)
    elif command == '/1m':
        read_send(chat_id)
        last_report = time.time()
        report_interval = 60    # report every 60 seconds
    elif command == '/1h':
        read_send(chat_id)
        last_report = time.time()
        report_interval = 3600  # report every 3600 seconds
    elif command == '/cancel':
        last_report = None
        report_interval = None  # clear periodic reporting
        bot.sendMessage(chat_id, "OK")
    else:
        bot.sendMessage(chat_id, "I don't understand")
def handle(msg):
    
    content_type, chat_type, chat_id = telepot.glance(msg)
    name=msg['from']['first_name']
    print msg
    if content_type=="text":
        command=msg['text']
        print 'Got command: %s'% command
    else:
        print content_type
        command=""
    pprint(msg)
    
    if command=='/start':
        bot.sendMessage(chat_id,"Hi "+name+",welcome to song downloader.Please send the song name and artist name in chat box.For example 'hello adele'")
    elif command=="":
        bot.sendMessage(chat_id,"Invalid command!Please enter the song and artist name to download song")
    else:
        if flag==1:
            bot.sendMessage(chat_id,"Server busy.Please try after 2-4 minutes.Sorry for inconvenience caused.")
            print "rejected"
        else:
            print "Debug1"
            query=command
            Id=getVidId(query)
            url=BASE_URL+Id
            print url
            content=urllib2.urlopen(url).read()
            json_data=json.loads(content)
            down_link=json_data['link']
            global title1
            title1=json_data['title']

            mp3send(down_link,chat_id)
Ejemplo n.º 27
0
Archivo: bot.py Proyecto: XayOn/katcr
 def on_callback_query(self, msg):
     """Get the button data."""
     _, from_id, query_data = telepot.glance(msg, flavor='callback_query')
     key, value = self.responses[from_id][int(query_data)]
     href = "<a href=\"{}\">{}</a>".format(
         get_short(self.shortener, value), key)
     self.sendMessage(from_id, href, parse_mode="html")
Ejemplo n.º 28
0
def handle(msg):
  content_type, chat_type, chat_id = telepot.glance(msg)
  print(content_type, chat_type, chat_id)

  lock.acquire()
  print(' lock acquired')

  #t_fm_db = sqlite3.connect("fm.db")
  #t_fm_cur = t_fm_db.cursor()

  if (content_type == 'text'):
    message_words = msg['text'].strip().lower().split()

    if (msg['text'][0] != "/"):
      return
    else:
      if (message_words[0] == "/start" and chat_type == 'private'):
        tgram_start(msg)
      elif (message_words[0].replace("/addfm@lastfm_channel_bot", "/addfm") == "/addfm"):
        tgram_addfm(msg)
      elif (message_words[0].replace("/rmfm@lastfm_channel_bot", "/rmfm") == "/rmfm"):
        tgram_rmfm(msg)
      elif (message_words[0].replace("/help@lastfm_channel_bot", "/help") == "/help"):
        tgram_help(msg)
      elif (message_words[0].replace("/github@lastfm_channel_bot", "/github") == "/github"):
        tgram_sauce(msg)

  fm_db.commit()

  #t_fm_db.commit()
  #t_fm_db.close()

  lock.release()
  print(" lock released")
Ejemplo n.º 29
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)
Ejemplo n.º 30
0
def callback(message, matches, chat_id):
    query_id, from_id, data = telepot.glance(message, flavor='callback_query')
    if data == "/help":
        res = show_help(0)
        if len(public_plugins) > 10:
            res.append([InlineKeyboardButton(text='Next Plugins ▶️', callback_data='/helpn 1')])
        markup = InlineKeyboardMarkup(inline_keyboard=res)
        msgid = (chat_id, message['message']['message_id'])
        return Message(from_id).edit_message(msgid, "Welcome to DaniRobo\nSelect One of these Items.",
                                             parse_mode="Markdown",
                                             reply_markup=markup)
    elif "/helpn" in data:
        num = int(matches)
        res = show_help(num)
        if len(public_plugins) > (num + 1) * 10 and num != 0:
            res.append([InlineKeyboardButton(text='◀️ Last Plugins', callback_data='/helpn ' + str(num - 1)),
                        InlineKeyboardButton(text='Next Plugins ▶️', callback_data='/helpn ' + str(num + 1))])
        elif len(public_plugins) > (num + 1) * 10:
            res.append([InlineKeyboardButton(text='Next Plugins ▶️', callback_data='/helpn ' + str(num + 1))])
        elif num != 0:
            res.append([InlineKeyboardButton(text='◀ Last Plugins', callback_data='/helpn ' + str(num - 1))])
        markup = InlineKeyboardMarkup(inline_keyboard=res)
        msgid = (chat_id, message['message']['message_id'])
        return Message(from_id).edit_message(msgid, "Welcome to Siarobo\nSelect One of these Items.",
                                             parse_mode="Markdown",
                                             reply_markup=markup)
    elif matches:
        tokenize = matches.split("--")
        matches = tokenize[0]
        markup = InlineKeyboardMarkup(
            inline_keyboard=[[InlineKeyboardButton(text='Return', callback_data='/helpn ' + tokenize[1])]])
        msgid = (chat_id, message['message']['message_id'])
        return Message(from_id).edit_message(msgid, show_shelp(matches), parse_mode="Markdown", reply_markup=markup)
Ejemplo n.º 31
0
def handle(msg):
    sender_id = msg['chat']['id']
    msg_recieved = msg['text']
    content_type, chat_type, chat_id = telepot.glance(msg)
    if content_type == 'text':
        text_message(msg_recieved, sender_id, msg)
Ejemplo n.º 32
0
def on_chat_message(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)

    vorname = msg['from']['first_name']
    username = msg['from']['username']
    id = msg['from']['id']
    msg['text'] = msg['text'].lower()

    keyboard = ""

    # print(msg['text'])
    print(msg)

    if msg['text'] in [
            "/start", "/start start", "start", "hallo", "Hallo", "Hi", "Start"
    ]:
        bot.sendMessage(chat_id, _("welcome") + " " + botcall + " " + vorname + "!" + \
            "\n" + _("toget_help_write_/help"))

    elif msg['text'] in ["/help", "hilfe", "help", "/hilfe"]:
        hilfetext = _("info_commands") + "\n" + "/status " + _("status_help") + "\n" + "/help " + _("help_help") + "\n" + \
             "/tg " + _("tg_help") + "\n" + "/lh " + _("lh_help") + "\n" + "/lh CALL " + _("lh_CALL_help")
        if id in grant:
            hilfetext += "\n\n" + "/gpio " + _(
                "gpio_help") + "\n" + "/sw " + _(
                    "sw_help") + "\n" + "/svx " + _("svx_help")
        bot.sendMessage(chat_id, botcall + " " + hilfetext)

    elif msg['text'] in ["/tg"]:
        bot.sendMessage(chat_id, talkgroups())

    elif "/lh" in msg['text']:
        if msg['text'] == "/lh":
            heard = lastheard('')
            bot.sendMessage(chat_id, heard)
        else:
            suche = msg['text'].split(" ")
            heard = lastheard(suche[1].upper())
            bot.sendMessage(chat_id, heard)

    ### BM Handle ###
    elif "/bm" in msg['text']:
        if id in grant:
            keyboard = InlineKeyboardMarkup(inline_keyboard=[
                [
                    InlineKeyboardButton(text=_('dropCallS1'),
                                         callback_data='/dropCallS1'),
                    InlineKeyboardButton(text=_('dropDynamicS1'),
                                         callback_data='/dropDynamicS1')
                ],
                [
                    InlineKeyboardButton(text=_('dropCallS2'),
                                         callback_data='/dropCallS2'),
                    InlineKeyboardButton(text=_('dropDynamicS2'),
                                         callback_data='/dropDynamicS2')
                ],
                [
                    InlineKeyboardButton(text=_('dropRepeater'),
                                         callback_data='/dropRepeater')
                ]
            ])

            bot.sendMessage(chat_id,
                            _('keyboard_software'),
                            reply_markup=keyboard)

    ### SVX Handle ###
    elif msg['text'] in ["/svx"]:
        if svxactive == 1:
            svxkey = InlineKeyboardMarkup(
                inline_keyboard=[[
                    InlineKeyboardButton(text=_('btn_start_svxlink'),
                                         callback_data='/startsvx'),
                    InlineKeyboardButton(text=_('btn_stop_svxlink'),
                                         callback_data='/killsvx')
                ],
                                 [
                                     InlineKeyboardButton(
                                         text=_('lh_echolink'),
                                         callback_data='/lhecho')
                                 ]])
            bot.sendMessage(chat_id,
                            _('keyboard_svxlink'),
                            reply_markup=svxkey)
            # dynamic section for logics
            btnlogic = [[
                InlineKeyboardButton(text=logic[0], callback_data=logic[0])
            ] for logic in svxlh]
            keyboard = InlineKeyboardMarkup(inline_keyboard=btnlogic)
            bot.sendMessage(chat_id,
                            _('keyboard_svxlink'),
                            reply_markup=keyboard)
            # dynamic section for DTMF-List
            buttons = [[
                InlineKeyboardButton(text=cmd[0], callback_data=cmd[1])
            ] for cmd in svxcommands]
            keyboard = InlineKeyboardMarkup(inline_keyboard=buttons)
            bot.sendMessage(chat_id,
                            _('keyboard_svxlink'),
                            reply_markup=keyboard)
        else:
            bot.sendMessage(chat_id, _("not_activ"))

    ### SW Handle ###
    elif msg['text'] in ["/sw"]:
        if id in grant:
            keyboard = InlineKeyboardMarkup(inline_keyboard=[
                [
                    InlineKeyboardButton(text=_('btn_start_mmdvm'),
                                         callback_data='/startmmdvm'),
                    InlineKeyboardButton(text=_('btn_stop_mmdvm'),
                                         callback_data='/killmmdvm')
                ],
                [
                    InlineKeyboardButton(text=_('btn_start_dmrgw'),
                                         callback_data='/startdmrgw'),
                    InlineKeyboardButton(text=_('btn_stop_dmrgw'),
                                         callback_data='/killdmrgw')
                ],
                [
                    InlineKeyboardButton(text=_('btn_start_ysfgw'),
                                         callback_data='/startysfgw'),
                    InlineKeyboardButton(text=_('btn_stop_ysfgw'),
                                         callback_data='/killysfgw')
                ],
                [
                    InlineKeyboardButton(text=_('btn_reboot'),
                                         callback_data='/reboot')
                ]
            ])
            bot.sendMessage(chat_id,
                            _('keyboard_software'),
                            reply_markup=keyboard)
        else:
            bot.sendMessage(chat_id, grantfehler)

    #### GPIO handle ####
    elif msg['text'] in ["/gpio"]:
        if gpioactive == 1:
            if id in grant:
                keyboard = []
                buttons = []
                on = _("on")
                off = _("off")
                buttons = [[
                    InlineKeyboardButton(text=gpo[1] + ' ' + on,
                                         callback_data=gpo[1] + "_on"),
                    InlineKeyboardButton(text=gpo[1] + ' ' + off,
                                         callback_data=gpo[1] + "_off")
                ] for gpo in gpioports]
                keyboard = InlineKeyboardMarkup(inline_keyboard=buttons)
                bot.sendMessage(chat_id, _('gpio'), reply_markup=keyboard)
                del keyboard, buttons
            else:
                bot.sendMessage(chat_id, grantfehler)
        else:
            bot.sendMessage(chat_id, _("not_activ"))

    elif msg['text'] in ["/testgw"]:
        testgwmc()

    elif msg['text'] in ["/status"]:
        status = ''
        # Eingänge lesen
        if gpioactive == 1:
            i = 0
            for gio in gpioports:
                if gpioports[i][2] == 0:
                    if GPIO.input(gio[0]) == GPIO.HIGH:
                        status += gio[1].upper() + " " + _("is_on") + "\n"
                    else:
                        status += gio[1].upper() + " " + _("is_off") + "\n"
                    i = i + 1
                elif gpioports[i][2] == 1:
                    if GPIO.input(gio[0]) == GPIO.HIGH:
                        status += gio[1].upper() + " " + _("is_off") + "\n"
                    else:
                        status += gio[1].upper() + " " + _("is_on") + "\n"
                    i = i + 1

        # Laufende Prozesse testen
        for proc in prozesse:
            status += "\n" + proc + " " + prozesschecker(proc)

        ## Temperaturen
        # CPU-Temperaturen auslesen
        tFile = open('/sys/class/thermal/thermal_zone0/temp')
        temp = float(tFile.read())
        tempC = temp / 1000
        status += "\n" + _("cpu_temp") + " " + str(round(tempC, 1)) + "°C"

        # read the sensors
        i = 0
        for row in sensors:
            status += '\n'
            status += read_sensor(sensors[i])
            i = i + 1

        bot.sendMessage(chat_id, status)

    elif msg['text'] in ["/reboot"]:
        if id in grant:
            bot.sendMessage(chat_id, _("rebooting_system"))
            os.system('sudo shutdown -r now')
        else:
            bot.sendMessage(chat_id, grantfehler)
    else:
        bot.sendMessage(
            chat_id,
            _("no_idea_command") + msg['text'] + " " + vorname + "!\n" +
            _("cmd_list_with /help."))

    # bot.sendMessage(chat_id, befehlsliste(id))
    initialkb(chat_id, id)
Ejemplo n.º 33
0
async def on_chat_message(msg):

    global answerData, lowerCountries

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

    #вписываем новый id в csv файл
    print(chat_id_str + ' может быть добавлен в список id')
    #

    with open('countrycap.log', 'a', encoding='utf8') as logFile:
        if content_type != 'text':
            return

        logFile.write('[' + strftime("%Y-%m-%d %H:%M:%S") + '][' +
                      chat_id_str + ' -> bot]: ' + msg['text'] + '\n')
        print('Chat:', content_type, chat_type, chat_id)
        print('Пльзователь ' + chat_id_str + ' написал:\n' +
              msg['text'].lower())
        request = msg['text']  #.lower()

        if request in ('/start', 'hi', 'help', 'привет', 'помоги мне',
                       'помощь', 'старт'):
            await bot.sendMessage(chat_id,
                                  answerData['welcome'])  #,reply_markup=rkh)
            logFile.write('[' + strftime("%Y-%m-%d %H:%M:%S") + '][bot -> ' +
                          chat_id_str + ']: ' + answerData['welcome'] + '\n')
            return
        elif request in ("тест"):
            testAnswers = ["Скопье", 'Тирана', 'Мапуту', 'Подгорица']
            inline_keyboard = []
            for a in range(len(testAnswers)):
                inline_keyboard.append([
                    InlineKeyboardButton(text=testAnswers[a],
                                         callback_data=testAnswers[a])
                ])
            ikm = InlineKeyboardMarkup(inline_keyboard=inline_keyboard)
            await bot.sendMessage(chat_id,
                                  'Выберете столицу Македонии:',
                                  reply_markup=ikm)
        elif request in answerData['countries'].keys():
            se = random.randint(0, 1)
            phraseNumber = random.randint(0, 4)
            if se == 0:
                add = answerData["addsToAnswer"]['start'][phraseNumber]
                await bot.sendMessage(chat_id,
                                      add + answerData['countries'][request])
                logFile.write('[' + strftime("%Y-%m-%d %H:%M:%S") +
                              '][bot -> ' + chat_id_str + ']: ' + add +
                              answerData['countries'][request] + '\n')
            else:
                add = answerData["addsToAnswer"]['end'][phraseNumber]
                await bot.sendMessage(
                    chat_id, answerData['countries'][request] + "." + add)
                logFile.write('[' + strftime("%Y-%m-%d %H:%M:%S") +
                              '][bot -> ' + chat_id_str + ']: ' +
                              answerData['countries'][request] + add + '\n')
            return
        elif request in lowerCountries:
            await bot.sendMessage(chat_id, answerData["lowCountryRequest"])
            logFile.write('[' + strftime("%Y-%m-%d %H:%M:%S") + '][bot -> ' +
                          chat_id_str + ']: ' +
                          answerData["lowCountryRequest"] + '\n')
            return
        elif request.lower() in ["хуй"]:
            await bot.sendMessage(chat_id, "Сам ты ХУЙ!")
            logFile.write('[' + strftime("%Y-%m-%d %H:%M:%S") + '][bot -> ' +
                          chat_id_str + ']: ' + "Сам ты ХУЙ!" + '\n')
            return
        else:
            await bot.sendMessage(chat_id, answerData['badRequest'])
Ejemplo n.º 34
0
def message_handler(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    if chat_type == u'private' and content_type == 'text':
        if 'entities' in msg and msg['entities'][0][
                'type'] == 'bot_command' and msg['text'][0] != '/':
            return
        user = get_user(chat_id)
        # print(get_user(chat_id).search_course(msg['text']))
        # print([course_to_str(c) for c in get_user(chat_id).search_course(msg['text'])])
        if msg['text'][0:4] == '/del':
            user.remove_course(msg['text'][4:])
            courses = user.get_courses()
            if len(courses) == 0:
                send_not_found_message(chat_id)
            else:
                messages = bot_messages_generator([
                    course_to_str(c) + '\n/del' + c['ident'] + '\n\n'
                    for c in courses
                ])
                for message in messages:
                    bot.sendMessage(chat_id, message)
            send_welcome_message(chat_id)
        elif msg['text'][0:4] == '/add':
            user.add_course(msg['text'][4:])
            bot.sendMessage(chat_id, 'با موفقیت ثبت شد')
            send_search_course_message(chat_id)
        elif user.menu_state == MenuState.GENERAL:
            if msg['text'] == 'انتخاب بخش':
                user.menu_state = MenuState.SELECT_DEPARTMENT
                send_select_department_message(chat_id)
            elif msg['text'] == 'جستجوی درس های بخش':
                user.menu_state = MenuState.SEARCH_COURSE
                send_search_course_message(chat_id)
            elif msg['text'] == 'درس های انتخاب شده':
                courses = user.get_courses()
                if len(courses) == 0:
                    send_not_found_message(chat_id)
                else:
                    messages = bot_messages_generator([
                        course_to_str(c) + '\n/del' + c['ident'] + '\n\n'
                        for c in courses
                    ])
                    for message in messages:
                        bot.sendMessage(chat_id, message)
            else:
                send_welcome_message(chat_id)

        elif user.menu_state == MenuState.SELECT_DEPARTMENT:

            if msg['text'] == 'بازگشت':
                user.menu_state = MenuState.GENERAL
                send_welcome_message(chat_id)

            elif msg['text'][0:4] == '/dep':
                user.dep_id = msg['text'][4:]
                bot.sendMessage(chat_id, 'با موفقیت ثبت شد')
                user.menu_state = MenuState.SEARCH_COURSE
                send_search_course_message(chat_id)

            else:
                departments = search_department(msg['text'])
                if len(departments) == 0:
                    send_not_found_message(chat_id)
                else:
                    messages = bot_messages_generator([
                        dep['title'] + ' ' + '/dep' + dep['id'] + '\n'
                        for dep in departments
                    ])
                    for message in messages:
                        bot.sendMessage(chat_id, message)

        elif user.menu_state == MenuState.SEARCH_COURSE:

            if msg['text'] == 'بازگشت':
                user.menu_state = MenuState.GENERAL
                send_welcome_message(chat_id)

            else:
                courses = user.search_course(msg['text'])
                if len(courses) == 0:
                    send_not_found_message(chat_id)
                else:
                    messages = bot_messages_generator([
                        course_to_str(c) + '\n/add' + c['ident'] + '\n\n'
                        for c in courses
                    ])
                    for message in messages:
                        bot.sendMessage(chat_id, message)
Ejemplo n.º 35
0
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="Ok!")
Ejemplo n.º 36
0
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    print(content_type, chat_type, chat_id)

    if content_type == 'text':
        text = msg['text']
        mode = text [:5]
        inputed_data = text[6:]
        print(msg['text'])

        ##이름검색자 시작.
        if '/name' in mode:
            worksheet = wb.get_sheet_by_name('총합')
            for row in range(2,worksheet.max_row+1):  
                for column in "B":  
                    cell_name = "{}{}".format(column, row)
                    worksheet[cell_name].value #여기 잠깐 고민좀(39-41)
            count = 0
            only_number = -1
            choice = []
            jchoice = '존재하지 않는 카드명 입니다.'
            for number in range(2,worksheet.max_row+1):
               	cell = "{}{}".format("B",number)
                if(inputed_data and (worksheet[cell].value).find(inputed_data) != -1):
                    print(worksheet[cell].value)
                    choice.append(str(worksheet[cell].value) + str("\n"))
                    count=count+1
                    only_number = number
                    jchoice = ''.join(choice)

            bot.sendMessage(chat_id, jchoice)

                    ##print((worksheet[cell_name].value).find(msg['text']))


            if(count == 1):
            	space = []
            	for alphabet in ['A','B','C','D','E','F','G','H','I','J']:
            		c = "{}{}".format(alphabet,only_number)
            		p = "{}{}".format(alphabet,1)
            		space.append(str(worksheet[p].value) + str("\t: ") + str(worksheet[c].value) + str("\n"))
            	jpnt = ''.join(space)
            	print(jpnt)
            	bot.sendMessage(chat_id, jpnt)


        #덱 검색자 시작.
        if '/deck' in mode:
            worksheet = wb.get_sheet_by_name('덱리')
            for row in range(2,worksheet.max_row+1):  
                for column in "A":  
                    cell_name = "{}{}".format(column, row)
                    worksheet[cell_name].value #여기 잠깐 고민좀(39-41)
            count = 0
            only_number = -1
            choice = []
            jchoice = '존재하지 않는 덱이름 입니다.'
            for number in range(2,worksheet.max_row+1):
                cell = "{}{}".format("A",number)
                if((worksheet[cell].value).find(inputed_data) != -1):
                    print(worksheet[cell].value)
                    choice.append(str(worksheet[cell].value) + str("\n"))
                    count=count+1
                    only_number = number
                    jchoice = ''.join(choice)

            bot.sendMessage(chat_id, jchoice)

                    ##print((worksheet[cell_name].value).find(msg['text']))


            if(count == 1):
                space = []
                for alphabet in ['B']:
                    c = "{}{}".format(alphabet,only_number)
                    p = "{}{}".format(alphabet,1)
                    space.append(str(worksheet[c].value) + str("\n"))
                jpnt = ''.join(space)
                print(jpnt)
                bot.sendMessage(chat_id, jpnt)



        #친선퀘 도둑 검색자 시작.
        if '/foxs' in mode:
            worksheet = wb.get_sheet_by_name('도둑')
            for row in range(2,worksheet.max_row+1):  
                for column in "A":  
                    cell_name = "{}{}".format(column, row)
                    worksheet[cell_name].value #여기 잠깐 고민좀(39-41)
            count = 0
            only_number = -1
            choice = []
            jchoice = '블랙리스트에 없습니다.'
            for number in range(2,worksheet.max_row+1):
                cell = "{}{}".format("A",number)

                if(inputed_data and (worksheet[cell].value).find(inputed_data) != -1):
                    print(worksheet[cell].value)
                    choice.append(str("\'")+str(inputed_data) + str("\'") + str("님이 블랙리스트에 있습니다!\n"))
                    count=count+1
                    only_number = number
                    jchoice = ''.join(choice)

            bot.sendMessage(chat_id, jchoice)
Ejemplo n.º 37
0
    def on_callback_query(self, msg):
        query_id, from_id, query_data = telepot.glance(msg,
                                                       flavor='callback_query')

        if self.get_domain() == -1:
            print('--->>>> ', query_id, from_id, query_data)
            self.set_domain(query_data)
            self.set_interaction_direction(-1)
        elif self.get_interaction_direction() == -1:
            print('--->>>> ', query_id, from_id, query_data)
            self.set_interaction_direction(int(query_data))
            if int(self.get_interaction_direction()) == 21:
                mode = "Ok go ahead and ask me something:"
                bot.sendMessage(from_id, mode)
            else:
                mode = "You have choosen: Enriching direction in " + str(
                    self.get_domain()) + " domain"
                bot.sendMessage(from_id, mode)
                x = babelnet.random_babelnet_id_in_domain(self.get_domain())
                print(x)
                lemmas = babelnet.db_search_terms(x)
                while lemmas == 0:
                    x = babelnet.random_babelnet_id_in_domain(
                        self.get_domain())
                    print(x)
                    lemmas = babelnet.db_search_terms(x)
                pprint.pprint(lemmas)
                dori = list()
                res = 0
                for lemma in lemmas:
                    g = db.search_by_field('c1', lemma)
                    dori.append(g)
                    res += len(g)

                if res > 0:
                    c = relation_to_ask(dori, babelnet.get_domain_relations())
                    print(c)
                    d, l = question_to_ask(c, lemmas[0],
                                           babelnet.get_relation_patterns(),
                                           babelnet.get_domain_relations(),
                                           self.get_domain())
                else:
                    c = 0
                    d, l = question_to_ask(c, lemmas[0],
                                           babelnet.get_relation_patterns(),
                                           babelnet.get_domain_relations(),
                                           self.get_domain())

                self.set_bot_question(d)
                self.set_lemma(lemmas[0])
                self.set_relation(l)

                bot.sendMessage(from_id, d)

        if self.get_interaction_direction() == -1:
            keyboard = InlineKeyboardMarkup(inline_keyboard=[[
                InlineKeyboardButton(text='You ask, I answer',
                                     callback_data='21'),
                InlineKeyboardButton(text='I ask, you help me learn',
                                     callback_data='22')
            ]])
            bot.sendMessage(from_id,
                            "Select direction:",
                            reply_markup=keyboard)
Ejemplo n.º 38
0
    def on_chat_message(self, msg):
        # Imprimir en consola mensaje recibido
        print('Mensaje recibido:')
        pprint(msg)

        # Obtener info basica del mensaje
        content_type, chat_type, chat_id = telepot.glance(msg)
        # bot.sendMessage(chat_id, '')

        # Si no es un chat privado, pasar
        if chat_type != 'private':
            return

        # Si el mensaje es texto
        if content_type == 'text':
            if is_waiting(chat_id):
                try:
                    # Parseamos usuario y contraseña
                    usuario, password = msg['text'].split()

                    # Chequear que el carnet cumple el formato correcto
                    pattern = re.compile('^([0-9]{2}-[0-9]{5})$')
                    assert (pattern.match(usuario))

                    # Guardamos en la base de datos
                    guardado = save_user(usuario, password, str(chat_id))
                    if guardado == 1:
                        bot.sendMessage(chat_id,
                                        'Se registró exitosamente tu cuenta.')
                    elif guardado == 2:
                        bot.sendMessage(
                            chat_id, 'Se actualizó correctamente tu cuenta.')
                    else:
                        pass

                except ValueError as e:
                    bot.sendMessage(
                        chat_id,
                        'Ocurrió un error leyendo el mensaje: <code>{}</code>\nVuelve a intentarlo con el comando /login'
                        .format(e),
                        parse_mode='HTML')

                except psycopg2.DataError as e:
                    bot.sendMessage(
                        chat_id,
                        'Ocurrió un error modificando la base de datos: <code>{}</code>'
                        .format(e),
                        parse_mode='HTML')

                except psycopg2.IntegrityError as e:
                    bot.sendMessage(
                        chat_id,
                        'Ocurrió un error guardando los datos: <code>{}</code>'
                        .format(e),
                        parse_mode='HTML')

                except AssertionError:
                    bot.sendMessage(
                        chat_id,
                        'El carnet debe tener formato XX-XXXXX. Intenta de nuevo con /login.'
                    )

            elif is_login(msg['text'], chat_id):
                bot.sendMessage(
                    chat_id,
                    'Por favor envíame tu nombre de usuario (e.g carnet) y tu contraseña separadas por un espacio.'
                )

            elif is_help(msg['text']):
                bot.sendMessage(chat_id, HELP)

            elif is_categoria(msg['text']):
                # Obtenemos las categorías
                r = requests.get(COMPUSHOW_URL + 'categories/')
                response = r.json()

                inline_keyboard = [[]]
                count = 0
                idx = 0
                for categoria in response:
                    if count > 1:
                        count = 0
                        idx += 1
                        inline_keyboard.append([])
                    msg = categoria['fields']['name'] + EMOJIS[
                        categoria['fields']['name']]
                    inline_keyboard[idx].append(
                        InlineKeyboardButton(text=msg,
                                             callback_data=categoria['pk']))
                    count += 1

                keyboard = InlineKeyboardMarkup(
                    inline_keyboard=inline_keyboard)
                bot.sendMessage(chat_id, 'Categorías:', reply_markup=keyboard)
                # for categoria in response:
                #     bot.sendMessage(chat_id, categoria['fields']['name'])

            else:
                bot.sendMessage(
                    chat_id,
                    'Si necesitas ayuda en como comunicarte conmigo, usa el comando /help mientras escuchas esta brutal playlist: {}'
                    .format(PLAYLIST_URL))
Ejemplo n.º 39
0
def on_callback_query(msg):
    query_id, from_id, query_data = telepot.glance(msg,
                                                   flavor='callback_query')
    chat_id = msg['message']['chat']['id']
    name = msg['from']['first_name']
    print('Callback Query:', query_id, from_id, name, query_data)

    #----При клике еды--------------------------------------------------------------------------
    if query_data in products:
        add_to_user(user_lists, chat_id, query_data)
        print(user_lists)
        cb_text = names[query_data] + " добавлен\а в список"
        bot.answerCallbackQuery(query_id, text=cb_text)

    #----При клике назад в меню------------------------------------------------------------------------------
    if query_data == 'main_menu':
        h_msg = "Главное Меню: \n(напишите /help для подробной информации)"
        bot.sendPhoto(chat_id, logo, caption=h_msg, reply_markup=keyboardMain)

    # ----Снэки--------------------------------------------------------------------------------
    if query_data == 'snack_start':
        mesg = "Доступные снэки: \n(нажмите на предмет чтобы добавить в список):"
        bot.sendPhoto(chat_id,
                      snacks_image,
                      caption=mesg,
                      reply_markup=keyboardSnacks)

    # ----Напитки--------------------------------------------------------------------------------
    if query_data == 'drink_start':
        mesg = "Доступные напитки: \n(нажмите на предмет чтобы добавить в список):"
        bot.sendPhoto(chat_id,
                      drink_image,
                      caption=mesg,
                      reply_markup=keyboardDrinks)

    # ----Кофe--------------------------------------------------------------------------------
    if query_data == 'coffee_start':
        mesg = "Доступное кофе: \n(нажмите на предмет чтобы добавить в список):"
        bot.sendPhoto(chat_id,
                      coffee_image,
                      caption=mesg,
                      reply_markup=keyboardCoffee)

    # ----Сеты--------------------------------------------------------------------------------
    if query_data == 'set_start':
        mesg = "Доступное сеты: \n(нажмите на предмет чтобы добавить в список):"
        bot.sendPhoto(chat_id,
                      set_image,
                      caption=mesg,
                      reply_markup=keyboardSet)

    # ----Соусы--------------------------------------------------------------------------------
    if query_data == 'sauce_start':
        mesg = "Доступное соусы: \n(нажмите на предмет чтобы добавить в список):"
        bot.sendPhoto(chat_id,
                      sauce_image,
                      caption=mesg,
                      reply_markup=keyboardSauce)

    #----К Заказу--------------------------------------------------------------------------------------
    if query_data == 'finish':
        keyb = InlineKeyboardMarkup(
            inline_keyboard=make_list_keyboard_c(user_lists, chat_id))
        pri = calc_price(user_lists, chat_id)
        num = calc_quantity(user_lists, chat_id)
        if pri == 0:
            bot.sendPhoto(
                chat_id,
                list_image,
                caption="Вы ничего не заказали.",
                reply_markup=InlineKeyboardMarkup(inline_keyboard=[
                    [
                        InlineKeyboardButton(text="[Глав. Меню]",
                                             callback_data='main_menu')
                    ],
                ]))
        else:
            mesg = "Внимательно проверьте ваш список! Вы заказали " + str(
                num) + " предмета на сумму " + str(
                    pri) + "KZT: \n[нажмите на предмет для удаление из списка]"
            bot.sendPhoto(chat_id, list_image, caption=mesg, reply_markup=keyb)

    # ----Подтверждение--------------------------------------------------------------------------------------
    if query_data == 'finish_order':
        pri = calc_price(user_lists, chat_id)
        if pri == 0:
            bot.sendPhoto(
                chat_id,
                list_image,
                caption="Вы ничего не заказали.",
                reply_markup=InlineKeyboardMarkup(inline_keyboard=[
                    [
                        InlineKeyboardButton(text="[Глав. Меню]",
                                             callback_data='main_menu')
                    ],
                ]))
        else:
            ord_name = msg['from']['first_name']
            ord_num = chat_id * 1000 + random.randint(0, 999)
            order = []
            order.append(ord_num)
            order.append(ord_name)
            order.append(get_products(user_lists, chat_id))
            orders.append(order)
            print("Orders: ", orders)
            mesg = "Ваш заказ принят. Номер вашего заказа №"+str(ord_num)+". Можете забрать заказ через 10 минут. Вы можете отменить заказ с помощью " \
                                                                          "команды \n/abort номер_заказа. Приятного аппетита!"
            clear_order(user_lists, chat_id)
            bot.sendPhoto(chat_id, confirm_image, caption=mesg)
            bot.answerCallbackQuery(query_id, text="Заказ принят")

    #----Удаление-------------------------------------------------------------------------------------
    if query_data[:3] == "del":
        del_item = query_data.split('/')[1]
        delete_item(user_lists, chat_id, del_item)
        del_text = "Успешно удален\а " + names[del_item]
        bot.answerCallbackQuery(query_id, text=del_text)

        #----Showlist------------------------------------------------------------------------------------------
        keyb = InlineKeyboardMarkup(
            inline_keyboard=make_list_keyboard(user_lists, chat_id))
        pri = calc_price(user_lists, chat_id)
        num = calc_quantity(user_lists, chat_id)
        mesg = "Это ваш список заказа. Вы заказали " + str(
            num) + " предмета на сумму " + str(
                pri) + "KZT: \n[нажмите на предмет для удаление из списка]"
        bot.sendPhoto(chat_id, list_image, caption=mesg, reply_markup=keyb)
Ejemplo n.º 40
0
def on_chat_message(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)

    text = msg['text']
    name = msg['from']['first_name']

    print(content_type, chat_type, chat_id, name, text)

    #----Начальное сообщение----------------------------------------------------

    if (text == "/start") | (text == "/neworder"):
        """""add_to_user(user_lists, chat_id, 'marg')
        print(user_lists)
        clear_order(user_lists, chat_id)
        print(user_lists)"""

        clear_order(user_lists, chat_id)

        h_msg = 'Здравствуйте, ' + name + '! Вас приветствует бот ресторана "HamStar"! Что вы хотите заказать? \n(напишите /help для подробного описания)'
        bot.sendPhoto(chat_id, logo, caption=h_msg, reply_markup=keyboardMain)

    #----Help Комманда------------------------------------------------------

    elif text == "/help":

        bot.sendMessage(
            chat_id,
            "Вы говорите с Telegram ботом Hamstar Restaurant, который принимает заказы через мессенджер Telegram. "
            "Этот бот был создан для упрощения процесс заказа еды в нашем ресторане. Этот бот поддерживает следующие комманды:\n"
            "/neworder - очищает ваш текущий список и начинает новую процедуру\n"
            "/showlist - показывает текущий список")

    #----Showlist Комманда---------------------------------------------------
    elif text == "/showlist":
        keyb = InlineKeyboardMarkup(
            inline_keyboard=make_list_keyboard(user_lists, chat_id))
        pri = calc_price(user_lists, chat_id)
        num = calc_quantity(user_lists, chat_id)
        mesg = "Это ваш список заказа. Вы заказали " + str(
            num) + " предмета на сумму " + str(
                pri) + "KZT: \n[нажмите на предмет для удаление из списка]"
        bot.sendPhoto(chat_id, list_image, caption=mesg, reply_markup=keyb)

    elif (text[:6] == "/abort") | (text[:9] == "/aspirine"):
        onum = int(text.split(' ')[1])
        res = abort_order(orders, onum)
        if res == 1:
            bot.sendMessage(chat_id,
                            text=str("Заказ " + str(onum) + " отменен."))
        else:
            bot.sendMessage(
                chat_id,
                text="Введенный вами номер заказа не зарегистрирован.")
        print(orders)
        print("Abort order")

    elif text == "/swordfish":
        nam = msg['from']['first_name']
        txt = "[Молодец, "+ nam +"! Правильно, фильм 'Пароль Рыба Меч', на англ. 'Swordfish'] \nЗдравствуйте администратор! Это комманды для управления заказами:\n/hesoyam - выводит список всех заказов\n" \
                                 "/aspirine номер_заказа - убрать заказ из списка (после выполнения)"
        bot.sendMessage(chat_id, text=txt)

        print(
            "Hacked by ", nam,
            " #####################################################################"
        )

    elif text == "/hesoyam":
        txt = order_to_txt(orders)
        bot.sendMessage(chat_id, text=txt, parse_mode='markdown')
Ejemplo n.º 41
0
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    #print(content_type, chat_type, chat_id)
    #pprint(msg)

    vorname = msg['from']['first_name']
    username = msg['from']['username']
    id = msg['from']['id']
    msg['text'] = msg['text'].lower()

    # print(msg['text'])

    if msg['text'] in [
            "/start", "/start start", "start", "hallo", "Hallo", "Hi", "Start"
    ]:
        bot.sendMessage(chat_id, "Herzlich willkommen bei " + botcall + " " + vorname + "!" + \
            "\nUm Hilfe zu erhalten, schreib /hilfe. Informationen und Hinweise bitte an @dj1jay.")

    elif msg['text'] in ["/hilfe", "hilfe"]:
        hilfetext = "Informationen und Kommandos:\n/status Gibt den Status des Repeaters aus\n/hilfe Hilfetext mit der" \
                           " Liste der Kommandos\n/tg Listet die in DMR geschalteten TG auf\n/lheared Gibt aus, wer als letztes lokal gehört wurde."\
             "\n/lastthr Letzte Relaisstation im ThüringenLink? \n/lastata Letzte Relais Station im Relaisverbund Berlin\n/lastecho letzte Echolink Station bei DB0FTS"
        if id in grant:
            hilfetext += "\n\n/killmmdvm Stoppt MMDVM\n/startmmdvm Startet MMDVM\n/killdmrgw Stoppt das DMRGateway\n/startdmrgw Startet DMRGateway" \
   "\n/killsvx Beende Svxlink\n/startsvx Starte Svxlink\n/switchthr Relaisverbund Wechseln nach Thüringen\n/switchata Relaisverbund Wechseln nach Berlin"\
    "\n/lhecho Letzte Station Echolink \n/txan Schaltet den Sender an\n/txaus Schaltet den Sender aus\n/rxan Schaltet den RX ein" \
    "\n/rxaus Schaltet den RX an\n/reboot start den Rechner neu"
        bot.sendMessage(chat_id, botcall + " " + hilfetext)

    elif msg['text'] in ["/tg"]:
        bot.sendMessage(chat_id, talkgroups())

    elif "/lheared" in msg['text']:
        if msg['text'] == "/lheared":
            heared = lastheared('')
            bot.sendMessage(chat_id, heared)
        else:
            suche = msg['text'].split(" ")
            heared = lastheared(suche[1].upper())
            bot.sendMessage(chat_id, heared)

    elif msg['text'] in ["/killmmdvm"]:
        if id in grant:
            prockiller("MMDVMHost")
            bot.sendMessage(chat_id, "Beende MMDVM...")
        else:
            bot.sendMessage(chat_id, grantfehler)

    elif msg['text'] in ["/startmmdvm"]:
        if id in grant:
            os.system(mmdvmaufruf)
            bot.sendMessage(chat_id, "Starte MMDVM")
        else:
            bot.sendMessage(chat_id, grantfehler)

    elif msg['text'] in ["/killdmrgw"]:
        if id in grant:
            prockiller("DMRGateway")
            bot.sendMessage(chat_id, "Beende DMRGateway...")
        else:
            bot.sendMessage(chat_id, grantfehler)

    elif msg['text'] in ["/startdmrgw"]:
        if id in grant:
            os.system(dmrgwaufruf)
            bot.sendMessage(chat_id, "Starte DMRGateway")
        else:
            bot.sendMessage(chat_id, grantfehler)

    elif msg['text'] in ["/killsvx"]:
        if id in grant:
            os.system(svxstop)
            bot.sendMessage(chat_id, "Beende SvxLink...")
        else:
            bot.sendMessage(chat_id, grantfehler)

    elif msg['text'] in ["/startsvx"]:
        if id in grant:
            os.system(svxaufruf)
            bot.sendMessage(chat_id, "Starte SvxLink")
        else:
            bot.sendMessage(chat_id, grantfehler)

## Svxlink Log

    elif msg['text'] in ["/lastthr"]:
        lhthr = subprocess.check_output(
            'grep "THR_Logic: Talker" /var/log/svxlink.log | tail -1 | cut -d: -f6',
            shell=True)
        bot.sendMessage(chat_id, "Zuletzt gehört im ThüringenLink:" + lhthr)
##
    elif msg['text'] in ["/lastata"]:
        lhata = subprocess.check_output(
            'grep "ATA_Logic: Talker" /var/log/svxlink.log | tail -1 | cut -d: -f6',
            shell=True)
        bot.sendMessage(chat_id, "Zuletzt gehört im Verbund Berlin:" + lhata)

    elif msg['text'] in ["/lastecho"]:
        lhecho = subprocess.check_output(
            'grep "EchoLink QSO state changed to CONNECTED" /var/log/svxlink.log | tail -1 | cut -d: -f4',
            shell=True)
        bot.sendMessage(chat_id, "Zuletzt per Echolink:" + lhecho)

    elif msg['text'] in ["/switchata"]:
        if id in grant:
            os.system(link951)
            bot.sendMessage(chat_id, "Wechsel zum Relaisverbund Berlin")
        else:
            bot.sendMessage(chat_id, grantfehler)

    elif msg['text'] in ["/switchthr"]:
        if id in grant:
            os.system(link341)
            bot.sendMessage(chat_id, "Wechsel zum Relaisverbund ThüringenLink")
        else:
            bot.sendMessage(chat_id, grantfehler)


###

    elif msg['text'] in ["/status"]:
        status = ''
        # Eingänge lesen
        if GPIO.input(13) == GPIO.HIGH:
            status += "TX ist aus\n"
        else:
            status += "TX is an\n"
        if GPIO.input(15) == GPIO.HIGH:
            status += "RX ist aus"
        else:
            status += "RX ist an"
        # Laufende Prozesse testen
        for proc in prozesse:
            status += "\n" + proc + " " + prozesschecker(proc)

        ## Temperaturen
        # CPU-Temperaturen auslesen
        tFile = open('/sys/class/thermal/thermal_zone0/temp')
        temp = float(tFile.read())
        tempC = temp / 1000
        status += "\nCPU Temperatur " + str(tempC)

        bot.sendMessage(chat_id, status)

    elif msg['text'] in ["/txaus"]:
        if id in grant:
            GPIO.output(13, GPIO.HIGH)
            bot.sendMessage(chat_id, "Sender ist aus!")
        else:
            bot.sendMessage(chat_id, grantfehler)
    elif msg['text'] in ["/txan"]:
        if id in grant:
            GPIO.output(13, GPIO.LOW)
            bot.sendMessage(chat_id, "Sender ist wieder an!")
        else:
            bot.sendMessage(chat_id, grantfehler)

    elif msg['text'] in ["/rxaus"]:
        if id in grant:
            GPIO.output(15, GPIO.HIGH)
            bot.sendMessage(chat_id, "Empfang ist aus!")
        else:
            bot.sendMessage(chat_id, grantfehler)
    elif msg['text'] in ["/rxan"]:
        if id in grant:
            GPIO.output(15, GPIO.LOW)
            bot.sendMessage(chat_id, "Empfang ist wieder an!")
        else:
            bot.sendMessage(chat_id, grantfehler)

    elif msg['text'] in ["/reboot"]:
        if id in grant:
            bot.sendMessage(chat_id, "Starte das System neu.")
            os.system('sudo shutdown -r now')
        else:
            bot.sendMessage(chat_id, grantfehler)
    else:
        bot.sendMessage(
            chat_id, 'Mit "' + msg['text'] + '" kann ich nichts anfangen, ' +
            vorname + "!\nEine Liste der Befehle bekommst du mit /hilfe.")
Ejemplo n.º 42
0
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["text"])
Ejemplo n.º 43
0
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)

    command = query_data.split("_")

    ### Brandmeister API Handler ###
    if bmapiactive == 1:
        apiurl = "https://api.brandmeister.network/"
        if query_data == "/dropCallS1":
            action = apiurl + "v1.0/repeater/setRepeaterDbus.php?action=dropCallRoute&slot=1&q="
            apistrg = action + dmrid
            bmsimple(query_id, apistrg)
        elif query_data == "/dropCallS2":
            action = apiurl + "v1.0/repeater/setRepeaterDbus.php?action=dropCallRoute&slot=2&q="
            apistrg = action + dmrid
            bmsimple(query_id, apistrg)
        elif query_data == "/dropDynamicS1":
            action = apiurl + "v1.0/repeater/setRepeaterTarantool.php?action=dropDynamicGroups&slot=1&q="
            apistrg = action + dmrid
            bmsimple(query_id, apistrg)
        elif query_data == "dropDynamicS2":
            action = apiurl + "v1.0/repeater/setRepeaterTarantool.php?action=dropDynamicGroups&slot=2&q="
            apistrg = action + dmrid
            bmsimple(query_id, apistrg)
        elif query_data == "/dropRepeater":
            action = apiurl + "v1.0/repeater/setRepeaterDbus.php?action=removeContext&q="
            apistrg = action + dmrid
            bmsimple(query_id, apistrg)

    # req = requests.post(apistrg, auth=HTTPBasicAuth(bmapi,''), data = {'talkgroup':262,'timeslot':0})
    # req.encoding = 'utf-8'

### GPIO switcher ###
    if gpioactive == 1:
        for i in range(len(gpioports)):
            if command[0] in gpioports[i]:
                print(
                    str(gpioports[i][0]) + " " + str(gpioports[i][1]) + " " +
                    str(gpioports[i][2]))
                if command[1] == "on" and gpioports[i][2] == 0:
                    GPIO.output(gpioports[i][0], GPIO.HIGH)
                    bot.answerCallbackQuery(query_id,
                                            gpioports[i][1] + " " + _("is_on"))
                elif command[1] == "on" and gpioports[i][2] == 1:
                    GPIO.output(gpioports[i][0], GPIO.LOW)
                    bot.answerCallbackQuery(query_id,
                                            gpioports[i][1] + " " + _("is_on"))
                elif command[1] == "off" and gpioports[i][2] == 0:
                    GPIO.output(gpioports[i][0], GPIO.LOW)
                    bot.answerCallbackQuery(
                        query_id, gpioports[i][1] + " " + _("is_off"))
                elif command[1] == "off" and gpioports[i][2] == 1:
                    GPIO.output(gpioports[i][0], GPIO.HIGH)
                    bot.answerCallbackQuery(
                        query_id, gpioports[i][1] + " " + _("is_off"))

### SVX Handler ####
    if svxactive == 1:
        if query_data == "/killsvx":
            os.system(SVXOff)
            bot.answerCallbackQuery(query_id, 'SVX' + " " + _("is_off"))
        elif query_data == "/startsvx":
            os.system(SVXOn)
            bot.answerCallbackQuery(query_id, 'SVX' + " " + _("is_on"))
        elif query_data == "/lhecho":
            lhecho = subprocess.check_output(
                'grep "EchoLink QSO state changed to CONNECTED" ' + svx_log +
                ' | tail -1 | cut -d: -f4',
                shell=True)
            bot.answerCallbackQuery(query_id,
                                    _("last_in_echolink") + ":" + lhecho)
            bot.sendMessage(from_id, _("last_in_echolink") + ": " + lhecho)

        for i in range(len(svxcommands)):
            if command[0] in svxcommands[i]:
                #print("CMD"+svxcommands[i][0])
                svxcmd = "echo " + svxcommands[i][1] + " > " + rep_logic
                print(svxcmd)
                try:
                    os.system(svxcmd)
                    bot.answerCallbackQuery(
                        query_id, svxcommands[i][1] + " " + _('done'))
                except:
                    bot.answerCallbackQuery(
                        query_id, svxcommands[i][1] + " " + _('svx_failure'))
        for i in range(len(svxlh)):
            if query_data in svxlh[i]:
                string = "grep" + " \"" + svxlh[i][
                    0] + ": Talker" + "\" " + svx_log + '| tail -1 | cut -d: -f6'
                lh = subprocess.check_output(string, shell=True)
                bot.answerCallbackQuery(
                    query_id,
                    _("last_heard") + " " + _("im") + svxlh[i][0] + " " + lh)
                bot.sendMessage(
                    from_id,
                    _("last_heard") + " " + _("im") + " " + svxlh[i][0] + " " +
                    lh)

### Software Handler ####
    if query_data == "/killmmdvm":
        if from_id in grant:
            prockiller("MMDVMHost")
            bot.answerCallbackQuery(query_id, _("stop_mmdvm"))
        else:
            bot.answerCallbackQuery(query_id, grantfehler)

    elif query_data == "/startmmdvm":
        if from_id in grant:
            os.system(mmdvmaufruf)
            bot.answerCallbackQuery(query_id, _("start_mmdvm"))
        else:
            bot.answerCallbackQuery(query_id, grantfehler)

    elif query_data == "/killdmrgw":
        if from_id in grant:
            prockiller("DMRGateway")
            bot.answerCallbackQuery(query_id, _("stop_dmrgw"))
        else:
            bot.answerCallbackQuery(query_id, grantfehler)

    elif query_data == "/startdmrgw":
        if from_id in grant:
            os.system(dmrgwaufruf)
            bot.answerCallbackQuery(query_id, _("start_dmrgw"))
        else:
            bot.answerCallbackQuery(query_id, grantfehler)
Ejemplo n.º 44
0
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)

    print(content_type, chat_type, chat_id, msg)

    if content_type == 'text':
        if "entities" in msg:
            command=None
            keywords=None
            for entity in msg["entities"]:
                if entity['type'] == 'bot_command':
                    order=msg['text'][entity['offset']+1:entity['offset']+entity['length']].split('@')
                    if type(order)==list:
                        print "order is a list"
                        if len(order)>1:
                            "print order has bot name"
                            if order[1]=="dfmtelegrambot":
                                order=order[0]
                                print "order is for me"
                            else:
                                print "order is for another bot"
                                order=None
                        else:
                            order=order[0]
                            print "order has not botname so i take it"

                    if type(order)==unicode:
                        print order
                        bot.sendMessage(chat_id, "Got the "+order+" order Mr. "+msg['from']['first_name']+"!")
                        command=order
                        #subscribe and teach commands are manager while detecting url entity
                        if command=="follow" or command=="watch":
                            if msg["entities"][0]["type"]=='bot_command' and entity['offset']+entity['length']+1<len(msg['text']):
                                link=msg['text'][entity['offset']+entity['length']+1:len(msg['text'])]
                                if command=="follow" and link[0]!="@":
                                    bot.sendMessage(chat_id,"Error: "+msg['from']['first_name']+", /follow require twitter account starting with @ .")
                                    break
                                bot.sendMessage(chat_id,"Source subscription result for "+msg['from']['first_name']+":\n"+submitSource(link,"twitter",msg))
                            else:
                                bot.sendMessage(chat_id,"Error: "+msg['from']['first_name']+", please check /help .")
                        elif command=="digest":
                            dfm_feedparser=feedparser.parse(dfm_feed)
                            digest="""
                            <b>Top 10 current news categorization</b>
                            <b>title summary predictions</b>
                            """
                            for dfm_entry in dfm_feedparser.entries:
                                tags=""
                                for tag in dfm_entry.tags:
                                    tags=tags+tag.label+"&nbsp"
                                digest=digest+"<a href=\""+dfm_entry['id']+"\">"+dfm_entry['title']+"</a>\n\n"

                            bot.sendMessage(chat_id, digest,parse_mode="HTML")
                        elif command=="help":
                            bot.sendMessage(chat_id, """*DFM Bot Commands:*
                            /subscribe _rss feed url_ Subscribe to an rss feed
                            /follow _twitter account_ follow a twitter account
                            /watch _twitter search_ watch for a twitter search
                            /teach _url_ _keywords_ teach dfm bot keywords (separated by commas) related to one news
                            /digest get current top 10 news in DFM
                            /help get this message (help message)
                            *To submit a news just post an url as chat message then i will catch it, scrap the web page, reply extract, keywords provided by author and predict categories.*
                            """,parse_mode="Markdown")

                if entity['type'] == 'url':
                    print "url and "+str(command)+" detected"

                    if command==None or command=="teach":
                        url=msg['text'][entity['offset']:entity['offset']+entity['length']]
                        print url
                        keywords=[]
                        if command=="teach":
                            print "Teaching"
                            keywords=msg['text'][entity['offset']+entity['length']+1:len(msg['text'])].strip().split(',')
                            print keywords

                        bot.sendMessage(chat_id, "Thank you for the news "+msg['from']['first_name']+"!")
                        print "Scraping"
                        results = submitUrl(url,msg,keywords)
                        if results != None:
                            if "text" in results["_source"]:
                                bot.sendMessage(chat_id,"News first lines "+msg['from']['first_name']+":\n\""+" ".join(results["_source"]["text"][0:250].strip().splitlines())+"...\"")
                            else:
                                bot.sendMessage(chat_id,"I was not able to read your news "+msg['from']['first_name']+".")
                        else:
                            bot.sendMessage(chat_id,"I was not able to read your news "+msg['from']['first_name']+".")

                        if "tags" in results["_source"]:
                            if type(results["_source"]["tags"])==list and len(results["_source"]["tags"])>0:
                                tags_message="Human tagged this news with: "
                                for tag in results["_source"]["tags"]:
                                    tags_message=tags_message+tag+" and "
                                tags_message=tags_message[:-5]
                                bot.sendMessage(chat_id,tags_message+" "+msg['from']['first_name']+".")
                        if "topics" in results["_source"]:
                            topics_message="Your news seems to talk about "
                            topics_scores=[]
                            for topic in results["_source"]["topics"]:
                                topics_message=topics_message+topic["label"]+" and "
                                topics_scores.append(topic["score"])
                            average_score=sum(topics_scores)/len(topics_scores)
                            topics_message=topics_message[:-5]
                            if average_score<45:
                                bot.sendMessage(chat_id,topics_message+" "+msg['from']['first_name']+" but i clearly doubt on this.")
                            else:
                                bot.sendMessage(chat_id,topics_message+" "+msg['from']['first_name']+" for sure.")
                        else:
                            bot.sendMessage(chat_id,"I have no idea what is it talking about "+msg['from']['first_name']+".")

                    elif command=="subscribe":
                        print "Subscribing"
                        link=msg['text'][entity['offset']:entity['offset']+entity['length']]
                        bot.sendMessage(chat_id,"Source subscription result for "+msg['from']['first_name']+":\n"+json.dumps(submitSource(link,"rss",msg)))
Ejemplo n.º 45
0
def on_callback_query(msg):
    query_id, chat_id, query_data = telepot.glance(msg,
                                                   flavor='callback_query')
    if (msg['message']['chat']['type'] == 'group'):
        chat_id = msg['message']['chat']['id']
    ide = (chat_id, msg['message']['message_id'])

    if (query_data[-3:] == "abo"):
        if (msg['message']['chat']['type'] == 'group'):
            bot.answerCallbackQuery(
                query_id,
                text="Sent you a personal message to avoid spoilers in group",
                show_alert=True)
        url1 = 'https://www.mangareader.net' + query_data[:-3]
        r = requests.get(url1, headers={'User-Agent': 'Mozilla/5.0'})
        page_soup = soup(r.content, 'html.parser')
        title = page_soup.find_all('table', class_='d41')
        img = page_soup.find('div', class_='d38')
        img = img.find('img').attrs['src']
        if (img[:6] != "https:"):
            img = "https:" + img
        title = title[0].find_all('td')
        href = []
        for i in range(0, len(title) - 2, 2):
            href.append(str(title[i].getText() + " " + title[i + 1].getText()))
        gen = (title[len(title) - 1].find_all('a'))
        s = ""
        for i in range(len(gen)):
            gen[i] = gen[i].getText()
            if (i == len(gen) - 1):
                s += gen[i]
            else:
                s += gen[i] + ", "
        href.append(title[len(title) - 2].getText() + s)
        s = ""
        for i in href:
            s += i + "\n \n"
        inl = []
        bot.sendPhoto(msg['from']['id'], img, caption=s)
        inl.append([
            InlineKeyboardButton(text="Read",
                                 parse_mode='Markdown',
                                 callback_data=str(query_data[:-3]) + "read")
        ])
        inl.append([
            InlineKeyboardButton(text="Back",
                                 parse_mode='Markdown',
                                 callback_data="searchback")
        ])
        bot.sendMessage(
            msg['from']['id'],
            "Choose your chapter from the Read list generated below",
            reply_markup=InlineKeyboardMarkup(inline_keyboard=inl))

    elif (query_data[-4:] == "read"):
        url1 = 'https://www.mangareader.net' + query_data[:-4]
        r = requests.get(url1, headers={'User-Agent': 'Mozilla/5.0'})
        page_soup = soup(r.content, 'html.parser')
        ep = page_soup.find("ul", class_="d44")
        ep = ep.find('a').attrs['href']
        pos = 0
        inl = []
        for i in range(-1, -5, -1):
            if (ep[i] == "/"):
                pos = i
                ep = int(ep[i + 1:])
                break
        if (ep <= 28):
            temp = []
            for i in range(1, ep + 1):
                if (i % 7 == 0):
                    temp.append(
                        InlineKeyboardButton(
                            text="Ch" + str(i),
                            parse_mode='Markdown',
                            callback_data=str(query_data[:-4]) + "/" + str(i) +
                            "open"))
                    inl.append(temp)
                    temp = []
                else:
                    temp.append(
                        InlineKeyboardButton(
                            text="Ch" + str(i),
                            parse_mode='Markdown',
                            callback_data=str(query_data[:-4]) + "/" + str(i) +
                            "open"))
                    if (i == ep):
                        inl.append(temp)
            bot.editMessageReplyMarkup(
                ide, reply_markup=InlineKeyboardMarkup(inline_keyboard=inl))

        elif (ep // 28 == 1):
            temp = []
            for i in range(1, 26):
                if (i % 7 == 0):
                    temp.append(
                        InlineKeyboardButton(
                            text="Ch" + str(i),
                            parse_mode='Markdown',
                            callback_data=str(query_data[:-4]) + "/" + str(i) +
                            "open"))
                    inl.append(temp)
                    temp = []
                else:
                    temp.append(
                        InlineKeyboardButton(
                            text="Ch" + str(i),
                            parse_mode='Markdown',
                            callback_data=str(query_data[:-4]) + "/" + str(i) +
                            "open"))
                    if (i == 25):
                        inl.append(temp)
            inl[3].append(
                InlineKeyboardButton(text="Ch26-" + str(ep),
                                     parse_mode='Markdown',
                                     callback_data=str(query_data[:-4]) + "/" +
                                     "26-" + str(ep) + "/"))
            bot.editMessageReplyMarkup(
                ide, reply_markup=InlineKeyboardMarkup(inline_keyboard=inl))

        else:
            temp = []
            rem = ep // 16
            for i in range(1, 16):
                low = rem * i - (rem - 1)
                high = rem * i
                if (i % 4 == 0):
                    temp.append(
                        InlineKeyboardButton(
                            text="Ch" + str(low) + "-" + str(high),
                            parse_mode='Markdown',
                            callback_data=str(query_data[:-4]) + "/" +
                            str(low) + "-" + str(high) + "/"))
                    inl.append(temp)
                    temp = []
                else:
                    temp.append(
                        InlineKeyboardButton(
                            text="Ch" + str(low) + "-" + str(high),
                            parse_mode='Markdown',
                            callback_data=str(query_data[:-4]) + "/" +
                            str(low) + "-" + str(high) + "/"))
                    if (i == 15):
                        inl.append(temp)
            inl[3].append(
                InlineKeyboardButton(text="Ch" + str(rem * 15 + 1) + "-" +
                                     str(ep),
                                     parse_mode='Markdown',
                                     callback_data=str(query_data[:-4]) + "/" +
                                     str(rem * 15 + 1) + "-" + str(ep) + "/"))
            bot.editMessageReplyMarkup(
                ide, reply_markup=InlineKeyboardMarkup(inline_keyboard=inl))

    elif (query_data[-1] == "/"):
        low = high = pos = 0
        q = ""
        for i in range(-2, -10, -1):
            if (query_data[i] == "/"):
                pos = i
        s = query_data[pos + 1:-1]
        for i in s:
            if (i == "-"):
                low = int(q)
                q = ""
            else:
                q = q + i
        high = int(q)
        inl = []

        if (high - low + 1 <= 16):
            temp = []
            for i in range(1, high - low + 2):
                if (i % 4 == 0):
                    temp.append(
                        InlineKeyboardButton(
                            text="Ch" + str(low - 1 + i),
                            parse_mode='Markdown',
                            callback_data=str(query_data[:pos]) + "/" +
                            str(low - 1 + i) + "open"))
                    inl.append(temp)
                    temp = []
                else:
                    temp.append(
                        InlineKeyboardButton(
                            text="Ch" + str(low - 1 + i),
                            parse_mode='Markdown',
                            callback_data=str(query_data[:pos]) + "/" +
                            str(low - 1 + i) + "open"))
            inl.append(temp)
            inl.append([
                InlineKeyboardButton(text="Back",
                                     parse_mode='Markdown',
                                     callback_data=query_data[:pos] + "read")
            ])
            bot.editMessageReplyMarkup(
                ide, reply_markup=InlineKeyboardMarkup(inline_keyboard=inl))

        elif ((high - low + 1) // 16 == 1):
            temp = []
            for i in range(1, 16):
                if (i % 4 == 0):
                    temp.append(
                        InlineKeyboardButton(
                            text="Ch" + str(low - 1 + i),
                            parse_mode='Markdown',
                            callback_data=str(query_data[:pos]) + "/" +
                            str(low - 1 + i) + "open"))
                    inl.append(temp)
                    temp = []
                else:
                    temp.append(
                        InlineKeyboardButton(
                            text="Ch" + str(low - 1 + i),
                            parse_mode='Markdown',
                            callback_data=str(query_data[:pos]) + "/" +
                            str(low - 1 + i) + "open"))
                    if (i == 15):
                        inl.append(temp)
            inl[3].append(
                InlineKeyboardButton(
                    text="Ch" + str(low + 15) + "-" + str(high),
                    parse_mode='Markdown',
                    callback_data=str(query_data[:pos]) + "/" + str(low + 15) +
                    "-" + str(high) + "/"))
            inl.append([
                InlineKeyboardButton(text="Back",
                                     parse_mode='Markdown',
                                     callback_data=query_data[:pos] + "read")
            ])
            bot.editMessageReplyMarkup(
                ide, reply_markup=InlineKeyboardMarkup(inline_keyboard=inl))

        else:
            temp = []
            rem = (high - low + 1) // 16
            slow = shigh = 0
            for i in range(1, 16):
                slow = low + rem * i - (rem - 1) - 1
                shigh = low + rem * i - 1
                if (i % 4 == 0):
                    temp.append(
                        InlineKeyboardButton(
                            text="Ch" + str(slow) + "-" + str(shigh),
                            parse_mode='Markdown',
                            callback_data=str(query_data[:pos]) + "/" +
                            str(slow) + "-" + str(shigh) + "/"))
                    inl.append(temp)
                    temp = []
                else:
                    temp.append(
                        InlineKeyboardButton(
                            text="Ch" + str(slow) + "-" + str(shigh),
                            parse_mode='Markdown',
                            callback_data=str(query_data[:pos]) + "/" +
                            str(slow) + "-" + str(shigh) + "/"))
                    if (i == 15):
                        inl.append(temp)
            inl[3].append(
                InlineKeyboardButton(
                    text="Ch" + str(low + rem * 15) + "-" + str(high),
                    parse_mode='Markdown',
                    callback_data=str(query_data[:pos]) + "/" +
                    str(low + rem * 15) + "-" + str(high) + "/"))
            inl.append([
                InlineKeyboardButton(text="Back",
                                     parse_mode='Markdown',
                                     callback_data=query_data[:pos] + "read")
            ])
            bot.editMessageReplyMarkup(
                ide, reply_markup=InlineKeyboardMarkup(inline_keyboard=inl))

    elif (query_data[-4:] == "open"):
        pos = 0
        num = ""
        for i in range(-5, -10, -1):
            if (query_data[i] == "/"):
                pos = i
                break
            else:
                num = num + query_data[i]
        num = int(num[::-1])
        url1 = 'https://www.mangareader.net' + query_data[:pos]
        r = requests.get(url1, headers={'User-Agent': 'Mozilla/5.0'})
        page_soup = soup(r.content, 'html.parser')
        ep = page_soup.find("ul", class_="d44")
        ep = ep.find('a').attrs['href']
        po = 0
        inl = []
        for i in range(-1, -5, -1):
            if (ep[i] == "/"):
                po = i
                ep = int(ep[i + 1:])
                break

        url1 = 'https://www.mangareader.net' + query_data[:-4]
        r = requests.get(url1, headers={'User-Agent': 'Mozilla/5.0'})
        page_soup = soup(r.content, 'html.parser')
        img = page_soup.find('img', id='ci').attrs['src']
        img = "https:" + img
        if (img):
            bot.sendPhoto(chat_id, img)
            inl = []
            if (num == 1):
                inl.append(
                    InlineKeyboardButton(text="N/A",
                                         parse_mode='Markdown',
                                         callback_data="hshsh"))
            else:
                inl.append(
                    InlineKeyboardButton(text="<< " + str(num - 1),
                                         parse_mode='Markdown',
                                         callback_data=query_data[:pos + 1] +
                                         str(num - 1) + "open"))
            inl.append(
                InlineKeyboardButton(text="<",
                                     parse_mode='Markdown',
                                     callback_data="whwus"))
            inl.append(
                InlineKeyboardButton(text="1",
                                     parse_mode='Markdown',
                                     callback_data="jsjhs"))
            inl.append(
                InlineKeyboardButton(text=">",
                                     parse_mode='Markdown',
                                     callback_data=query_data[:-4] + "/2ope"))
            if (num == ep):
                inl.append(
                    InlineKeyboardButton(text="end",
                                         parse_mode='Markdown',
                                         callback_data="dhddh"))
            else:
                inl.append(
                    InlineKeyboardButton(text=str(num + 1) + " >>",
                                         parse_mode='Markdown',
                                         callback_data=query_data[:pos + 1] +
                                         str(num + 1) + "open"))
            bot.sendMessage(
                msg['from']['id'],
                "Ch " + str(num) +
                ": Use the slider to jump pages or chapters",
                reply_markup=InlineKeyboardMarkup(inline_keyboard=[inl]))

    elif (query_data[-3:] == "ope"):
        s = query_data[:-3]
        pg = po = pos = 0
        ch = 0
        for i in range(-1, -10, -1):
            if (s[i] == "/" and pg == 0):
                pg = int(s[i + 1:])
                po = i
            elif (s[i] == "/" and pg != 0):
                ch = int(s[i + 1:po])
                pos = i
                break

        url1 = 'https://www.mangareader.net' + s[:pos]
        r = requests.get(url1, headers={'User-Agent': 'Mozilla/5.0'})
        page_soup = soup(r.content, 'html.parser')
        ep = page_soup.find("ul", class_="d44")
        ep = ep.find('a').attrs['href']
        posi = 0
        inl = []
        for i in range(-1, -5, -1):
            if (ep[i] == "/"):
                posi = i
                ep = int(ep[i + 1:])
                break

        url1 = 'https://www.mangareader.net' + query_data[:-3]
        r = requests.get(url1, headers={'User-Agent': 'Mozilla/5.0'})
        page_soup = soup(r.content, 'html.parser')
        img = page_soup.find('img', id='ci').attrs['src']
        img = "https:" + img
        if (img):
            msg_id = msg['message']['message_id']
            msg_id = str(int(msg_id) - 1)
            media = json.dumps({'type': 'photo', 'media': img})
            message = f"https://api.telegram.org/bot{TOKEN}/editMessageMedia?chat_id={chat_id}&message_id={msg_id}&media={media}"
            result = requests.post(message)
            inl = []
            if (ch == 1):
                inl.append(
                    InlineKeyboardButton(text="N/A",
                                         parse_mode='Markdown',
                                         callback_data="hshsh"))
            else:
                inl.append(
                    InlineKeyboardButton(text="<< " + str(ch - 1),
                                         parse_mode='Markdown',
                                         callback_data=s[:pos + 1] +
                                         str(ch - 1) + "open"))
            if (pg == 1):
                inl.append(
                    InlineKeyboardButton(text="<",
                                         parse_mode='Markdown',
                                         callback_data="whwus"))
            else:
                inl.append(
                    InlineKeyboardButton(text="<",
                                         parse_mode='Markdown',
                                         callback_data=s[:po + 1] +
                                         str(pg - 1) + "ope"))
            inl.append(
                InlineKeyboardButton(text=str(pg),
                                     parse_mode='Markdown',
                                     callback_data="jsjhs"))
            inl.append(
                InlineKeyboardButton(text=">",
                                     parse_mode='Markdown',
                                     callback_data=s[:po + 1] + str(pg + 1) +
                                     "ope"))
            if (ch == ep):
                inl.append(
                    InlineKeyboardButton(text="end",
                                         parse_mode='Markdown',
                                         callback_data="dhddh"))
            else:
                inl.append(
                    InlineKeyboardButton(text=str(ch + 1) + " >>",
                                         parse_mode='Markdown',
                                         callback_data=s[:pos + 1] +
                                         str(ch + 1) + "open"))
        bot.editMessageReplyMarkup(
            ide, reply_markup=InlineKeyboardMarkup(inline_keyboard=[inl]))

    elif (query_data == "searchback"):
        query_id, chat_id, query_data = telepot.glance(msg,
                                                       flavor='callback_query')
        if (msg['message']['chat']['type'] == 'group'):
            chat_id = msg['message']['chat']['id']
        ide = (chat_id, msg['message']['message_id'])
        bot.answerCallbackQuery(query_id,
                                text="Search Again!!!",
                                show_alert=True)
Ejemplo n.º 46
0
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    print(content_type, chat_type, chat_id)
    p_path = join("players", "p_" + str(chat_id))

    def print_room(location):
        room = kanto[location['room']]
        u_list = users_list(location['region'], location['room'])
        u_str = ''
        for user in u_list.values():
            if u_str == '':
                u_str = user
            else:
                u_str = '{0}, {1}'.format(u_str, user)
        str = ''
        if len(u_list) == 1:
            str = 'Here you can see another trainer:\n' + u_str
        elif len(u_list) > 1:
            str = 'Here you can see other trainers:\n' + u_str

        if len(str) > 0:
            str = '\n' + str

        bot.sendMessage(chat_id,
                        room.shortdescription + "\n" + room.description + str)

    def p_delete():
        p_shelve = shelve.open(join("players", "p_" + str(chat_id)))
        location = p_shelve['location']
        l_shelve = shelve.open('locations', writeback=True)
        room = l_shelve[location['region']][location['room']]
        del room[chat_id]
        pprint(dict(l_shelve))
        l_shelve.close()
        p_shelve.close()
        remove(p_path)

    def users_list(region, room):
        l_shelve = shelve.open('locations')
        room = dict(l_shelve[region][room])
        pprint(dict(l_shelve))
        if chat_id in room.keys():
            del room[chat_id]
        return room

    if content_type == 'text':
        txt = msg['text']
        if not exists(p_path):
            if '/start' in txt:
                bot.sendMessage(
                    chat_id,
                    "Welcome to PokeMUD! Let's create your character!")
                bot.sendMessage(chat_id, "To register type /register Name")
            if '/register' in txt:
                with shelve.open(p_path) as p_shelve:
                    p_register(p_shelve, txt[10:], chat_id)
        else:
            p_shelve = shelve.open(p_path)
            name = p_shelve['info']['name']
            location = p_shelve['location']

            def move_user(new_region, new_room):
                l_shelve = shelve.open('locations', writeback=True)
                old_region = location['region']
                old_room = location['room']
                region_dic = l_shelve[old_region]
                room_dic = region_dic[old_room]
                if chat_id in room_dic.keys():
                    del room_dic[chat_id]
                region_dic = l_shelve[new_region]
                room_dic = region_dic[new_room]
                room_dic[chat_id] = name
                p_shelve['location'] = {'region': new_region, 'room': new_room}
                l_shelve.close()
                print_room(p_shelve['location'])

            room = kanto[location['room']]
            if '/player' in txt:
                bot.sendMessage(
                    chat_id,
                    "Name: " + p_shelve['info']['name'] + "\nLocation: " +
                    location['region'] + " " + location['room'])
            elif '/location' in txt:
                print_room(location)
            elif txt == '/north':
                if room.n is not None:
                    move_user('kanto', room.n)
                else:
                    bot.sendMessage(chat_id, "Sorry, you can't go that way")
            elif txt == '/south':
                if room.s is not None:
                    move_user('kanto', room.s)
                else:
                    bot.sendMessage(chat_id, "Sorry, you can't go that way")
            elif txt == '/east':
                if room.e is not None:
                    move_user('kanto', room.e)
                else:
                    bot.sendMessage(chat_id, "Sorry, you can't go that way")
            elif txt == '/west':
                if room.w is not None:
                    move_user('kanto', room.w)
                else:
                    bot.sendMessage(chat_id, "Sorry, you can't go that way")
            elif txt == '/up':
                if room.u is not None:
                    move_user('kanto', room.u)
                else:
                    bot.sendMessage(chat_id, "Sorry, you can't go that way")
            elif txt == '/down':
                if room.d is not None:
                    move_user('kanto', room.d)
                else:
                    bot.sendMessage(chat_id, "Sorry, you can't go that way")
            elif '/delete' in txt:
                if txt[8:] == p_shelve['info']['name']:
                    p_delete(chat_id)

            p_shelve.close()
Ejemplo n.º 47
0
def handle(msg):

    # Configurações da variavel para controlar
    # a estrutura de decisao e tambem a variavel
    # que salva os dados do chat em uma tupla
    command = msg['text']
    content_type, chat_type, chat_id = telepot.glance(msg)
    m = telepot.namedtuple.Message(**msg)

    # função criada para fazer uma verificação
    # e ver se a messagem foi enviada de um grupo
    # ou de um chat privado e tambem mostrar para
    # o responsavel pelo bot quem esta utilizando
    # e quais comandos e em que hora ** NO FUTURO SALVAR ISSO NO BANCO**
    def getinfo(chat_id):
        if chat_id < 0:
            print 'Menssage do tipo %s: \n' % (content_type, )

            print 'Chat ID : %s' % m.chat[0]
            print 'Tipo de chat : %s' % m.chat[1]
            print 'Nome do Grupo: %s' % m.chat[2]
            print 'Username : %s' % m.chat[3]
            print 'First Name: %s' % m.chat[4]
            print 'Last Name: %s' % m.chat[5]
            print 'Enviada por %s' % (m.from_, )
            print time.strftime('%Y-%m-%d %H:%M:%S')
            print '--------------------------------------'
        else:
            print 'Messagem do tipo %s: \n' % (content_type, )

            print 'Chat ID : %s' % m.chat[0]
            print 'Tipo de chat : %s' % m.chat[1]
            print 'Username : %s' % m.chat[3]
            print 'First Name: %s' % m.chat[4]
            print 'Last Name: %s' % m.chat[5]
            print time.strftime('%Y-%m-%d %H:%M:%S')
            print '--------------------------------------'

    if command == '/start':
        start(chat_id, keyboard)
        getinfo(chat_id)

    elif command == 'Temperatura':
        temperature(chat_id, command)
        getinfo(chat_id)

    elif command == 'Processos':
        process(chat_id, command)
        getinfo(chat_id)

    elif command == 'Memoria':
        memory(chat_id, command)
        getinfo(chat_id)

    elif command == 'UpTime':
        upTime(chat_id, command)
        getinfo(chat_id)

    elif command == 'UsoSD':
        sdCard(chat_id, command)
        getinfo(chat_id)

    elif command == 'Data':
        date(chat_id, command)
        getinfo(chat_id)

    elif command == 'Rede':
        network(chat_id, command)
        getinfo(chat_id)

    elif command == 'IP':
        ip(chat_id, command)
        getinfo(chat_id)

    elif command == '/help':
        help(chat_id, command)
        getinfo(chat_id)

# menssagem de erro caso o usuario digite alguma coisa manualmente
    else:
        bot.sendMessage(chat_id, 'Use os comandos no teclado')
        bot.sendMessage(chat_id, 'Ainda nao sei ler =(')
Ejemplo n.º 48
0
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    trans_tab = dict.fromkeys(map(ord, u'\u0301\u0308'), None)
    namebot = normalize('NFKC', normalize('NFKD', bot.getMe().get("username")).translate(trans_tab)).lower()

    #\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\#
    # - # - # Normalizando string comando # - # - #
    texto = msg.get("text","sinTexto")
    parametros=texto.split(" ",1)
    stringCMD=parametros[0].split("@")
    comando=normalize('NFKC', normalize('NFKD', stringCMD[0]).translate(trans_tab)).lower()
    if len(stringCMD) > 1:
        callbot = normalize('NFKC', normalize('NFKD', stringCMD[1]).translate(trans_tab)).lower()
    else:
        callbot = namebot

    #\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\#
    def sendRandom(c_type,answer,capt = None):
        try:
            if c_type == "photo":
                bot.sendPhoto(chat_id, answer, caption=capt, parse_mode="HTML")
            elif c_type == "text":
                bot.sendMessage(chat_id, answer, parse_mode="HTML")
            elif c_type == "sticker":
                bot.sendSticker(chat_id, answer)
        except(TypeError, NameError, ValueError):
            bot.sendMessage(chat_id,"problemas de envio")

    #\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\#
    def initial():
        try:
            if chat_type == 'private':
                if comando == "/start":
                    txt="Que quieres?:\n\n"\
                    "Puedes enviar /galletadelafortuna\n"\
                    "para recibir una galleta de la fortuna\n\n"\
                    "envía /help para ver los demas comandos"
                elif comando == "/help":
                    txt="<b>Lista de Comandos</b>:\n"\
                    "/GalletadelaFortuna - una galleta de la fortuna.\n"\
                    "/Haluze - imagen random de un servidor ruso.\n"\
                    "/sticker - se envia un sticker\n"\
                    "/dedGrup -  envia el meme de ded grup.\n"\
                    "/Horoscopo [signo]* - tu horoscopo.\n\n"\
                    "<pre>* : parametro obigatorio</pre>"
            # - # - # - # - # - #
            elif callbot == namebot:
                if comando == "/start":
                    txt="¿Que quieres?:\n\n"\
                    "Puedes enviar /galletadelafortuna\n"\
                    "para recibir una galleta de la fortuna"
                elif comando == "/help":
                    txt = "Solo por interno"
            # - # - # - # - # - #
            sendRandom("text",txt)
        except(TypeError, NameError, ValueError):
            bot.sendMessage(chat_id,"problemas iniciales")

    #\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\#
    def galletas_Random():
        try:
            idRandom = str(randint(4,178))
            Photo = "t.me/picturesBank/" + idRandom
            capt = "Tu <b>galleta de la fortuna</b>, puedes solicitar luego"
            # - # - # - # - # - #
            sendRandom("photo",Photo,capt)
        except(TypeError, NameError, ValueError):
            bot.sendMessage(chat_id,"problemas con galletas")

    #\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\#
    def haluze_Random():
        try:
            rndPhoto = str(randint(7,21787))
            Photo = "halbot.haluze.sk/image/" + rndPhoto
            capt = "servidor <a href=\""+Photo+"\">haluze</a> de Rusia"
            # - # - # - # - # - #
            sendRandom("photo",Photo,capt)
        except(TypeError, NameError, ValueError):
            bot.sendMessage(chat_id,"problemas con haluze")

    #\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\#
    def sticker_Random():
        try:
            if comando == "/sticker":
                stickersList = [
                    "CAADAQADxwEAAxi_A_v9_T_9ezeBFgQ","CAADAQADwgEAAxi_A5DDSzE--rx0FgQ",
                    "CAADBQADyRkAAribGhZcu8LcUrw5phYE","CAADBQADyBkAAribGhaiuCpwS1kBjBYE"
                    ]
            rndSticker = choice(stickersList)
            sendRandom("sticker",rndSticker)
        except(TypeError, NameError, ValueError):
            bot.sendMessage(chat_id,"problemas con sticker")

    #\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\#
    def horoscopo_Random():
        try:
            if len(parametros) > 1:
                listSigno = parametros[1].split(" ",1)
                signo = normalize('NFKC', normalize('NFKD', listSigno[0]).translate(trans_tab)).lower()
            else:
                signo = "ninguno"
            # - # - # - # - # - #
            if signo=="aries":
                text = "Aries: siempre con humitos en la cabeza, hace algo por la vida, el horoscopo no sirve wn!"
            elif signo=="tauro":
                text = "Tauro: que mierda buscai en el horoscopo, levantate de esa silla y sal a trabajar."
            elif signo=="geminis":
                text = "Géminis: weon bipolar, aqui esta toda la verdad, pero es mentira."
            elif signo=="cancer":
                text = "Cáncer: gente weona que cree que le dire que le va a pasar hoy, bañate antes de salir."
            elif signo=="leo":
                text = "Leo: no wn, no estan los numeros del loto aca, no gasti tu plata en wea y comprate comida de verdad."
            elif signo=="virgo":
                text = "Virgo: eres un virgo de mierda, deja de leer el horóscopo, moriras virgen!!"
            elif signo=="libra":
                text = "Libra: balanceate este, si queri balance hace mas deporte y sale a carretear con los amigos."
            elif signo=="escorpio":
                text = "Escorpio: uy, que miedo, ahí viene el alacran!!"
            elif signo=="escorpion":
                text = "Escorpio: el signo es ESCORPIO, no escorpion!!"
            elif signo=="sagitario":
                text = "Sagitario: ni tan santo, igual seiya te cago con la armadura."
            elif signo=="capricornio":
                text = "Capricornio: otro wn mas buscando su salud aca, sale a respirar aigre."
            elif signo=="acuario":
                text = "Acuario: sale a trabajar, la plata no llega sola, leyendo el horoscopo no te vai a jubilar antes."
            elif signo=="piscis":
                text = "Piscis: el horoscopo es pa mentes cerradas, abrete y lanzate a la vida."
            elif signo=="negro":
                text = "Negro teni el hoyo"
            elif signo=="chino":
                text = "no te conformas con las galletas?"
            elif signo=="ninguno":
                text = "debes ingresar un signo. ej: <code>/horoscopo aries</code>"
            else:
                text = "Algo esta mal, revisalo e intenta de nuevo"
            # - # - # - # - # - #
            sendRandom("text",text)
        except(TypeError, NameError, ValueError):
            bot.sendMessage(chat_id,"problemas con horoscopo")

    #\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\#
    def dedgrup_Random():
        try:
            sendRandom("text","ded grup")
            sendRandom("sticker","CAADBAADZgADddnUCDenF6VnTTiDFgQ")
        except(TypeError, NameError, ValueError):
            bot.sendMessage(chat_id,"problemas con dedgrup")

    #\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\#
    def noRandom():
        try:
            if chat_type == 'private':
                if texto[0] == "/":
                    noComando =  "El comando " +comando+ " no está implementado \nMás información en /help"                    
                else:
                    noComando =  "esto no funciona así\nMás información en /help"
                sendRandom("text", noComando)
        except(TypeError, NameError, ValueError):
            bot.sendMessage(chat_id,"problemas de no Random")

    #\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\#
    try:
        if comando=="/start" or comando=="/help":
            initial()
        elif comando=="/galletadelafortuna":
            galletas_Random()
        elif comando=="/haluze":
            haluze_Random()
        elif comando=="/horoscopo":
            horoscopo_Random()
        elif comando=="/sticker":
            sticker_Random()
        elif comando=="/dedgrup":
            dedgrup_Random()
        else:
            noRandom()
    except(IndexError):
        bot.sendMessage(chat_id,"problemas con el Bot")
        print ('error...')
Ejemplo n.º 49
0
def on_chosen_inline_result(msg):
    result_id, from_id, query_string = telepot.glance(
        msg, flavor='chosen_inline_result')
    print 'Chosen Inline Result:', result_id, from_id, query_string
Ejemplo n.º 50
0
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    print(content_type, chat_type, chat_id)

    if content_type == 'text':
        TelegramBot.sendMessage(chat_id, "You said '{}'".format(msg["text"]))
Ejemplo n.º 51
0
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 == 'play':
        bot.answerCallbackQuery(query_id, text='play')
        print('pressed play')
        os.system('ssh ' + kueche_IP + ' " mpc volume 100 && mpc play"')
        os.system(
            'ssh ' + schlafzi_IP +
            ' " sudo systemctl stop snapclient && omxplayer -o alsa --loop /home/pi/rain.mp3"'
        )
        os.system(
            'ssh ' + wohnzi_IP +
            ' " /volumio/app/plugins/system_controller/volumio_command_line_client/volumio.sh play"'
        )

    elif query_data == 'stop':
        bot.answerCallbackQuery(query_id, text='stop')
        print('pressed stop')
        os.system('ssh ' + kueche_IP + ' " mpc stop && mpc volume 100"')
        os.system(
            'ssh ' + schlafzi_IP +
            ' " killall omxplayer.bin  && sudo systemctl start snapclient"')
        os.system(
            'ssh ' + wohnzi_IP +
            ' " /volumio/app/plugins/system_controller/volumio_command_line_client/volumio.sh stop"'
        )

    elif query_data == 'next':
        bot.answerCallbackQuery(query_id, text='next')
        print('pressed next')
        os.system(
            'ssh ' + wohnzi_IP +
            ' " /volumio/app/plugins/system_controller/volumio_command_line_client/volumio.sh next"'
        )

    elif query_data == 'schlafzi-on':
        bot.answerCallbackQuery(query_id, text='Schlafzimmer angeschaltet!')
        plug_schlafzi_on_command = "/home/pi/hs100/hs100.sh on -i " + plug_schlafzi_IP
        print(plug_schlafzi_on_command)
        os.system(plug_schlafzi_on_command)

    elif query_data == 'kueche-on':
        bot.answerCallbackQuery(query_id, text='Kueche angeschaltet!')
        os.system('ssh ' + kueche_IP + ' " mpc volume 100 && mpc play"')
        plug_kueche_on_command = "/home/pi/hs100/hs100.sh on -i " + plug_kueche_IP
        print(plug_kueche_on_command)
        os.system(plug_kueche_on_command)

    elif query_data == 'wohnzi-on':
        bot.answerCallbackQuery(query_id, text='Wohnzimmer angeschaltet!')
        plug_wohnzi_on_command = "/home/pi/hs100/hs100.sh on -i " + plug_wohnzi_IP
        print(plug_wohnzi_on_command)
        os.system(plug_wohnzi_on_command)

    elif query_data == 'schlafzi-off':
        bot.answerCallbackQuery(query_id, text='Schlafzimmer aus!')
        os.system(
            'killall alles-off-30.sh')  #zuerst evlt  bestehende timer canceln
        os.system(
            'killall alles-off-45.sh')  #zuerst evtl bestehende timer canceln
        print('schlafzi pressed off')

        os.system('/home/pi/pi-music-bot/schlafzi-off.sh')

    elif query_data == 'kueche-off':
        bot.answerCallbackQuery(query_id, text='Kueche aus!')
        #os.system('killall alles-off-30.sh') #zuerst evlt  bestehende timer canceln
        #os.system('killall alles-off-45.sh') #zuerst evtl bestehende timer canceln
        print('kueche pressed off')
        os.system('/home/pi/pi-music-bot/kueche-off.sh')
        os.system('ssh ' + kueche_IP + ' " mpc stop"')

    elif query_data == 'wohnzi-off':
        bot.answerCallbackQuery(query_id, text='Wohnzimmer aus!')
        os.system(
            'killall alles-off-30.sh')  #zuerst evlt  bestehende timer canceln
        os.system(
            'killall alles-off-45.sh')  #zuerst evtl bestehende timer canceln
        print('wohnzi pressed off')
        os.system('/home/pi/pi-music-bot/wohnzi-off.sh')

    elif query_data == 'alles-off':
        print('alles pressed off')
        os.system(
            'killall alles-off-30.sh')  #zuerst evlt  bestehende timer canceln
        os.system(
            'killall alles-off-45.sh')  #zuerst evtl bestehende timer canceln
        bot.answerCallbackQuery(query_id, text='Alles aus!')
        os.system('/home/pi/pi-music-bot/alles-off.sh')

    elif query_data == 'alles-off-30':
        print('alles30 pressed off')
        os.system(
            'killall alles-off-30.sh')  #zuerst evlt  bestehende timer canceln
        os.system(
            'killall alles-off-45.sh')  #zuerst evtl bestehende timer canceln
        bot.answerCallbackQuery(query_id, text='Timer 30 min!')
        os.system('/home/pi/pi-music-bot/alles-off-30.sh &')

    elif query_data == 'alles-off-45':
        os.system(
            'killall alles-off-30.sh')  #zuerst evlt  bestehende timer canceln
        os.system(
            'killall alles-off-45.sh')  #zuerst evtl bestehende timer canceln
        print('alles45 pressed off')
        bot.answerCallbackQuery(query_id, text='Timer 45 min!')
        os.system('/home/pi/pi-music-bot/alles-off-45.sh &')

    elif query_data == 'alles-off-cancel':
        print('alles off canceled')
        bot.answerCallbackQuery(query_id, text='Timer abgebrochen!!')
        os.system('killall alles-off-30.sh')
        os.system('killall alles-off-45.sh')

    elif query_data == 'playlist1':
        print('playlist1 pressed')
        bot.answerCallbackQuery(query_id, text='Playlist 1 play!')
        os.system('curl ' + wohnzi_IP +
                  '/api/v1/commands/?cmd="playplaylist&name=playlist1"')

    elif query_data == 'playlist2':
        print('playlist2 pressed')
        bot.answerCallbackQuery(query_id, text='Playlist 2 play!')
        os.system('curl ' + wohnzi_IP +
                  '/api/v1/commands/?cmd="playplaylist&name=playlist2"')

    elif query_data == 'playlist3':
        print('playlist2 pressed')
        bot.answerCallbackQuery(query_id, text='Playlist 3 play!')
        os.system('curl ' + wohnzi_IP +
                  '/api/v1/commands/?cmd="playplaylist&name=playlist3"')

    elif query_data == 'playlist4':
        print('playlist4 pressed')
        bot.answerCallbackQuery(query_id, text='Playlist 4 play!')
        os.system('curl ' + wohnzi_IP +
                  '/api/v1/commands/?cmd="playplaylist&name=playlist4"')

    elif query_data == 'playlist5':
        print('playlist5 pressed')
        bot.answerCallbackQuery(query_id, text='Playlist 5 play!')
        os.system('curl ' + wohnzi_IP +
                  '/api/v1/commands/?cmd="playplaylist&name=playlist5"')

    elif query_data == 'playlist6':
        print('playlist6 pressed')
        bot.answerCallbackQuery(query_id, text='Playlist 6 play!')
        os.system('curl ' + wohnzi_IP +
                  '/api/v1/commands/?cmd="playplaylist&name=playlist6"')

    elif query_data == 'playlist7':
        print('playlist7 pressed')
        bot.answerCallbackQuery(query_id, text='Playlist 7 play!')
        os.system('curl ' + wohnzi_IP +
                  '/api/v1/commands/?cmd="playplaylist&name=playlist7"')

    elif query_data == 'playlist8':
        print('playlist8 pressed')
        bot.answerCallbackQuery(query_id, text='Playlist 8 play!')
        os.system('curl ' + wohnzi_IP +
                  '/api/v1/commands/?cmd="playplaylist&name=playlist8"')
Ejemplo n.º 52
0
def on_chat_message(msg):
    chat_id = msg['chat']['id']  # Receiving the message from telegram
    command = msg['text']  # Getting text from the message

    if command == '/track':
        trackid = subprocess.Popen("curl " + wohnzi_IP + "/api/v1/getstate",
                                   stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE,
                                   shell=True)
        (outputRAW, error) = trackid.communicate()
        if trackid.returncode != 0:
            bot.sendMessage(
                chat_id,
                str("Wohnzi aus? Full Error Message: %d %s %s" %
                    (trackid.returncode, outputRAW, error)))
        else:
            title = outputRAW.decode().split(
                '\"'
            )[9]  #curl status string split and select 9th word, which is the track title
            artist = outputRAW.decode().split('\"')[
                13]  #..13th word, is artist
            albumart = outputRAW.decode().split('\"')[
                21]  #.. 21th word, is albumart link
            bot.sendMessage(chat_id, str(albumart))
            bot.sendMessage(chat_id, str(artist) + str(' - ') + str(title))

    elif command == '/dose1':
        dose1 = subprocess.Popen("/home/pi/hs100/hs100.sh -i " +
                                 plug_schlafzi_IP + " status",
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE,
                                 shell=True)
        (output, error) = dose1.communicate()
        if dose1.returncode != 0:
            bot.sendMessage(
                chat_id,
                str("WLAN zu schlecht? Full Error Message: %d %s %s" %
                    (dose1.returncode, output, error)))
        else:
            outputSplit = output.decode().split(',\n')
            bot.sendMessage(
                chat_id,
                str(outputSplit[1]) + str(outputSplit[18]) +
                str(outputSplit[19]))

    elif command == '/dose2':
        dose2 = subprocess.Popen("/home/pi/hs100/hs100.sh -i " +
                                 plug_kueche_IP + " status",
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE,
                                 shell=True)
        (output, error) = dose2.communicate()
        if dose2.returncode != 0:
            bot.sendMessage(
                chat_id,
                str("WLAN zu schlecht? Full Error Message: %d %s %s" %
                    (dose2.returncode, output, error)))
        else:
            outputSplit = output.decode().split(',\n')
            bot.sendMessage(
                chat_id,
                str(outputSplit[1]) + str(outputSplit[18]) +
                str(outputSplit[19]))

    elif command == '/dose3':
        dose3 = subprocess.Popen("/home/pi/hs100/hs100.sh -i " +
                                 plug_wohnzi_IP + " status",
                                 stdout=subprocess.PIPE,
                                 stderr=subprocess.PIPE,
                                 shell=True)
        (output, error) = dose3.communicate()
        if dose3.returncode != 0:
            bot.sendMessage(
                chat_id,
                str("WLAN zu schlecht? Full Error Message: %d %s %s" %
                    (dose3.returncode, output, error)))
        else:
            outputSplit = output.decode().split(',\n')
            bot.sendMessage(
                chat_id,
                str(outputSplit[1]) + str(outputSplit[18]) +
                str(outputSplit[19]))

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

    keyboard = InlineKeyboardMarkup(inline_keyboard=[
        [
            InlineKeyboardButton(text='\U000025B6 play', callback_data='play'),
            InlineKeyboardButton(text='\U000025FB stop', callback_data='stop'),
            InlineKeyboardButton(text='\U000023E9 next', callback_data='next')
        ],
        [
            InlineKeyboardButton(text='\U0001F4C41',
                                 callback_data='playlist1'),
            InlineKeyboardButton(text='\U0001F4C42',
                                 callback_data='playlist2'),
            InlineKeyboardButton(text='\U0001F4C43',
                                 callback_data='playlist3'),
            InlineKeyboardButton(text='\U0001F4C44',
                                 callback_data='playlist4'),
            InlineKeyboardButton(text='\U0001F4C45',
                                 callback_data='playlist5'),
            InlineKeyboardButton(text='\U0001F4C46',
                                 callback_data='playlist6'),
            InlineKeyboardButton(text='\U0001F4C47',
                                 callback_data='playlist7'),
            InlineKeyboardButton(text='\U0001F4C48', callback_data='playlist8')
        ],
        [
            InlineKeyboardButton(text='\U0001F6CF \U0001F50A ',
                                 callback_data='schlafzi-on'),
            InlineKeyboardButton(text='\U0001F374\U0001F50A',
                                 callback_data='kueche-on'),
            InlineKeyboardButton(text='\U0001F6CB \U0001F50A',
                                 callback_data='wohnzi-on')
        ],
        [
            InlineKeyboardButton(text='\U0001F6CF \U0001F507',
                                 callback_data='schlafzi-off'),
            InlineKeyboardButton(text='\U0001F374\U0001F507',
                                 callback_data='kueche-off'),
            InlineKeyboardButton(text='\U0001F6CB \U0001F507',
                                 callback_data='wohnzi-off')
        ],
        [
            InlineKeyboardButton(
                text='\U0001F6CF\U0001F374\U0001F6CB\U0001F507',
                callback_data='alles-off'),
            InlineKeyboardButton(text='\U0001F552 t-30',
                                 callback_data='alles-off-30'),
            InlineKeyboardButton(text='\U0001F552 t-45',
                                 callback_data='alles-off-45'),
            InlineKeyboardButton(text='\U0001F552\U0000274C',
                                 callback_data='alles-off-cancel')
        ],
    ])

    bot.sendMessage(chat_id,
                    ('Hi! Um den aktuellen Titel zu sehen, gib /track ein!'),
                    reply_markup=keyboard)
Ejemplo n.º 53
0
    def on_chat_message(self, msg):
        content_type, chat_type, chat_id = telepot.glance(msg)
        print(content_type, chat_type, chat_id)

        # get available buttons for keyboard
        food_pref = menu.keys()

        # when user wants to find nearest canteen, use Google Maps API to get details to get there
        if content_type == 'location':
            x = msg['location']['latitude']
            y = msg['location']['longitude']
            #parse location from telegram and change into gmaps format
            origins = [[x, y]]
            destinations = [[1.346628, 103.686028], [1.348363, 103.685482],
                            [1.344189, 103.685439], [1.352270, 103.685298],
                            [1.354908, 103.686477], [1.351721, 103.681082],
                            [1.352692, 103.682108], [1.350299, 103.680914],
                            [1.354395, 103.688173], [1.347029, 103.680254],
                            [1.342459, 103.682427], [1.348746, 103.677614]]
            # nearest canteen determined
            n = Nearest_Canteen(x, y)
            listz = (GetAllDistance_Canteen(origins, destinations))
            distance_timetowalk = listz[
                n]  # extract time and duration for the nearest canteen
            menu_response = ('The nearest food location is ' + canfood[n] +
                             '.\nIt is approximately ' +
                             distance_timetowalk[0] +
                             ' away\nWhich is about ' +
                             distance_timetowalk[1] + ' if you walk.')
            menu_keyboard = ReplyKeyboardMarkup(
                one_time_keyboard=True,
                keyboard=[[KeyboardButton(text=pref)]
                          for pref in food_pref] + [[
                              KeyboardButton(text='Find Nearest Canteen',
                                             request_location=True)
                          ]])

            bot.sendMessage(chat_id, menu_response, reply_markup=menu_keyboard)
            bot.sendMessage(
                chat_id, 'What can I do for you?'
            )  # added this line to get user to choose options again if required

            # move to second state for user to choose options
            self.state = choose_second_button
        else:

            try:

                #initial response when bot is started
                if msg['text'] == '/start' or self.state == 0:  # consider /start for resetting bot

                    response = 'Welcome to NTU Food Bot!\nFood decisions are very personal,\nso I will only work in private chats!!'

                    bot.sendMessage(chat_id, response)

                    # prepare custom keyboard
                    choose_first_keyboard = ReplyKeyboardMarkup(
                        one_time_keyboard=True,
                        keyboard=[[KeyboardButton(text=pref)]
                                  for pref in food_pref] +
                        [[
                            KeyboardButton(text='Find Nearest Canteen',
                                           request_location=True)
                        ]])

                    response = 'What can I do for you?'

                    bot.sendMessage(chat_id,
                                    response,
                                    reply_markup=choose_first_keyboard)

                    # move to next state
                    self.state = choose_second_button

                # to avoid repeating welcome message after bot is started
                elif (self.state > choose_first_button):

                    msg_text = msg['text']
                    # placeholders for keyboard and response
                    menu_keyboard = ReplyKeyboardMarkup(
                        one_time_keyboard=True,
                        keyboard=[[KeyboardButton(text=pref)]
                                  for pref in food_pref] +
                        [[
                            KeyboardButton(text='Find Nearest Canteen',
                                           request_location=True)
                        ]])
                    menu_response = ''

                    #separate into different functions when different buttons are selected
                    if (self.state == choose_second_button):

                        #when food preference is chosen
                        if 'Preference' in msg_text:

                            #update context preference for later re-use
                            self.pref = msg_text

                            #load list of canteens for the chosen preference
                            which_canteen = menu[self.pref]

                            #prepare keyboard and response to get user selection of canteen
                            menu_keyboard = ReplyKeyboardMarkup(
                                one_time_keyboard=True,
                                keyboard=[[KeyboardButton(text=canteens)]
                                          for canteens in which_canteen.keys()
                                          ] +
                                [[KeyboardButton(text='Return to main menu')]])

                            menu_response = 'Which canteen?'

                            # move to next state
                            self.state = choose_third_button

                        #when user want to give review about a stall
                        elif 'Give/Check stall rating' in msg_text:

                            #load list of canteens for review
                            which_canteen = menu['Give/Check stall rating']

                            # prepare keyboard and response to get user selection of canteen
                            menu_keyboard = ReplyKeyboardMarkup(
                                one_time_keyboard=True,
                                keyboard=[[KeyboardButton(text=canteens)]
                                          for canteens in which_canteen.keys()
                                          ] +
                                [[KeyboardButton(text='Return to main menu')]])

                            menu_response = 'Which canteen?'

                            # move to next state
                            self.state = review_stall_button

                    #for user to choose what food type they prefer
                    elif (self.state == choose_third_button):

                        if msg_text != 'Return to main menu':

                            # update context canteen for later re-use
                            self.can = msg_text

                            # load list of food types for the chosen canteen
                            what_food_type = menu[self.pref][self.can]

                            # prepare keyboard and response to get user selection of food type
                            menu_keyboard = ReplyKeyboardMarkup(
                                one_time_keyboard=True,
                                keyboard=[[KeyboardButton(text=stalls)]
                                          for stalls in what_food_type.keys()
                                          ] +
                                [[KeyboardButton(text='Return to main menu')]])

                            menu_response = 'What food type?'

                            # move to next state
                            self.state = list_stalls

                        else:

                            menu_response = 'What can I do for you?'

                            self.state = choose_second_button

                    #return list of stalls for the chosen food type
                    elif (self.state == list_stalls):

                        if msg_text != 'Return to main menu':

                            # update context food type for later re-use
                            self.type = msg_text

                            # load list of stalls for the chosen food type
                            menu_response = menu[self.pref][self.can][
                                self.type]

                            # move to second state for user to choose options
                            self.state = choose_second_button

                            bot.sendMessage(chat_id,
                                            menu_response,
                                            reply_markup=menu_keyboard)
                            bot.sendMessage(
                                chat_id, 'What can I do for you?'
                            )  # added this line to get user to choose options again if required
                            return

                        else:

                            menu_response = 'What can I do for you?'

                            self.state = choose_second_button

                    #for user to choose stall
                    elif (self.state == review_stall_button):

                        if msg_text != 'Return to main menu':

                            # update context canteen for later re-use
                            self.can = msg_text

                            # load list of stalls for the chosen canteen
                            which_stall = menu['Give/Check stall rating'][
                                self.can]

                            # prepare keyboard and response to get user selection of stall
                            menu_keyboard = ReplyKeyboardMarkup(
                                one_time_keyboard=True,
                                keyboard=[[KeyboardButton(text=stalls)]
                                          for stalls in which_stall.keys()] +
                                [[KeyboardButton(text='Return to main menu')]])

                            menu_response = 'Which stall?'

                            # move to next state
                            self.state = review_give_ratings

                        else:

                            menu_response = 'What can I do for you?'

                            self.state = choose_second_button

                    #for user to enter rating for stall
                    elif (self.state == review_give_ratings):

                        if msg_text != 'Return to main menu':

                            # update context stall for later re-use
                            self.stall = msg_text

                            # obtain the position of the stall in the ratings lists from the dictionary
                            list_pos = menu['Give/Check stall rating'][
                                self.can][self.stall]

                            # prepare keyboard and response to get user rating of stall from 1 to 5
                            menu_keyboard = ReplyKeyboardMarkup(
                                one_time_keyboard=True,
                                keyboard=[[KeyboardButton(text=rating)]
                                          for rating in range(1, 6)] +
                                [[KeyboardButton(text='Return to main menu')]])

                            response = (
                                'The current rating for the stall is ' +
                                str(rating_avg[list_pos]) + 'тнР')

                            menu_response = "Please choose your rating for the stall.\nIf you don't want to give a rating, press 'Return to main menu'."

                            bot.sendMessage(chat_id, response)

                            # move to next state
                            self.state = review_get_rating

                            # store position in list
                            self.stallkey = list_pos

                        else:

                            menu_response = 'What can I do for you?'

                            self.state = choose_second_button

                    #for updating user rating to the rating database
                    elif (self.state == review_get_rating):

                        if msg_text != 'Return to main menu':

                            # update context rating for later re-use
                            self.rating = msg_text

                            # update numerator with addition of user rating
                            rating_num[self.stallkey] = rating_num[
                                self.stallkey] + int(self.rating)

                            # update denominator with addition of user rating
                            rating_div[self.stallkey] += 1

                            # obtain new average rating
                            before_rounding = rating_num[
                                self.stallkey] / rating_div[self.stallkey]

                            # round up value of average rating as accuracy required is only 1 decimal place, so round function is adequate
                            rating_avg[self.stallkey] = round(
                                before_rounding, 2)

                            # thank user for their rating
                            menu_response = 'Thank you for your review!'

                            # move to second state for user to choose options
                            self.state = choose_second_button

                            bot.sendMessage(chat_id,
                                            menu_response,
                                            reply_markup=menu_keyboard)
                            bot.sendMessage(
                                chat_id, 'What can I do for you?'
                            )  # added this line to get user to choose options again if required
                            return

                        else:

                            menu_response = 'What can I do for you?'

                            self.state = choose_second_button

                    bot.sendMessage(chat_id,
                                    menu_response,
                                    reply_markup=menu_keyboard)
                    return

            except:  # edge case, if user use their normal keyboard instead of custom keyboards
                bot.sendMessage(chat_id,
                                'Error, please use the keyboard provided!')
Ejemplo n.º 54
0
 def on_callback_query(self, msg):
     print("Callback")
     query_id, chat_id, data = telepot.glance(msg, flavor='callback_query')
     self.handleText(msg, chat_id, msg['data'])
Ejemplo n.º 55
0
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)

    if content_type == 'text':

        print(msg['chat']['first_name'], msg['chat']['last_name'], content_type, chat_type, chat_id, msg['text'])

        if msg['text'] == '/notification':
            activity.append([chat_id, 'notification'])
            bot.sendMessage(chat_id, 'Привет, ' + msg['chat']['first_name'])
            bot.sendMessage(chat_id, 'Создадим напоминание')
            bot.sendMessage(chat_id, 'Введи текст напоминания:')
            table.append([chat_id, 'null', 'null', 'note'])

        elif [chat_id, 'notification'] in activity:
            flag = True
            flag1 = True
            for i in range(0, len(table)):
                if table[i] == [chat_id, 'null', 'null', 'note']:
                    table[i] = [chat_id, msg['text'], 'null', 'date']
                    bot.sendMessage(chat_id, 'OK, теперь введи дату в формате HH:MM.DD-MM-YY')
                    flag = False
                    flag1 = False
                    break

            if flag1:
                for i in range(0, len(table)):
                    if table[i][0] == chat_id and table[i][3] == 'date':
                        table[i][2] = msg['text']
                        table[i][3] = 'ready'
                        bot.sendMessage(chat_id, 'Готово!')
                        activity.remove([chat_id, 'notification'])
                        flag = False
                        break

            if flag:
                bot.sendMessage(chat_id, 'Пользуйся командами, пес')

        if msg['text'] == '/show_notifications':
            bot.sendMessage(chat_id, 'Список твоих уведомлений:')
            for i in range(0, len(table)):
                if table[i][0] == chat_id:
                    bot.sendMessage(chat_id, table[i][1] + ", " + table[i][2])

        if msg['text'] == '/delete_notification':
            bot.sendMessage(chat_id,
                            'В формате HH:MM.DD-MM-YY введи дату, '
                            'на которую у тебя стоит уведомление, которое ты хочешь удалить')
            activity.append([chat_id, 'delete_notification'])

        elif [chat_id, 'delete_notification'] in activity:
            flag2 = True
            for i in range(0, len(table)):
                if table[i][0] == chat_id and table[i][2] == msg['text']:
                    bot.sendMessage(chat_id, 'Уведомление ' + table[i][1] + ' от ' + table[i][2] + ' удалено')
                    del table[i]
                    flag2 = False
                    break
            if flag2:
                bot.sendMessage(chat_id, 'на это время уведомлений нет')
            activity.remove([chat_id, 'delete_notification'])

    else:
        print(msg['chat']['first_name'], msg['chat']['last_name'], content_type, chat_type, chat_id)
        if [chat_id, 'notification'] in activity:
            bot.sendMessage(chat_id, 'нужно напоминание!')
        else:
            bot.sendMessage(chat_id, 'Пользуйся командами, пес')
Ejemplo n.º 56
0
def handle(msg):
    flavor = telepot.flavor(msg)

    summary = telepot.glance(msg, flavor=flavor)
    print flavor, summary
Ejemplo n.º 57
0
    def initOptionals(self):
        self.mfrom = self.original.get("from")
        if self.mfrom is not None:
            self.mfrom = Person(self.mfrom)

        self.fw_from = self.original.get('forward_from')
        if self.fw_from is not None:
            self.fw_from = Person(self.fw_from)

        self.fw_from_chat = self.original.get('forward_from_chat')
        if self.fw_from_chat is not None:
            self.fw_from_chat = Chat(self.fw_from_chat)

        self.fw_msg_id = self.original.get('forward_from_message_id')
        self.fw_date = self.original.get('forward_date')

        self.reply = self.original.get('reply_to_message')
        if self.reply is not None:
            self.reply = Message(self.reply)

        self.date = self.original.get('edit_date')

        content_type, _, _ = telepot.glance(self.original)
        self.content_type = content_type
        self.known_content = [
            "text", "photo", "new_chat_member", "sticker", "video", "document",
            "voice", "video_note", "audio"
        ]

        self.content = None

        if self.content_type == "text":
            self.content = Text(self.original["text"])

        if self.content_type == "photo":
            self.content = Photos(self.original["photo"])

        if self.content_type == "sticker":
            self.content = Sticker(self.original["sticker"])

        if self.content_type == "video":
            self.content = Video(self.original["video"])

        if self.content_type == "document":
            self.content = Document(self.original["document"])

        if self.content_type == "voice":
            self.content = Voice(self.original["voice"])

        if self.content_type == "video_note":
            self.content = VideoNote(self.original["video_note"])

        if self.content_type == "audio":
            self.content = Audio(self.original["audio"])

        if self.content_type == "new_chat_member":
            self.new_chat_participant = Person(
                self.original["new_chat_participant"])
            self.new_chat_member = Person(self.original["new_chat_member"])
            self.new_chat_members = [
                Person(person) for person in self.original["new_chat_members"]
            ]

        self.init_opt = True
Ejemplo n.º 58
0
def on_chat_message(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    if 'reply_to_message' in msg:#it's a reply
        reply = replyhandler.handle(msg)
        bot.sendMessage(chat_id, reply)
    elif msg['text'].strip() == '/klasemen':
        reply = 'KLASEMEN LIGA BADR 2017\n'
        reply += '=======================\n'
        players = herokudb.getStandings()
        reply += ''
        count = 1
        for player in players:
            reply += "{}. {}   {}-{}-{}  {}\n".format(
                count, player[0], player[1], player[2], player[3], player[4])
            count += 1

        reply += '=======================\n'
        reply += ('Klasemen di atas belum menggunakan tie break.'
                  ' Versi lebih akurat cek: http://challonge.com/badrleague')
        bot.sendMessage(chat_id, reply)
    elif msg['text'].strip() == '/start' or msg['text'].strip() == '/help':
        reply = "BADR(o)BOT v0.2.3\n"
        reply += "Command yg tersedia:\n"
        reply += "/matchinfo - melihat hasil/jadwal tanding player\n"
        reply += "/klasemen - melihat klasemen saat ini\n"
        reply += "/teamhistory - melihat histori tim yg digunakan player\n"
        reply += "/updateskor - khusus admin (@yahyaman)\n\n"
        reply += "Coming soon:\n"
        reply += "(belum ada - silakan request)"
        bot.sendMessage(chat_id, reply)
    elif msg['text'].strip() == '/updateskor':
        reply = 'Command ini khusus Admin! Situ siapa? :p'
        force = None
        if msg['from']['id'] == ADMIN_ID:
            reply = 'Update skor dgn membalas chat ini:\n'
            reply += 'player1 tim1 skor1 player2 tim2 skor2\n'
            reply += 'Contoh:\n'
            reply += 'yahya juve 2 amri chelsea 1'
            force = ForceReply(force_reply=True, selective=True)

        bot.sendMessage(chat_id, reply, reply_to_message_id=msg['message_id'], reply_markup=force)
    elif msg['text'].strip() == '/teamhistory':
        reply = 'Pilih player:'
        players = herokudb.getPlayerList()
        count = 0
        buttons = []
        btn_row = []
        for player in players:
            count += 1
            data = "history-" + str(player[0])
            btn_row.append(InlineKeyboardButton(text=player[1], callback_data=data))
            if count % 3 == 0:
                buttons.append(btn_row)
                btn_row = []
        #add last btns if present
        if len(btn_row) > 0:
            buttons.append(btn_row)

        keyboard = InlineKeyboardMarkup(inline_keyboard=buttons)
        bot.sendMessage(chat_id, reply, reply_markup=keyboard)
    elif msg['text'].strip() == '/matchinfo':
        reply = 'Pilih player:'
        players = herokudb.getPlayerList()
        buttons = helper.buildPlayerListButtons('match')
        keyboard = InlineKeyboardMarkup(inline_keyboard=buttons)
        bot.sendMessage(chat_id, reply, reply_markup=keyboard)
    else:
        bot.sendMessage(chat_id, "On progress!")
Ejemplo n.º 59
0
def handle(msg):
    print("Message: " + str(msg))
    # Add person as allowed
    content_type, chat_type, chat_id = telepot.glance(msg)
    txt = ""
    if 'text' in msg:
        txt = txt + msg['text']
    elif 'caption' in msg:
        txt = txt + msg['caption']
    # Addme and rmme only valid on groups and personal chats.
    if msg['chat']['type'] != 'channel':
        if "/addme" == txt.strip()[:6]:
            if msg['chat']['type'] != 'private':
                bot.sendMessage(
                    chat_id,
                    "This command is meant to be used only on personal chats.")
            else:
                used_password = "******".join(txt.strip().split(" ")[1:])
                if used_password == PASSWORD:
                    allowed.add(msg['from']['id'])
                    save_allowed(allowed)
                    bot.sendMessage(
                        chat_id, msg['from']['first_name'] +
                        ", you have been registered " +
                        "as an authorized user of this bot.")
                else:
                    bot.sendMessage(chat_id, "Wrong password.")
        if "/rmme" == txt.strip()[:5]:
            allowed.remove(msg['from']['id'])
            save_allowed(allowed)
            bot.sendMessage(
                chat_id,
                "Your permission for using the bot was removed successfully.")
    if is_allowed(msg):
        if txt != "":
            if "/add " == txt[:5]:
                txt_split = txt.strip().split(" ")
                if len(txt_split) == 2 and "#" == txt_split[1][0]:
                    tag = txt_split[1].lower()
                    name = ""
                    if msg['chat']['type'] == "private":
                        name = name + "Personal chat with " + msg['chat'][
                            'first_name'] + (
                                (" " + msg['chat']['last_name'])
                                if 'last_name' in msg['chat'] else "")
                    else:
                        name = msg['chat']['title']
                    chats[tag] = {'id': chat_id, 'name': name}
                    bot.sendMessage(chat_id, name + " added with tag " + tag)
                    save_status(chats)
                else:
                    bot.sendMessage(
                        chat_id,
                        "Incorrect format. It should be _/add #{tag}_",
                        parse_mode="Markdown")
            elif "/rm " == txt[:4]:
                txt_split = txt.strip().split(" ")
                if len(txt_split) == 2 and "#" == txt_split[1][0]:
                    tag = txt_split[1].lower()
                    if tag in chats:
                        if chats[tag]['id'] == chat_id:
                            del chats[tag]
                            bot.sendMessage(
                                chat_id,
                                "Tag " + tag + " deleted from taglist.")
                            save_status(chats)
                            return
                        else:
                            bot.sendMessage(
                                chat_id,
                                "You can't delete a chat's tag from a different chat."
                            )
                    else:
                        bot.sendMessage(chat_id,
                                        "Tag doesn't exist on TagList")
                else:
                    bot.sendMessage(
                        chat_id,
                        "Incorrect format. It should be _/rm #{tag}_",
                        parse_mode="Markdown")

            elif "/taglist" == txt.strip()[:8]:
                tags_names = []
                for tag, chat in chats.items():
                    tags_names.append((tag, chat['name']))
                response = "<b>TagList</b>"
                for (tag, name) in sorted(tags_names):
                    response = response + "\n<b>" + tag + "</b>: <i>" + name + "</i>"
                bot.sendMessage(chat_id, response, parse_mode="HTML")
            elif "#" == txt[0]:
                txt_split = txt.strip().split(" ")
                i = 0
                tags = []
                while i < len(txt_split) and txt_split[i][0] == "#":
                    tags.append(txt_split[i].lower())
                    i += 1
                if i != len(txt_split) or 'reply_to_message' in msg:
                    approved = []
                    rejected = []
                    for tag in tags:
                        if tag in chats:
                            if chats[tag]['id'] != chat_id:
                                approved.append(chats[tag]['name'])
                                bot.forwardMessage(chats[tag]['id'], chat_id,
                                                   msg['message_id'])
                                if 'reply_to_message' in msg:
                                    bot.forwardMessage(
                                        chats[tag]['id'], chat_id,
                                        msg['reply_to_message']['message_id'])
                        else:
                            rejected.append(tag)
                    if len(rejected) > 0:
                        bot.sendMessage(chat_id,
                                        "Failed to send messages to tags <i>" +
                                        ", ".join(rejected) + "</i>",
                                        parse_mode="HTML")
                else:
                    bot.sendMessage(
                        chat_id,
                        "Failed to send a message only with tags which is not a reply to another message"
                    )
Ejemplo n.º 60
0
    def on_callback_query(self, msg):
        query_id, from_id, query_data = telepot.glance(msg,
                                                       flavor='callback_query')
        ## Si se recibió un voto
        if query_data.split()[0] == "/voto":
            # Obtenemos el carnet del usuario
            conn = psycopg2.connect(DATABASE_URL, sslmode='require')
            cur = conn.cursor()

            # Chequeamos si ya el usuario existe
            cur.execute('SELECT carnet FROM usuario WHERE chat_id = %s;',
                        (str(from_id), ))
            row = cur.fetchone()
            if not row or not row[0]:
                bot.sendMessage(
                    from_id,
                    'Parece que no has iniciado sesión. Utiliza el comando /login.'
                )
                conn.commit()
                cur.close()
                conn.close()
                return

            student_id = row[0]
            data = {
                'nominee': query_data.split()[1],
                'categoria': query_data.split()[2],
                'student_id': student_id,
                'token': TOKEN
            }
            r = requests.post(COMPUSHOW_URL + 'voting_from_bot/', data=data)

            response = r.json()
            if response.get('success', False):
                bot.sendMessage(from_id, 'Voto registrado')
                bot.answerCallbackQuery(query_id, 'Voto registrado')
            elif not response.get('error', False):
                bot.sendMessage(from_id, 'Ya votaste por esta categoría')
                bot.answerCallbackQuery(
                    query_id, 'Ocurrió un error registrando el voto')
            else:
                bot.sendMessage(
                    from_id, 'Ocurrió un error registrando el voto: {}'.format(
                        response.get('error')))
                bot.answerCallbackQuery(
                    query_id, 'Ocurrió un error registrando el voto')

            conn.commit()
            cur.close()
            conn.close()
            return

        r = requests.get(COMPUSHOW_URL + 'category/',
                         params={'pk': query_data})
        response = r.json()
        categoria = response['categoria']
        nominados = response['nominados']

        bot.answerCallbackQuery(query_id, text=categoria[0]['fields']['name'])

        nominados_btns = []
        for nominado in nominados:
            # Nominado
            nominado_set = ""
            if nominado['person']:
                nominado_set += "{} {}".format(
                    escape(nominado['person'][0]['fields']['name']),
                    escape(nominado['person'][0]['fields']['surname']))

            # Si hay persona extra:
            if nominado['personOpt']:
                nominado_set += ", {} {}".format(
                    escape(nominado['personOpt'][0]['fields']['name']),
                    escape(nominado['personOpt'][0]['fields']['surname']))

            if nominado['nominee'] and nominado['nominee'][0]['fields'][
                    'extra']:
                nominado_set += "\n{}".format(
                    escape(nominado['nominee'][0]['fields']['extra']))

            nominados_btns.append([
                InlineKeyboardButton(text=nominado_set,
                                     callback_data="/voto {} {}".format(
                                         nominado['nominee'][0]['pk'],
                                         categoria[0]['fields']['name']))
            ])

        keyboard = InlineKeyboardMarkup(inline_keyboard=nominados_btns)
        bot.sendMessage(from_id,
                        '<b>{}</b>\n{}\nNominados:'.format(
                            categoria[0]['fields']['name'],
                            categoria[0]['fields']['description']),
                        reply_markup=keyboard,
                        parse_mode='HTML')