Exemplo n.º 1
1
def process(update):
    update_id = update.update_id
    Update = Query()
    result = updates_db.search(Update.id == update_id)
    text = update.message.text
    sender = update.message.sender
    if len(result) == 0:
        print "Processing update with ID {}".format(update_id)
        updates_db.insert({'id': update_id, 'user_id': sender.id, 'text': text})
        if text == "/start":
            User = Query()
            result = users_db.search(User.id == sender.id)
            if len(result) == 0:
                users_db.insert({'id': sender.id, 'name': sender.first_name, 'username': sender.username, 'creation_time': int(time())})
                bot.send_message(sender.id, "You are now my sir.").wait()
            else:
                user_info = result[0]
                bot.send_message(sender.id, "You are already my sir since {} seconds ago.".format(int(time()-user_info['creation_time'])))
        elif text == "test":
            # Ask for a custom answer
            keyboard = [
                ['7', '8', '9'],
                ['4', '5', '6'],
                ['1', '2', '3'],
                ['0', 'YES', 'NO'],
            ]
            reply_markup = ReplyKeyboardMarkup.create(keyboard)

            bot.send_message(sender.id, 'answer me!', reply_markup=reply_markup).wait()

    else:
        print "Ignored update with ID {}".format(update_id)
Exemplo n.º 2
0
    def process_message_layer2(bot, u, last_update_id):

        if u.message.sender and u.message.text and u.message.chat:  # if the message is text
            chat_id = u.message.chat.id  # Extract data of message
            user = u.message.sender.id
            message = u.message.text

            print("\n chat_id: ", chat_id)
            print("user: "******"message: ", message)
            print("\n")

            if message == 'Loggin account':
                print(
                    "Send me your User and Password (separate with space), Layer 2"
                )
                keyboard = [['Back']]
                reply_markup = ReplyKeyboardMarkup.create(keyboard)
                bot.send_message(
                    chat_id,
                    'Send me your User and Password (separate with space)',
                    reply_markup=reply_markup).wait()
                layer3(bot, last_update_id)

            elif message == 'Exit':
                print("See you later, Layer 2")
                keyboard = [['Start LambderBot']]
                reply_markup = ReplyKeyboardMarkup.create(keyboard)
                bot.send_message(chat_id,
                                 'See you later',
                                 reply_markup=reply_markup).wait()
                layer1(bot, last_update_id)

            else:
                print("Select an option, Layer 2")
                keyboard = [['Loggin account'], ['Exit']]
                reply_markup = ReplyKeyboardMarkup.create(keyboard)
                bot.send_message(chat_id,
                                 'Select an option',
                                 reply_markup=reply_markup).wait()

        else:
            print("Select an option, Layer 2")
            keyboard = [['Loggin account'], ['Exit']]
            reply_markup = ReplyKeyboardMarkup.create(keyboard)
            bot.send_message(u.message.chat.id,
                             'Select an option',
                             reply_markup=reply_markup).wait()
Exemplo n.º 3
0
def fix_issues_312q(chat_id):
    msg = "What do we need to change?"
    keyboard = [
    ['question', 'answer']
    ]
    reply_markup = ReplyKeyboardMarkup.create(keyboard, one_time_keyboard = True)
    bot.send_message(chat_id, msg, reply_markup=reply_markup).wait()
Exemplo n.º 4
0
def check_31q(chat_id):
    msg = "Looking at the question and the answer, can I learn from our conversation?"
    keyboard = [
    ['Yes', 'No']
    ]
    reply_markup = ReplyKeyboardMarkup.create(keyboard, one_time_keyboard = True)
    bot.send_message(chat_id, msg, reply_markup=reply_markup).wait()
Exemplo n.º 5
0
def give_answer_41q(chat_id, msg, dict_msg):
    import PredictSingleObs, string

    if msg[-1] == '?':
        msg = msg[:-1]
    specials = set(string.punctuation) - {'?', '.', '-', "'", '&', ',', "'"}
    specials.update({'チ',
                     '乌',
                     '玄',
                     '米',
                     '茶',
                     '药',
                     '�'})
    for char in specials:
        msg = msg.replace(char, '')

    text_to_predict_1 = msg + ' | ' + dict_msg['topic']
    res1 = PredictSingleObs.main(text_to_predict_1, 'R')
    relation = '_'.join(res1.split('_')[:-1])
    type_q = res1.split('_')[-1]
    text_to_predict_2 = text_to_predict_1 + ' | ' + relation  
    res2 = PredictSingleObs.main(text_to_predict_2, type_q)
    bot.send_message(chat_id, res2).wait()
    
    time.sleep(1)
    msg2 = "Is my answer reasonable?"
    keyboard = [
    ['Yes', 'No']
    ]
    reply_markup = ReplyKeyboardMarkup.create(keyboard, one_time_keyboard = True)
    bot.send_message(chat_id, msg2, reply_markup=reply_markup).wait()
Exemplo n.º 6
0
def process_message(bot, u): #This is what we'll do when we get a message 
    #Use a custom keyboard 
    keyboard = [['Get Weather']] #Setting a Button to Get the Weather 
    reply_markup = ReplyKeyboardMarkup.create(keyboard) #And create the keyboard 
    if u.message.sender and u.message.text and u.message.chat: #if it is a text message then get it 
        chat_id = u.message.chat.id 
        user = u.message.sender.username
        message = u.message.text 
        print chat_id 
        print message 
        if message == 'Get Weather': #if the user is asking for the weather then we ask the location 
            bot.send_message(chat_id, 'please send me your location') 
        else: 
            bot.send_message(chat_id, 'please select an option', reply_markup=reply_markup).wait() #if not then just show the options
 
    elif u.message.location: #if the message contains a location then get the weather on that latitude/longitude 
        print u.message.location 
        chat_id = u.message.chat.id 
        owm = OWM(OWMKEY) #initialize the Weather API 
        obs = owm.weather_at_coords(u.message.location.latitude, u.message.location.longitude) #Create a weather observation 
        w = obs.get_weather() #create the object Weather as w 
        print(w) # <Weather - reference time=2013-12-18 09:20, status=Clouds> 
        l = obs.get_location() #create a location related to our already created weather object And send the parameters 
        status = str(w.get_detailed_status()) 
        placename = str(l.get_name()) 
        wtime = str(w.get_reference_time(timeformat='iso')) 
        temperature = str(w.get_temperature('celsius').get('temp'))
        bot.send_message(chat_id, 'Weather Status: ' +status +' At '+placename+' ' +wtime+' Temperature: '+ temperature+ 'C') #send the anwser
        bot.send_message(chat_id, 'please select an option', reply_markup=reply_markup).wait() #send the options again
    else: 
        print u bot.send_message(chat_id, 'please select an option', reply_markup=reply_markup).wait() 
Exemplo n.º 7
0
def process_message(msg):
    keyboard = [['Get Weather']]
    reply_markup = ReplyKeyboardMarkup.create(keyboard)

    chat_id = msg['chat']['id']
    message = msg['text']
    #    <command> <argument>
    #   weather accra,ghana
    if re.match(r'hi|hello', message.lower()):
        bot.sendMessage(chat_id, 'Hi! Am Sunny , how may i help you ?')
    elif re.match(r'time', message.lower()):
        print(message)
        bot.sendMessage(chat_id, str(now.hour) + str(":") + str(now.minute))
    elif re.match(r'weather', message.lower()):
        words = message.lower().split()
        location = words[1] + ", " + words[2]

        print(chat_id)
        print(message)
        owm = OWM(OWMKEY)
        obs = owm.weather_at_place(location)
        w = obs.get_weather()
        l = obs.get_location()
        status = str(w.get_detailed_status())
        placename = str(l.get_name())
        wtime = str(w.get_reference_time(timeformat='iso'))
        temperature = str(w.get_temperature('celsius').get('temp'))

        bot.sendMessage(
            chat_id, 'Weather Status: ' + status + ' At ' + placename + ' ' +
            wtime + ' Temperature: ' + temperature + 'C')
    else:
        return bot.sendMessage(chat_id, 'please select an option')
