예제 #1
0
async def on_chat_message(msg):

    global answerData, lowerFormulas

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

    # 'a' = append, сохраняем в блокноте
    with open('papaz.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', 'привет', 'помощь', 'старт',
                       'start'):
            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 ("Test1"):
            testAnswers = [
                "Pifagor", 'Gerodot', 'Efklid', 'Arhimed', 'Ahmed', 'Otvet'
            ]
            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 ("Test2"):
            testAnswers = [
                "(m*S)", '(m*a)', '(S/t)', '(a*b)', '(da+da)',
                'Tochno ne otvet'
            ]
            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['formulas'].keys():
            add = answerData["addsToAnswer"]
            await bot.sendMessage(chat_id, answerData['formulas'][request])
            logFile.write('[' + strftime("%Y-%m-%d %H:%M:%S") + '][bot -> ' +
                          chat_id_str + ']: ' +
                          answerData['formulas'][request] + '\n')
            return
        elif request in lowerFormulas:
            await bot.sendMessage(chat_id, answerData["lowRequest"])
            logFile.write('[' + strftime("%Y-%m-%d %H:%M:%S") + '][bot -> ' +
                          chat_id_str + ']: ' + answerData["lowRequest"] +
                          '\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'])
예제 #2
0
파일: telebot.py 프로젝트: sj1024/telebot
 def common(self):
     return [[
         InlineKeyboardButton(text='Home', callback_data='/start'),
         InlineKeyboardButton(text='Back', callback_data='/back')
     ]]
예제 #3
0
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)

    response = bot.getUpdates()

    user_first_name = response[0]['message']['from']['first_name']
    user_id = response[0]['message']['from']['id']
    user_text = response[0]['message']['text']

    print(user_first_name, "id:", user_id)
    print(user_first_name, "said:", user_text)

    if msg['text'] == "s":
        markup = ReplyKeyboardMarkup(keyboard=[
            [KeyboardButton(text='Calculator')],
            [KeyboardButton(text='/currency')],
            [KeyboardButton(text='Translate')],
            # [KeyboardButton(text='Test')],
            # [ForceReply(force_reply='Test')],
            [KeyboardButton(text='sorry')],
        ])
        bot.sendMessage(chat_id, 'Please select', reply_markup=markup)

    if content_type == 'text':

        def no_letters(a):
            letter = []
            for x in a:
                if x.isalpha():
                    letter.append(x)
            if letter:
                return False
            return True

    if msg['text'] == 'Calculator':
        bot.sendMessage(chat_id,
                        "Ok, " + user_first_name + " write what you want!")

    elif msg['text'] == 'T':

        # In message links

        mark = InlineKeyboardMarkup(inline_keyboard=[
            [
                InlineKeyboardButton(text='Link for google',
                                     url="https://google.com")
            ],
            [InlineKeyboardButton(text='callback_data', callback_data="data")],
            [
                InlineKeyboardButton(text='/switch_inline_query',
                                     switch_inline_query="query")
            ],
            [
                InlineKeyboardButton(
                    text='/switch_inline_query_current_chat',
                    switch_inline_query_current_chat="'text':'text'")
            ],
        ])
        bot.sendMessage(chat_id=chat_id, text="testing", reply_markup=mark)

    elif msg['text'] == "sh":
        get = bot.getMe()
        update = bot.getUpdates()
        user_profile_photo = bot.getUserProfilePhotos(user_id)
        bot.sendMessage(chat_id, f"me {get}")
        bot.sendMessage(chat_id, f"me {update}")
        bot.sendMessage(chat_id, f"me {user_profile_photo}")

    elif msg['text'] == '/me':
        inline_markup = telepot.namedtuple.InlineKeyboardMarkup(
            telepot.namedtuple.InlineKeyboardButton(text="This is keyboard"))
        bot.sendMessage(chat_id, "text", reply_markup=inline_markup)

    elif msg['text'] == '/currency':
        bot.sendMessage(chat_id, Currency().get_currency())

    else:
        bot.sendMessage(chat_id, "Sorry")
예제 #4
0
def afterMap(lang):
    text = translate.optionChanged(lang)
    return InlineKeyboardMarkup(inline_keyboard=[
        [InlineKeyboardButton(text=text[0], callback_data='settings')],
        [InlineKeyboardButton(text=text[1], callback_data='start')],
    ])
예제 #5
0
파일: MyBot.py 프로젝트: flasophi/SPYThon
    def on_chat_message(self, msg):

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

        if content_type == 'text':

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

            if command == '/start':
                self.bot.sendMessage(
                    chat_id, "Hello " + name +
                    "! I'm your SPYThon bot. Please register yourself with /registermyself to get started."
                )

            elif command == '/help':
                self.bot.sendMessage(
                    chat_id,
                    """First you can register with: /registermyself. \n Then you can use: /registerterrarium terrariumID password to become the only owner of the terrarium..\n
                 Then you can check how your reptile is doing by: /check terrariumID.\n If you want to set the temperature control just type:
                 /temperature terrariumID, and if you wish to set the dawn and dusk hours of your terrarium type:
                 /light terrariumID""")

            elif command == '/registermyself':  # Register the speaker as a user

                payload = {'nickname': name, 'ID': chat_id}
                URL = 'http://' + self.catalogIP + ':' + self.catalogport + '/add_user'
                try:
                    r = requests.post(URL, data=json.dumps(payload))
                    r.raise_for_status()
                except requests.HTTPError as err:
                    self.bot.sendMessage(chat_id,
                                         'An error happened. Try again.')
                    print err
                    return

                self.bot.sendMessage(
                    chat_id, "Congratulations " + name +
                    "! You have been registered. You can now connect to your reptile."
                )

            elif command == '/deletemyself':

                URL = 'http://' + self.catalogIP + ':' + self.catalogport + '/delete_user'
                try:
                    r = requests.get(URL, params={'UserID': chat_id})
                    r.raise_for_status()
                except requests.HTTPError as err:
                    self.bot.sendMessage(chat_id,
                                         'An error happened. Try again.')
                    print err
                    return

                self.bot.sendMessage(
                    chat_id, "Hey " + name +
                    "! It's sad to see you leave. Come back soon!")

            elif command.startswith(
                    '/registerterrarium'
            ):  # Associate a terrarium (identified by its ID)
                # to the speaker (identified by the chat_id).
                # If the speaker or the terrarium are not registered, raise an error.

                params_bot = command.split(' ')

                if len(params_bot) < 3:
                    self.bot.sendMessage(
                        chat_id,
                        'The correct syntax is: /registerterrarium terrariumID password'
                    )
                    return

                try:
                    r = requests.get('http://' + self.catalogIP + ':' +
                                     self.catalogport + '/user/',
                                     params={'ID': chat_id})
                    r.raise_for_status()
                except requests.HTTPError as err:
                    self.bot.sendMessage(chat_id,
                                         'Please register yourself first.')
                    return

                payload = {
                    'IDTerr': params_bot[1],
                    'IDUs': chat_id,
                    'pws': params_bot[2]
                }
                URL = 'http://' + self.catalogIP + ':' + self.catalogport + '/associate/'
                try:
                    r = requests.get(URL, params=payload)
                    r.raise_for_status()
                except requests.HTTPError as err:
                    if r.status_code == 401:
                        self.bot.sendMessage(chat_id,
                                             'Password is not correct.')
                    else:
                        self.bot.sendMessage(
                            chat_id,
                            'An error happened. Try again. (syntax is: /registerterrarium terrariumID password)'
                        )
                    return

                self.bot.sendMessage(
                    chat_id, "Congratulations " + name + "! The terrarium " +
                    params_bot[1] +
                    " has been associated to you. Only you will have access to the terrarium."
                )

            elif command.startswith('/check'):

                params_bot = command.split(' ')

                if len(params_bot) < 2:
                    self.bot.sendMessage(
                        chat_id, 'Correct syntax is: /check terrariumID')
                    return

                try:
                    r1 = requests.get('http://' + self.catalogIP + ':' +
                                      self.catalogport + '/terrarium/',
                                      params={'ID': params_bot[1]})
                    r1.raise_for_status()
                    terr = r1.json()['terrarium']
                    if terr['user'] != str(chat_id):
                        self.bot.sendMessage(
                            chat_id,
                            "You can't check the terrarium. Please register and associate yourself to the terrarium."
                        )
                        return
                except requests.HTTPError as err:
                    self.bot.sendMessage(
                        chat_id,
                        'An error happened. Try again and check the connection of the terrarium. (Correct syntax is: /check terrariumID)'
                    )
                    return

                keyboard = InlineKeyboardMarkup(inline_keyboard=[
                    [
                        InlineKeyboardButton(text='Photo',
                                             callback_data='photo_' +
                                             terr['IP'] + '_' +
                                             str(terr['port'])),
                        InlineKeyboardButton(text='Temperature',
                                             callback_data='temp_' +
                                             terr['IP'] + '_' +
                                             str(terr['port']))
                    ],
                    [
                        InlineKeyboardButton(text='Humidity',
                                             callback_data='hum_' +
                                             terr['IP'] + '_' +
                                             str(terr['port'])),
                        InlineKeyboardButton(text='Lock Status',
                                             callback_data='lock_' +
                                             terr['IP'] + '_' +
                                             str(terr['port']))
                    ]
                ])

                msg = self.bot.sendMessage(chat_id,
                                           'What do you want to see?',
                                           reply_markup=keyboard)

            elif command.startswith('/temperature'):
                params_bot = command.split(' ')

                if len(params_bot) < 2:
                    self.bot.sendMessage(
                        chat_id, 'Correct syntax is: /temperature terrariumID')
                    return

                try:
                    r1 = requests.get('http://' + self.catalogIP + ':' +
                                      self.catalogport + '/terrarium/',
                                      params={'ID': params_bot[1]})
                    r1.raise_for_status()
                    terr = r1.json()['terrarium']
                    if terr['user'] != str(chat_id):
                        self.bot.sendMessage(
                            chat_id,
                            "You can't control the terrarium. Please associate to the terrarium."
                        )
                        return
                except requests.HTTPError as err:
                    self.bot.sendMessage(
                        chat_id,
                        'An error happened. Try again and check the connection of the terrarium. (syntax is: /temperature terrariumID)'
                    )
                    return

                self.user_states.append({
                    'user': chat_id,
                    'state': 'temp',
                    'terr': terr['ID']
                })
                self.bot.sendMessage(
                    chat_id,
                    'Please type the reference daytime temperature or type STOP to deactivate the control.'
                )

            elif command.startswith('/light'):
                params_bot = command.split(' ')

                if len(params_bot) < 2:
                    self.bot.sendMessage(
                        chat_id, 'Correct syntax is: /light terrariumID')
                    return

                try:
                    r1 = requests.get('http://' + self.catalogIP + ':' +
                                      self.catalogport + '/terrarium/',
                                      params={'ID': params_bot[1]})
                    r1.raise_for_status()
                    terr = r1.json()['terrarium']
                    if terr['user'] != str(chat_id):
                        self.bot.sendMessage(
                            chat_id,
                            "You can't control the terrarium. Please associate to the terrarium."
                        )
                        return
                except requests.HTTPError as err:
                    self.bot.sendMessage(
                        chat_id,
                        'An error happened. Try again and check the connection of the terrarium. (syntax is: /light terrariumID)'
                    )
                    return

                self.user_states.append({
                    'user': chat_id,
                    'state': 'light',
                    'terr': terr['ID']
                })
                self.bot.sendMessage(
                    chat_id,
                    'Please type the times in which you want the light to turn on and off (HH:MM) or type STOP to deactivate the control.'
                )

            else:

                send1 = 0
                send2 = 0

                # check if the user is engaged in a conversation

                for state in self.user_states:
                    if state['user'] == chat_id and state['state'] == 'temp':
                        send1 = 1
                        break

                    elif state['user'] == chat_id and state['state'] == 'light':
                        send2 = 1
                        break

                # Conversation about reference temperature
                if send1:

                    if msg['text'] == 'STOP':
                        temp = 'null'
                    else:
                        try:
                            temp = float(msg['text'])
                        except:
                            self.bot.sendMessage(
                                chat_id,
                                'This is not a valid number or STOP. Try again.'
                            )
                            self.user_states.remove(state)
                            return

                    try:
                        r = requests.get('http://' + self.catalogIP + ':' +
                                         str(self.catalogport) +
                                         '/changetemp/',
                                         params={
                                             'IDTerr': state['terr'],
                                             'temp': temp
                                         })
                        r.raise_for_status()

                    except requests.HTTPError as err:
                        self.bot.sendMessage(
                            chat_id,
                            'An error happened. Try again and check the connection of the temperature control.'
                        )
                        self.user_states.remove(state)
                        return

                    if temp != 'null':
                        self.bot.sendMessage(
                            chat_id,
                            'The reference temperature of ' + state['terr'] +
                            ' has been correctly set to %.1f Celsius degrees.'
                            % temp)
                    else:
                        self.bot.sendMessage(
                            chat_id,
                            'Temperature control has been deactivated.')

                    self.user_states.remove(state)

                # Conversation about light cycle
                elif send2:

                    r = re.compile('\d\d:\d\d \d\d:\d\d')

                    if msg['text'] == 'STOP':
                        dawn = 'null'
                        dusk = 'null'

                    elif r.match(msg['text']) != None:
                        dawn = msg['text'].split(' ')[0]
                        dusk = msg['text'].split(' ')[1]

                        # check on the hour feasibility
                        dawn_h = int(dawn.split(':')[0])
                        dawn_m = int(dawn.split(':')[1])
                        dusk_h = int(dusk.split(':')[0])
                        dusk_m = int(dusk.split(':')[1])

                        if dawn_h > 24 or dusk_h > 24 or dawn_m > 59 or dusk_m > 59:
                            self.bot.sendMessage(
                                chat_id,
                                "The times are not feasible. Don't try to fool me."
                            )
                            self.user_states.remove(state)
                            return

                    else:
                        self.bot.sendMessage(
                            chat_id, 'The format is not correct. Try again.')
                        self.user_states.remove(state)
                        return

                    try:
                        r = requests.get('http://' + self.catalogIP + ':' +
                                         self.catalogport +
                                         '/changelightcycle/',
                                         params={
                                             'IDTerr': state['terr'],
                                             'dawn': dawn,
                                             'dusk': dusk
                                         })
                        r.raise_for_status()

                    except requests.HTTPError as err:
                        self.bot.sendMessage(
                            chat_id,
                            'An error happened. Try again and check the connection of the light control.'
                        )
                        self.user_states.remove(state)
                        print err
                        return

                    if dawn != 'null':
                        self.bot.sendMessage(
                            chat_id, 'The light of ' + state['terr'] +
                            ' will turn on at ' + dawn +
                            ' and will turn off at %s.' % dusk)
                    else:
                        self.bot.sendMessage(
                            chat_id,
                            'Light cycle control has been deactivated.')

                    self.user_states.remove(state)

                else:
                    self.bot.sendMessage(
                        chat_id,
                        "I don't understand... try to write in Parseltongue, or write /help."
                    )
예제 #6
0
def on_callback_query(msg):
    print('msg:', msg)
    query_id, from_id, query_data, = telepot.glance(msg,
                                                    flavor='callback_query')
    print(
        'Callback Query:',
        query_id,
        from_id,
        query_data,
    )
    # cancel
    if query_data == 'yes_cancel':
        x = requests.post(f'http://127.0.0.1:{port}/printer/print/cancel',
                          headers={"X-Api-Key": f'{api_key}'})
        print(x.text)
        bot.sendMessage(chatid_mt, 'Got it')
    # pause
    elif query_data == 'yes_pause':
        x = requests.post(f'http://127.0.0.1:{port}/printer/print/pause',
                          headers={"X-Api-Key": f'{api_key}'})
        print(x.text)
        bot.sendMessage(chatid_mt, 'Got it')
    # Pi
    elif "pi_sh" in query_data:
        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [
                InlineKeyboardButton(text='yes', callback_data='pi_sy'),
                InlineKeyboardButton(text='no', callback_data='no')
            ],
        ])
        bot.sendMessage(chatid_mt,
                        'do you really want to shoutdown your pi',
                        reply_markup=keyboard)
    elif "pi_re" in query_data:
        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [
                InlineKeyboardButton(text='yes', callback_data='pi_ry'),
                InlineKeyboardButton(text='no', callback_data='no')
            ],
        ])
        bot.sendMessage(chatid_mt,
                        'do you really want to reboot your pi',
                        reply_markup=keyboard)
    elif "pi_sy" in query_data:
        bot.sendMessage(chatid_mt, 'Got it')
        x = requests.post(f'http://127.0.0.1:{port}/machine/shutdown',
                          headers={"X-Api-Key": f'{api_key}'})
        print(x.text)
    elif "pi_ry" in query_data:
        bot.sendMessage(chatid_mt, 'Got it')
        x = requests.post(f'http://127.0.0.1:{port}/machine/reboot',
                          headers={"X-Api-Key": f'{api_key}'})
        print(x.text)
    # Print
    elif "p:," in query_data:
        a, gcode = query_data.split(":,")
        print(a)
        print(gcode)
        if gcode == 'filename_too_long':
            bot.sendMessage(
                chatid_mt,
                'the original filename has too many characters to use it with the telegram bot. (max 60 characters)'
            )
        else:
            keyboard = InlineKeyboardMarkup(inline_keyboard=[
                [
                    InlineKeyboardButton(text='yes',
                                         callback_data='p,:%s' % gcode),
                    InlineKeyboardButton(text='no', callback_data='no')
                ],
            ])
            bot.sendMessage(chatid_mt,
                            'do you really want to start printing of %s' %
                            gcode,
                            reply_markup=keyboard)
    elif "p,:" in query_data:
        a, gcode = query_data.split(",:")
        print(a)
        print(gcode)
        x = requests.post(
            f'http://127.0.0.1:{port}/printer/print/start?filename={gcode}',
            headers={"X-Api-Key": f'{api_key}'})
        print(x.text)
    # Gcode_macro
    elif "g:," in query_data:
        a, macro = query_data.split(":,")
        if macro == 'gcode_macro_too_long':
            bot.sendMessage(
                chatid_mt,
                'the original macro name has too many characters to use it with the telegram bot. (max 60 characters)'
            )
        else:
            keyboard = InlineKeyboardMarkup(inline_keyboard=[
                [
                    InlineKeyboardButton(text='yes',
                                         callback_data='g,:%s' % macro),
                    InlineKeyboardButton(text='no', callback_data='no')
                ],
            ])
            bot.sendMessage(chatid_mt,
                            'do you really want to execute %s' % macro,
                            reply_markup=keyboard)
    elif "g,:" in query_data:
        a, macro = query_data.split(",:")
        x = requests.post(
            f'http://127.0.0.1:{port}/printer/gcode/script?script={macro}',
            headers={"X-Api-Key": f'{api_key}'})
        print(x.text)
        bot.sendMessage(chatid_mt, 'okay I have executed %s' % macro)
    # Power
    elif "po:," in query_data:
        a, device = query_data.split(":,")
        if device == 'device_name_too_long':
            bot.sendMessage(
                chatid_mt,
                'the original Device name has too many characters to use it with the telegram bot. (max 60 characters)'
            )
        else:
            keyboard = InlineKeyboardMarkup(inline_keyboard=[
                [
                    InlineKeyboardButton(text='On',
                                         callback_data='on,:%s' % device),
                    InlineKeyboardButton(text='Off',
                                         callback_data='of,:%s' % device),
                    InlineKeyboardButton(text='Status',
                                         callback_data='st,:%s' % device)
                ],
            ])
            bot.sendMessage(chatid_mt,
                            'what do you want to do with %s' % device,
                            reply_markup=keyboard)
    elif "on,:" in query_data:
        a, device = query_data.split(",:")
        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [
                InlineKeyboardButton(text='yes',
                                     callback_data='on:,%s' % device),
                InlineKeyboardButton(text='no', callback_data='no')
            ],
        ])
        bot.sendMessage(chatid_mt,
                        'do you really want to turn on %s' % device,
                        reply_markup=keyboard)
    elif "of,:" in query_data:
        a, device = query_data.split(",:")
        keyboard = InlineKeyboardMarkup(inline_keyboard=[
            [
                InlineKeyboardButton(text='yes',
                                     callback_data='of:,%s' % device),
                InlineKeyboardButton(text='no', callback_data='no')
            ],
        ])
        bot.sendMessage(chatid_mt,
                        'do you really want to turn off %s' % device,
                        reply_markup=keyboard)
    elif "on:," in query_data:
        a, device = query_data.split(":,")
        x = requests.post(
            f'http://127.0.0.1:{port}/machine/device_power/on?{device}',
            headers={"X-Api-Key": f'{api_key}'})
        print(x.text)
        bot.sendMessage(chatid_mt, 'okay I have turned on %s' % device)
    elif "of:," in query_data:
        a, device = query_data.split(":,")
        x = requests.post(
            f'http://127.0.0.1:{port}/machine/device_power/off?{device}',
            headers={"X-Api-Key": f'{api_key}'})
        print(x.text)
        bot.sendMessage(chatid_mt, 'okay I have turned off %s' % device)
    elif "st,:" in query_data:
        a, device = query_data.split(",:")
        os.system(f'bash {DIR}/scripts/power_state.sh "{device}"')
    # no
    elif query_data == 'no':
        bot.sendMessage(chatid_mt, 'Okay, i do nothing')