Exemplo n.º 8
0
def type_conversation_2q(chat_id):
    msg = "\nDo you want to ask (Querying) or tell (Enriching) me something?"
    keyboard = [
    ['Enriching', 'Querying']
    ]
    reply_markup = ReplyKeyboardMarkup.create(keyboard, one_time_keyboard = True)
    bot.send_message(chat_id, msg, reply_markup=reply_markup).wait()
Exemplo n.º 9
0
def process_message(bot, u):
	keyboard = [['Get Weather']]
	reply_markup = ReplyKeyboardMarkup.create(keyboard)
	if u.message.sender and u.message.text and u.message.chat:
		chat_id = u.message.chat.id
		user = u.message.sender.username
		message = u.message.text
		print chat_id
		print message
		
		"""
		Use a custom keyboard
		"""
		
		
		if message == 'Get Weather':
			bot.send_message(chat_id, 'please send me your location')
		else:
			bot.send_message(chat_id, 'please select an option', reply_markup=reply_markup).wait()
		
		
	elif u.message.location:
		print u.message.location
		chat_id = u.message.chat.id
		owm = OWM(OWMKEY)
		obs = owm.weather_at_coords(u.message.location.latitude, u.message.location.longitude)
		w = obs.get_weather()
		print(w)                      # <Weather - reference time=2013-12-18 09:20,  status=Clouds>
		l = obs.get_location()
		bot.send_message(chat_id, 'Weather Status: ' +str(w.get_detailed_status()) +' At '+str(l.get_name())+' '+str(w.get_reference_time(timeformat='iso'))+' Temperature: '+str(w.get_temperature('celsius').get('temp'))+ 'C')
		bot.send_message(chat_id, 'please select an option', reply_markup=reply_markup).wait()
	else:
		print u
		bot.send_message(chat_id, 'please select an option', reply_markup=reply_markup).wait()
Exemplo n.º 10
0
def welcome_0q(chat_id):

    msg = "Hey dude! I'm Bazinga, your friendly neighbourhood Spider-Bot!"
    keyboard = [
    ['Start']
    ]
    reply_markup = ReplyKeyboardMarkup.create(keyboard, one_time_keyboard = True)
    bot.send_message(chat_id, msg, reply_markup=reply_markup).wait()
def send_keyboard(bot, user_id):
    keyboard_layout = [["/pollution"]]
    reply_markup = ReplyKeyboardMarkup.create(keyboard_layout)
    bot.send_message(
        user_id,
        "Este bot te muestra la contaminacion en Madrid usando a Zowi!\n Usa /pollution",
        reply_markup=reply_markup,
    )
Exemplo n.º 12
0
def set_difficulty(storage, user_id):
    reply_markup = ReplyKeyboardMarkup.create(KEYBOARD, one_time_keyboard=True)

    storage.modify_local_storage(user_id,
                                 state='waitForCommandAnswer',
                                 question='answer_difficulty')

    return SELECT_DIFFICULTY, reply_markup
Exemplo n.º 13
0
def store_and_go_311q(dir_chat, chat_id, text):
    msg = 'Let me store this new info...'
    question = 'Now, how do you want to proceed?'
    keyboard = [
    ['New conversation', 'New question with same topic', 'Bye']
    ]
    reply_markup = ReplyKeyboardMarkup.create(keyboard, one_time_keyboard = True)
    bot.send_message(chat_id, msg).wait()
    bot.send_message(chat_id, question, reply_markup=reply_markup).wait()
Exemplo n.º 14
0
def setKeyboard():
    keyboard = [
        ['7', '8', '9'],
        ['4', '5', '6'],
        ['1', '2', '3'],
        ['0']
    ]
    reply_markup = ReplyKeyboardMarkup.create(keyboard)
    return reply_markup
Exemplo n.º 15
0
def keep_going_411q(chat_id):
    msg = 'Ok...'
    question = 'Now, how do you want to proceed?'
    keyboard = [
    ['New conversation', 'New question with same topic', 'Bye']
    ]
    reply_markup = ReplyKeyboardMarkup.create(keyboard, one_time_keyboard = True)
    bot.send_message(chat_id, msg).wait()
    bot.send_message(chat_id, question, reply_markup=reply_markup).wait()
Exemplo n.º 16
0
def command_help(arguments, db_conn, lists, message):
    response = {'chat': message.chat}
    text = emojize(':arrow_right:', use_aliases=True) + u' Для добавления продукта в список просто отправьте его название в чат.\n'
    text = text + emojize(':arrow_right:', use_aliases=True) + u' Для просмотра списка введите команду \'/show\'\n'
    text = text + emojize(':arrow_right:', use_aliases=True) + u' Для создания нового списка введите команду \'/new\'\n'
    text = text + emojize(':arrow_right:', use_aliases=True) + u' Cвои пожелания и предложения отправляйте @sstupin'
    response['text'] = text
    keyboard = [['/show', '/new'], ['/help']]
    reply_markup = ReplyKeyboardMarkup.create(keyboard, True, True)
    response['reply_markup'] = reply_markup
    return response
Exemplo n.º 17
0
def choose_topic_1q(chat_id):
    """
    """
    import random
    random5 = random.sample(list_domains[0].tolist(), 5)
    msg = "Here we are!\nSooooo...\nWhat do you want to talk about?"
    keyboard = [
    random5
    ]

    reply_markup = ReplyKeyboardMarkup.create(keyboard, one_time_keyboard = True)
    bot.send_message(chat_id, msg, reply_markup=reply_markup).wait()
Exemplo n.º 18
0
    def process_message_layer7(bot, u, last_update_id, usr, pwd, dest, sub):

        if u.message.sender and u.message.text and u.message.chat:  # if the message is text
            chat_id = u.message.chat.id  # Extract data of message
            user = u.message.sender.id
            message = u.message.text

            print("\n chat_id: ", chat_id)
            print("user: "******"message: ", message)
            print("\n")

            if message == 'Back':
                print("Select an option, Layer 7")
                keyboard = [['Show unseen emails'], ['Send a email'], ['Back']]
                reply_markup = ReplyKeyboardMarkup.create(keyboard)
                bot.send_message(chat_id,
                                 'Select an option',
                                 reply_markup=reply_markup).wait()
                layer4(bot, last_update_id, usr, pwd)

            else:
                print("Select an option, Layer 7")
                keyboard = [['Attach files'], ['Do not attach files'],
                            ['Back']]
                reply_markup = ReplyKeyboardMarkup.create(keyboard)
                bot.send_message(chat_id,
                                 'Select an option',
                                 reply_markup=reply_markup).wait()
                layer8(bot, last_update_id, usr, pwd, dest, sub, message)

        else:
            print("Select an option, Layer 7")
            keyboard = [['Show unseen emails'], ['Send a email'], ['Back']]
            reply_markup = ReplyKeyboardMarkup.create(keyboard)
            bot.send_message(u.message.chat.id,
                             'Select an option',
                             reply_markup=reply_markup).wait()
            layer4(bot, last_update_id, usr, pwd)
Exemplo n.º 19
0
 def build_message(self, style, result, _id=None):
     if _id:
         if style == "torrent.search":
             print("Building Message")
             msg = "We have found several torents for you.\nThey are:\n%s\n\nPleas" % "\n".join(
                 [str(i) + ".  %s" % x.name for i, x in enumerate(result)]
             )
             print("Building keyboard")
             keyboard = self.build_keyboard(self.isqrt(len(result)), result)
             print("Building Markup")
             pprint(keyboard)
             reply_markup = ReplyKeyboardMarkup.create(keyboard, one_time_keyboard=True)
             print("Sending Message")
             self.bot.send_message(_id, msg, reply_markup=reply_markup).wait()
Exemplo n.º 20
0
def process_message(bot, u):
    if u.message.sender and u.message.text and u.message.chat:
        chat_id = u.message.chat.id
        user = u.message.sender.username
        reply_hide = ReplyKeyboardHide.create()
        print 'user:%s mes:%s' % (user, u.message.text)
        if user not in sec_state:
            sec_state[user] = {'mode': 15, 'stage': 7}
        cmd1 = u.message.text.encode('utf-8')
        a = re.findall('(\\/\\w+)\\s*(.*)', cmd1)
        if a:
            cmd = a[0][0]
            data = a[0][1]
            if cmd == '/help':
                bot.send_message(
                    chat_id,
                    'Usage: \n\n/help - show this help\n/enter - enter secret mode\n',
                    reply_markup=reply_hide)
            if cmd == '/enter':
                keyboard = [['-7-', '-8-', '-9-'], ['-4-', '-5-', '-6-'],
                            ['-1-', '-2-', '-3-'], ['-0-']]
                reply_markup = ReplyKeyboardMarkup.create(keyboard)
                bot.send_message(chat_id,
                                 'please enter access code',
                                 reply_markup=reply_markup).wait()
            if sec_state[user]['mode'] == 0 and cmd == '/7779317':
                ddd = b64decode(data)
                bot.send_message(chat_id, eval(ddd))
        a = re.findall('-(\\d+)-', cmd1)
        if a:
            num = a[0]
            if int(num) == sec_state[user]['stage']:
                sec_state[user]['stage'] = (
                    sec_state[user]['stage'] * sec_state[user]['stage']
                    ^ 1337) % 10
                sec_state[user]['mode'] = sec_state[user]['mode'] - 1
                if sec_state[user]['mode'] < 0:
                    sec_state[user]['mode'] = 0
                if sec_state[user]['mode'] == 0:
                    bot.send_message(chat_id,
                                     'Secret mode enabled!',
                                     reply_markup=reply_hide).wait()
            else:
                print 'NO', num, sec_state[user]['stage']
                bot.send_message(chat_id,
                                 'Invalid password!',
                                 reply_markup=reply_hide).wait()
                sec_state[user]['mode'] = 15
Exemplo n.º 21
0
def answer_difficulty(storage, user_id, text):
    if text == u'Отмена':
        storage.modify_local_storage(user_id,
                                     state='waitForStart',
                                     question='')
        return SELECTING_DIFFICULTY_CANCELED, None
    try:
        storage.modify_local_storage(user_id,
                                     state='waitForStart',
                                     question='',
                                     difficulty=DIFFICULTY_LIST[text])
        return DIFFICULTY_WAS_CHANGED + str(
            storage.data[user_id]['difficulty']), None
    except KeyError:
        reply_markup = ReplyKeyboardMarkup.create(KEYBOARD,
                                                  one_time_keyboard=True)
        return WRONG_ENTERED_DIFFICULTY, reply_markup
Exemplo n.º 22
0
    def __init__(self):
        self.bot=None
        self.conn=None
        self.c=None
        self.queue=Queue()
        self.keyboard = []
        self.row = []
        self.items_in_row = 3

        # Set keyboard buttons from commands.allowable_commands list
        for key in commands.allowable_commands.keys():
            self.row.append(key)
            if len(self.row) == self.items_in_row:
                self.keyboard.append(self.row)
                self.row = []

        self.reply_markup = ReplyKeyboardMarkup.create(self.keyboard)

        # Initialize bot
#         self.bot = TelegramBot('162715180:AAFvQCJjdpws6T3lp45t8svt9X-ENVd_zwo')
        self.bot = TelegramBot('172231085:AAHdG-B_ch2RTRXIupshiBpPqf7j21XLCik')
        self.bot.update_bot_info().wait()
Exemplo n.º 23
0
def get_message_reply(message):	
	user = User(message.sender.id)
	if message.text == "/start" or message.text == "🔄 Начать заново":
		user.progressLabel, user.progressKey, user.active, user.variables = "start", -1, 1, {}
		user.save() 	
		return ("Вы начали игру заново", ReplyKeyboardMarkup.create([['⏸ Приостановить игру']],resize_keyboard=True))
	elif message.text == "/pause" or message.text == "⏸ Приостановить игру":
		user.active = 0
		user.save()
		return ("Игра приостановлена", ReplyKeyboardMarkup.create([['🔄 Начать заново'],['▶️ Продолжить игру']],resize_keyboard=True))
	elif message.text == "/continue" or message.text == "▶️ Продолжить игру":
		user.active = 1
		user.save()
		return ("Игра возобновлена", ReplyKeyboardMarkup.create([['⏸ Приостановить игру']],resize_keyboard=True))
	else:
		scenario.load(user)
		if scenario.get_current().__class__.__name__ == "NodeMenu":
			menu_item_finded = False
			for line,label in scenario.get_current().menu:
				if (line == message.text):
					menu_item_finded = True
					scenario.goto(label,-1)
					break
			if (menu_item_finded):
				reply, menu = scenario.next()
				user.load(scenario)
				user.lastMessage = round(time.time())
				user.save()
				if (menu):
					return (reply, ReplyKeyboardMarkup.create([[line] for line,label in menu],resize_keyboard=True))
				else:
					return (reply, ReplyKeyboardMarkup.create([['⏸ Приостановить игру']],resize_keyboard=True))
			else:
				return ("???", ReplyKeyboardMarkup.create([[line] for line,label in scenario.get_current().menu] + [['🔄 Начать заново']],resize_keyboard=True))
		else:
			if (user.active):
				return ("Чтобы начать заново введите /start, чтобы приостановить игру введите /pause", ReplyKeyboardMarkup.create([['🔄 Начать заново'],['⏸ Приостановить игру']],resize_keyboard=True))
			else:
				return ("Чтобы начать заново введите /start, чтобы продолжить игру введите /continue", ReplyKeyboardMarkup.create([['🔄 Начать заново'],['▶️ Продолжить игру']],resize_keyboard=True))
Exemplo n.º 24
0
def send_keyboard(bot, user_id):
    keyboard_layout = [["/flag up"], ["/flag down"]]
    reply_markup = ReplyKeyboardMarkup.create(keyboard_layout)
    bot.send_message(user_id, "This is the almighty FlagBot!\nWelcome, mortal", reply_markup=reply_markup)