예제 #7
0
#-*. coding: utf-8 -*-
#authors: David Quesada López y Mateo García Fuentes
import telepot
from telepot.namedtuple import InlineKeyboardMarkup, InlineKeyboardButton
from telepot.namedtuple import ReplyKeyboardMarkup, KeyboardButton
import db
import translate

#Este inline no se está usando
afterRate = InlineKeyboardMarkup(inline_keyboard=[
    [InlineKeyboardButton(text='Choose location', callback_data='init')],
    [
        InlineKeyboardButton(text="Choose type of establishments",
                             callback_data='type')
    ],
    [
        InlineKeyboardButton(text='Choose establishment',
                             callback_data='establishment')
    ],
])  #Volver a puntuacion, fotos etc


#KeyboardMarkups
def markupLocation(lang):
    text = translate.markupLocation(lang)
    return ReplyKeyboardMarkup(
        keyboard=[[KeyboardButton(text=text[0], request_location=True)],
                  [KeyboardButton(text=text[1])]],
        resize_keyboard=True,
        one_time_keyboard=True)
class TimePlanner(telepot.helper.ChatHandler):

    keyboard1_0 = InlineKeyboardMarkup(inline_keyboard=[[
        InlineKeyboardButton(text='Yes', callback_data='yes1_0'),
        InlineKeyboardButton(text='No', callback_data='no1_0'),
    ]])
    keyboard1_1 = InlineKeyboardMarkup(inline_keyboard=[[
        InlineKeyboardButton(text='Next', callback_data='next1_1'),
    ]])
    keyboard1_2 = InlineKeyboardMarkup(inline_keyboard=[[
        InlineKeyboardButton(text='Next', callback_data='next1_2'),
    ]])
    keyboard1_3 = InlineKeyboardMarkup(inline_keyboard=[[
        InlineKeyboardButton(text='Next', callback_data='next1_3'),
    ]])
    keyboard1_4 = InlineKeyboardMarkup(inline_keyboard=[[
        InlineKeyboardButton(text='Upload', callback_data='upload1_4'),
        InlineKeyboardButton(text='Exit', callback_data='exit1_4'),
    ]])
    keyboard1_5 = InlineKeyboardMarkup(inline_keyboard=[[
        InlineKeyboardButton(text='Next', callback_data='next1_5'),
    ]])
    keyboard1_6 = InlineKeyboardMarkup(inline_keyboard=[[
        InlineKeyboardButton(text='Exit', callback_data='exit1_6'),
    ]])
    keyboard2_0 = InlineKeyboardMarkup(inline_keyboard=[
        [
            InlineKeyboardButton(text='Add User', callback_data='add2_0'),
            InlineKeyboardButton(text='Delete User', callback_data='delete2_0')
        ],
        [
            InlineKeyboardButton(text='Namelist', callback_data='namelist2_0'),
            InlineKeyboardButton(text='Exit', callback_data='exit2_0')
        ]
    ])
    keyboard2_3 = InlineKeyboardMarkup(inline_keyboard=[[
        InlineKeyboardButton(text='Back', callback_data='back2_3'),
    ]])
    keyboard3_0 = InlineKeyboardMarkup(inline_keyboard=[[
        InlineKeyboardButton(text='Yes', callback_data='yes3_0'),
        InlineKeyboardButton(text='No', callback_data='no3_0'),
    ]])

    def __init__(self, *args, **kwargs):
        super(TimePlanner, self).__init__(*args, **kwargs)

        # Retrieve from database
        global planner_records
        if self.id in planner_records:
            self._edit_msg_ident = planner_records[self.id]
            self._editor = telepot.helper.Editor(
                self.bot,
                self._edit_msg_ident) if self._edit_msg_ident else None
        else:
            self._edit_msg_ident = None
            self._editor = None

    def _plan1_0(self):
        sent = self.sender.sendMessage("Do you have a Html file for upload?",
                                       reply_markup=self.keyboard1_0)
        self._editor = telepot.helper.Editor(self.bot, sent)
        self._edit_msg_ident = telepot.message_identifier(sent)

    def _plan1_1(self):
        sent = self.sender.sendMessage(
            'Once you are done logging in, press the "Next" button to proceed.',
            reply_markup=self.keyboard1_1)
        self._editor = telepot.helper.Editor(self.bot, sent)
        self._edit_msg_ident = telepot.message_identifier(sent)

    def _plan1_2(self):
        sent = self.sender.sendMessage(
            'Once you are on the printable page, press the "Next" button to proceed.',
            reply_markup=self.keyboard1_2)
        self._editor = telepot.helper.Editor(self.bot, sent)
        self._edit_msg_ident = telepot.message_identifier(sent)

    def _plan1_3(self):
        sent = self.sender.sendMessage(
            'Once you have saved the file, press the "Next" button to proceed.',
            reply_markup=self.keyboard1_3)
        self._editor = telepot.helper.Editor(self.bot, sent)
        self._edit_msg_ident = telepot.message_identifier(sent)

    def _plan1_4(self):
        sent = self.sender.sendMessage(
            "Great! We're done with getting the file. We can either proceed with uploading the file, or do it another time.",
            reply_markup=self.keyboard1_4)
        self._editor = telepot.helper.Editor(self.bot, sent)
        self._edit_msg_ident = telepot.message_identifier(sent)

    def _plan1_5(self):
        sent = self.sender.sendMessage(
            'Once you have uploaded the Html file, press the "Next" button to proceed.',
            reply_markup=self.keyboard1_5)
        self._editor = telepot.helper.Editor(self.bot, sent)
        self._edit_msg_ident = telepot.message_identifier(sent)

    def _plan1_6(self):
        sent = self.sender.sendMessage(
            "Awesome! Group admin Tsukimiya will save a copy of your file once he's ready. If you haven't done so, you can add yourself as a user in the group via /user to facilitate timetable comparison.",
            reply_markup=self.keyboard1_6)
        self._editor = telepot.helper.Editor(self.bot, sent)
        self._edit_msg_ident = telepot.message_identifier(sent)

    def _plan2_0(self):
        sent = self.sender.sendMessage("How may I help you?",
                                       reply_markup=self.keyboard2_0)
        self._editor = telepot.helper.Editor(self.bot, sent)
        self._edit_msg_ident = telepot.message_identifier(sent)

    def _plan2_1(self):
        sent = self.sender.sendMessage(
            'Type out the name you would like to add, following this format-> Example: Add Arcine'
        )
        self._editor = telepot.helper.Editor(self.bot, sent)
        self._edit_msg_ident = telepot.message_identifier(sent)

    def _plan2_2(self):
        sent = self.sender.sendMessage(
            'Type out the name you would like to remove, following this format-> Example: Remove Fabre'
        )
        self._editor = telepot.helper.Editor(self.bot, sent)
        self._edit_msg_ident = telepot.message_identifier(sent)

    def _plan2_3(self):
        displaynames = namelist
        sent = self.sender.sendMessage("These are names added currently: " +
                                       str(', '.join(displaynames)),
                                       reply_markup=self.keyboard2_3)
        self._editor = telepot.helper.Editor(self.bot, sent)
        self._edit_msg_ident = telepot.message_identifier(sent)
        print(', '.join(displaynames))

    def _plan3_0(self):
        sent = self.sender.sendMessage(
            'Would you like to compare your free time?',
            reply_markup=self.keyboard3_0)
        self._editor = telepot.helper.Editor(self.bot, sent)
        self._edit_msg_ident = telepot.message_identifier(sent)

    def _cancel_last(self):
        if self._editor:
            self._editor.editMessageReplyMarkup(reply_markup=None)
            self._editor = None
            self._edit_msg_ident = None

    def on_chat_message(self, msg):
        chat_id = msg['chat']['id']
        command = msg['text']
        namevalue = str(command)
        grpname = msg['chat']['first_name']
        print(chat_id)

        if command == '/start':
            bot.sendMessage(
                chat_id, "Hello! " + str(grpname) +
                " Nice to meet you! How may I help you?")
            bot.sendMessage(
                chat_id,
                "Use /upload to upload your html file, /user to register yourself as a user, /compare to start comparing timetables, and /help should you require any assistance. Let's get started!"
            )
        elif command == '/upload':
            self._plan1_0()
        elif command == '/user':
            self._plan2_0()
        elif command == '/compare':
            self._plan3_0()
        elif command == '/help':
            bot.sendMessage(
                chat_id,
                "https://68.media.tumblr.com/e1f5efa7b149ec74841299f1f77a7d7d/tumblr_n0ag27Uxxz1qbvovho2_500.gif"
            )
        elif "Add" in namevalue:
            namevalue = namevalue.replace("Add ", "")
            bot.sendMessage(chat_id,
                            "Awesome! " + namevalue + " has been added.")
            n01 = namevalue
            namelist.append(n01)
            print(namevalue)
            print(namelist)
            print(', '.join(namelist))
            print(namelist[0])
        elif "Remove" in namevalue:
            namevalue = namevalue.replace("Remove ", "")
            try:
                namelist.remove(namevalue)
            except ValueError:
                bot.sendMessage(chat_id,
                                "Sorry! " + namevalue + " does not exist.")
            else:
                bot.sendMessage(chat_id,
                                "Awesome! " + namevalue + " has been removed.")
            print(namevalue)
            print(namelist)
        elif command == '/test':
            myname = namelist[0]
            try:
                with open(myname + ".html") as fp:
                    soup = BeautifulSoup(fp, 'html.parser')
                    bot.sendMessage(chat_id, soup.table.table.get_text())
                    print(soup.table.table.get_text())
            except:
                bot.sendMessage(chat_id, "File not found!")
                print("File not recognised!")
            else:
                bot.sendMessage(chat_id, "Success!")
        else:
            bot.sendMessage(chat_id, "...")

    def on_callback_query(self, msg):
        query_id, from_id, query_data = telepot.glance(msg,
                                                       flavor='callback_query')

        if query_data == 'yes1_0':
            self._cancel_last()
            self.sender.sendMessage(
                "Great! Please upload your file as an attachment. Please tag group admin Tsukimiya so that he easily can find your attachment."
            )
            self._plan1_5()
            self.close()
        elif query_data == 'no1_0':
            self._cancel_last()
            self.sender.sendMessage(
                "Please use the following link to login and access Stars Planner: https://sso.wis.ntu.edu.sg/webexe88/ntlm/sso_express.asp?app=https://wish.wis.ntu.edu.sg/pls/webexe/aus_stars_planner.main."
            )
            self._plan1_1()
            self.close()
        elif query_data == 'next1_1':
            self._cancel_last()
            self.sender.sendMessage(
                'You should see "Printable Page" on your Stars Planner located on the right. Click on it go access the page.'
            )
            self._plan1_2()
            self.close()
        elif query_data == 'next1_2':
            self._cancel_last()
            self.sender.sendMessage(
                'Right click "Save As" and save the webpage as a Html file.')
            self.sender.sendMessage(
                "Please save the name of the file as the SAME name that you will use/have used in the add user option. Note: The name is case-sensitive."
            )
            self._plan1_3()
            self.close()
        elif query_data == 'next1_3':
            self._cancel_last()
            self._plan1_4()
            self.close()
        elif query_data == 'upload1_4':
            self._cancel_last()
            self.sender.sendMessage(
                "Great! Please upload your file as an attachment. Please tag group admin Tsukimiya so that he easily can find your attachment."
            )
            self._plan1_5()
            self.close()
        elif query_data == 'exit1_4':
            self.bot.answerCallbackQuery(query_id,
                                         text="Nice working with you.")
            self.sender.sendMessage(
                "Use the /upload function whenever you're ready to proceed with uploading the file."
            )
            self._cancel_last()
            self.close()
        elif query_data == 'next1_5':
            self._cancel_last()
            self._plan1_6()
            self.close()
        elif query_data == 'exit1_6':
            self.bot.answerCallbackQuery(query_id,
                                         text="Nice working with you.")
            self._cancel_last()
            self.close()
        elif query_data == 'add2_0':
            self._cancel_last()
            self._plan2_1()
            self.close()
        elif query_data == 'delete2_0':
            self._cancel_last()
            self._plan2_2()
            self.close()
        elif query_data == 'namelist2_0':
            self._cancel_last()
            self._plan2_3()
            self.close()
        elif query_data == 'exit2_0':
            self.bot.answerCallbackQuery(query_id,
                                         text="Nice working with you.")
            self.sender.sendMessage("See you again.")
            self._cancel_last()
            self.close()
        elif query_data == 'next2_2':
            self._cancel_last()
            self._plan2_0()
            self.close()
        elif query_data == 'back2_3':
            self._cancel_last()
            self._plan2_0()
            self.close()
        elif query_data == 'yes3_0':
            self._cancel_last()
            self.sender.sendMessage("Let's get started then!")
            self.close()
        elif query_data == 'no3_0':
            self._cancel_last()
            self.sender.sendMessage("I'm always ready.")
            self.close()
        else:
            self.bot.answerCallbackQuery(query_id, text="Request timeout.")
            self._cancel_last()
            self.close()

    def on__idle(self, event):
        self.sender.sendMessage(
            'Need a break? No worries, I will always be here to assist you.')
        self.close()

    def on_close(self, ex):
        # Save to database
        global planner_records
        planner_records[self.id] = (self._edit_msg_ident)
예제 #9
0
    cop = open('copiaSeg', 'r')
    admin[0] = int(cop.readline())
    for u in cop:
        users.append(int(u))
    cop.close()


# If there was a copy of the data, we load the previous admin and users
if os.path.exists('copiaSeg'):
    leerCopiaSeg()

# The different keyboards that the bot will use

keyboardLogin = InlineKeyboardMarkup(inline_keyboard=[
    [
        InlineKeyboardButton(text='Alumno', callback_data='alumno'),
        InlineKeyboardButton(text='Profesor', callback_data='profesor')
    ],
])
keyboardUser = InlineKeyboardMarkup(inline_keyboard=[
    [
        InlineKeyboardButton(text='Enviar mensaje al profesor.',
                             callback_data='msg_user')
    ],
])