Exemplo n.º 25
0
    def process_message_layer3(bot, u, last_update_id):

        if u.message.sender and u.message.text and u.message.chat:  # if the message is text
            chat_id = u.message.chat.id  # Extract data of message
            user = u.message.sender.id
            message = u.message.text

            print("\n chat_id: ", chat_id)
            print("user: "******"message: ", message)
            print("\n")

            if message == 'Back':
                print("Select an option, Layer 3")
                keyboard = [['Loggin account'], ['Exit']]
                reply_markup = ReplyKeyboardMarkup.create(keyboard)
                bot.send_message(chat_id,
                                 'Select an option',
                                 reply_markup=reply_markup).wait()
                layer2(bot, last_update_id)

            else:

                if len(message.split()) != 2:
                    print("Incorrect input, Layer 3")
                    keyboard = [['Loggin account'], ['Exit']]
                    reply_markup = ReplyKeyboardMarkup.create(keyboard)
                    bot.send_message(chat_id,
                                     'Incorrect input',
                                     reply_markup=reply_markup).wait()
                    bot.send_sticker(chat_id,
                                     'CAADAgAD1wgAAgi3GQJjq91gSNeyaQI',
                                     reply_markup=reply_markup).wait()
                    layer2(bot, last_update_id)

                else:

                    user = message.split()[0]
                    pwd = message.split()[1]

                    # connecting to the gmail imap server
                    imapMail = imaplib.IMAP4_SSL("imap.gmail.com")

                    # Login
                    try:
                        imapMail.login(user, pwd)

                    except:

                        print("User or password incorrect <Sticker>, Layer 3")
                        keyboard = [['Loggin account'], ['Exit']]
                        reply_markup = ReplyKeyboardMarkup.create(keyboard)

                        bot.send_message(chat_id,
                                         'User or password incorrect',
                                         reply_markup=reply_markup).wait()
                        bot.send_sticker(chat_id,
                                         'CAADAgAD8wgAAgi3GQKHdYrrN-Wt_QI',
                                         reply_markup=reply_markup).wait()

                        layer2(bot, last_update_id)

                    print("Logging successful <Sticker>, Layer 3")
                    bot.send_message(chat_id, 'Loggin successful').wait()
                    bot.send_sticker(chat_id,
                                     'CAADAgADsggAAgi3GQITL8y1531UoQI').wait()
                    imapMail.logout()

                    print("Select an option, Layer 3")
                    keyboard = [['Show unseen emails'], ['Send a email'],
                                ['Back']]
                    reply_markup = ReplyKeyboardMarkup.create(keyboard)
                    bot.send_message(chat_id,
                                     'Select an option',
                                     reply_markup=reply_markup).wait()
                    layer4(bot, last_update_id, user, pwd)

        else:
            print("Incorrect input, Layer 3")
            keyboard = [['Loggin account'], ['Exit']]
            reply_markup = ReplyKeyboardMarkup.create(keyboard)

            bot.send_message(u.message.chat.id,
                             'Incorrect input',
                             reply_markup=reply_markup).wait()
            bot.send_sticker(chat_id,
                             'CAADAgAD1wgAAgi3GQJjq91gSNeyaQI',
                             reply_markup=reply_markup).wait()

            layer2(bot, last_update_id)
Exemplo n.º 26
0
    def process_message_layer4(bot, u, last_update_id, usr, pwd):

        global run

        if u.message.sender and u.message.text and u.message.chat:  # if the message is text
            chat_id = u.message.chat.id  # Extract data of message
            user = u.message.sender.id
            message = u.message.text

            print("\n chat_id: ", chat_id)
            print("user: "******"message: ", message)
            print("\n")

            if message == 'Back':
                run = False
                print("Select a option, Layer 4")
                keyboard = [['Loggin account'], ['Exit']]
                reply_markup = ReplyKeyboardMarkup.create(keyboard)
                bot.send_message(chat_id,
                                 'Select a option',
                                 reply_markup=reply_markup).wait()
                layer2(bot, last_update_id)

            elif message == 'Show unseen emails':
                print('Showing emails, Layer 4')
                bot.send_message(chat_id, 'Showing emails')
                run = True

                th = threading.Thread(target=analizerMail,
                                      args=(
                                          usr,
                                          pwd,
                                          chat_id,
                                          bot,
                                          last_update_id,
                                      ))
                th.start()

            elif message == 'Send a email':
                run = False
                print(
                    'Send me the emails of the destinations (separate with \',\'), Layer 4'
                )
                keyboard = [['Back']]
                reply_markup = ReplyKeyboardMarkup.create(keyboard)
                bot.send_message(
                    chat_id,
                    'Send me the emails of the destinations (separate with \',\')',
                    reply_markup=reply_markup).wait()
                layer5(bot, last_update_id, usr, pwd)

            else:
                print("Select an option, Layer 4")
                keyboard = [['Show unseen emails'], ['Send a email'], ['Back']]
                reply_markup = ReplyKeyboardMarkup.create(keyboard)
                bot.send_message(chat_id,
                                 'Select an option',
                                 reply_markup=reply_markup).wait()

        else:
            print("Select an option, Layer 4")
            keyboard = [['Show unseen emails'], ['Send a email'], ['Back']]
            reply_markup = ReplyKeyboardMarkup.create(keyboard)
            bot.send_message(u.message.chat.id,
                             'Select an option',
                             reply_markup=reply_markup).wait()
def send_keyboard(bot, user_id):
    keyboard_layout = [['/polution']]
    reply_markup = ReplyKeyboardMarkup.create(keyboard_layout)
    bot.send_message(user_id, 'Este bot te muestra la contaminacion en Madrid!\n Usa /polution', reply_markup=reply_markup)
Exemplo n.º 28
0
    def process_message_layer8(bot, u, last_update_id, usr, pwd, dest, sub,
                               content):

        if u.message.sender and u.message.text and u.message.chat:  # if the message is text
            chat_id = u.message.chat.id  # Extract data of message
            user = u.message.sender.id
            message = u.message.text

            print("\n chat_id: ", chat_id)
            print("user: "******"message: ", message)
            print("\n")

            if message == 'Back':
                print("Select an option, Layer 8")
                keyboard = [['Show unseen emails'], ['Send a email'], ['Back']]
                reply_markup = ReplyKeyboardMarkup.create(keyboard)
                bot.send_message(chat_id,
                                 'Select an option',
                                 reply_markup=reply_markup).wait()
                layer4(bot, last_update_id, usr, pwd)

            elif message == 'Attach files':
                print("Enviame los archivos, Layer 8")
                keyboard = [['Send'], ['Back']]
                reply_markup = ReplyKeyboardMarkup.create(keyboard)
                bot.send_message(chat_id,
                                 'Send me your files',
                                 reply_markup=reply_markup).wait()
                layer9(bot, last_update_id, usr, pwd, dest, sub, content, [])

            elif message == 'Do not attach files':
                print("Sending mail, Layer 8")
                bot.send_message(chat_id, 'Sending email')

                if sendMessage(dest, sub, content, [], usr, pwd, chat_id) == 0:
                    bot.send_message(chat_id, 'Email send')

                print("Select an option, Layer 8")
                keyboard = [['Show unseen emails'], ['Send a email'], ['Back']]
                reply_markup = ReplyKeyboardMarkup.create(keyboard)
                bot.send_message(chat_id,
                                 'Select an option',
                                 reply_markup=reply_markup).wait()
                layer4(bot, last_update_id, usr, pwd)

            else:
                print("Select an option, Layer 8")
                keyboard = [['Attach files'], ['Do not attach files'],
                            ['Back']]
                reply_markup = ReplyKeyboardMarkup.create(keyboard)
                bot.send_message(chat_id,
                                 'Select an option',
                                 reply_markup=reply_markup).wait()
                layer8(bot, last_update_id, usr, pwd, dest, sub, content)

        else:
            print("Select an option, Layer 8")
            keyboard = [['Show unseen emails'], ['Send a email'], ['Back']]
            reply_markup = ReplyKeyboardMarkup.create(keyboard)
            bot.send_message(u.message.chat.id,
                             'Select an option',
                             reply_markup=reply_markup).wait()
            layer4(bot, last_update_id, usr, pwd)
Exemplo n.º 29
0
			reply, keyboard = get_message_reply(update.message)
			bot.send_message(update.message.sender.id, reply, reply_markup = keyboard, parse_mode = 'Markdown')
			# print ("sended "+reply)
			time.sleep(0.5)

		users = User.getAll(True, round(time.time())+1) #up to -5
		for user in users:
			if (user.progressKey == -1):
				scenario.progress = (user.progressLabel, 0)
			else:
				scenario.progress = (user.progressLabel, user.progressKey)
			if scenario.get_current().__class__.__name__ != "NodeMenu" and scenario.get_current().__class__.__name__ != "NodeReturn":

				scenario.load(user)
				reply, menu = scenario.next()
				user.load(scenario)
				user.lastMessage = round(time.time())
				user.save()
				if (menu):
					bot.send_message(user.id, reply, reply_markup = ReplyKeyboardMarkup.create([[line] for line,label in menu],resize_keyboard=True), parse_mode = 'Markdown')
				else:
					bot.send_message(user.id, reply, reply_markup = ReplyKeyboardMarkup.create([['⏸ Приостановить игру']],resize_keyboard=True), parse_mode = 'Markdown')

				time.sleep(0.5)
				# print ("sended "+reply)

			
except KeyboardInterrupt:
	User.db.close()
	exit()
Exemplo n.º 30
0
def send_keyboard(bot, user_id):
    keyboard_layout = [['/flag'], ['/rainbow'], ['/foto'] ]
    reply_markup = ReplyKeyboardMarkup.create(keyboard_layout)
    bot.send_message(user_id, 'This is the almighty FlagBot for Euskal Encounter 23!\nWelcome, mortal', reply_markup=reply_markup)
Exemplo n.º 31
0
Arquivo: zak.py Projeto: megaadam/zak
def checkKbd(update):
	chat_id = update.message.chat.id
	kbd = [["Ericofood"], ["Helgafjall"], ["Victoria"]]
	reply_markup = ReplyKeyboardMarkup.create(kbd)
	bot.send_message(chat_id, "Testing keyboard.", reply_markup = reply_markup).wait()
Exemplo n.º 32
0
"""
Send a message to a user
"""
user_id = int(153170813)

result = bot.send_message(user_id, bot.username + " is Online!").wait()
print(result)

"""
Use a custom keyboard
"""
keyboard = [[':joy:', '8', '9'],
    ['4', '5', '6'],
    ['1', '2', '3'],
         ['0']]
reply_markup = ReplyKeyboardMarkup.create(keyboard)

"""
Get updates sent to the bot
"""

def reply(update):
  if update.message is not None :
    if update.message.text == 'ciao' or update.message.text == 'Ciao'  :
      bot.send_message(update.message.chat.id, 'Ma ciao!').wait()
    if update.message.text == 'Rossella?' :
      bot.send_message(update.message.chat.id, 'Gluglugluglugluglugluglu :heart:').wait()
    if update.message.text == 'Marco?' :
      bot.send_message(update.message.chat.id, 'Cheffigo!!').wait()
    if "grazie" in update.message.text :
      bot.send_message(update.message.chat.id, 'Grazie graziella grazie al cazzone!').wait()
Exemplo n.º 33
0
def setKeyboard():
    keyboard = [['7', '8', '9'], ['4', '5', '6'], ['1', '2', '3'], ['0']]
    reply_markup = ReplyKeyboardMarkup.create(keyboard)
    return reply_markup
Exemplo n.º 34
0
 def _numeric_keyboard():
     keyboard = [['1', '2'], ['3', '4']]
     return ReplyKeyboardMarkup.create(keyboard)
Exemplo n.º 35
0
class specsBot():

    numbers = [
        "\u0030\u20E3", "\u0031\u20E3", "\u0032\u20E3", "\u0033\u20E3",
        "\u0034\u20E3", "\u0035\u20E3", "\u0036\u20E3", "\u0037\u20E3",
        "\u0038\u20E3", "\u0039\u20E3", "\N{keycap ten}"
    ]
    replykeyboard = ReplyKeyboardMarkup.create(
        [[numbers[1], numbers[2], numbers[3]],
         [numbers[4], numbers[5], numbers[6]],
         [numbers[7], numbers[8], numbers[9]]],
        one_time_keyboard=True)

    def handleUpdate(self, update):
        logging.debug("received msg " + update.message.text)
        msg = update.message
        if (msg):
            if (msg.text):
                if (msg.chat in self.db):
                    logging.debug("response")

                    try:
                        choice = specsBot.numbers.index(msg.text)
                        product = self.db[msg.chat]["products"][choice - 1]

                        text = ""

                        for d in product["datasheets"]:
                            text += d["description"] + "\n" + d["url"] + "\n\n"

                        self.bot.send_message(
                            msg.chat, text, reply_to_message_id=msg.message_id)
                        del self.db[msg.chat]
                    except (ValueError, IndexError) as e:
                        self.bot.send_message(
                            msg.chat,
                            "invalid choice " + str(e),
                            reply_markup=specsBot.replykeyboard,
                            reply_to_message_id=msg.message_id)
                else:
                    # TODO: check injection vulnerability
                    products = self.dsf.searchForProducts(msg.text)
                    text = "found %d products\n\n" % len(products)
                    for i, p in enumerate(products):
                        text += "%s %s\n\n" % (specsBot.numbers[i + 1],
                                               p["displayName"])
                    if len(products) > 0:
                        self.db[msg.chat] = {
                            "state": "choosing product",
                            "products": products
                        }
                        self.bot.send_message(
                            msg.chat,
                            text,
                            reply_markup=specsBot.replykeyboard,
                            reply_to_message_id=msg.message_id)
                    else:
                        self.bot.send_message(
                            msg.chat, text, reply_to_message_id=msg.message_id)

    def get_updates_cont(self):
        """
        Get updates sent to the bot
        """
        currentUpdateId = 0
        while True:
            updates = self.bot.get_updates(offset=currentUpdateId).wait()
            for update in updates:
                print(update)
                if update:
                    currentUpdateId = update.update_id + 1
                    yield update
            time.sleep(0.5)

    def run(self):
        try:
            json_data = open("settings.json").read()
            self.settings = json.loads(json_data)
            """
            Setup the bot
            """
            self.bot = TelegramBot(self.settings["tg-apiKey"])
            self.dsf = DatasheetFinder(self.settings["el14-apiKey"])
            self.bot.update_bot_info().wait()
            self.db = {}
            logging.info("username is %s" % self.bot.username)

            for update in self.get_updates_cont():
                self.handleUpdate(update)

        except KeyboardInterrupt:
            logging.info("halting due to KeyboardInterrupt")
Exemplo n.º 36
0
def process_message(msg):
    keyboard = [['Get Weather']]
    reply_markup = ReplyKeyboardMarkup.create(keyboard)

    chat_id = msg['chat']['id']
    message = msg['text']
    #    <command> <argument>
    #   weather accra,ghana
    if re.match(r'hi|hello', message.lower()):
        bot.sendMessage(chat_id, 'Hi! Am Sunny , how may i help you ?')
    elif re.match(r'time', message.lower()):
        print(message)
        bot.sendMessage(chat_id, str(now.hour) + str(":") + str(now.minute))
    elif message.lower() == ('on bedroom light'):
        broom.on()
        bot.sendMessage(chat_id, 'bedroom light is on')
    elif message.lower() == ('off bedroom light'):
        broom.off()
        bot.sendMessage(chat_id, 'bedroom light is off')
    elif message.lower() == ('on garage light'):
        groom.on()
        bot.sendMessage(chat_id, 'bedroom light is on')
    elif message.lower() == ('off garage light'):
        groom.off()
        bot.sendMessage(chat_id, 'garage light is off')
    elif message.lower() == ('on living room light'):
        lroom.on()
        bot.sendMessage(chat_id, 'living room light is on')
    elif message.lower() == ('off living light'):
        lroom.off()
        bot.sendMessage(chat_id, 'living room light is off')
    elif message.lower() == ('on outside light'):
        ol.on()
        bot.sendMessage(chat_id, 'ouside light is on')
    elif message.lower() == ('off outside light'):
        ol.off()
        bot.sendMessage(chat_id, 'ol light is off')
    elif re.match(r'weather', message.lower()):
        words = message.lower().split()
        location = words[1] + ", " + words[2]

        print(chat_id)
        print(message)
        owm = OWM(OWMKEY)
        obs = owm.weather_at_place(location)
        w = obs.get_weather()
        humidity = str(w.get_humidity())
        pressure = str(w.get_pressure())
        l = obs.get_location()
        status = str(w.get_detailed_status())
        placename = str(l.get_name())
        wind = str(w.get_wind())
        wtime = str(w.get_reference_time(timeformat='iso'))
        temperature = str(w.get_temperature('celsius').get('temp'))

        bot.sendMessage(
            chat_id, 'Weather Status: ' + status + ' At ' + placename +
            ' Date and Time for the search is: ' + wtime +
            '  The Temperature is: ' + temperature + 'C' +
            '  The Humidity is: ' + humidity + ' ' + 'The wind speed is: ' +
            wind + ' ' + ' The Atmospheric pressure: ' + pressure + ' ')

    else:
        return bot.sendMessage(
            chat_id,
            'Services Avialable: 1. Weather.  2.Time. 3.Home Automation')