keyboardAdminMsg = InlineKeyboardMarkup(inline_keyboard=[
    [
        InlineKeyboardButton(text='Enviar mensaje al grupo.',
                             callback_data='difusion')
    ],
예제 #10
0
 def create_url_button(self, topic):
     return InlineKeyboardButton(
         text=topic,
         url="https://t.me/" + self.tree.get_username_by_topic(topic) +
         "?start=foo")
예제 #11
0
파일: panel.py 프로젝트: mm4130/spntaBot
def callback(message, matches, chat_id):
    locks = {
        'lock_link': 'قفل لینک📎',
        'lock_username': '******',
        'lock_photo': 'قفل عکس🖼',
        'lock_doc': 'قفل گیف🌠',
        'lock_film': 'قفل فیلم🎥',
        'lock_music': 'قفل موزیک🎼',
        'lock_voice': 'قفل ویس🗣',
        'lock_game': 'قفل بازی🏓',
        'lock_doc': 'قفل فایل📁',
        'lock_contact': 'قفل مخاطب🔢',
        'lock_sticker': 'قفل استیکر🎭',
        'lock_bots': 'قفل ورود ربات🤖',
        'lock_fwd': 'قفل فوروارد 🔂',
        'lock_spam': 'قفل اسپم 👿',
        'lock_tg': 'قفل پیام ورود و خروج 🚶',
        'lock_loc': 'قفل لوکیشن(مکان)🗺',
        'lock_all': 'قفل گروه🔕',
        'lock_video_note': 'قفل ویدیو مسیج🤳'
    }
    query_id, from_id, data = telepot.glance(message, flavor='callback_query')
    if is_mod2(message['message'], message):
        if data == "/admins":
            owner = r.hget('owner', chat_id)
            if owner:
                oner = '[{}](tg://user?id={})'.format(owner, owner)
            else:
                oner = 'وجود ندارد❌'
            mods = r.smembers('mod:{}'.format(chat_id))
            if mods:
                mod = ''
                for x in mods:
                    mod += '\n>[{}](tg://user?id={})'.format(x, x)
            else:
                mod = 'وجود ندارد❌'

            text = '''👤 ادمین اصلی : {}

            👥 سایر ادمین ها :
            {}'''.format(oner, mod)

            key = [[
                InlineKeyboardButton(text='🏛 منوی اصلی',
                                     callback_data='/back'),
            ]]
            markup = InlineKeyboardMarkup(inline_keyboard=key)
            msgid = (chat_id, message['message']['message_id'])
            return Message(chat_id).edit_message(msgid,
                                                 text,
                                                 parse_mode="Markdown",
                                                 reply_markup=markup)
        if data == '/back':
            text = "📋به پنل تنظیمات ربات خوش آمدید برای مدیریت گروه از کیبورد زیر استفاده کنید." \
                   "(فقط ادمین های ربات در گروه قابلیت کار کردن با این کیبورد را دارند)"
            ex = int(r.ttl('expire:{}'.format(chat_id))) - time.time()
            days = int(ex / 86400)
            key = [[
                InlineKeyboardButton(text='🔐 منوی قفل ها',
                                     callback_data='/locks'),
                InlineKeyboardButton(text='📝تنظیمات پیام',
                                     callback_data='/pmsetting'),
            ],
                   [
                       InlineKeyboardButton(text='👥لیست مدیران',
                                            callback_data='/admins'),
                   ],
                   [
                       InlineKeyboardButton(text='روز {}'.format(days),
                                            callback_data='/expire'),
                       InlineKeyboardButton(text='📆شارژ گروه',
                                            callback_data='/expire'),
                   ],
                   [
                       InlineKeyboardButton(text='💡ورود به کانال راهنما💡',
                                            url='https://t.me/spntaHelp'),
                   ]]
            markup = InlineKeyboardMarkup(inline_keyboard=key)
            msgid = (chat_id, message['message']['message_id'])
            return Message(chat_id).edit_message(msgid,
                                                 text,
                                                 parse_mode="Markdown",
                                                 reply_markup=markup)
        if data == '/pmsetting':
            get_spam = r.hget('get_spam', chat_id) or '10,1'
            value = get_spam.split(',')
            NUM_MAX = value[0]
            TIME_LIMIT = value[1]
            key = [[
                InlineKeyboardButton(text='🔽 تعداد مجاز پیام در دقیقه 🔽',
                                     callback_data='hem')
            ],
                   [
                       InlineKeyboardButton(text='➖',
                                            callback_data='spam_num_down'),
                       InlineKeyboardButton(text='{}'.format(NUM_MAX),
                                            callback_data='hem'),
                       InlineKeyboardButton(text='➕',
                                            callback_data='spam_num_up'),
                   ],
                   [
                       InlineKeyboardButton(text='               ',
                                            callback_data='hem')
                   ],
                   [
                       InlineKeyboardButton(
                           text='🔽 تایم محدودیت کاربر(به دقیقه)🔽',
                           callback_data='hem')
                   ],
                   [
                       InlineKeyboardButton(text='➖',
                                            callback_data='spam_time_down'),
                       InlineKeyboardButton(text='{}'.format(TIME_LIMIT),
                                            callback_data='hem'),
                       InlineKeyboardButton(text='➕',
                                            callback_data='spam_time_up'),
                   ],
                   [
                       InlineKeyboardButton(text='🏛 منوی اصلی',
                                            callback_data='/back'),
                   ]]
            text = 'منوی تنظیمات ارسال پیام🗯'
            markup = InlineKeyboardMarkup(inline_keyboard=key)
            msgid = (chat_id, message['message']['message_id'])
            return Message(chat_id).edit_message(msgid,
                                                 text,
                                                 parse_mode="Markdown",
                                                 reply_markup=markup)
        spam = re.compile('spam_')
        if spam.search(data):
            pat = data.replace('spam_', '')
            if pat == 'time_down':
                getwww = r.hget('get_spam', chat_id) or '10,1'
                vvv = getwww.split(',')
                mmm = vvv[1]
                sss = vvv[0]
                num = int(mmm) - 1
                r.hset('get_spam', chat_id, '{},{}'.format(sss, num))
                get_spam = r.hget('get_spam', chat_id) or '10,1'
                value = get_spam.split(',')
                NUM_MAX = value[0]
                TIME_LIMIT = value[1]
                key = [[
                    InlineKeyboardButton(text='🔽 تعداد مجاز پیام در دقیقه 🔽',
                                         callback_data='hem')
                ],
                       [
                           InlineKeyboardButton(text='➖',
                                                callback_data='spam_num_down'),
                           InlineKeyboardButton(text='{}'.format(NUM_MAX),
                                                callback_data='hem'),
                           InlineKeyboardButton(text='➕',
                                                callback_data='spam_num_up'),
                       ],
                       [
                           InlineKeyboardButton(text='               ',
                                                callback_data='hem')
                       ],
                       [
                           InlineKeyboardButton(
                               text='🔽 تایم محدودیت کاربر(به دقیقه)🔽',
                               callback_data='hem')
                       ],
                       [
                           InlineKeyboardButton(
                               text='➖', callback_data='spam_time_down'),
                           InlineKeyboardButton(text='{}'.format(num),
                                                callback_data='hem'),
                           InlineKeyboardButton(text='➕',
                                                callback_data='spam_time_up'),
                       ],
                       [
                           InlineKeyboardButton(text='🏛 منوی اصلی',
                                                callback_data='/back'),
                       ]]
                text = '''منوی تنظیمات ارسال پیام🗯
(فقط ادمین های ربات در گروه قابلیت کار کردن با این کیبورد را دارند)

اخرین تغییرات :
👤 [{}](tg://user?id={})
├ `Pm setting`
└ `{} => {}`'''.format(message['from']['first_name'], message['from']['id'],
                       pat, num)
                markup = InlineKeyboardMarkup(inline_keyboard=key)
                msgid = (chat_id, message['message']['message_id'])
                return Message(chat_id).edit_message(msgid,
                                                     text,
                                                     parse_mode="Markdown",
                                                     reply_markup=markup)
            if pat == 'time_up':
                getwww = r.hget('get_spam', chat_id) or '10,1'
                vvv = getwww.split(',')
                mmm = vvv[1]
                sss = vvv[0]
                num = int(mmm) + 1
                r.hset('get_spam', chat_id, '{},{}'.format(sss, num))
                get_spam = r.hget('get_spam', chat_id) or '10,1'
                value = get_spam.split(',')
                NUM_MAX = value[0]
                TIME_LIMIT = value[1]
                key = [[
                    InlineKeyboardButton(text='🔽 تعداد مجاز پیام در دقیقه 🔽',
                                         callback_data='hem')
                ],
                       [
                           InlineKeyboardButton(text='➖',
                                                callback_data='spam_num_down'),
                           InlineKeyboardButton(text='{}'.format(NUM_MAX),
                                                callback_data='hem'),
                           InlineKeyboardButton(text='➕',
                                                callback_data='spam_num_up'),
                       ],
                       [
                           InlineKeyboardButton(text='               ',
                                                callback_data='hem')
                       ],
                       [
                           InlineKeyboardButton(
                               text='🔽 تایم محدودیت کاربر(به دقیقه)🔽',
                               callback_data='hem')
                       ],
                       [
                           InlineKeyboardButton(
                               text='➖', callback_data='spam_time_down'),
                           InlineKeyboardButton(text='{}'.format(num),
                                                callback_data='hem'),
                           InlineKeyboardButton(text='➕',
                                                callback_data='spam_time_up'),
                       ],
                       [
                           InlineKeyboardButton(text='🏛 منوی اصلی',
                                                callback_data='/back'),
                       ]]
                text = '''منوی تنظیمات ارسال پیام🗯
(فقط ادمین های ربات در گروه قابلیت کار کردن با این کیبورد را دارند)

اخرین تغییرات :
👤 [{}](tg://user?id={})
├ `Pm setting`
└ `{} => {}`'''.format(message['from']['first_name'], message['from']['id'],
                       pat, num)
                markup = InlineKeyboardMarkup(inline_keyboard=key)
                msgid = (chat_id, message['message']['message_id'])
                return Message(chat_id).edit_message(msgid,
                                                     text,
                                                     parse_mode="Markdown",
                                                     reply_markup=markup)
            if pat == 'num_down':
                getwww = r.hget('get_spam', chat_id) or '10,1'
                vvv = getwww.split(',')
                mmm = vvv[0]
                sss = vvv[1]
                num = int(mmm) - 1
                r.hset('get_spam', chat_id, '{},{}'.format(num, sss))
                get_spam = r.hget('get_spam', chat_id) or '10,1'
                value = get_spam.split(',')
                NUM_MAX = value[0]
                TIME_LIMIT = value[1]
                key = [[
                    InlineKeyboardButton(text='🔽 تعداد مجاز پیام در دقیقه 🔽',
                                         callback_data='hem')
                ],
                       [
                           InlineKeyboardButton(text='➖',
                                                callback_data='spam_num_down'),
                           InlineKeyboardButton(text='{}'.format(num),
                                                callback_data='hem'),
                           InlineKeyboardButton(text='➕',
                                                callback_data='spam_num_up'),
                       ],
                       [
                           InlineKeyboardButton(text='               ',
                                                callback_data='hem')
                       ],
                       [
                           InlineKeyboardButton(
                               text='🔽 تایم محدودیت کاربر(به دقیقه)🔽',
                               callback_data='hem')
                       ],
                       [
                           InlineKeyboardButton(
                               text='➖', callback_data='spam_time_down'),
                           InlineKeyboardButton(text='{}'.format(TIME_LIMIT),
                                                callback_data='hem'),
                           InlineKeyboardButton(text='➕',
                                                callback_data='spam_time_up'),
                       ],
                       [
                           InlineKeyboardButton(text='🏛 منوی اصلی',
                                                callback_data='/back'),
                       ]]
                text = '''منوی تنظیمات ارسال پیام🗯
(فقط ادمین های ربات در گروه قابلیت کار کردن با این کیبورد را دارند)

اخرین تغییرات :
👤 [{}](tg://user?id={})
├ `Pm setting`
└ `{} => {}`'''.format(message['from']['first_name'], message['from']['id'],
                       pat, num)
                markup = InlineKeyboardMarkup(inline_keyboard=key)
                msgid = (chat_id, message['message']['message_id'])
                return Message(chat_id).edit_message(msgid,
                                                     text,
                                                     parse_mode="Markdown",
                                                     reply_markup=markup)
            if pat == 'num_up':
                getwww = r.hget('get_spam', chat_id) or '10,1'
                vvv = getwww.split(',')
                mmm = vvv[0]
                sss = vvv[1]
                num = int(mmm) + 1
                r.hset('get_spam', chat_id, '{},{}'.format(num, sss))
                get_spam = r.hget('get_spam', chat_id) or '10,1'
                value = get_spam.split(',')
                NUM_MAX = value[0]
                TIME_LIMIT = value[1]
                key = [[
                    InlineKeyboardButton(text='🔽 تعداد مجاز پیام در دقیقه 🔽',
                                         callback_data='hem')
                ],
                       [
                           InlineKeyboardButton(text='➖',
                                                callback_data='spam_num_down'),
                           InlineKeyboardButton(text='{}'.format(num),
                                                callback_data='hem'),
                           InlineKeyboardButton(text='➕',
                                                callback_data='spam_num_up'),
                       ],
                       [
                           InlineKeyboardButton(text='               ',
                                                callback_data='hem')
                       ],
                       [
                           InlineKeyboardButton(
                               text='🔽 تایم محدودیت کاربر(به دقیقه)🔽',
                               callback_data='hem')
                       ],
                       [
                           InlineKeyboardButton(
                               text='➖', callback_data='spam_time_down'),
                           InlineKeyboardButton(text='{}'.format(TIME_LIMIT),
                                                callback_data='hem'),
                           InlineKeyboardButton(text='➕',
                                                callback_data='spam_time_up'),
                       ],
                       [
                           InlineKeyboardButton(text='🏛 منوی اصلی',
                                                callback_data='/back'),
                       ]]
                text = '''منوی تنظیمات ارسال پیام🗯
(فقط ادمین های ربات در گروه قابلیت کار کردن با این کیبورد را دارند)

اخرین تغییرات :
👤 [{}](tg://user?id={})
├ `Pm setting`
└ `{} => {}`'''.format(message['from']['first_name'], message['from']['id'],
                       pat, num)
                markup = InlineKeyboardMarkup(inline_keyboard=key)
                msgid = (chat_id, message['message']['message_id'])
                return Message(chat_id).edit_message(msgid,
                                                     text,
                                                     parse_mode="Markdown",
                                                     reply_markup=markup)

        if data == '/locks':
            key = []
            for lock in locks:
                key.append([
                    InlineKeyboardButton(text=r.hget(lock, chat_id) and '«✔️»'
                                         or '«✖️»',
                                         callback_data='/' + lock),
                    InlineKeyboardButton(text=locks[lock],
                                         callback_data='/' + lock)
                ])
            key.append([
                InlineKeyboardButton(text='🏛 منوی اصلی',
                                     callback_data='/back'),
            ])
            markey = InlineKeyboardMarkup(inline_keyboard=key)

            text = 'برای تغییر حالت قفل بر روی آن کلیک کنید👌'
            msgid = (chat_id, message['message']['message_id'])
            return Message(chat_id).edit_message(msgid,
                                                 text,
                                                 parse_mode="Markdown",
                                                 reply_markup=markey)

        if matches[0] == 'lock_':
            l = matches[0] + matches[1]
            text = '''📋به پنل تنظیمات ربات خوش آمدید برای مدیریت گروه از کیبورد زیر استفاده کنید.
(فقط ادمین های ربات در گروه قابلیت کار کردن با این کیبورد را دارند)

اخرین تغییرات :
👤 [{}](tg://user?id={})
 ├ `settings changed`
 └ `{} =>'''.format(message['from']['first_name'], message['from']['id'], l)
            key = []
            for lock in locks:
                if lock == l:
                    if r.hget(lock, chat_id):
                        r.hdel(lock, chat_id)
                        text += ' OFF`'
                        status = '«✖️»'
                        bot.answerCallbackQuery(query_id, 'غیر فعال شد✖️')
                    else:
                        r.hset(lock, chat_id, True)
                        text += ' ON`'
                        status = '«✔️»'
                        bot.answerCallbackQuery(query_id, 'فعال شد ✔️')
                else:
                    status = r.hget(lock, chat_id) and '«✔️»' or '«✖️»'
                key.append([
                    InlineKeyboardButton(text=status,
                                         callback_data='/' + lock),
                    InlineKeyboardButton(text=locks[lock],
                                         callback_data='/' + lock)
                ])
            key.append([
                InlineKeyboardButton(text='🏛 منوی اصلی',
                                     callback_data='/back'),
            ])
            markey = InlineKeyboardMarkup(inline_keyboard=key)
            msgid = (chat_id, message['message']['message_id'])
            return Message(chat_id).edit_message(msgid,
                                                 text,
                                                 parse_mode="Markdown",
                                                 reply_markup=markey)
예제 #12
0
def getRigServerData(chat_id, markupReturnData, closeList):
    markup_contents = []
    markup_contents_2ndHalf = []
    minerUpStatus = ["empty"]
    count = 1
    message_server = ""

    while 1:
        try:
            #send stats of rig to cilent
            aFile = open(userNameDict[chat_id] + "_" + str(count) + "_" +
                         "statsServer.txt")

            #read stats of the selected miner
            allDetails = aFile.readlines()

            #if file time difference is less than 5mins(300sec), means it's still up (using epoch as time)
            if abs(int(time.time()) - int(allDetails[0])) < 300:
                #blue circle picture
                minerUpStatus.append("🔵")
            else:
                #red circle picture
                minerUpStatus.append("🔴")

            # only read stats of the miner selected by the user
            if str(count) != markupReturnData[1] or closeList:
                aFile.close()
                count += 1
                continue

        #if file does not exist
        except IOError:
            #exception thrown if file doesn't exist
            break

        #if cannot find username in dict (RAM's database)
        except KeyError:
            bot.sendMessage(
                chat_id,
                "Error searching for username. \nPlease input \n/start <username> \nagain."
            )
            return

        except Exception as ex:
            print(ex, "exception when reading file")

        else:
            #clear it each markup must have text so example mine2 markup will send miner1's stats as text
            message_server = ""

            #No. GPUs
            allDetails[46] = allDetails[46].split()
            message_server += "\nNo. of GPUs = " + allDetails[46][1]

            #Temp
            allDetails[31] = allDetails[31].split()
            message_server += "\nTemp = " + allDetails[31][1] + "degrees\n"

            #Status
            allDetails[43] = allDetails[43].split()
            message_server += "\nMining Status = " + allDetails[43][
                3] + " " + allDetails[43][4]

            #Hash rate
            allDetails[49] = allDetails[49].split()
            message_server += "\nHash rate = " + allDetails[49][1]

            #pop out from RAM to save RAM space since no longer inused
            aFile.close()

        count += 1

    #create buttons of miner1 to the miner number that user selected to see the stats
    #condition assignment is used so that it won't stop at int(markupReturnData[1]) if closeList is True
    for i in range(1, count if closeList else int(markupReturnData[1]) + 1):
        markup_contents.append([
            InlineKeyboardButton(
                text="miner" + str(i) + " " + str(minerUpStatus[i]),
                callback_data=markupReturnData[0] + "_" + str(i))
        ])

        if i == int(markupReturnData[1]):
            if not closeList:
                if len(markup_contents) != 0:
                    markup_contents.pop()
                markup_contents.append([
                    InlineKeyboardButton(
                        text="miner" + str(i) + " " + str(minerUpStatus[i]),
                        callback_data=markupReturnData[0] + "+" + str(i))
                ])

    for i in range(int(markupReturnData[1]) + 1, count):

        markup_contents_2ndHalf.append([
            InlineKeyboardButton(
                text="miner" + str(i) + " " + str(minerUpStatus[i]),
                callback_data=markupReturnData[0] + "_" + str(i))
        ])

    #create Markup from
    minerInfoButtons = InlineKeyboardMarkup(inline_keyboard=markup_contents)

    #useful when server restarted and user clicked on previous inLine buttons
    try:
        print(markupReturnData)
        markupDict[chat_id] = bot.editMessageText(
            telepot.message_identifier(markupDict[chat_id]),
            text=markupReturnData[0] + " status",
            reply_markup=minerInfoButtons)
    except Exception as ex:
        print(ex, "editMessage failed")
        markupDict[chat_id] = bot.sendMessage(chat_id,
                                              text=markupReturnData[0] +
                                              " status",
                                              reply_markup=minerInfoButtons)

    minerInfoButtons = InlineKeyboardMarkup(
        inline_keyboard=markup_contents_2ndHalf)

    #Don't send it there are no 2nd half of the buttons after the drop down list
    if len(message_server) != 0:
        #useful when server restarted and user clicked on previous inLine buttons
        #markupDict[str(chat_id)+str("_1")] instead of markupDict[chat_id] as is to store identifier of 2nd half of the message/buttons
        try:
            markupDict[str(chat_id) + str("_1")] = bot.editMessageText(
                telepot.message_identifier(markupDict[str(chat_id) +
                                                      str("_1")]),
                text=message_server,
                reply_markup=minerInfoButtons)
        except:
            markupDict[str(chat_id) + str("_1")] = bot.sendMessage(
                chat_id, text=message_server, reply_markup=minerInfoButtons)
    else:
        #try to delete dropdownlist if user selected to close it
        try:
            bot.deleteMessage(
                telepot.message_identifier(markupDict[str(chat_id) +
                                                      str("_1")]))
        except:
            pass
예제 #13
0
    def on_chat_message(self, msg):
        global state, stall, stall1, can
        content_type, chat_type, chat_id = telepot.glance(msg)
        if content_type == 'text':

            # get message payload
            msg_text = msg['text']

            if (msg_text.startswith('/')):

                # parse the command excluding the '/'
                command = msg_text[1:].lower()

                # prepare the correct response based on the given command
                if (command == 'start'):
                    #display current weather at start of bot
                    weather = Weather()

                    # Lookup WOEID via http://weather.yahoo.com.
                    client = yweather.Client()
                    Singapore_NTU = client.fetch_woeid(
                        'Nanyang Technological University')
                    lookup = weather.lookup(Singapore_NTU)
                    condition = lookup.condition()
                    response = "Current Weather in NTU: " + condition[
                        'text'] + '\n\nRating Stalls or Finding Food? \nTo Rate a Stall, enter /rate\nTo Find Food, enter /find \n\nTo view all commands, enter /list'
                    bot.sendMessage(chat_id, response)

                elif (command == 'list'):
                    #dispaly list of avaiable commands
                    response = 'Here are a list of all available commands: \n/start Begin your food journey! \n/rate Rate your dining experience at stall! \n/find Find delicious food by location or cuisine! \n/feedback Send any feedback, queries or errors spotted to us! \n/quit Exit what you are doing'
                    bot.sendMessage(chat_id, response)
                elif (command == 'feedback'):
                    #set state to 4 to receive feedback from user
                    self.state = 4
                    bot.sendMessage(chat_id,
                                    'Please enter feedback your feedback!')
                elif (command == 'rate'):
                    #set state to 1 to proceed to next stage of rating process
                    self.state = 1
                    canlist = [
                        'Canteen 1', 'Canteen 2', 'Canteen 4', 'Canteen 9',
                        'Canteen 11', 'Canteen 13', 'Canteen 14', 'Canteen 16',
                        'Koufu', 'NIE Canteen', 'North Hill Canteen',
                        'North Spine Foodcourt', 'Pioneer Canteen'
                    ]
                    rm = ReplyKeyboardMarkup(
                        one_time_keyboard=True,
                        keyboard=[[KeyboardButton(text=i)] for i in canlist])
                    bot.sendMessage(chat_id, 'Choose Canteen', reply_markup=rm)

                elif (command == 'find'):
                    response = 'Filter by Canteen or Cuisine?'
                    confirm_keyboard = InlineKeyboardMarkup(inline_keyboard=[
                        [
                            InlineKeyboardButton(text='Canteen',
                                                 callback_data='can')
                        ],
                        [
                            InlineKeyboardButton(text='Cuisine',
                                                 callback_data='cui')
                        ],
                    ])
                    bot.sendMessage(chat_id,
                                    response,
                                    reply_markup=confirm_keyboard)
                elif (command == 'quit'):
                    #used to exit and reset to initial state
                    self.state = 0
            elif (self.state == 0):
                #initial state. Prompt if no valid command is entered
                bot.sendMessage(
                    chat_id,
                    "Hi, please enter /start to begin! \n\nFor feedback, please enter \n/feedback \n\nTo exit at anytime, enter /quit"
                )
            elif (self.state == 1):
                self.check = 0
                conn_string = "host='ec2-54-225-237-64.compute-1.amazonaws.com' dbname='d7dkk1sep0usei' user='******' password='******'"
                conn = psycopg2.connect(conn_string)
                cursor = conn.cursor()
                cursor.execute("SELECT * FROM store")
                rlist = cursor.fetchall()

                #check if user input for canteen is valid (matches with that in master list from database table "store")
                for i in range(len(rlist)):
                    if (msg_text == rlist[i][0]):
                        self.check = 1
                #if input valid, we set state to the next state, and prompt user for input of stall
                if (self.check):
                    can = msg_text
                    otpt = "List of stalls in " + msg_text + "\n"
                    self.stall = []
                    #find list of stalls in selected canteen
                    for i in range(0, len(rlist)):
                        if (rlist[i][0] == msg_text):
                            otpt = otpt + rlist[i][2] + "\n"
                            self.stall.append(rlist[i][2])
                    RM = ReplyKeyboardMarkup(
                        one_time_keyboard=True,
                        keyboard=[[KeyboardButton(text=stall)]
                                  for stall in self.stall])

                    bot.sendMessage(chat_id, otpt, reply_markup=RM)
                    self.state = 2
                #if input invalid, stay at current state and prompt user for input of canteen again
                else:
                    canlist = [
                        'Canteen 1', 'Canteen 2', 'Canteen 4', 'Canteen 9',
                        'Canteen 11', 'Canteen 13', 'Canteen 14', 'Canteen 16',
                        'Koufu', 'NIE Canteen', 'North Hill Canteen',
                        'North Spine Foodcourt', 'Pioneer Canteen'
                    ]
                    rm = ReplyKeyboardMarkup(
                        one_time_keyboard=True,
                        keyboard=[[KeyboardButton(text=i)] for i in canlist])
                    bot.sendMessage(chat_id, 'Choose Canteen', reply_markup=rm)
                    self.state = 1

            elif (self.state == 2):
                self.check = 0
                #check if user input of stall is valid
                for i in range(len(self.stall)):
                    if (msg_text == self.stall[i]):
                        self.check = 1
                #for valid input, ask user to input ratings and move to next state, state 3
                if (self.check == 1):
                    self.stall1 = msg_text
                    self.state = 3
                    RM = ReplyKeyboardMarkup(
                        one_time_keyboard=True,
                        keyboard=[[KeyboardButton(text=rating)]
                                  for rating in ['5', '4', '3', '2', '1']])
                    bot.sendMessage(chat_id, "Input Ratings", reply_markup=RM)
                #for invalid stall input, prompt user for input of stall, while remaining at current state
                else:
                    bot.sendMessage(chat_id,
                                    "Input Stall: ",
                                    reply_markup=ReplyKeyboardMarkup(
                                        one_time_keyboard=True,
                                        keyboard=[[KeyboardButton(text=stall)]
                                                  for stall in self.stall]))

            elif (self.state == 3):
                #for valid rating input, attempt to save review using rate.py. check for multiple rating by single user is made in rate.py
                if ((msg_text == '1') | (msg_text == '2') | (msg_text == '3') |
                    (msg_text == '4') | (msg_text == '5')):
                    self.state = 0
                    bot.sendMessage(
                        chat_id, rate(can, self.stall1, msg_text,
                                      str(chat_id)))
                #for invalid rating input, prompt user for rating input and remain at current state
                else:
                    self.state = 3
                    bot.sendMessage(
                        chat_id,
                        "Input Ratings",
                        reply_markup=ReplyKeyboardMarkup(
                            one_time_keyboard=True,
                            keyboard=[[KeyboardButton(text=rating)]
                                      for rating in ['5', '4', '3', '2', '1']
                                      ]))
            elif (self.state == 4):
                #send feedback and userid to the admin and return to initial state
                response = str(msg_text) + '\nUserID : ' + str(chat_id)
                bot.sendMessage(408469886, response)
                bot.sendMessage(chat_id,
                                'Thank you, your feedback was recorded!')
                self.state = 0
예제 #14
0
    def on_callback_query(self, msg):
        query_id, from_id, query_data = telepot.glance(msg,
                                                       flavor='callback_query')

        #Handle Callback Query
        inline_message_id = msg['message']['chat']['id'], msg['message'][
            'message_id']
        bot.editMessageReplyMarkup(inline_message_id, reply_markup=None)

        #for finding stalls by location, provide list of canteens for user to choose from
        if (query_data == 'can'):
            #choice1="Canteen"
            canteen_keyboard = InlineKeyboardMarkup(inline_keyboard=[
                [InlineKeyboardButton(text='Canteen 1', callback_data='can1')],
                [InlineKeyboardButton(text='Canteen 2', callback_data='can2')],
                [InlineKeyboardButton(text='Canteen 4', callback_data='can2')],
                [InlineKeyboardButton(text='Canteen 9', callback_data='can9')],
                [
                    InlineKeyboardButton(text='Canteen 11',
                                         callback_data='can11')
                ],
                [
                    InlineKeyboardButton(text='Canteen 13',
                                         callback_data='can13')
                ],
                [
                    InlineKeyboardButton(text='Canteen 14',
                                         callback_data='can14')
                ],
                [
                    InlineKeyboardButton(text='Canteen 16',
                                         callback_data='can16')
                ],
                [InlineKeyboardButton(text='Koufu', callback_data='koufu')],
                [
                    InlineKeyboardButton(text='NIE Canteen',
                                         callback_data='niecan')
                ],
                [
                    InlineKeyboardButton(text='North Hill Canteen',
                                         callback_data='nhcan')
                ],
                [
                    InlineKeyboardButton(text='North Spine Food Court',
                                         callback_data='nspine')
                ],
                [
                    InlineKeyboardButton(text='Pioneer Canteen',
                                         callback_data='piocan')
                ],
            ])

            bot.sendMessage(from_id,
                            "Select Canteen",
                            reply_markup=canteen_keyboard)
        #thereafter, use findstall.py to output list of filtered and sorted stalls in selected canteen
        elif (query_data == 'can1'):
            response = findstall("Canteen", "Canteen 1")
            bot.sendMessage(from_id, response)
        elif (query_data == 'can2'):
            response = findstall("Canteen", "Canteen 2")
            bot.sendMessage(from_id, response)
        elif (query_data == 'can4'):
            response = findstall("Canteen", "Canteen 4")
            bot.sendMessage(from_id, response)
        elif (query_data == 'can9'):
            response = findstall("Canteen", "Canteen 9")
            bot.sendMessage(from_id, response)
        elif (query_data == 'can11'):
            response = findstall("Canteen", "Canteen 11")
            bot.sendMessage(from_id, response)
        elif (query_data == 'can13'):
            response = findstall("Canteen", "Canteen 13")
            bot.sendMessage(from_id, response)
        elif (query_data == 'can14'):
            response = findstall("Canteen", "Canteen 14")
            bot.sendMessage(from_id, response)
        elif (query_data == 'can16'):
            response = findstall("Canteen", "Canteen 16")
            bot.sendMessage(from_id, response)
        elif (query_data == 'koufu'):
            response = findstall("Canteen", "Koufu")
            bot.sendMessage(from_id, response)
        elif (query_data == 'niecan'):
            response = findstall("Canteen", "NIE Canteen")
            bot.sendMessage(from_id, response)
        elif (query_data == 'nhcan'):
            response = findstall("Canteen", "North Hill Canteen")
            bot.sendMessage(from_id, response)
        elif (query_data == 'nspine'):
            response = findstall("Canteen", "North Spine Foodcourt")
            bot.sendMessage(from_id, response)
        elif (query_data == 'piocan'):
            response = findstall("Canteen", "Pioneer Canteen")
            bot.sendMessage(from_id, response)

        #for finding stalls by cuisine, provide list of cuisine types for user to choose from
        elif (query_data == 'cui'):
            cuisine_keyboard = InlineKeyboardMarkup(inline_keyboard=[
                [InlineKeyboardButton(text="Drinks", callback_data="cui1")],
                [InlineKeyboardButton(text="Western", callback_data="cui2")],
                [InlineKeyboardButton(text="Chinese", callback_data="cui3")],
                [InlineKeyboardButton(text="Muslim", callback_data="cui4")],
                [InlineKeyboardButton(text="Indian", callback_data="cui5")],
                [InlineKeyboardButton(text="Japanese", callback_data="cui6")],
                [InlineKeyboardButton(text="Korean", callback_data="cui7")],
                [
                    InlineKeyboardButton(text="Yong Tau Fu",
                                         callback_data="cui8")
                ],
                [
                    InlineKeyboardButton(text="Economical Rice",
                                         callback_data="cui9")
                ],
                [
                    InlineKeyboardButton(text="Chicken Rice",
                                         callback_data="cui10")
                ],
                [InlineKeyboardButton(text="Asian", callback_data="cui11")],
                [InlineKeyboardButton(text="Dessert", callback_data="cui12")],
                [InlineKeyboardButton(text="Malay", callback_data="cui13")],
                [InlineKeyboardButton(text="Thai", callback_data="cui14")],
                [
                    InlineKeyboardButton(text="Vietnamese",
                                         callback_data="cui15")
                ],
            ])
            bot.sendMessage(from_id,
                            "Select Cuisine",
                            reply_markup=cuisine_keyboard)

        #thereafter, use findstall.py to output list of filtered and sorted stalls for selected cuisine
        elif (query_data == 'cui1'):
            response = findstall("Cuisine", "Drinks")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui2'):
            response = findstall("Cuisine", "Western")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui3'):
            response = findstall("Cuisine", "Chinese")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui4'):
            response = findstall("Cuisine", "Muslim")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui5'):
            response = findstall("Cuisine", "Indian")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui6'):
            response = findstall("Cuisine", "Japanese")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui7'):
            response = findstall("Cuisine", "Korean")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui8'):
            response = findstall("Cuisine", "Yong Tau Fu")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui9'):
            response = findstall("Cuisine", "Economical Rice")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui10'):
            response = findstall("Cuisine", "Chicken Rice")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui11'):
            response = findstall("Cuisine", "Asian")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui12'):
            response = findstall("Cuisine", "Dessert")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui13'):
            response = findstall("Cuisine", "Malay")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui14'):
            response = findstall("Cuisine", "Thai")
            bot.sendMessage(from_id, response)
        elif (query_data == 'cui15'):
            response = findstall("Cuisine", "Vietnamese")
            bot.sendMessage(from_id, response)

        # answer callback query or else telegram will forever wait on this
        bot.answerCallbackQuery(query_id)
예제 #15
0
def on_chat_message(msg):
    print(msg)
    content_type, chat_type, chat_id = telepot.glance(msg)
    print('Chat:', content_type, chat_type, chat_id)

    if content_type != 'text':
        return
    else:
        command = msg['text']

    print("[*] Command : %s" % command)

    if command.endswith('@' + config['BOTINFO'].get('username')):
        command = "@".join(command.split('@')[:-1])

    if command == '/auth':
        if chat_id not in config['INVITE'] and chat_id not in config[
                'AUTH_USERS']:
            config['INVITE'].append(chat_id)
            bot.sendMessage(chat_id, 'The admin will process your request.')
        elif chat_id in config['INVITE']:
            bot.sendMessage(chat_id, 'Your access is pending.')
        else:
            bot.sendMessage(chat_id, 'You already have access.')
        return

    if chat_id not in config['AUTH_USERS']:
        bot.sendMessage(chat_id, 'You don\'t have access...')
        print('UNAUTHORIZED ACCESS by %s' % _get_chat(chat_id))
        return

    if command == '/ping':
        bot.sendMessage(chat_id, "PONG")
        return

    elif command == '/check':
        config["SEND_PIC"] = True
        return

    elif command == '/settings':
        keyboard = InlineKeyboardMarkup(inline_keyboard=[[
            InlineKeyboardButton(text="Modules", callback_data="modules:list"),
            InlineKeyboardButton(text="Config", callback_data="config:list"),
        ]])
        global inline_id
        inline_id = bot.sendMessage(chat_id,
                                    'Settings :',
                                    reply_markup=keyboard)
        return

    elif command == '/list_invites':
        kb_list = [
            InlineKeyboardButton(text=_get_chat(u),
                                 callback_data="auth:chat:%s" % u)
            for u in config['INVITE']
        ]
        kb_auth = [
            InlineKeyboardButton(text=_get_chat(u),
                                 callback_data="auth:chat:%s" % u)
            for u in config['AUTH_USERS'] if u != config['SUPER_USER']
        ]

        if len(kb_auth) > 0:
            keyboard_auth = InlineKeyboardMarkup(inline_keyboard=[
                kb_auth,
            ])
            bot.sendMessage(chat_id,
                            'Authorized chats :',
                            reply_markup=keyboard_auth)

        if len(kb_list) > 0:
            keyboard_list = InlineKeyboardMarkup(inline_keyboard=[
                kb_list,
            ])
            global inline_id
            inline_id = bot.sendMessage(chat_id,
                                        'Waiting List :',
                                        reply_markup=keyboard_list)
            config['INVITE'] = []
        else:
            bot.sendMessage(chat_id, 'No chats in the waiting list...')

        return
예제 #16
0
    def on_callback_query(self, msg):
        query_id, from_id, query_data = telepot.glance(msg, flavor='callback_query')
        a = TeleUser.objects.get(user_id=msg['from']['id'])
        if a.state==4:
            if query_data=='delete':
                deleteword=Word.objects.get(pk=self._delete).delete()
                bot.editMessageReplyMarkup(msg_identifier=self._message_ind_delet,reply_markup=None)
                bot.answerCallbackQuery(query_id, text=' لغط خذف شد ')

            else:
                edit=Word.objects.get(pk=query_data)
                text='کلمه : {word}\n\n معنی : {means}\n\n ✅تعداد پاسخ صحیح : {sahih}\n \n ❌تعداد پاسخ غلط : {ghalat}\n \n ⏳زمان تکرار بعدی : {time}\n ..'.format(word=edit.word,
                                                         means=edit.meaning,sahih=edit.correct_answer,
                                                         ghalat=edit.wrong_answer,time=edit.next_review_time)

                key = InlineKeyboardMarkup(inline_keyboard=[
                    [InlineKeyboardButton(text='حذف این لغت', callback_data='delete')]])
                detail=self.sender.sendMessage(text,reply_markup=key)
                if self._message_ind_delet:
                    bot.editMessageReplyMarkup(msg_identifier=self._message_ind_delet,reply_markup=None)
                    self._message_ind_delet=telepot.message_identifier(detail)
                else:
                    self._message_ind_delet = telepot.message_identifier(detail)
                self._delete=edit.pk


        else:
            if query_data == 'shoro':
                count=Word.objects.filter(teleuser=a).count()
                if count>3:
                    bot.answerCallbackQuery(query_id, text='برای هر سوال 60 ثانیه وقت دارید')
                    a.state=5
                    a.save()
                    self._answer = self._show_next_question(msg=msg)
                else:
                    self.sender.sendMessage('برای شروع فرایند مرور باید حداقل 4 کلمه وارد کنید \n یکی از گزینه های زیر را انتخاب کنید ')
                    a.state=1
                    a.save()

            elif query_data == 'end':
                a.state=1
                a.save()
                key1 = ReplyKeyboardMarkup(
                    keyboard=[[KeyboardButton(text='ثبت لغت جدید ✍🏻'), KeyboardButton(text='مرور لغت ها 🔎')],
                              [KeyboardButton(text='لیست لغت های ثبت شده📝'),
                               KeyboardButton(text='معرفی به دوستان❣️')]],
                    resize_keyboard=True, one_time_keyboard=True)
                self.sender.sendMessage('برای ادامه یکی از گزینه ها را انتخاب کنید', reply_markup=key1)
                self.close()

            elif query_data== str(self._answer):
                days=[1,1,2,5,10,20,40]
                bot.answerCallbackQuery(query_id, text=' درسته ')

                id=self._answer

                word=Word.objects.get(id=id)
                i=word.level
                if i<7:
                    word.next_review_time=datetime.now()+timedelta(days=days[i])
                else:
                    word.next_review_time = datetime.now() + timedelta(days=40)

                self._score= self._score+5
                word.level = word.level + 1
                word.correct_answer=word.correct_answer+1
                word.save()
                a.points=a.points+5
                a.save()
                self._answer = self._show_next_question(msg=msg)

            else:
                if self._answer==None:

                    key1 = ReplyKeyboardMarkup(
                        keyboard=[[KeyboardButton(text='ثبت لغت جدید ✍🏻'), KeyboardButton(text='مرور لغت ها 🔎')],
                                  [KeyboardButton(text='لیست لغت های ثبت شده📝'),
                                   KeyboardButton(text='معرفی به دوستان❣️')]],
                        resize_keyboard=True, one_time_keyboard=True)
                    self.sender.sendMessage('برای شروع مجدد یکی از گزینه های زیر را انتخاب کنید',reply_markup=key1)
                    a.state=1
                    a.save()
                else:
                    id = self._answer
                    word = Word.objects.get(id=id)
                    word.level=0
                    word.wrong_answer=word.wrong_answer+1
                    word.save()
                    bot.answerCallbackQuery(query_id, text='ghalat')
                    self._answer = self._show_next_question(msg=msg)
예제 #17
0
파일: lover.py 프로젝트: hidercorp/teleapi
class Lover(telepot.helper.ChatHandler):
    keyboard = InlineKeyboardMarkup(inline_keyboard=[[
        InlineKeyboardButton(text='Yes', callback_data='yes'),
        InlineKeyboardButton(text='um ...', callback_data='no'),
    ]])

    def __init__(self, *args, **kwargs):
        super(Lover, self).__init__(*args, **kwargs)

        # Retrieve from database
        global propose_records
        if self.id in propose_records:
            self._count, self._edit_msg_ident = propose_records[self.id]
            self._editor = telepot.helper.Editor(
                self.bot,
                self._edit_msg_ident) if self._edit_msg_ident else None
        else:
            self._count = 0
            self._edit_msg_ident = None
            self._editor = None

    def _propose(self):
        self._count += 1
        sent = self.sender.sendMessage('%d. Would you marry me?' % self._count,
                                       reply_markup=self.keyboard)
        self._editor = telepot.helper.Editor(self.bot, sent)
        self._edit_msg_ident = telepot.message_identifier(sent)

    def _cancel_last(self):
        if self._editor:
            self._editor.editMessageReplyMarkup(reply_markup=None)
            self._editor = None
            self._edit_msg_ident = None

    def on_chat_message(self, msg):
        self._propose()

    def on_callback_query(self, msg):
        query_id, from_id, query_data = telepot.glance(msg,
                                                       flavor='callback_query')

        if query_data == 'yes':
            self._cancel_last()
            self.sender.sendMessage('Thank you!')
            self.close()
        else:
            self.bot.answerCallbackQuery(
                query_id, text='Ok. But I am going to keep asking.')
            self._cancel_last()
            self._propose()

    def on__idle(self, event):
        self.sender.sendMessage(
            'I know you may need a little time. I will always be here for you.'
        )
        self.close()

    def on_close(self, ex):
        # Save to database
        global propose_records
        propose_records[self.id] = (self._count, self._edit_msg_ident)
예제 #18
0
    def on_chat_message(self, msg):
        from_id = msg['from']['id']
        # self._sender.sendMessage(from_id)
        user=TeleUser.objects.filter(user_id=from_id)
        if user:
            a = TeleUser.objects.get(user_id=from_id)
            key1 = ReplyKeyboardMarkup(
                keyboard=[[KeyboardButton(text='ثبت لغت جدید ✍🏻'), KeyboardButton(text='مرور لغت ها 🔎')],
                          [KeyboardButton(text='لیست لغت های ثبت شده📝'), KeyboardButton(text='معرفی به دوستان❣️')]],
                resize_keyboard=True, one_time_keyboard=True)
            if msg['text']=='/back':
                a.state = 1
                a.save()
                self.sender.sendMessage('یکی از گزینه های زیر را انتخاب کنید', reply_markup=key1)

            else:

                if a.state==1:
                    if msg['text']=='ثبت لغت جدید ✍🏻':
                        a.state =2
                        a.save()
                        self.sender.sendMessage('لغت مورد نظر را وارد کنید. /back',reply_markup=ReplyKeyboardRemove(remove_keyboard=True))
                    elif msg['text']=='مرور لغت ها 🔎':
                        wordscount = Word.objects.filter(teleuser=a).count()
                        review= Word.objects.filter(teleuser=a).filter(
                            Q(next_review_time__lte=datetime.now()) | Q(next_review_time=None)).count()
                        memory=wordscount-review

                        key2=InlineKeyboardMarkup(inline_keyboard=[
                            [InlineKeyboardButton(text=' مرور لغت ها', callback_data='shoro')],[InlineKeyboardButton(text='بازگشت به منوی اصلی', callback_data='end')
                         ]])

                        text='📉 \n شما  {count}  لغت ثبت کرده اید✒️ \n \n {review} لغت برای مرور دارید!💡\n \n  و موفق به حفظ  {mem}  لغت شده اید.📌\n \n .'.format(mem=memory,count=wordscount,review=review)
                        send=self.sender.sendMessage(text,reply_markup=key2)
                        self._id=msg['from']['id']

                        self._message_ind=telepot.message_identifier(send)

                    elif msg['text']=='لیست لغت های ثبت شده📝':
                        list=Word.objects.filter(teleuser=a.pk)
                        n=0
                        for i in list:
                            n=n+1
                            text = '{count}- {word} '.format(count=n,word=i.word)
                            key= InlineKeyboardMarkup(inline_keyboard=[
                                [InlineKeyboardButton(text='جزییات مرور 🔎', callback_data=str(i.pk))]])
                            self.sender.sendMessage(text,reply_markup=key)

                        a.state=4
                        a.save()
                    elif msg['text']=='معرفی به دوستان❣️':
                        self.sender.sendMessage('معرفی کن دیگه')

                    else:
                        self.sender.sendMessage('یکی از گزینه های زیر را انتخاب کنید', reply_markup=key1)
                        a.state=1
                        a.save()

                elif a.state==2:
                    form = WordForm(data={
                        'word': msg['text'],
                        'teleuser': a.pk,
                    })
                    if form.is_valid():
                        form.save()
                        self.sender.sendMessage('معنی این لغت را وارد کنید', reply_markup=ReplyKeyboardRemove(remove_keyboard=True))
                        a.state=3
                        a.save()
                    else:
                        self.sender.sendMessage(form.errors)

                elif a.state == 3:
                    word = Word.objects.filter(teleuser=a).last()
                    if word.meaning:
                        text='معنی این لغت را قبلا ثبت کرده اید: {mani}'.format(mani=word.meaning)
                        self.sender.sendMessage(text, reply_markup=key1)
                    else:
                        word.meaning=msg['text']
                        word.save()
                        a.state=2
                        a.save()
                        self.sender.sendMessage('لغت ثبت شد، برای ادامه لغت بعدی را ثبت کنید یا /back به منوی اصلی')
                elif a.state==5:
                    a.state = 1
                    a.save()
                    self.close()

                else:
                    self.sender.sendMessage('یکی از گزینه های زیر را انتخاب کنید', reply_markup=key1)
                    a.state=1
                    a.save()



        else:

            form = TeleUserForm(data={
                # 'user_name': msg['from']['username'],
                'user_id': from_id,
                # 'first_name': msg['from']['first_name'],
                'state': 1,
            })
            if form.is_valid():
                form.save()
                key1 = ReplyKeyboardMarkup(
                    keyboard=[[KeyboardButton(text='ثبت لغت جدید')]],
                    resize_keyboard=True)
                self.sender.sendMessage('برای ثبت لغت جدید دکمه ثبت را انتخاب کنید',reply_markup=key1)
            else:
                self.sender.sendMessage(form.errors)
예제 #19
0
def on_chat_message(msg):
    content_type, chat_type, chat_id = telepot.glance(msg, 'chat')
    print(content_type)
    print(chat_id)
    if str(chat_id) != chatid_mt:
        print('chat id are not same')
        bot.sendMessage(chat_id,
                        'you have no permission to communicate with me.')
    else:
        if content_type == 'document':
            file_id = msg['document']['file_id']
            file_name = msg['document']['file_name']
            if file_name.endswith('.gcode'):
                print(file_id)
                print(file_name)
                os.system(f'{DIR}/scripts/upload.sh "{file_id}" "{file_name}"')
        else:
            chat_id = msg['chat']['id']
            command = msg['text']
            if "@" in command:
                command, x = command.split("@")
            print('Got chat: %s' % chat_id)
            print('chat  id: %s' % chatid_mt)
            print('Got command: %s' % command)
            if str(chat_id) != chatid_mt:
                print('chat id are not same')
                bot.sendMessage(
                    chat_id, 'you have no permission to communicate with me.')
            else:
                print('chat id are same')
                if command == '/help':
                    os.system(f'bash {DIR}/scripts/telegram.sh 6')
                if command == '/gif':
                    os.system(f'{DIR}/scripts/gif.sh &')
                elif command == '/state':
                    os.system(f'bash {DIR}/scripts/telegram.sh 5')
                elif command == '/print':
                    os.system(f'bash {DIR}/scripts/list_files.sh')
                elif command == '/gcode_macro':
                    os.system(f'bash {DIR}/scripts/gcode.sh')
                elif command == '/power':
                    os.system(f'bash {DIR}/scripts/power.sh')
                elif command == '/host':
                    content_type, chat_type, chat_id = telepot.glance(msg)
                    keyboard = InlineKeyboardMarkup(inline_keyboard=[
                        [
                            InlineKeyboardButton(text='shutdown',
                                                 callback_data='pi_sh'),
                            InlineKeyboardButton(text='reboot',
                                                 callback_data='pi_re')
                        ],
                    ])
                    bot.sendMessage(chat_id,
                                    'what do you want to do with your pi',
                                    reply_markup=keyboard)
                elif command == '/pause':
                    content_type, chat_type, chat_id = telepot.glance(msg)
                    keyboard = InlineKeyboardMarkup(inline_keyboard=[
                        [
                            InlineKeyboardButton(text='yes',
                                                 callback_data='yes_pause'),
                            InlineKeyboardButton(text='no', callback_data='no')
                        ],
                    ])
                    bot.sendMessage(chat_id,
                                    'do you really want to pause',
                                    reply_markup=keyboard)
                elif command == '/resume':
                    x = requests.post(
                        f'http://127.0.0.1:{port}/printer/print/resume',
                        headers={"X-Api-Key": f'{api_key}'})
                    print(x.text)
                elif command == '/cancel':
                    content_type, chat_type, chat_id = telepot.glance(msg)
                    keyboard = InlineKeyboardMarkup(inline_keyboard=[
                        [
                            InlineKeyboardButton(text='yes',
                                                 callback_data='yes_cancel'),
                            InlineKeyboardButton(text='no', callback_data='no')
                        ],
                    ])
                    bot.sendMessage(chat_id,
                                    'do you really want to abort',
                                    reply_markup=keyboard)
예제 #20
0
파일: cgembot.py 프로젝트: echogrey/gembot
def on_callback_query(msg):
    """ Function used to determine what action to take
        when a button on the custom keyboard is pressed.
        Using telepot.glance, the bot is able to see if the
        data in the recieved "message" has the flavor 'callback_query',
        and if so, if the callback data corresponds to any of the
        if-cases in on_callback_query.
        
    Args:
        msg: the message sent from the user.
    Returns:
        Depending on the callback data, either:
        - new custom keyboard with labels and callback data
        - a photo of a university building with it's corresponding
        name and programme information, sent by the bot
        - a message with information about the GEM discoverer,
        sent by the bot
        - 
    """

    query_id, from_id, data = telepot.glance(msg, flavor='callback_query')
    print('Callback query:', query_id, from_id, data)
    global message_with_inline_keyboard

    if data == 'photo':

        #   see function get_photo(arg)

        search, photo = get_photo(0)
        bot.sendPhoto(from_id, photo)
        bot.sendMessage(
            from_id,
            emoji.emojize(":balloon:This is a picture of ") + search)
        bot.sendMessage(
            from_id,
            'To find out more about the shown university, just reply with keywords of the university name'
        )

    elif data == 'info':

        #   If the info button is pressed, the bot
        #   replies with a message about the GEM Discoverer programme

        bot.sendMessage(
            from_id,
            emoji.emojize(
                "Welcome to the GEM bot:two_men_holding_hands::two_women_holding_hands:! This is a bot "
                "that\'s supposed to give you info regarding NTU's GEM Discoverer. "
                "\nGEM Discoverer offers various programmes that place students globally for overseas internships, summer studies, business/cultural executive programmes and language training. All programmes are credit-bearing and designed to enhance your cross-cultural intelligence."
                "\nTo start, use /start "
                "\nIf you like this bot, please vote for GEM Saiko!!!:airplane::ticket::bus::tropical_drink:"
            ))

    elif data == 'region':

        #   University list - opens a new custom keyboard with buttons
        #   for each region.

        msg_idf = telepot.message_identifier(message_with_inline_keyboard)

        my_keyboard = [[
            InlineKeyboardButton(text='Asia', callback_data='Asia'),
            InlineKeyboardButton(text='Europe', callback_data='Europe'),
        ],
                       [
                           InlineKeyboardButton(text='North America',
                                                callback_data='North America'),
                           InlineKeyboardButton(text='South America',
                                                callback_data='South America'),
                       ],
                       [
                           InlineKeyboardButton(text='Oceania',
                                                callback_data='Oceania'),
                       ],
                       [
                           InlineKeyboardButton(
                               text=emoji.emojize('Back to Main Menu:house:'),
                               callback_data='main_menu'),
                       ]]

        markup = InlineKeyboardMarkup(inline_keyboard=my_keyboard)
        bot.editMessageText(
            msg_idf,
            emoji.emojize('Where would you like to go?:paw_prints:'),
            reply_markup=markup)

    elif data == 'main_menu':

        #   The main menu (custom keyboard) is opened

        msg_idf = telepot.message_identifier(message_with_inline_keyboard)

        markup = InlineKeyboardMarkup(inline_keyboard=[
            [
                dict(text=emoji.emojize('What is GEM?:eyes:'),
                     callback_data='info')
            ],
            [
                dict(text=emoji.emojize('Check university list:books:'),
                     callback_data='region')
            ],
            [
                dict(text=emoji.emojize(
                    'Explore a mysterious university:ghost:'),
                     callback_data='photo')
            ],
            [
                dict(
                    text=emoji.emojize(
                        'Official GEM Discoverer URL:sparkles:'),
                    url=
                    'http://global.ntu.edu.sg/GMP/gemdiscoverer/Pages/index.aspx'
                )
            ],
        ])

        bot.editMessageText(
            msg_idf,
            emoji.emojize(
                "Welcome to GEM bot:rocket:You're lovin' it!:love_letter:"),
            reply_markup=markup)

    elif data in contid:

        #   If the user presses one of the region buttons in the
        #   university list, the bot replies with a list of countries
        #   that offers exchange programmes for NTU students

        country = contid[data]
        message = ''
        for c in country:
            message = message + c + '\n'
        bot.sendMessage(
            from_id,
            emoji.emojize(
                '>>> Well received!:palm_tree: Now pick one from the following countries: \n'
            ) + message)
        bot.sendMessage(
            from_id,
            'To see available universities in a specific country, reply with the desired country name (case sensitive!)'
        )
예제 #21
0
def optionChanged(lang):
    text = translate.optionChanged(lang)
    return InlineKeyboardMarkup(inline_keyboard=[
        [InlineKeyboardButton(text=text[0], callback_data='sback')],
        [InlineKeyboardButton(text=text[1], callback_data='restart')],
    ])
예제 #22
0
class Lover(telepot.helper.ChatHandler):
    keyboard = InlineKeyboardMarkup(inline_keyboard=[
        [  #<-- Menu awal
            InlineKeyboardButton(text='Beri pakan', callback_data='pakan'),
            InlineKeyboardButton(text='Pengaturan', callback_data='setting')
        ],
        [
            InlineKeyboardButton(text='um ...', callback_data='no'),
            InlineKeyboardButton(text='keluar', callback_data='keluar')
        ]
    ])
    keyboard1 = InlineKeyboardMarkup(inline_keyboard=[
        [  #<-- Terusan Pengaturan dari Menu Awal
            InlineKeyboardButton(text='Set penjadwalan pemberian pakan?',
                                 callback_data='waktu')
        ],
        [
            InlineKeyboardButton(text='Set dosis pemberian pakan?',
                                 callback_data='dosis')
        ]
    ])
    keyboard2 = InlineKeyboardMarkup(inline_keyboard=[
        [
            InlineKeyboardButton(text='Kolam 1', callback_data='pknk1'),
            InlineKeyboardButton(text='Kolam 2', callback_data='pknk2')
        ],
        [
            InlineKeyboardButton(text='Kolam 3', callback_data='pknk3'),
            InlineKeyboardButton(text='Semua Kolam', callback_data='pknkAll')
        ], [InlineKeyboardButton(text='Kembali', callback_data='kembali')]
    ])
    keyboard3 = InlineKeyboardMarkup(inline_keyboard=[
        [  #<-- Terusan Pengaturan-Waktu dari Menu Awal
            InlineKeyboardButton(text='Kolam 1', callback_data='wkolam1'),
            InlineKeyboardButton(text='Kolam 2', callback_data='wkolam2')
        ],
        [
            InlineKeyboardButton(text='Kolam 3', callback_data='wkolam3'),
            InlineKeyboardButton(text='Semua Kolam', callback_data='wkolamAll')
        ],
        [InlineKeyboardButton(text='Kembali', callback_data='kembali')]
    ])
    keyboard4 = InlineKeyboardMarkup(inline_keyboard=[
        [  #-- Terusan Pengaturan-Takaran dari Menu Awal
            InlineKeyboardButton(text='Kolam 1', callback_data='dkolam1'),
            InlineKeyboardButton(text='Kolam 2', callback_data='dkolam2')
        ],
        [
            InlineKeyboardButton(text='Kolam 3', callback_data='dkolam3'),
            InlineKeyboardButton(text='Semua Kolam', callback_data='dkolamAll')
        ],
        [InlineKeyboardButton(text='Kembali', callback_data='kembali')]
    ])
    keyboard5 = ReplyKeyboardMarkup(
        keyboard=[[
            KeyboardButton(text="1:00", callback_data='1'),
            KeyboardButton(text="2:00", callback_data='2'),
            KeyboardButton(text="3:00", callback_data='3'),
            KeyboardButton(text="4:00", callback_data='4'),
            KeyboardButton(text="5:00", callback_data='5'),
            KeyboardButton(text="6:00", callback_data='6'),
            KeyboardButton(text="7:00", callback_data='7'),
            KeyboardButton(text="8:00", callback_data='8')
        ],
                  [
                      KeyboardButton(text="9:00", callback_data='9'),
                      KeyboardButton(text="10:00", callback_data='10'),
                      KeyboardButton(text="11:00", callback_data='11'),
                      KeyboardButton(text="12:00", callback_data='12'),
                      KeyboardButton(text="13:00", callback_data='13'),
                      KeyboardButton(text="14:00", callback_data='14'),
                      KeyboardButton(text="15:00", callback_data='15'),
                      KeyboardButton(text="16:00", callback_data='16')
                  ],
                  [
                      KeyboardButton(text="17:00", callback_data='17'),
                      KeyboardButton(text="18:00", callback_data='18'),
                      KeyboardButton(text="19:00", callback_data='19'),
                      KeyboardButton(text="20:00", callback_data='20'),
                      KeyboardButton(text="21:00", callback_data='21'),
                      KeyboardButton(text="22:00", callback_data='22'),
                      KeyboardButton(text="23:00", callback_data='23'),
                      KeyboardButton(text="24:00", callback_data='0')
                  ]])

    def __init__(self, *args, **kwargs):
        super(Lover, self).__init__(*args, **kwargs)

        # Retrieve from database
        global propose_records
        if self.id in propose_records:
            self._edit_msg_ident = propose_records[self.id]
            self._editor = telepot.helper.Editor(
                self.bot,
                self._edit_msg_ident) if self._edit_msg_ident else None
        else:
            self._edit_msg_ident = None
            self._editor = None

    def _propose(self):
        sent = self.sender.sendMessage('Apa yang bisa saya bantu?',
                                       reply_markup=self.keyboard)
        self._editor = telepot.helper.Editor(self.bot, sent)
        self._edit_msg_ident = telepot.message_identifier(sent)

    """
    def _propose_time(self):
        current_time = time.strftime("%H:%M", t)
        (h, m) = current_time.split(':')
        result = int(h) * 3600 + int(m) * 60
        
        (h, m) = setTime1.split(':')
        timeklm1 = int(h) * 3600 + int(m) * 60
        
        (h, m) = setTime2.split(':')
        timeklm2 = int(h) * 3600 + int(m) * 60
        
        (h, m) = setTime3.split(':')
        timeklm3 = int(h) * 3600 + int(m) * 60
    """

    def _cancel_last(self):
        if self._editor:
            self._editor.editMessageReplyMarkup(reply_markup=None)
            self._editor = None
            self._edit_msg_ident = None

    def on_chat_message(self, msg):
        if msg['from']['id'] != CHATID:
            bot.sendMessage(chat_id,
                            "Maaf ini adalah bot pribadi. Akses ditolak!")
            self.close()
        self._cancel_last()
        self._propose()
        '''
        command = msg['text']
        if (command == '/hi'):
            bot.sendMessage(chat_id, "Hi")
        '''

    def on_callback_query(self, msg):
        query_id, from_id, query_data = telepot.glance(msg,
                                                       flavor='callback_query')

        if query_data == 'keluar':
            self._cancel_last()
            self.sender.sendMessage('Terima kasih! \nBye..')
            self.close()

        # == Setting ==
        elif query_data == 'setting':
            self.bot.answerCallbackQuery(query_id,
                                         text='Ok. Pertanyaan berikutnya...')
            self._cancel_last()
            sent = self.sender.sendMessage('Apa yang ingin anda atur?',
                                           reply_markup=self.keyboard1)
            self._editor = telepot.helper.Editor(self.bot, sent)
            self._edit_msg_ident = telepot.message_identifier(sent)

        elif query_data == 'waktu':
            self.bot.answerCallbackQuery(query_id,
                                         text='Ok. Pertanyaan berikutnya...')
            self._cancel_last()
            sent = self.sender.sendMessage(
                'Kolam mana yang ingin anda atur penjadwalan pakannya?',
                reply_markup=self.keyboard3)
            self._editor = telepot.helper.Editor(self.bot, sent)
            self._edit_msg_ident = telepot.message_identifier(sent)

        elif query_data == 'wkolam1':
            self.bot.answerCallbackQuery(
                query_id, text='Penjadwalan akan diset ke waktu terpilih')
            self._cancel_last()
            sent = self.sender.sendMessage(
                'Silhkan pilih waktu yang diinginkan.. ',
                reply_markup=self.keyboard5)

        elif query_data == 'dosis':
            self.bot.answerCallbackQuery(query_id,
                                         text='Ok. Pertanyaan berikutnya...')
            self._cancel_last()
            sent = self.sender.sendMessage(
                'Kolam mana yang ingin anda atur dosis pakannya?',
                reply_markup=self.keyboard4)
            self._editor = telepot.helper.Editor(self.bot, sent)
            self._edit_msg_ident = telepot.message_identifier(sent)

        # ==pemberian pakan==
        elif query_data == 'pakan':
            self.bot.answerCallbackQuery(query_id,
                                         text='Ok. Pertanyaan berikutnya...')
            self._cancel_last()
            sent = self.sender.sendMessage(
                'Kolam mana yang ingin anda beri pakan?',
                reply_markup=self.keyboard2)
            self._editor = telepot.helper.Editor(self.bot, sent)
            self._edit_msg_ident = telepot.message_identifier(sent)

        elif query_data == 'pknk1':
            if setTime1 == 'null':
                self.bot.answerCallbackQuery(
                    query_id,
                    text='Ok. Pemberian pakan pada kolam 1 akan dilakukan...')
                self._cancel_last()
                #!! kasi pakan, kamera jalan,
                stat1 = 1
                self.sender.sendMessage(
                    'Pemberian pakan pada kolam 1 telah selesai \nketikkan perintah /dokumentasi untuk mendapat rekaman video..'
                )
                self.close()
            else:
                if stat1 == 0:
                    self.bot.answerCallbackQuery(query_id,
                                                 text='Peringatan !!!')
                    self._cancel_last()
                    self.sender.sendMessage(
                        'Pemberian pakan pada kolam 1 Telah dijadwlkan pada pukul'
                        + setTime1 +
                        '\nketikkan perintah /force1 untuk memberikan pakan sekarang juga..'
                    )
                    self.close()

        else:
            self.bot.answerCallbackQuery(
                query_id, text='Ok. Tapi aku akan terus bertanya.')
            self._cancel_last()
            self._propose()

    def on__idle(self, event):
        self.sender.sendMessage(
            'Saya tahu Anda mungkin perlu sedikit waktu. Aku akan selalu di sini untukmu.'
        )
        self._cancel_last()
        self.close()

    def on_close(self, ex):
        # Save to database
        global propose_records
        propose_records[self.id] = (self._edit_msg_ident)
예제 #23
0
def inlineBack(lang):
    text = translate.back(lang)
    return InlineKeyboardMarkup(inline_keyboard=[
        [InlineKeyboardButton(text=text, callback_data='back')],
    ])
예제 #24
0
def handle(
        msg
):  #a function to tell the bot what to do when users answer with text
    global id_info
    text = []
    text_match = []
    recommend = []
    frequentroad = []
    #using glance function to take the necessary info.
    content_type, chat_type, chat_id = telepot.glance(msg)
    print(content_type, chat_type, chat_id)
    #making a custom keyboard for user to use
    keyboard = InlineKeyboardMarkup(inline_keyboard=[[
        InlineKeyboardButton(text='Yeah', callback_data='press')
    ], [InlineKeyboardButton(text="Nah I'm good", callback_data='press1')]])
    if content_type == 'text':  #check if what user sends is a text
        if chat_id not in id_info:  #check if it is a new user
            id_info[chat_id] = {
                "interaction": 1,
                "road": {}
            }  #creat a new entry in its memory
        else:
            id_info[chat_id]["interaction"] += 1
            #create a list of frequent searched roads
            recommend = sorted(id_info[chat_id]["road"],
                               key=lambda key: id_info[chat_id]["road"][key],
                               reverse=True)
        if id_info[chat_id]["interaction"] % 2 == 1:
            #check if the current user actually has any frequent searched roads
            for road, time in id_info[chat_id]["road"].items():
                if time > 4:
                    frequentroad.append(road)
            if len(frequentroad) == 0:
                bot.sendMessage(
                    chat_id, "Hey %s, where are you going ?" %
                    msg['chat']['first_name'])
            else:
                #making a proper response if the user has frequent searched roads
                if len(frequentroad) == 1:
                    recroad = frequentroad[0]
                    keyboard1 = InlineKeyboardMarkup(inline_keyboard=[[
                        InlineKeyboardButton(text=recroad,
                                             callback_data=recroad)
                    ]])
                else:
                    recroad1 = recommend[0]
                    recroad2 = recommend[1]
                    keyboard1 = InlineKeyboardMarkup(
                        inline_keyboard=[[
                            InlineKeyboardButton(text=recroad1,
                                                 callback_data=recroad1)
                        ],
                                         [
                                             InlineKeyboardButton(
                                                 text=recroad2,
                                                 callback_data=recroad2)
                                         ]])
                bot.sendMessage(
                    chat_id,
                    "Hey %s, are you going here ? What, you think I don't remember :D"
                    % msg['chat']['first_name'],
                    reply_markup=keyboard1)
                bot.sendMessage(chat_id, "Or are you going somewhere else ?")
        else:
            #searching for info
            key = msg['text']
            #marking how many times a user search a road for recommendation
            if key not in id_info[chat_id]["road"]:
                id_info[chat_id]["road"][key] = 1
            else:
                id_info[chat_id]["road"][key] += 1
            #searching and filtering for relevant info
            chrome.get(
                "https://www.onemotoring.com.sg/content/onemotoring/en/on_the_roads/traffic_news.html"
            )
            list_acc = chrome.find_elements(By.CSS_SELECTOR,
                                            ".cell.cell80.textleft")
            for ele in list_acc:
                text.append(ele.text)
            for acc in text:
                if key in acc:
                    text_match.append(acc)
            if len(text_match) == 0:
                bot.sendMessage(
                    chat_id,
                    "Sorry I can't find anything. Maybe check your spelling ? Or maybe it's your lucky day!!"
                )
            else:
                bot.sendMessage(chat_id, "Okay here's what I found")
                for info in text_match:
                    bot.sendMessage(chat_id, info)
                bot.sendMessage(
                    chat_id,
                    "I'd be careful if I were you!! Wait I'm a bot...")
            bot.sendMessage(chat_id,
                            "You wanna check anything else mastaa ?",
                            reply_markup=keyboard)
예제 #25
0
def show_result(chat_id, bot, user_id_token, Flag4XF, markup_key = None, ex_key = None, *sh4c, **kwargs):
    global flag4editmessage

    Show2customer = ""
    markup = ReplyKeyboardMarkup(keyboard=markup_key)
    if Flag4XF == "X":
        text_Flag4XF = "اتمام"
    elif Flag4XF == "F":
        text_Flag4XF = "موجود است"

    if not flag4editmessage:
        
        if not ex_key:
            if sh4c[-1] == 0:
                ex_key = tnxfromseller + pluskeymessage + menuskeymessage + editkeymessage + newproductkey
            else:
                ex_key = next_product
        else:
            ex_key += ":"    
        try:
            bot.sendMessage(chat_id, ex_key , reply_markup = markup)
        except:
            pass

    if kwargs:
        if "price_ware" in kwargs:
            inline_markup = InlineKeyboardMarkup(inline_keyboard = [
                                                 [dict(text = 'ویرایش️', callback_data = ("E"+kwargs["title"])),
                                                 InlineKeyboardButton(text = 'حذف', callback_data = ("D"+kwargs["title"])),
                                                 InlineKeyboardButton(text = text_Flag4XF, callback_data = (Flag4XF + kwargs["title"]))]])
        
        else:
            inline_markup = InlineKeyboardMarkup(inline_keyboard = [
                                                 [dict(text = 'ویرایش️', callback_data = ("E"+kwargs["title"])),
                                                 InlineKeyboardButton(text = 'حذف', callback_data = ("D"+kwargs["title"]))]])
        Show2customer += kwargs["title"] + "\n\n"
        if "file_id" in kwargs and not flag4editmessage:
            try:
                bot.sendPhoto(chat_id, kwargs["file_id"])
            except:
                pass
        if "context" in kwargs:
            Show2customer += kwargs["context"] + "\n\n"

        if "price_ware" in kwargs:
            Show2customer += "قیمت: " + kwargs["price_ware"] + " " + kwargs["currency_ware"] + "\n"

        if "discount" in kwargs:
            Show2customer += "تخفیف: " + kwargs["discount"] + "درصد \n"
            final_price = str(int((100 - int(kwargs["discount"])) * int(kwargs["price_ware"])/100))
            
            Show2customer += "قیمت نهایی: " + final_price + " " + kwargs["currency_ware"] + "\n\n"
            try:
                if not flag4editmessage:
                    bot.sendMessage(chat_id, Show2customer, reply_markup = inline_markup)                    
                else:
                    flag4editmessage = False
                    bot.editMessageText(chat_id, Show2customer, reply_markup = inline_markup)
            except:
                pass
        else:
            try:
                if not flag4editmessage:
                    bot.sendMessage(chat_id, Show2customer, reply_markup = inline_markup)
                else:
                    flag4editmessage = False                
                    bot.editMessageText(chat_id, Show2customer, reply_markup = inline_markup)
            except:
                pass
### If you need proxy, uncomment the following part
#proxy_url = "<URL>:<PORT>"
#telepot.api._pools = {'default': urllib3.ProxyManager(proxy_url=proxy_url, num_pools=3, maxsize=10, retries=False, timeout=30),}
#telepot.api._onetime_pool_spec = (urllib3.ProxyManager, dict(proxy_url=proxy_url, num_pools=1, maxsize=1, retries=False, timeout=30))

### Insert your token here. Don't expose your token to others!
bot = telepot.Bot('XXXXXXXXX:EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE')

if args.xtext:
    msg = bot.getMe()
    logger.info("BEGIN: getMe(): {!r}".format(msg))
    ALMMSG = args.xtext

if args.e:
    users = eco[:]
    ALMMSG = "ECO ALERT(24x7) \n"+ALMMSG

keyboard=None
if args.fullname and args.type=="PROBLEM" :
    callback_info="disable;{};{}".format(args.fullname,args.name)
    my_inline_keyboard = [[ InlineKeyboardButton(text="Disable this notification", callback_data=callback_info) ]]
    keyboard = InlineKeyboardMarkup(inline_keyboard=my_inline_keyboard)


for one in users:
    logger.info("Notification to user {}. Msg: {}".format(one, ALMMSG))
    if keyboard:
        bot.sendMessage(one, ALMMSG, reply_markup=keyboard)
    else:
        bot.sendMessage(one, ALMMSG)
예제 #27
0
def new_gifts_result(msg,
                     dri,
                     next_gifts=False,
                     category_id=None,
                     price_oriented=False,
                     price_index=None):
    chat_id = str(msg['from']['id'])

    if category_id:
        callback_data = 'next_' + str(category_id)
    elif price_oriented:
        callback_data = 'nextoriented_' + str(price_index)
    else:
        callback_data = 'next'

    redis_info = redis_db.get(chat_id)
    if redis_info is None:
        redis_info = create_initial_redis_info(dri)
        redis_db.set(chat_id, redis_info)
    if type(redis_info) != str:
        redis_info = redis_info.decode('utf-8')
    print(str(redis_info))
    r = UserRedisInfo(**json.loads(str(redis_info)))

    if not next_gifts and not price_oriented and category_id is None:
        r.new_gifts_slide_number = 0
    if not next_gifts and not price_oriented and category_id is not None:
        r.categories_slide_number[category_id] = 0
    if not next_gifts and price_oriented:
        r.price_oriented_slide_number[price_index] = 0

    if category_id:
        c_gifts = [
            g for g in dri.gifts if str(g.category_id) == str(category_id)
        ]
        gifts = c_gifts[-(
            new_gifts_count_constant +
            r.categories_slide_number[category_id]):len(c_gifts) -
                        r.categories_slide_number[category_id]]
    elif price_oriented:
        gifts = dri.gifts[-(
            new_gifts_count_constant +
            r.price_oriented_slide_number[price_index]):len(dri.gifts) -
                          r.price_oriented_slide_number[price_index]]
    else:
        gifts = dri.gifts[-(new_gifts_count_constant +
                            r.new_gifts_slide_number):len(dri.gifts) -
                          r.new_gifts_slide_number]
    images = [i.gift_image for i in gifts]

    if len(gifts) == 0:
        bot.sendMessage(chat_id, finished_fa)

    for i in range(len(gifts)):
        if i == len(gifts) - 1:
            keyboard = [[
                InlineKeyboardButton(text=gift_fa,
                                     callback_data='order_' +
                                     str(gifts[i].id)),
                InlineKeyboardButton(text=next_fa, callback_data=callback_data)
            ]]
        else:
            keyboard = [[
                InlineKeyboardButton(text=gift_fa,
                                     callback_data='order_' + str(gifts[i].id))
            ]]
        markup = InlineKeyboardMarkup(inline_keyboard=keyboard)
        bot.sendPhoto(chat_id,
                      open(
                          app.config['UPLOAD_FOLDER'] +
                          str(gifts[i].category_id) + '/' + images[i], 'rb'),
                      caption=str(gifts[i].gift_specification) + '\n' +
                      str(gifts[i].gift_price),
                      reply_markup=markup)

    if category_id:
        if len(gifts) == 0:
            r.categories_slide_number[category_id] = 0
        r.categories_slide_number[category_id] += len(gifts)
    elif price_oriented:
        if len(gifts) == 0:
            r.price_oriented_slide_number[price_index] = 0
        r.price_oriented_slide_number[price_index] += len(gifts)
    else:
        if len(gifts) == 0:
            r.new_gifts_slide_number = 0
        r.new_gifts_slide_number += len(gifts)

    redis_db.set(chat_id, json.JSONEncoder().encode(r.__dict__))
예제 #28
0
def on_chat_message(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)


    # Everything that will be executed when the bot receives the command "/start"
    if content_type == 'text' and msg['text'] == '/start':
      cur= db.cursor()
      cur.execute("SELECT chat_id FROM Users WHERE chat_id= %s", (str(chat_id),)) # Interrogates the DB to find the ID of the user who sent the command "/start"
      q= str(cur.fetchall())
      cur.close()
      query_t= re.sub("\[|\]|\'|\(|\)|\,", '', str(q)) # Removes from the resulting string any character that might make its use inside the function difficult 
      print("The query returned",query_t)
      user_info= list(msg['from'].values())[4] # Stores user info in a list format 
      
      if query_t == "": # An empty query result means that the user's info is not in the DB
          cur= db.cursor()
          cur.execute("INSERT INTO Users(chat_id, username) VALUES (%s,%s)", (str(chat_id),str(user_info)))
          db.commit()
          print("New user added to the database",str(chat_id),str(user_info))
          
      bot.sendMessage(chat_id, "This bot can translate and pronounce things to and from Japanese. Use the command /help to get to know more about how the bot works. はじめましょうね :)")


    # Everything that will be executed when the bot receives the command "/pronunciation + string to pronounce"   
    elif content_type == 'text' and str(msg['text'])[0:14] == '/pronunciation':
        print("Pronunciation service requested from "+str(chat_id))
        message= str(msg['text'])
        mp= message[15:len(message)] # Subs every character after the command "/pronunciation"
        print("Message to pronounce: "+mp)
        
        if mp == '':
            print("Empty message, notifying the user")
            bot.sendMessage(chat_id, "Wrong syntax, use the /help command to know more about the usage of the pronunciation command")

        else:
            language= str(translator.detect(mp)) # Makes use of the translator object to detect the language of the message to pronounce

            if 'ja' or 'cn' in language: 
                print("Language is JA")
                # A temp mp3 file with the pronunciation request is created, sent to the user and eliminated
                pronunciation= gTTS(text=mp, lang='ja')
                pronunciation.save("pronunciation.mp3")
                print("pronunciation.mp3 file has been saved")
                bot.sendAudio(chat_id, open('pronunciation.mp3', 'rb'), title='Pronunciation of '+mp)
                print("pronunciation.mp3 file has been sent to "+str(chat_id))
                os.remove("pronunciation.mp3")
                print("pronunciation.mp3 file has been removed")
                params= (str(chat_id),'pronunciation','ja',mp,str(msg['date']))
                cur= db.cursor()
                cur.execute("INSERT INTO Texts(chat_id, type, language_og, contentbefore, timestamp_txt) VALUES (%s, %s, %s, %s, %s)", params)
                db.commit()
                print("Informations about the pronunciation have been added to the database")
                
            else:
                print("Language is not JA")
                bot.sendMessage(chat_id, "The message is not in Japanese. To have the bot pronunciating something, please send a message in Japanese")

                
    # Everything that will be executed when the bot receives the command "/translation + string to translate"               
    elif content_type == 'text' and str(msg['text'])[0:12] == '/translation':
        print("Translation service requested from "+str(chat_id))
        message= str(msg['text'])
        mp= message[13:len(message)] # Subs every character after the command "/translation"
        print("Message to translate: "+mp)
        
        if mp == '':
            print("Empty message, notifying the user")
            bot.sendMessage(chat_id, "Wrong syntax, use the /help command to know more about the usage of the translation command")
            
        else:
            language= str(translator.detect(mp))
            
            if 'ja' in language: # Translation from Japanese to English
                print("Searching for a pre-existing translation for "+mp+" in the database...")
                cur= db.cursor()
                cur.execute("SELECT DISTINCT contentafter FROM Texts WHERE language_og= 'ja' AND type= 'translation' AND contentbefore= %s", (mp,))
                q= str(cur.fetchall())
                cur.close()
                query_t= re.sub("\[|\]|\'|\(|\)|\,", '', str(q)) # Removes from the resulting string any character that might make its use inside the function difficult
                print("The query returned",query_t)
                
                if query_t == '':
                    print("Pre-existing translation not found, "+mp+" will be translated using the googletrans API")
                    translation= translator.translate(mp, dest='en')
                    print(translation.origin, ' -> ', translation.text)
                    bot.sendMessage(chat_id, translation.text)
                    print("The translation has been sent to "+str(chat_id))
                    params= (str(chat_id),'translation','ja',mp,translation.text,str(msg['date']))
                    cur= db.cursor()
                    cur.execute("INSERT INTO Texts(chat_id, type, language_og, contentbefore, contentafter, timestamp_txt) VALUES (%s, %s, %s, %s, %s, %s)", params)
                    db.commit()
                    print("Informations about the translation have been added to the database")
                    
                else:
                    print("A pre-existing translation has been found")
                    bot.sendMessage(chat_id, query_t)
                    print("The translation has been sent to "+str(chat_id))
                    params= (str(chat_id),'translation','ja',mp,query_t,str(msg['date']))
                    cur= db.cursor()
                    cur.execute("INSERT INTO Texts(chat_id, type, language_og, contentbefore, contentafter, timestamp_txt) VALUES (%s, %s, %s, %s, %s, %s)", params)
                    db.commit()
                    print("Informations about the translation have been added to the database")

            else: # Translation from the language of the text to Japanese
                lcode= language[14:16]
                print("Searching for a pre-existing translation for "+mp+" in the database...")
                cur= db.cursor()
                cur.execute("SELECT DISTINCT contentafter FROM Texts WHERE language_og=%s AND type= 'translation' AND contentbefore= %s", (lcode,mp))
                q= str(cur.fetchall())
                cur.close()
                print(q)
                query_t= re.sub("\[|\]|\'|\(|\)|\,", '', str(q)) # Removes from the resulting string any character that might make its use inside the function difficult
                print("The query returned",query_t)
                
                if query_t == '':
                    print("Pre-existing translation not found, "+mp+" will be translated using the googletrans API")
                    translation= translator.translate(mp, dest='ja')
                    print(translation.origin, ' -> ', translation.text)
                    bot.sendMessage(chat_id, translation.text)
                    print("The translation has been sent to "+str(chat_id))
                    params= (str(chat_id),'translation',lcode,mp,translation.text,str(msg['date']))
                    cur= db.cursor()
                    cur.execute("INSERT INTO Texts(chat_id, type, language_og, contentbefore, contentafter, timestamp_txt) VALUES (%s, %s, %s, %s, %s, %s)", params)
                    db.commit()
                    print("Informations about the translation have been added to the database")
                    
                else:
                    print("A pre-existing translation has been found")
                    bot.sendMessage(chat_id, query_t)
                    print("The translation has been sent to "+str(chat_id))
                    lcode= language[14:16]
                    params= (str(chat_id),'translation',lcode,mp,query_t,str(msg['date']))
                    cur= db.cursor()
                    cur.execute("INSERT INTO Texts(chat_id, type, language_og, contentbefore, contentafter, timestamp_txt) VALUES (%s, %s, %s, %s, %s, %s)", params)
                    db.commit()
                    print("Information about the translation has been added to the database")


    # Everything that will be executed when the bot receives the command "/queries"                
    elif content_type == 'text' and str(msg['text'])[0:8] == '/queries':
        # Creation of the Telegram inline keyboard which will be sent to the user to query the bot's database 
        markup = InlineKeyboardMarkup(inline_keyboard=[
             [dict(text='Total number of messages sent to the bot from the first startup to the moment the query has been executed', callback_data='n_total')],
             [InlineKeyboardButton(text='Date of the first message sent to the bot (/start, /help, /queries and /advanced messages are not counted)', callback_data='first')],
             [dict(text='Date of the last message sent to the bot (/start, /help, /queries and /advanced messages are not counted)', callback_data='last')],
             [InlineKeyboardButton(text='Total number of pronunciation requests sent to the bot from the first startup to the moment the query has been executed', callback_data='pronun')],
             [dict(text='Total number of translation requests sent to the bot from the first startup to the moment the query has been executed', callback_data='trans')],
             ])
        bot.sendMessage(chat_id, "Use the buttons to perform basic queries on the bot's database", reply_markup=markup)


    # Everything that will be executed when the bot receives the command "/help"    
    elif content_type == 'text' and str(msg['text'])[0:5] == '/help':
        # Creation of the Telegram inline keyboard which will be sent to the user to find more info on the bot
        markup = InlineKeyboardMarkup(inline_keyboard=[
             [dict(text='Translation', callback_data='translation')],
             [InlineKeyboardButton(text='Vocal translation', callback_data='voice')],
             [InlineKeyboardButton(text='Pronunciation', callback_data='pronunciation')],
             [dict(text='Queries', callback_data='queries')],
             [InlineKeyboardButton(text='Switch to using bot inline', switch_inline_query='')],
             ])
        bot.sendMessage(chat_id, 'Help section, use the buttons to get information on how the bot works', reply_markup=markup)


    # Everything that will be executed when the bot receives a voice message (translation of the voice note to Japanese)            
    elif content_type == 'voice':
        bot.download_file(msg['voice']['file_id'], './voice.ogg') # Saves the voice message as a .ogg audio file
        # The two following lines create a Linux command-line to convert voice.ogg to a .wav file using the program ffmpeg, to be used by the Speech Recognition utility, and execute it 
        command= subprocess.Popen(["ffmpeg","-i","voice.ogg","-ab", "128000", "voice.wav"], stdout=subprocess.PIPE) 
        output= command.communicate()[0]
        r= sr.Recognizer() # Instantiates speech recogniser object
        
        with sr.AudioFile("voice.wav") as source:
            audio= r.record(source)
            
        try:
            message= r.recognize_sphinx(audio) # What is said in the voice message is recognised using CMU Sphinx
            bot.sendMessage(chat_id,"The bot thinks you said '"+message+"'")
            print("Searching for a pre-existing translation for "+message+" in the database...")
            cur= db.cursor()
            cur.execute("SELECT DISTINCT contentafter FROM Texts WHERE language_og= 'en' AND type= 'translation' AND contentbefore= %s OR language_og= 'en' AND type= 'v_translation' AND contentbefore= %s", (message,message))
            q= str(cur.fetchall())
            cur.close()
            query_t= re.sub("\[|\]|\'|\(|\)|\,", '', str(q)) # Removes from the resulting string any character that might make its use inside the function difficult
            print("The query returned",query_t)
            
            if query_t == '':
                print("Pre-existing translation not found, "+message+" will be translated using the googletrans API")
                translation= translator.translate(message, dest='ja')
                print(translation.origin, ' -> ', translation.text)
                bot.sendMessage(chat_id, translation.text)
                print("The translation has been sent to "+str(chat_id))
                params= (str(chat_id),'v_translation','en',message,translation.text,str(msg['date']))
                cur= db.cursor()
                cur.execute("INSERT INTO Texts(chat_id, type, language_og, contentbefore, contentafter, timestamp_txt) VALUES (%s, %s, %s, %s, %s, %s)", params)
                db.commit()
                print("Information about the translation has been added to the database")
                
            else:
                print("A pre-existing translation has been found")
                bot.sendMessage(chat_id, query_t)
                print("The translation has been sent to "+str(chat_id))
                params= (str(chat_id),'v_translation','en',message,query_t,str(msg['date']))
                cur= db.cursor()
                cur.execute("INSERT INTO Texts(chat_id, type, language_og, contentbefore, contentafter, timestamp_txt) VALUES (%s, %s, %s, %s, %s, %s)", params)
                db.commit()
                print("Information about the translation has been added to the database")
        except sr.UnknownValueError:
            print("Bot could not understand voice message")
            bot.sendMessage(chat_id,"The bot could not understand your voice message. Make sure to send only voice messages in English and to also make sure they are understandable")
        except sr.RequestError as e:
            print("Sphinx error; {0}".format(e))
            bot.sendMessage(chat_id,"An error occurred, please try later")
  
        # The two audio files are then removed when no longer needed
        os.remove("voice.ogg")
        os.remove("voice.wav")
예제 #29
0
def condicoes(chatID, msg):
            if(msg == '/start'):
                    inicio(chatID, bot)

########################### CURSOS
            elif(msg == 'Cursos'):
                    bot.sendMessage(
                        chatID,
                        "Cursos oferecidos pela Fatec Profº Jessen Vidal",
                        reply_markup=InlineKeyboardMarkup(
                            inline_keyboard=[
                                [InlineKeyboardButton(text="Análise e Desenvolvimento de Sistemas", callback_data='ADS')],
                                [InlineKeyboardButton(text="Automação e Manufatura Digital", callback_data='ATM')],
                                [InlineKeyboardButton(text="Banco de Dados", callback_data='BD')],
                                [InlineKeyboardButton(text="Gestão da Produção Industrial", callback_data='GPI')],
                                [InlineKeyboardButton(text="Gestão Empresarial", callback_data='GE')],
                                [InlineKeyboardButton(text="Logística", callback_data='LOG')],
                                [InlineKeyboardButton(text="Manutenção de Aeronaves", callback_data='MA')],
                                [InlineKeyboardButton(text="Projetos de Estruturas Aeronáuticas", callback_data='PEA')]
                            ]
                        )
                    )
            elif(msg == 'ADS'):
                    txt = open('CursosOferecidos/ADS.md','r')
                    bot.sendMessage(
                        chatID,
                        txt.read(),
                        'Markdown',
                        reply_markup=InlineKeyboardMarkup(
                            inline_keyboard=[
                                [InlineKeyboardButton(text="Matriz Curricular", callback_data='matADS')]
                            ]
                        )
                    )
                    txt.close()

            elif(msg == 'matADS'):
                    bot.sendMessage(chatID, "Enviando Matriz Curricular...")
                    doc = open ("CursosOferecidos/matCurADS.pdf",'rb')
                    bot.sendDocument(chatID, doc)
                    doc.close()

            elif(msg == 'ATM'):
                    txt = open('CursosOferecidos/ATM.md','r')
                    bot.sendMessage(
                        chatID,
                        txt.read(),
                        'Markdown',
                        reply_markup=InlineKeyboardMarkup(
                            inline_keyboard=[
                                [InlineKeyboardButton(text="Matriz Curricular", callback_data='matATM')]
                            ]
                        )
                    )
                    txt.close()

            elif(msg == 'matATM'):
                    bot.sendMessage(chatID, "Enviando Matriz Curricular...")
                    doc = open ("CursosOferecidos/matCurATM.pdf",'rb')
                    bot.sendDocument(chatID, doc)
                    doc.close()

            elif(msg == 'BD'):
                    txt = open('CursosOferecidos/BD.md','r')
                    bot.sendMessage(
                        chatID,
                        txt.read(),
                        'Markdown',
                        reply_markup=InlineKeyboardMarkup(
                            inline_keyboard=[
                                [InlineKeyboardButton(text="Matriz Curricular", callback_data='matBD')]
                            ]
                        )
                    )
                    txt.close()

            elif(msg == 'matBD'):
                    bot.sendMessage(chatID, "Enviando Matriz Curricular...")
                    doc = open ("CursosOferecidos/matCurBD.pdf",'rb')
                    bot.sendDocument(chatID, doc)
                    doc.close()

            elif(msg == 'GPI'):
                    txt = open('CursosOferecidos/GPI.md','r')
                    bot.sendMessage(
                        chatID,
                        txt.read(),
                        'Markdown',
                        reply_markup=InlineKeyboardMarkup(
                            inline_keyboard=[
                                [InlineKeyboardButton(text="Matriz Curricular", callback_data='matGPI')]
                            ]
                        )
                    )
                    txt.close()

            elif(msg == 'matGPI'):
                    bot.sendMessage(chatID, "Enviando Matriz Curricular...")
                    doc = open ("CursosOferecidos/matCurGPI.pdf",'rb')
                    bot.sendDocument(chatID, doc)
                    doc.close()


            elif(msg == 'GE'):
                    txt = open('CursosOferecidos/GE.md','r')
                    bot.sendMessage(
                        chatID,
                        txt.read(),
                        'Markdown',
                    )
                    txt.close()

            elif(msg == 'LOG'):
                    txt = open('CursosOferecidos/LOG.md','r')
                    bot.sendMessage(
                        chatID,
                        txt.read(),
                        'Markdown',
                        reply_markup=InlineKeyboardMarkup(
                            inline_keyboard=[
                                [InlineKeyboardButton(text="Matriz Curricular", callback_data='matLOG')]
                            ]
                        )
                    )
                    txt.close()

            elif(msg == 'matLOG'):
                    bot.sendMessage(chatID, "Enviando Matriz Curricular...")
                    doc = open ("CursosOferecidos/matCurLOG.pdf",'rb')
                    bot.sendDocument(chatID, doc)
                    doc.close()


            elif(msg == 'MA'):
                    txt = open('CursosOferecidos/MA.md','r')
                    bot.sendMessage(
                        chatID,
                        txt.read(),
                        'Markdown',
                        reply_markup=InlineKeyboardMarkup(
                            inline_keyboard=[
                                [InlineKeyboardButton(text="Matriz Curricular", callback_data='matMA')]
                            ]
                        )
                    )
                    txt.close()

            elif(msg == 'matMA'):
                    bot.sendMessage(chatID, "Enviando Matriz Curricular...")
                    doc = open ("CursosOferecidos/matCurMA.pdf",'rb')
                    bot.sendDocument(chatID, doc)
                    doc.close()

            elif(msg == 'PEA'):
                    txt = open('CursosOferecidos/PEA.md','r')
                    bot.sendMessage(
                        chatID,
                        txt.read(),
                        'Markdown',
                        reply_markup=InlineKeyboardMarkup(
                            inline_keyboard=[
                                [InlineKeyboardButton(text="Matriz Curricular", callback_data='matPEA')]
                            ]
                        )
                    )
                    txt.close()

            elif(msg == 'matPEA'):
                    bot.sendMessage(chatID, "Enviando Matriz Curricular...")
                    doc = open ("CursosOferecidos/matCurPEA.pdf",'rb')
                    bot.sendDocument(chatID, doc)
                    doc.close()

##########################################################################################################

########################### COMO SER ALUNO
            elif (msg == 'Como ser Aluno'):
                    keyboard=ReplyKeyboardMarkup(
                        keyboard=[
                            [
                                KeyboardButton(text="Como se Inscrever"),
                                KeyboardButton(text="Provas Anteriores"),
                                KeyboardButton(text="Vestibular"),
                                KeyboardButton(text="Voltar")
                            ]
                        ],resize_keyboard=True
                    )
                    bot.sendMessage(chatID,"Todas as informações mais relevantes sobre a como se tornar aluno estão aqui...", reply_markup=keyboard)

            elif(msg == 'Como se Inscrever'):
                    txt = open('ComoSerAluno/Textos/comoSeInscrever.md','r')	#Abre o arquivo comoSeInscrever.md com o atributo leitura
                    bot.sendMessage(chatID,txt.read(),'Markdown')	#Envia mensagem com o conteúdo do arquivo 'txt'
                    txt.close()	#Fecha o arquivo

                    bot.sendMessage(chatID, "Enviando Manual do candidato...")
                    doc = open ("ComoSerAluno/manualCandidato.pdf",'rb')
                    bot.sendDocument(chatID, doc)
                    doc.close()

            elif(msg == 'Provas Anteriores'):
                    bot.sendMessage(chatID, "Enviando Prova do 1 semestre de 2017...")
                    doc = open ("ComoSerAluno/1semestre2017-PROVA.pdf",'rb')
                    bot.sendDocument(chatID, doc)
                    doc.close()

                    bot.sendMessage(chatID, "Enviando gabarito do 1 semestre de 2017...")
                    doc = open ("ComoSerAluno/1semestre2017-GABARITO.pdf",'rb')
                    bot.sendDocument(chatID, doc)
                    doc.close()

                    bot.sendMessage(chatID, "Enviando Prova do 2 semestre de 2017...")
                    doc = open ("ComoSerAluno/2semestre2017-PROVA.pdf",'rb')
                    bot.sendDocument(chatID, doc)
                    doc.close()

                    bot.sendMessage(chatID, "Enviando gabarito do 2 semestre de 2017...")
                    doc = open ("ComoSerAluno/2semestre2017-GABARITO.pdf",'rb')
                    bot.sendDocument(chatID, doc)
                    doc.close()

            elif(msg == 'Vestibular'):
                    txtHelp = open('ComoSerAluno/Textos/vestibular.md','r')	#Abre o arquivo Hellovestibular.md com o atributo leitura
                    bot.sendMessage(chatID,txtHelp.read(),'Markdown')	#Envia mensagem com o conteúdo do arquivo 'txtHelp.txt'
                    txtHelp.close()	#Fecha o arquivo

                    bot.sendMessage(chatID,'''Geralmente o vestibular ocorre nas escolas Estevam Ferri(Endereço: R. Cantídio Miragaia, 100 - Monte Castelo, São José dos Campos - SP, 12215-110)\nMarechal Rondon (Endereço: Praça Francisco Escobar, 165 - Monte Castelo, São José dos Campos - SP, 12215-170)\nambas em São José dos Campos''')

                    bot.sendMessage(chatID,"Enviando a localização da escola Estevam Ferri ...")
                    bot.sendLocation(chatID, -23.1829646,-45.8747777)

                    bot.sendMessage(chatID,"Enviando a localização da escola Marechal Rondon...")
                    bot.sendLocation(chatID, -23.183795, -45.874392)

########################### COMO CHEGAR
            elif (msg == 'Como Chegar'):
                    txtHelp = open('ComoChegar/Textos/txt01.md','r')

                    keyboard=ReplyKeyboardMarkup(
                        keyboard=[
                            [
                                KeyboardButton(text="Fatec no Mapa"),
                                KeyboardButton(text="Imagens"),
                                KeyboardButton(text="Voltar")
                            ]
                        ],
                        resize_keyboard=True
                    )

                    bot.sendMessage(chatID,	txtHelp.read(),'Markdown', reply_markup=keyboard)

                    txtHelp.close()	#Fecha o arquivo

            elif(msg == 'Fatec no Mapa'):
                    bot.sendMessage(chatID,"Enviando localização...")
                    bot.sendLocation(chatID, -23.162578,-45.7967319)

            elif (msg == 'Imagens'):
                    bot.sendMessage(chatID, "Enviando imagem...")
                    imgFatec = open("ComoChegar/Imagens/VistaFatec01.jpg","rb")
                    bot.sendPhoto(chatID, imgFatec)
                    imgFatec.close()
##########################################################################################################

########################### SOBRE A FATEC
            elif (msg == 'Sobre a Fatec'):
                    txtHelp = open('SobreFatecSjc/Textos/introducaoSobreAFatec.md','r')
                    keyboard=ReplyKeyboardMarkup(
                        keyboard=[
                            [
                                KeyboardButton(text="+ Sobre Fatec"),
                                KeyboardButton(text="Projetos"),
                                KeyboardButton(text="Regulamento Interno"),
                                KeyboardButton(text="Voltar")
                            ]
                        ],resize_keyboard=True
                    )
                    bot.sendMessage(chatID, txtHelp.read(), 'Markdown', reply_markup=keyboard)
                    txtHelp.close()

            elif (msg == '+ Sobre Fatec'):
                    txtHelp = open('SobreFatecSjc/Textos/sobreFatec.md','r')
                    bot.sendMessage(chatID, txtHelp.read(), 'Markdown')
                    txtHelp.close()
                    bot.sendContact(chatID, "551239054979", "FatecSJC", "01")
                    bot.sendContact(chatID, "551239052423", "FatecSJC", "02")
                    bot.sendContact(chatID, "551239054699", "FatecSJC", "03")

            elif (msg == 'Regulamento Interno'):
                    bot.sendMessage(chatID, "Enviando regulamento...")
                    doc = open ("RegulamentoInterno/regulamentoGeral.pdf",'rb')
                    bot.sendDocument(chatID, doc)
                    doc.close()

#### Projetos
            elif (msg== 'Projetos'):
                    bot.sendMessage(
                        chatID,
                        "Projetos atuais da Fatec Profº Jessen Vidal",
                        reply_markup=InlineKeyboardMarkup(
                            inline_keyboard=[
                                [InlineKeyboardButton(text="Agencia Inova CPS", callback_data='Agencia Inova')],
                                [InlineKeyboardButton(text="BAJA", callback_data='BAJA')],
                                [InlineKeyboardButton(text="Relações Internacionais", callback_data='Relações Internacionais')],
                                [InlineKeyboardButton(text="Cimatech", callback_data='Cimatech')],
                                [InlineKeyboardButton(text="Escola de Inovadores", callback_data='Escola de Inovadores')],
                                [InlineKeyboardButton(text="Escritório de Carreiras", callback_data='Escritório de Carreiras')],
                                [InlineKeyboardButton(text="Fatec Business Mentoring", callback_data='FBM')],
                                [InlineKeyboardButton(text="Projeto IBM HACKaTruck", callback_data='Projeto IBM HACKaTruck')],
                                [InlineKeyboardButton(text="Vestec", callback_data='Vestec')],
                                [InlineKeyboardButton(text="Megazord", callback_data='Megazord')],
                            ]
                        )
                    )

            elif (msg=="Agencia Inova"):
                    bot.sendMessage(chatID, "Aguarde um instante...")

                    txt = open('SobreFatecSjc/Textos/Projetos/agenciaInovaPaulaSouza.md','r')
                    img = open("SobreFatecSjc/imgProjetosInternos/imgAgenciaInovaPaulaSouza.jpg","rb")
                    bot.sendPhoto(chatID, img, txt.read())
                    txt.close()
                    img.close()

                    txtPP = open('SobreFatecSjc/Textos/Projetos/agenciaInovaPaulaSouzaPP.md','r')
                    bot.sendMessage(chatID,txtPP.read(),'Markdown')
                    txtPP.close()

                    bot.sendContact(chatID, "5512987456578", "Renato", "Galvão")

            elif (msg=="BAJA"):
                    bot.sendMessage(chatID, "Aguarde um instante...")

                    txt = open('SobreFatecSjc/Textos/Projetos/baja.md','r')
                    img = open("SobreFatecSjc/imgProjetosInternos/imgBajaSaeBrasil.png","rb")
                    bot.sendPhoto(chatID, img, txt.read())
                    txt.close()
                    img.close()

                    txtPP = open('SobreFatecSjc/Textos/Projetos/bajaPP.md','r')
                    bot.sendMessage(chatID,txtPP.read(),'Markdown')
                    txtPP.close()

                    bot.sendMessage(chatID, "Aguarde um momento, estamos carregando a foto do projeto...")

                    imgPP = open("SobreFatecSjc/imgProjetosInternos/imgBaja01.jpg","rb")
                    bot.sendPhoto(chatID, imgPP, "Foto do projeto em 2015")
                    imgPP.close()

            elif (msg=="Relações Internacionais"):
                    bot.sendMessage(chatID, "Aguarde um instante...")

                    txt = open('SobreFatecSjc/Textos/Projetos/nucleoDeRelacoesInternacionais.md','r')
                    img = open("SobreFatecSjc/imgProjetosInternos/imgNucleoDeRelacoesInternacionais.jpg","rb")
                    bot.sendPhoto(chatID, img, txt.read())
                    txt.close()
                    img.close()

                    txt = open('SobreFatecSjc/Textos/Projetos/nucleoDeRelacoesInternacionaisPP.md','r')
                    bot.sendMessage(chatID,txt.read(),'Markdown')
                    txt.close()

            elif (msg=="Cimatech"):
                    bot.sendMessage(chatID, "Aguarde um instante...")

                    txt = open('SobreFatecSjc/Textos/Projetos/cimatech.md','r')
                    img = open("SobreFatecSjc/imgProjetosInternos/imgCimatech.png","rb")
                    bot.sendPhoto(chatID, img, txt.read())
                    txt.close()
                    img.close()

                    txtPP = open('SobreFatecSjc/Textos/Projetos/cimatechPP.md','r')
                    bot.sendMessage(chatID,txtPP.read(),'Markdown')
                    txtPP.close()

            elif (msg=="Escola de Inovadores"):
                    bot.sendMessage(chatID, "Aguarde um instante...")
                    bot.sendSticker(chatID, "CAADAQADNQYAAjN-VQp9fRoNVhK8sQI")

                    txt = open('SobreFatecSjc/Textos/Projetos/escolaDeInovadores.md','r')
                    img = open("SobreFatecSjc/imgProjetosInternos/imgEscoladeInovadores.png","rb")
                    bot.sendPhoto(chatID, img, txt.read())
                    txt.close()
                    img.close()

                    txt = open('SobreFatecSjc/Textos/Projetos/escolaDeInovadoresPP.md','r')
                    bot.sendMessage(chatID,txt.read(),'Markdown')
                    txt.close()

            elif (msg=="Escritório de Carreiras"):
                    bot.sendMessage(chatID, "Aguarde um instante...")

                    txt = open('SobreFatecSjc/Textos/Projetos/escritorioDeCarreiras.md','r')
                    img = open("SobreFatecSjc/imgProjetosInternos/imgEscritorioDeCarreiras.png","rb")
                    bot.sendPhoto(chatID, img, txt.read())
                    txt.close()
                    img.close()

                    txt = open('SobreFatecSjc/Textos/Projetos/escritorioDeCarreirasPP.md','r')
                    bot.sendMessage(chatID,txt.read(),'Markdown')
                    txt.close()

            elif (msg=="FBM"):
                    bot.sendMessage(chatID, "Aguarde um instante...")

                    txt = open('SobreFatecSjc/Textos/Projetos/fbm.md','r')
                    img = open("SobreFatecSjc/imgProjetosInternos/imgFBM.png","rb")
                    bot.sendPhoto(chatID, img, txt.read())
                    txt.close()
                    img.close()

                    txt = open('SobreFatecSjc/Textos/Projetos/fbmPP.md','r')
                    bot.sendMessage(chatID,txt.read(),'Markdown')
                    txt.close()

                    bot.sendContact(chatID, "551239054979", "ContatoFBM", "01")
                    bot.sendContact(chatID, "551239052423", "ContatoFBM", "02")
                    bot.sendContact(chatID, "551239054699", "ContatoFBM", "03")


            elif (msg=="Projeto IBM HACKaTruck"):
                    bot.sendMessage(chatID, "Aguarde um instante...")

                    txt = open('SobreFatecSjc/Textos/Projetos/projetoIBMHACKaTruck.md','r')
                    img = open("SobreFatecSjc/imgProjetosInternos/imgHackTruck03.jpg","rb")
                    bot.sendPhoto(chatID, img, txt.read())
                    txt.close()
                    img.close()

                    txt = open('SobreFatecSjc/Textos/Projetos/projetoIBMHACKaTruckPP.md','r')
                    bot.sendMessage(chatID,txt.read(),'Markdown')
                    txt.close()

                    txt = open('SobreFatecSjc/Textos/Projetos/projetoIBMHACKaTruckLink.md','r')
                    bot.sendMessage(chatID,txt.read(),'Markdown')
                    txt.close()

                    txt = open('SobreFatecSjc/Textos/Projetos/projetoIBMHACKaTruckYT.md','r')
                    bot.sendMessage(chatID,txt.read(),'Markdown')
                    txt.close()

            elif (msg=="Vestec"):
                    bot.sendMessage(chatID, "Aguarde um instante...")

                    txt = open('SobreFatecSjc/Textos/Projetos/vestec.md','r')
                    img = open("SobreFatecSjc/imgProjetosInternos/imgVestec.png","rb")
                    bot.sendPhoto(chatID, img, txt.read())
                    txt.close()
                    img.close()

                    txt = open('SobreFatecSjc/Textos/Projetos/vestecPP.md','r')
                    bot.sendMessage(chatID,txt.read(),'Markdown')
                    txt.close()

            elif (msg=="Megazord"):
                    bot.sendMessage(chatID, "Aguarde um instante...")

                    txt = open('SobreFatecSjc/Textos/Projetos/megazord.md','r')
                    img = open("SobreFatecSjc/imgProjetosInternos/imgMegazord.png","rb")
                    bot.sendPhoto(chatID, img, txt.read())
                    img.close()
                    txt.close()

                    txt = open('SobreFatecSjc/Textos/Projetos/megazordPP.md','r')
                    bot.sendMessage(chatID,txt.read(),'Markdown')
                    txt.close()

                    img = open("SobreFatecSjc/imgProjetosInternos/imgMegazord01.jpg","rb")
                    bot.sendPhoto(chatID, img)
                    img.close()

                    img = open("SobreFatecSjc/imgProjetosInternos/imgMegazord02.jpg","rb")
                    bot.sendPhoto(chatID, img)
                    img.close()

                    bot.sendMessage(chatID,"https://www.youtube.com/user/MegazordAerodesign")
                    bot.sendMessage(chatID,"https://www.facebook.com/megazordaerodesign?hc_ref=ARTOOGrhjaoVa14Y36pTJtl6rInOIgA928tr-YknVHuiL2RRHBKKQwji2kGgggUb89o")
                    bot.sendMessage(chatID,"Para mais informações entre em contato com: Carlos ou Murilo")

                    bot.sendContact(chatID, "5512988281517", "Carlos", "Megazord")
                    bot.sendContact(chatID, "5512997527525", "Murilo", "Megazord")

##########################################################################################################

            elif (msg == 'Voltar'):
                    inicio(chatID, bot)
예제 #30
0
def handle(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    print(content_type, chat_type, chat_id)  # debug msg received

    if content_type == 'text':
        response = bot.getUpdates()
        print(response)  # debug id response
        # bot.sendMessage(chat_id, msg['text'])
        msg_received = msg['text'].lower()
        print(msg['text'])  # debug input
        print(msg_received)  # debug lowered input
        if msg_received == '/start':
            print("bot started")
            bot.sendMessage(
                chat_id,
                "Hi! I'm a bot that tells you your course schedule and plan your meetings! Feel free to ask me stuff :)"
            )
            bot.sendMessage(
                chat_id,
                "If you want to know your course schedule, type in Course. If you want to plan your meetings, type in Meetings. If you want to know anything about me, just type in whatever you want and hope I understand :)"
            )
        elif msg_received == 'hi':
            bot.sendMessage(
                chat_id, reply_dict[msg_received] + ', ' +
                response[0]['message']['from']['first_name'] + '!')
        elif msg_received == 'hi bot':
            bot.sendMessage(
                chat_id, reply_dict[msg_received] + ', ' +
                response[0]['message']['from']['first_name'] + '!')
        elif msg_received == 'hello':
            bot.sendMessage(
                chat_id, reply_dict[msg_received] + ', ' +
                response[0]['message']['from']['first_name'] + '!')
        elif msg_received == 'good morning':
            bot.sendMessage(
                chat_id, reply_dict[msg_received] + ', ' +
                response[0]['message']['from']['first_name'] + '!')
        elif msg_received == 'good afternoon':
            bot.sendMessage(
                chat_id, reply_dict[msg_received] + ', ' +
                response[0]['message']['from']['first_name'] + '!')
        elif msg_received == 'good evening':
            bot.sendMessage(
                chat_id, reply_dict[msg_received] + ', ' +
                response[0]['message']['from']['first_name'] + '!')
        elif msg_received == 'good night':
            bot.sendMessage(
                chat_id, reply_dict[msg_received] + ', ' +
                response[0]['message']['from']['first_name'] + '!')
        elif msg_received == 'good day':
            bot.sendMessage(
                chat_id, reply_dict[msg_received] + ', ' +
                response[0]['message']['from']['first_name'] + '!')
        elif msg_received == 'hey':
            bot.sendMessage(
                chat_id, reply_dict[msg_received] + ', ' +
                response[0]['message']['from']['first_name'] + '!')
        elif msg_received.find('rude') != -1:
            bot.sendMessage(chat_id, reply_dict['rude'])
        elif msg_received == 'meetings':
            bot.sendMessage(chat_id, reply_dict[msg_received])
            inlines_keyboard = [[]]
            for i in range(0, len(days)):
                print(days[i])
                inlines_keyboard.append([
                    InlineKeyboardButton(text=days[i], callback_data=days[i])
                ])
            keyboard = InlineKeyboardMarkup(inline_keyboard=inlines_keyboard)
            bot.sendMessage(chat_id, 'Choose a day!', reply_markup=keyboard)
        elif msg_received in reply_dict:
            print(reply_dict[msg_received])  # debug reply
            if second_reply[msg_received] == 1:
                bot.sendMessage(chat_id, reply_dict[msg_received])
        else:
            bot.sendMessage(
                chat_id,
                "Sorry, I don't know what to reply to such conversation yet. :'( "
            )