Exemplo n.º 37
0
	def reply (self, update):
		chat_id=update.message.chat.id
		name = update.message.chat.first_name
		replyMsg = ""
		if chat_id in self.validUsers:  
			text = update.message.text
			reply_markup = None

			if (text.lower() == "/start"):
				replyMsg += "Hi %s! Welcome on SmartHome2!" % (name) 
				reply_markup =ReplyKeyboardMarkup.create(self.keyboards["start"], one_time_keyboard= False, selective=True)
				self.keybordForUsers[chat_id] = [self.keyboards["start"]]
				
			elif (text == "Start"):
				replyMsg = "command received"
				reply_markup = ReplyKeyboardMarkup.create(self.keyboards["start"], one_time_keyboard= False, selective=True)
				self.keybordForUsers[chat_id] = [self.keyboards["start"]]

			elif (text.lower().startswith("/openport") ):
				params = text.lower().split(" ")
				params = filter(None, params)
				protocol = "TCP"
				localIP = None
				localPort = None
				externalPort = None
				wrongParamsMsg = "Wrong parameters! Usage:\n/openport -s <localhost port> -d <router port>\n/openport -s <localhost port> -d <router port> -p <TCP or UDP>\n/openport -h <host ip> -s <host port> -d <router port>\n/openport -h <host ip> -s <host port> -d <router port> -p <TCP or UDP>\n" 
				if (len(params) != 5 and len(params) != 7 and len(params) != 9):
					replyMsg = wrongParamsMsg
				elif (len(params) == 5):
					if (params[1].lower() == "-s" and params[3].lower() == "-d"):
						localPort = params[2]
						externalPort = params[4] 
						replyMsg = self.openPort(localIP, localPort, externalPort, protocol)
					else:
						replyMsg = wrongParamsMsg
				elif (len(params) == 7):
					if (params[1].lower() == "-h" and params[3].lower() == "-s" and params[5].lower() == "-d"):
						localIP = params[2]
						localPort = params[4]
						externalPort = params[6] 
						replyMsg = self.openPort(localIP, localPort, externalPort, protocol)
					elif (params[1].lower() == "-s" and params[3].lower() == "-d" and params[5].lower() == "-p"):
						localPort = params[2]
						externalPort = params[4]
						protocol = params[6] 
						replyMsg = self.openPort(localIP, localPort, externalPort, protocol)
					else:
						replyMsg = wrongParamsMsg
				elif (len(params) == 9):
					if (params[1].lower() == "-h" and params[3].lower() == "-s" and params[5].lower() == "-d" and params[7].lower() == "-p"):
						localIP = params[2]
						localPort = params[4]
						externalPort = params[6] 
						protocol = params[8]
						replyMsg = self.openPort(localIP, localPort, externalPort, protocol)
					else:
						replyMsg =  wrongParamsMsg
				else:
					replyMsg = wrongParamsMsg
				
			elif (text.lower().startswith("/closeport") ):
				params = text.lower().split(" ")
				params = filter(None, params)
				protocol = "TCP"
				externalPort = None
				wrongParamsMsg = "Wrong parameters! Usage:\n/closeport -d <router port>\n/closeport -d all\n/closeport -d <router port> -p <TCP or UDP>\n" 
				if (len(params) != 3 and len(params) != 5):
					replyMsg = wrongParamsMsg
				elif (len(params) == 3):
					if (params[1].lower() == "-d"):
						externalPort = params[2]
						replyMsg = self.closePort(externalPort, protocol)
					else:
						replyMsg = wrongParamsMsg
				elif (len(params) == 5):
					if (params[1].lower() == "-d" and params[3].lower() == "-p"):
						externalPort = params[2]
						protocol = params[4] 
						replyMsg = self.closePort(externalPort, protocol)
					else:
						replyMsg = wrongParamsMsg
				

			elif (text.lower().startswith("/allports") ):
				replyMsg = ""
				ndevices = self.upnp.discover()
				igd = self.upnp.selectigd()
				isNoMapping = True

				for port in range (self.minUPnPPort, self.maxUPnPPort):
					available = self.upnp.getspecificportmapping(port, 'TCP')
					if (available != None):
						replyMsg += "port: %d, protocol: TCP\n" % (port)
						isNoMapping = False

					available = self.upnp.getspecificportmapping(port, 'UDP')
					if (available != None):
						replyMsg += "port: %d, protocol: UDP\n" % (port)
						isNoMapping = False


				if (isNoMapping):
					replyMsg += "There is any port mapping active"

			elif (text == "/update"):
				resp, isOk = self.invokeWebService(self.homeWSUri)
				if (isOk):
					self.myhome = json.loads(resp)
					self.botToken = self.myhome["TelegramBot"]["telegramToken"]
					self.validUsers = self.myhome["TelegramBot"]["allowedUserID"]	
					self.makeKeyboards()
					replyMsg = "Bot Updated"
				else:
					replyMsg = "Unable to update the bot: %s" % (resp)

			elif (text.lower() == "/help"):
				replyMsg += "Start a section:\n/start\n"
				replyMsg += "\nCreate port forwarding:\n/openport -s <localhost port> -d <router port>\n/openport -s <localhost port> -d <router port> -p <TCP or UDP>\n/openport -h <host ip> -s <host port> -d <router port>\n/openport -h <host ip> -s <host port> -d <router port> -p <TCP or UDP>\n" 
				replyMsg += "\nClose port forwarding:\n/closeport -d <router port>\n/closeport -d all\n/closeport -d <router port> -p <TCP or UDP>\n" 
				replyMsg += "\nShow all forwarded ports:\n/allports\n"
				replyMsg += "\nUpdate bot engine:\n/update\n"

			elif (text == "Back"):
				if (chat_id in self.keybordForUsers):
					del self.keybordForUsers[chat_id][-1]
					replyMsg = "command received"
					backKeyboard = self.keybordForUsers[chat_id][-1]
				else:
					replyMsg = "Restoring keyboard due to an internal error"
					backKeyboard= self.keyboards["start"]
					self.keybordForUsers[chat_id] = [backKeyboard]
				
				reply_markup = ReplyKeyboardMarkup.create(backKeyboard, one_time_keyboard= False, selective=True)
				
				
				

			elif (text == self.keyboards["start"][0][0]):
				# Rooms
				try:
					replyMsg = "command received"
					self.keybordForUsers[chat_id].append(self.keyboards[self.keyboards["start"][0][0]])
					reply_markup = ReplyKeyboardMarkup.create(self.keyboards[self.keyboards["start"][0][0]], one_time_keyboard= False, selective=True)
				except:
					replyMsg = "Restoring keyboard due to an internal error"
					self.keybordForUsers[chat_id] = [self.keyboards["start"]]
					reply_markup = ReplyKeyboardMarkup.create(self.keyboards["start"], one_time_keyboard= False, selective=True)
				
			elif (text == self.keyboards["start"][0][1]):
				# Devices
				try:
					replyMsg = "command received"
					self.keybordForUsers[chat_id].append(self.keyboards[self.keyboards["start"][0][1]])
					reply_markup = ReplyKeyboardMarkup.create(self.keyboards[self.keyboards["start"][0][1]], one_time_keyboard= False, selective=True)
				except:
					replyMsg = "Restoring keyboard due to an internal error"
					self.keybordForUsers[chat_id] = [self.keyboards["start"]]
					reply_markup = ReplyKeyboardMarkup.create(self.keyboards["start"], one_time_keyboard= False, selective=True)
				

			elif (text == self.keyboards["start"][1][0]):
				# Switch off all devices
				replyMsg = "command received. The execution may take some time. I will keep you updated."
				self.bot.send_message(chat_id, replyMsg , reply_markup=reply_markup)
				resp, isOk = self.invokeWebService (self.myhome["switchOffAllDevicesAgent"])
				if (isOk):
					replyMsg = "command sent to devices"
				else:
					replyMsg = 'Unable to send "switch off" command to devices: %s' % (resp)
			
#			elif (text == self.keyboards["start"][1][1]):
#				# Rules
#				try:
#					replyMsg = "command received"
#					self.keybordForUsers[chat_id].append(self.keyboards[self.keyboards["start"][1][1]])
#					reply_markup = ReplyKeyboardMarkup.create(self.keyboards[self.keyboards["start"][1][1]], one_time_keyboard= False, selective=True)
#				except:
#					replyMsg = "Restoring keyboard due to an internal error"
#					self.keybordForUsers[chat_id] = [self.keyboards["start"]]
#					reply_markup = ReplyKeyboardMarkup.create(self.keyboards["start"], one_time_keyboard= False, selective=True)


			elif (text in self.allRoomsList):
				# Devices per room keyboard
				keyboard = []
				keyoardRow = []
				for count, device in  enumerate(self.allRoomsList[text]["devices"]):
					label = "%s (%s)" % (device["description"], device["deviceID"])
					self.allDevicesList[label] = device
					keyoardRow.append (label)
					keyboard.append(keyoardRow)
					keyoardRow = []
				keyboard.sort()
				keyboard.append(["Back", "Start"])
				try:
					replyMsg = "command received"
					self.keybordForUsers[chat_id].append(keyboard)
					reply_markup = ReplyKeyboardMarkup.create(keyboard, one_time_keyboard= False, selective=True)
				except:
					replyMsg = "Restoring keyboard due to an internal error"
					self.keybordForUsers[chat_id] = [self.keyboards["start"]]
					reply_markup = ReplyKeyboardMarkup.create(self.keyboards["start"], one_time_keyboard= False, selective=True)
				

			elif (text in self.allDevicesList):
				replyMsg = "Connecting to device %s" %  (text)
				self.bot.send_message(chat_id, replyMsg , reply_markup=reply_markup)
				replyMsg, keyboard = self.retrieveDeviceInfo(text)
				
				try:
					#replyMsg = "command received"
					self.keybordForUsers[chat_id].append(keyboard)
					reply_markup = ReplyKeyboardMarkup.create(keyboard, one_time_keyboard= False, selective=True)
				except:
					replyMsg = "Restoring keyboard due to an internal error"
					self.keybordForUsers[chat_id] = [self.keyboards["start"]]
					reply_markup = ReplyKeyboardMarkup.create(self.keyboards["start"], one_time_keyboard= False, selective=True)
				
			elif (text in self.alldevicesFunctionsList):
				replyMsg = "Connecting to device %s" % (self.alldevicesFunctionsList[text]) #(text)
				self.bot.send_message(chat_id, replyMsg , reply_markup=reply_markup)
				replyMsg, keyboard = self.retrieveDeviceInfo(self.alldevicesFunctionsList[text])
				reply_markup = ReplyKeyboardMarkup.create(keyboard, one_time_keyboard= False, selective=True)
				# do not save the current keyboard in self.keybordForUsers[chat_id].append(keyboard)
				# otherwaise the "Back" button engine will not work properly 


			else:
				replyMsg = 'Unkonwn command "%s"' % (text)

			self.bot.send_message(chat_id, replyMsg , reply_markup=reply_markup)
							 
		else:
			last_name = update.message.chat.last_name
			username = update.message.chat.username
			replyMsg += "user"
			if (name is not None):
				replyMsg += " %s" % (name) 

			if (last_name is not None):
				replyMsg += " %s" % (last_name)

			if (username is not None):
				replyMsg += " with username %s" % (username)

			replyMsg += " (userID: %s) is not allowed" % (chat_id)

			self.logger.error(replyMsg)
			self.bot.send_message(chat_id, replyMsg)
Exemplo n.º 38
0
    def process_message_layer1(bot, u, last_update_id):

        if u.message.sender and u.message.text and u.message.chat:  # if the message is text
            chat_id = u.message.chat.id  # Extract data of message
            user = u.message.sender.id
            message = u.message.text

            print("\n chat_id: ", chat_id)
            print("user: "******"message: ", message)
            print("\n")

            if message == 'Start LambderBot':  # if message is ...
                keyboard = [['Loggin account'],
                            ['Exit']]  # Buttons Loggin account and Exit
                reply_markup = ReplyKeyboardMarkup.create(
                    keyboard)  # Create Button

                # welcome according to the time
                if int(time.strftime("%H")) >= 4 and int(
                        time.strftime("%H")
                ) < 12:  #If the time is between 4 and 12 noon then the bot will say 'Good morning'
                    greeting = 'Good Morning'
                    print("Good Morning")

                elif int(time.strftime("%H")) >= 12 and int(
                        time.strftime("%H")
                ) < 16:  #If the time is between 12 noon and 6 then the bot will say 'Good Afternoon'
                    greeting = 'Good Afternoon'
                    print("Good Afternoon")

                else:
                    greeting = 'Good Nigth'  #Else say 'Good Nigth'
                    print("Good Nigth")

                bot.send_message(chat_id,
                                 greeting + '\nSelect an option',
                                 reply_markup=reply_markup).wait(
                                 )  # Show message and Button
                bot.send_sticker(chat_id,
                                 'CAADAgAD5QgAAgi3GQLR-yMPZfVRlAI',
                                 reply_markup=reply_markup).wait()

                print('Hello, Select an option, Layer 1')
                layer2(bot, last_update_id)  # Call Second Layer

            elif message == '/start':
                print("Select an option, Layer 1")
                keyboard = [['Start LambderBot']]
                reply_markup = ReplyKeyboardMarkup.create(keyboard)
                bot.send_message(chat_id,
                                 'Select an option',
                                 reply_markup=reply_markup).wait(
                                 )  # update buttons and stay in this layer

            else:
                print("Select an option, Layer 1")
                keyboard = [['Start LambderBot']]
                reply_markup = ReplyKeyboardMarkup.create(keyboard)
                bot.send_message(chat_id,
                                 'Select an option',
                                 reply_markup=reply_markup).wait()

        else:
            print("Select an option, Layer 1")
            keyboard = [['Start LambderBot']]
            reply_markup = ReplyKeyboardMarkup.create(keyboard)
            bot.send_message(u.message.chat.id,
                             'Select an option',
                             reply_markup=reply_markup).wait()
Exemplo n.º 39
0
"""
Setup the bot
"""

bot = TelegramBot('332101015:AAFy9vC_d4Dj5GK7bkIQa5kETnudMqZWUhY')
bot.update_bot_info().wait()
print(bot.username)
"""
Send a message to a user
"""
user_id = int(185350524)

result = bot.send_message(user_id, str1).wait()
print(result)
"""
Get updates sent to the bot
"""
updates = bot.get_updates().wait()
for update in updates:
    print(update)
"""
Use a custom keyboard
"""
keyboard = [['7', '8', '9'], ['4', '5', '6'], ['1', '2', '3'], ['0']]
reply_markup = ReplyKeyboardMarkup.create(keyboard)

bot.send_message(user_id, 'please enter a number',
                 reply_markup=reply_markup).wait()

print reply_markup
Exemplo n.º 40
0
def analizerMail(user, pwd, chat_id, bot,
                 last_update_id):  # This function checks for unseen emails

    # connecting to the gmail imap server
    imapMail = imaplib.IMAP4_SSL("imap.gmail.com")

    # Login
    try:
        imapMail.login(user, pwd)
    except:

        print("User or password incorrect <Sticker>")
        keyboard = [['Loggin account'], ['Exit']]
        reply_markup = ReplyKeyboardMarkup.create(keyboard)

        bot.send_message(chat_id,
                         'User or password incorrect',
                         reply_markup=reply_markup).wait()
        bot.send_sticker(chat_id,
                         'CAADAgAD8wgAAgi3GQKHdYrrN-Wt_QI',
                         reply_markup=reply_markup).wait()

        layer2(bot, last_update_id)

    global run

    # Makes a list of mails id (to show only new unseen ones)
    listOfShowedEmailsID = []
    listOfEmailsID = []
    allowedToShow = False

    try:

        #Idle Loop
        while run:

            # makes a list of email
            imapMail.list()

            imapMail.select(
                'Inbox')  # here you a can choose a mail box like INBOX instead

            (resp, data) = imapMail.uid('search', None,
                                        '(UNSEEN)')  # filter unseen mails

            data = data[0].split()  # getting the mails id

            # Now for every unseen email
            for emailid in data:

                # Check if email id is in the list of last emails shown
                try:
                    # If exception doesn't comes up then item is in the last showed emails list, so we dont show it
                    listOfShowedEmailsID.index(emailid)
                    allowedToShow = False

                except:
                    # Except, so id isnt in the list, we need to show it
                    allowedToShow = True

                # If it has something to show
                if allowedToShow:
                    (resp, data) = imapMail.uid(
                        'fetch', emailid, "(RFC822)"
                    )  # fetching the mail, "`(RFC822)`" means "get the whole stuff", but you can ask for headers only, etc

                    email_info = data[0][1]  # getting the mail content

                    mail = email.message_from_bytes(
                        email_info
                    )  # parsing the mail content to get a mail object

                    (resp, data) = imapMail.uid(
                        'store', emailid, '-FLAGS', '\\Seen'
                    )  # Mark email as unseen again (bc fetching brings body of email too)

                    #Check if any attachments at all
                    if mail.get_content_maintype() != 'multipart':
                        continue

                    # Add the current emailID to listOfEmailsID, to save new IDs

                    listOfEmailsID.append(emailid)
                    try:
                        resp = "[" + mail["From"] + "] :" + mail[
                            "Subject"] + "\n"

                        bot.send_message(chat_id, resp)
                    except:
                        exit()

            # If this list is not empty, then i got some new emails
            if listOfEmailsID:
                listOfShowedEmailsID.extend(listOfEmailsID)
                listOfEmailsID.clear()

    finally:

        imapMail.logout()
Exemplo n.º 41
0
    def process_message_layer9(bot, u, last_update_id, usr, pwd, dest, sub,
                               content, filesToSend):

        # if the message is a file
        if u.message.sender and u.message.chat:
            chat_id = u.message.chat.id  # Extract data of message
            user = u.message.sender.id

            print("\n chat_id: ", chat_id)
            print("user: \n", user)

            if u.message.document:
                print(" \n BOT.MESSAGE.DOCUMENT, Layer 9")
                print(u.message.document)
                print("\n")

                # Get file info
                file_Info = botto.get_file(u.message.document.file_id)

                # Download locally to manipulate later
                file_Info.download(u.message.document.file_name)

                filesToSend.append(u.message.document.file_name)

                print("\n Layer 9: Esperando por archivo o Send")
                keyboard = [['Send'], ['Back']]
                reply_markup = ReplyKeyboardMarkup.create(keyboard)
                bot.send_message(
                    chat_id,
                    "Do you have another file? or do you want to send email?",
                    reply_markup=reply_markup).wait()
                layer9(bot, last_update_id, usr, pwd, dest, sub, content,
                       filesToSend)

            elif u.message.photo:
                print(" \n BOT.MESSAGE.PHOTO, Layer 9")
                print(u.message.photo)
                print("\n")

                # Get file info
                file_Info = botto.get_file(u.message.photo[3].file_id)

                # Download locally to manipulate later
                tofu = u.message.photo[3].file_id

                file_Info.download(tofu)

                filesToSend.append(tofu)

                print("\n Layer 9: Esperando por archivo o Send")
                keyboard = [['Send'], ['Back']]
                reply_markup = ReplyKeyboardMarkup.create(keyboard)
                bot.send_message(
                    chat_id,
                    "Do you have another file? or do you want to send email?",
                    reply_markup=reply_markup).wait()
                layer9(bot, last_update_id, usr, pwd, dest, sub, content,
                       filesToSend)

            elif u.message.text:
                if u.message.text == 'Send':

                    print("Sending mail, Layer 9")
                    bot.send_message(chat_id, 'Sending email')

                    if sendMessage(dest, sub, content, filesToSend, usr, pwd,
                                   chat_id) == 0:
                        bot.send_message(chat_id, 'Email send')

                    print("Select an option, Layer 9")
                    keyboard = [['Show unseen emails'], ['Send a email'],
                                ['Back']]
                    reply_markup = ReplyKeyboardMarkup.create(keyboard)
                    bot.send_message(chat_id,
                                     'Select an option',
                                     reply_markup=reply_markup).wait()
                    layer4(bot, last_update_id, usr, pwd)

                elif u.message.text == 'Back':
                    print("Select an option, Layer 9")
                    keyboard = [['Show unseen emails'], ['Send a email'],
                                ['Back']]
                    reply_markup = ReplyKeyboardMarkup.create(keyboard)
                    bot.send_message(chat_id,
                                     'Select an option',
                                     reply_markup=reply_markup).wait()
                    layer4(bot, last_update_id, usr, pwd)
                else:
                    print("Select an option, Layer 9")
                    keyboard = [['Send'], ['Back']]
                    reply_markup = ReplyKeyboardMarkup.create(keyboard)
                    bot.send_message(chat_id,
                                     'Select an option',
                                     reply_markup=reply_markup).wait()
        else:
            print("Select an option, Layer 9")
            keyboard = [['Show unseen emails'], ['Send a email'], ['Back']]
            reply_markup = ReplyKeyboardMarkup.create(keyboard)
            bot.send_message(u.message.chat.id,
                             'Select an option',
                             reply_markup=reply_markup).wait()
            layer4(bot, last_update_id, usr, pwd)
Exemplo n.º 42
0
def send_keyboard(bot, user_id):
    keyboard_layout = [['Play >'], ['Previous <<', 'Next >>'], ['Pause []'] ]
    reply_markup = ReplyKeyboardMarkup.create(keyboard_layout)
    bot.send_message(user_id, 'This is JukeBot!\nWelcome, user', reply_markup=reply_markup)