Esempio n. 1
0
    def retrieve_telegram_id(self, data):
        api_token = dict(data)['value'][0]
        auth = dict(data)['auth_code'][0]

        bot = TelegramBot(api_token)
        bot.update_bot_info().wait()

        if bot.username is not None:
            updates = bot.get_updates().wait()
            data = dict()
            for update in updates:
                id = update._asdict()['message']._asdict()['sender']._asdict(
                )['id']
                text = update._asdict()['message']._asdict()['text']
                data[id] = text

            if auth in list(data.values()):
                user_id = list(data.keys())[list(data.values()).index(auth)]
            return 'er1'
            # Send a welcome message
            welcome_message = """Welcome to HealthChecks B
                            Notifications via Telegram Messanger."""
            bot.send_message(user_id, welcome_message).wait()

            return user_id
        return 'er2'
def telegram_bot(url, regexs):
    bot = TelegramBot(BOT_API_TOKEN)
    bot.update_bot_info().wait()
    print(bot.username)
    bot.send_message(CHAT_ID, "[%s] Bot Starting" % str(datetime.now())).wait()
    while (True):
        diff = diff_html(url, regexs)
        if diff:
            for diff_message in diff:
                ticket = ["Ticket", "ticket"]
                print diff_message
                for t in ticket:
                    print t
                    if t in diff_message:
                        bot.send_message(
                            CHAT_ID,
                            "TICKET WORD APPEARED IN A DIFF!!1111").wait()
                        sleep(2)
                        bot.send_message(
                            CHAT_ID,
                            "TICKET WORD APPEARED IN A DIFF!!1111").wait()
                bot.send_message(CHAT_ID,
                                 "Last updates:\n %s" % diff_message).wait()
        else:
            print("LOG: No diff")
        sleep(CYCLE_TIME)
Esempio n. 3
0
File: main.py Progetto: auzias/pikon
def main():
    try:
        with open('API_KEY', 'r') as f:
            api_key = f.read().replace('\n', '')
    except IOError:
        print "please write the api key in file `API_KEY`"
        exit(1)

    bot = TelegramBot(api_key)
    bot.update_bot_info().wait()
    print(bot.username)

    last_update_id = int(0)
    while True:
        try:
            updates = bot.get_updates(offset=last_update_id+1, timeout=5).wait()
            for update in updates:
                last_update_id = update.update_id
                #print(update)
                process_update(bot, update)
        except KeyboardInterrupt:
            # Allow ctrl-c.
            raise KeyboardInterrupt
        except Exception as e:
            print "---\nException: "
            print e
            traceback.print_exc()
            pass
Esempio n. 4
0
def setupBot(apitoken):
    """
    Setup the bot
    """
    bot = TelegramBot(apitoken)
    bot.update_bot_info().wait()
    return bot
Esempio n. 5
0
def main():
    print '[+] Starting bot...'

    # Read the config file
    print '[+] Reading config file...'
    config = ConfigParser.ConfigParser()
    config.read([os.path.expanduser('./config')])

    # Read data
    bot_name = config.get('bot', 'name')
    bot_token = config.get('bot', 'token')
    cool_answers_raw = config.get('phrases', 'cool_answers')
    cool_answers = [ answer for answer in cool_answers_raw.split('"') if answer and answer!=',']

    # Last mssg id:
    last_id = int(load_last_id())
    print '[+] Last id: %d' % last_id

    # Configure regex
    regex = re.compile('[%s]' % re.escape(string.punctuation))

    # Create bot
    print '[+] Connecting bot...'
    bot = TelegramBot(bot_token)
    bot.update_bot_info().wait()
    print '\tBot connected! Bot name: %s' % bot.username

    while True:
        try:
            updates = bot.get_updates(offset=last_id).wait()

            for update in updates:
                id = update.message.message_id
                update_id = update.update_id
                user = update.message.sender

                chat_id = update.message.chat.id
                text = update.message.text

                if int(update_id) > last_id:
                    last_id = update_id
                    save_last_id(last_id)
                    save_log(id, update_id, chat_id, text)

                    #text = regex.sub('', text)
                    words = text.split()

                    for word in words:
                        # Process commands:
                        if 'http://' in word or 'https://' in word:
                            # Get a random answer phrase:
                            answer = random.choice(cool_answers)
                            bot.send_message(chat_id, answer)

        except (KeyboardInterrupt, SystemExit):
            print '\nkeyboardinterrupt caught (again)'
            print '\n...Program Stopped Manually!'
            raise
Esempio n. 6
0
    def notify(self, check):

        bot = TelegramBot(self.channel.value)
        bot.update_bot_info().wait()

        if bot.username is not None:
            # Send a welcome message
            notification = 'The check with name:' + check.name + \
                'and code:' + str(check.code) + '  has gone ' + check.status
            bot.send_message(self.channel.telegram_id, notification).wait()
Esempio n. 7
0
def start():
    bot = TelegramBot(token)
    bot.update_bot_info().wait()
    print(bot.username)
    #foto belle -33909375
    #user_id = int(23263342)

    #result = bot.send_message(user_id, 'Salve ragazzi').wait()
    #XXX WebHook automatico non funzionante
    result = bot.set_webhook(token)
    print('*****Il risultato:' % (result))
    return "ok"
Esempio n. 8
0
def start():
 bot = TelegramBot(token)
 bot.update_bot_info().wait()
 print(bot.username)
 #foto belle -33909375 
 #user_id = int(23263342)

 #result = bot.send_message(user_id, 'Salve ragazzi').wait()
 #XXX WebHook automatico non funzionante
 result = bot.set_webhook(token)
 print('*****Il risultato:' % (result))
 return "ok"
Esempio n. 9
0
    def run(self):
        init_logging()
        """
		TODO: create directory for archive if it does not excist already
		"""
        bot = TelegramBot(BOT_ID)
        bot.update_bot_info().wait()
        print(bot.username)
        logging.info("Bot %s running", bot.username)

        page_source = download(URL)
        old_titles = titles(page_source)

        logging.info("First set of titles parsed")
        minutes = 60 * INTERVAL

        # Disabled sending messages to the channel to decrease spam

        result = bot.send_message(DEV_PERSONAL_ID,
                                  "The blog will be watched").wait()
        #		print("Sending channel: " + str(result))
        logging.info("Sending channel: " + str(result))

        while True:
            time.sleep(minutes)
            try:
                page_source = download(URL)
                new_titles = titles(page_source)
                diff = new_titles.has_changed(old_titles)
            except socket.error:
                diff = -2

            if (diff == -2):
                print("No internet connection")
                logging.info("No internet connection")
            elif (diff < 0):
                print("no changes were made")
                logging.info("No changes were made")
            else:
                print("Changes on target")
                logging.info("Changes on target")
                save_index(page_source)
                message = message_hj()
                old_titles = new_titles
                try:
                    message.add_title_in_cleartxt(new_titles.get_title(diff))
                    message.send_to_telegram(bot)

                except:
                    fallback_msg = message_hj()
                    fallback_msg.fallback_without_title()
                    fallback_msg.send_to_telegram(bot)
Esempio n. 10
0
class TelegramBroadcaster():
    """
    Setup the bot
    """
    def __init__(self):
        self.bot = TelegramBot('<BOT_KEY>')
        self.bot.update_bot_info().wait()
        self.user_id = int(<CHANNEL_KEY>) # channel goyanglib
        print(self.bot.username)

    def send(self, message):
        result = self.bot.send_message(self.user_id, message).wait()
        print(result)
Esempio n. 11
0
def update():
    bot = TelegramBot(token)
    bot.update_bot_info().wait()

    if 'chat' in request.json['message']:
        chat = request.json['message']['chat']['id']
        if 'text' in request.json['message']:
            text = request.json['message']['text']
            if text.find('vice') != -1:
                bot.send_message(chat, vice()).wait()
            if text.find('drink') != -1:
                bot.send_photo(chat, bill()).wait()

    #Print in console for fast Debugging
    print(json.dumps(request.json))
    return "ok"
Esempio n. 12
0
def update():
 bot = TelegramBot(token)
 bot.update_bot_info().wait()

 if 'chat' in request.json['message']:
  chat = request.json['message']['chat']['id']
  if 'text' in request.json['message']:
   text = request.json['message']['text']
   if text.find('vice') != -1:
    bot.send_message(chat, vice()).wait()
   if text.find('drink') != -1:
    bot.send_photo(chat,bill()).wait()

 #Print in console for fast Debugging
 print(json.dumps(request.json))
 return "ok"
Esempio n. 13
0
def telebot(news):
    """
	This Telegram bot sends a message about stock news to a user using 
	TWX bot library. More about this library may be find at:
	https://pythonhosted.org/twx/twx/botapi/botapi.html#module-twx.botapi
	"""
    bot = TelegramBot('182387487:AAGiA489MZtosNOkhLjzo3_6l7xCYkG4N5A')
    bot.update_bot_info().wait()
    updates = bot.get_updates().wait()
    for update in updates:
        user_id, = re.findall("sender=User.id=(\d+)", str(update))
        if user_id not in users:
            users.append(user_id)
    for user in users:
        user_id = int(user)
        bot.send_message(user_id, news)
Esempio n. 14
0
def telebot(news):
	"""
	This Telegram bot sends a message about stock news to a user using 
	TWX bot library. More about this library may be find at:
	https://pythonhosted.org/twx/twx/botapi/botapi.html#module-twx.botapi
	"""
	bot = TelegramBot('182387487:AAGiA489MZtosNOkhLjzo3_6l7xCYkG4N5A')
	bot.update_bot_info().wait()
	updates = bot.get_updates().wait()
	for update in updates:
	    user_id, = re.findall("sender=User.id=(\d+)", str(update))
	    if user_id not in users:
	    	users.append(user_id)
	for user in users:
		user_id = int(user)
		bot.send_message(user_id, news)
Esempio n. 15
0
class Botonio:
    """Principal class to run the Bot"""
    def __init__(self, token):
        self.users = {}
        self.bot = TelegramBot(token)
        self.bot.update_bot_info().wait()
        self.offset = 1
        updates = self.bot.get_updates().wait()
        if isinstance(updates, Error):
            print(updates)
            raise Exception('Error to conect with Telegram.')
        if len(updates):
            self.offset = updates[-1].update_id

    def start(self):
        while True:
            updates = self.bot.get_updates(offset=self.offset).wait()
            if not len(updates):
                continue
            self.offset = updates[-1].update_id
            self.offset += 1
            for update in updates:
                if update.message is None:
                    continue
                sender = update.message.sender
                if sender.id not in self.users:
                    user = User(sender.first_name, sender.id)
                    self.users[user.user_id] = user
                else:
                    user = self.users[sender.id]
                if update.message.text == 'stop':
                    del self.users[user]
                    continue
                messages = user.process_message(update.message.text)
                if isinstance(messages, tuple):
                    self.bot.send_message(
                        user.user_id,
                        messages[0],
                        reply_markup=self._numeric_keyboard()).wait()
                else:
                    self.bot.send_message(user.user_id, messages).wait()

    @staticmethod
    def _numeric_keyboard():
        keyboard = [['1', '2'], ['3', '4']]
        return ReplyKeyboardMarkup.create(keyboard)
Esempio n. 16
0
def main():
    try:
        with open('API_KEY', 'r') as f:
            api_key = f.read().replace('\n', '')
    except IOError:
        print "please write the api key in file `API_KEY`"
        exit(1)

    bot = TelegramBot(api_key)
    bot.update_bot_info().wait()
    print(bot.username)

    last_update_id = int(0)
    last_fortune = (datetime.now() - timedelta(minutes=31))
    while True:
        try:
            updates = bot.get_updates(offset=last_update_id+1, timeout=5).wait()
            for update in updates:
                last_update_id = update.update_id
                print(update)
                process_update(bot, update)
            global rems
            for rem in rems:
                if rem.when < datetime.now():
                    bot.send_message(rem.chatid, "=== RAPPEL ===\n\n" +
                            unicode(rem.what))
                    print "removing reminder " + str(rem.id)
                    rems = [r for r in rems if r.id != rem.id]
                    print "rems = " + str(rems)

            odd = random.randint(0, 100)
            thirty_minutes = (datetime.now() - datetime.timedelta(minutes=5))
            if last_fortune < thirty_minutes and 50 < odd:
                last_fortune = datetime.datetime.now()
                msg = subprocess.check_output("fortune") + ' #fortune'
                bot.send_message(update.message.chat.id, msg)
        except KeyboardInterrupt:
            # Allow ctrl-c.
            raise KeyboardInterrupt
        except Exception as e:
            print "---\nException: "
            print e
            traceback.print_exc()
            pass
Esempio n. 17
0
File: main.py Progetto: ASrey/nitsh
def main():
    try:
        with open('API_KEY', 'r') as f:
            api_key = f.read().replace('\n', '')
    except IOError:
        print "please write the api key in file `API_KEY`"
        exit(1)

    bot = TelegramBot(api_key)
    bot.update_bot_info().wait()
    print(bot.username)

    last_update_id = int(0)
    while True:
        try:
            updates = bot.get_updates(offset=last_update_id+1, timeout=5).wait()
            for update in updates:
                last_update_id = update.update_id
                print(update)
                process_update(bot, update)
            global rems
            for rem in rems:
                if rem.when < datetime.now():
                    bot.send_message(rem.chatid, "=== RAPPEL ===\n\n" +
                            unicode(rem.what))
                    print "removing reminder " + str(rem.id)
                    rems = [r for r in rems if r.id != rem.id]
                    print "rems = " + str(rems)

        except KeyboardInterrupt:
            # Allow ctrl-c.
            raise KeyboardInterrupt
        except Exception as e:
            print "---\nException: "
            print e
            traceback.print_exc()
            pass
Esempio n. 18
0
class DevopsBot:
    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()

    def _monitor():
        print("Monitor")

    def _listen():
        print("Listen")

    def new_user(self, name, lastname, userid):
        # Insert a row of data
        strr="INSERT INTO Telegram VALUES (\""+name+"\",\""+lastname+"\",\""+str(userid)+"\")"
        print(strr)
        # Save (commit) the changes
        try:
            self.c.execute(strr)
            self.conn.commit()
            self._send_message(userid, "Welcome, "+name+" "+lastname)
        except Exception as e:# sqlite3.IntegrityError:
            print(e)
            self._send_message(userid, "Thanks, "+name+" "+lastname+". No need to reregister")

    def handle_messages(self):
        # Initialize DB
        self.conn = sqlite3.connect('telegram.db')
        self.c = self.conn.cursor()

        # Create tables
        self.c.execute('''create table if not exists Telegram (name STRING, last_name STRING, userid STRING UNIQUE)''')

        while True:
            print ("Waiting for message in queue")
            message = self.queue.get()
            user_info = message[1]
            user_id = user_info[0]
            first_name = user_info[1]
            last_name = user_info[2]
            if last_name is None:
                last_name = "N/A"
            print ("Got and handle message "+str(message.text))
            res="Command not understood"
            try:
                #Extract the command
                cmd_list = message.text.split()
                if str(message.text) == "/start":
                    self.new_user(first_name, last_name, user_id)
                    continue
                #Replace protocol command with OS command
                cmd = commands.allowable_commands[cmd_list[0]]
                cmd_list[0] = cmd
                runner = Command(cmd_list)
                runner.run(5)
                print("RES "+str(runner.res)+" /RES")
                self._send_message(message.sender.id, runner.res)
            except Exception as e:
                print ("Except: "+str(e))

    def _send_message(self, uid, message):
        self.bot.send_message(int(uid), message, reply_markup=self.reply_markup)

    def listen(self):
        offset=0
        while (True):
            updates = self.bot.get_updates(offset).wait()
            for cnt,update in enumerate(updates):
                offset=update.update_id+1
                print("Putting message: "+str(update.message.text))
                self.queue.put(update.message)
Esempio n. 19
0
class DevopsBot:
    authenticated = False
    auth_token = None
    MESSAGE_TYPE_START = "/start"
    def __init__(self):
        self.bot=None
        self.conn=None
        self.c=None
        self.mem_alert = False
        self.disk_alert = False

        # Initialize DB
        self.conn = sqlite3.connect('telegram.db')
        self.c = self.conn.cursor()
        
        # Create tables
        self.c.execute('''create table if not exists Telegram (name STRING, last_name STRING, userid STRING UNIQUE)''')

        # Initialize bot
        self.bot = TelegramBot('TELEGRAM_BOT_UNIQUE_ID_GOES_HERE')
        self.bot.update_bot_info().wait()

    def new_user(self, name, lastname, userid):
        # Insert a row of data
        print "DEBUG: %s , %s , %s " % (name , lastname, userid)
        strr="INSERT INTO Telegram VALUES (\""+name+"\",\""+lastname+"\",\""+str(userid)+"\")"
        print(strr)
        # Save (commit) the changes
        try:
            self.c.execute(strr)
            self.conn.commit()
            self._send_message(userid, "Welcome, "+name+" "+lastname)
        except:# sqlite3.IntegrityError:
            self._send_message(userid, "Thanks, "+name+" "+lastname+". No need to reregister")


    def _subproc_run(self, cmd, decode=True):
        print(cmd)
        log = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
        if not decode:
            return log.communicate()[0]
        return log.communicate()[0].strip()

    def _handle_message(self,message):
        print(str(message.text))
	if message.text == self.MESSAGE_TYPE_START:
		from random import randint
		rand_seed = randint(1000, 1999)
		send_factor.two_factor_authenticate(rand_seed, str(message.sender.id))
		self._send_message(message.sender.id, "Please enter the number token your received via SMS")
		self.auth_token = str(rand_seed)
		return
	if not self.authenticated and message.text.isdigit():
		if self.auth_token == message.text:
			self.new_user(message.sender.first_name, message.sender.last_name, message.sender.id)
			self.authenticated = True
			return 
		else:
			self._send_message(message.sender.id, 'Wrong token, try again.')
			return
	if not self.authenticated:
		if message.sender.id in self._get_users_list():
			self.authenticated = True
		else:
			self._send_message(message.sender.id, "Please authenticate using /start first.")
			return

        res="Command not understood"
        try:
            cmd_list = message.text.split()
            print(cmd_list)
            print(cmd_list[0])
            print(commands.allowable_commands)
            cmd = commands.allowable_commands[cmd_list[0]]
            cmd_list[0] = cmd
            print "DEBUG: %s" % cmd
            print("FINAL:"+cmd+"END")
            res = self._subproc_run(cmd_list)
            self._send_message(message.sender.id, res)
        except:
            self._send_message(message.sender.id, res)

    def _send_message(self, uid, message):
        self.bot.send_message(int(uid), message)

    def operation_loop(self):
        offset=0
        while (True):
            print(offset)
            updates = self.bot.get_updates(offset).wait()
            for cnt,update in enumerate(updates):
                self._handle_message(update.message)
                offset=update.update_id+1
            self._fire_alert()

    def _get_users_list(self):
        userslist = []
        self.c.execute("SELECT userid FROM Telegram")
        for row in self.c.fetchall():
            userslist.append(row[0])
        return userslist

    def _fire_alert(self):
        self.userlist = self._get_users_list()
        self.memory = os.path.isfile("/tmp/memfile")
        if self.memory is True and self.mem_alert is False:
            self.mem_alert = True
            for user in self.userlist:
                self._send_message(int(user), "Your system is unstable, check out Memory by typing /mem -m")
        
        if self.memory is False and self.mem_alert is True:
            for user in self.userlist:
                self._send_message(int(user), "Your system is now OK, Memory-wise")
                self.mem_alert = False
        
        self.disk_space = os.path.isfile("/tmp/diskfile")
        if self.disk_space is True and self.disk_alert is False:
            self.disk_alert = True
            for user in self.userlist:
                self._send_message(int(user), "Your system is unstable, check out disk_space by typing /df -h")
        
        if self.disk_space is False and self.disk_alert is True:
            for user in self.userlist:
                self._send_message(int(user), "Your system is now OK, Disk-wise")
                self.disk_alert = False
Esempio n. 20
0
def main():
    print '[+] Starting bot...'

    # Read the config file
    print '[+] Reading config file...'
    config = ConfigParser.ConfigParser()
    config.read([os.path.expanduser('./config')])

    # Read data
    bot_name = config.get('bot', 'name')
    bot_token = config.get('bot', 'token')
    user_id = config.get('user', 'allowed')

    # Last mssg id:
    last_id = int(load_last_id())
    print '[+] Last id: %d' % last_id

    # Configure regex
    regex = re.compile('[%s]' % re.escape(string.punctuation))

    # Create bot
    print '[+] Connecting bot...'
    bot = TelegramBot(bot_token)
    bot.update_bot_info().wait()
    print '\tBot connected! Bot name: %s' % bot.username

    # Create media player controllers:
    player = MediaPlayer()
    if not player.connect_to_player():
        print 'Error connecting to player. Exiting...'
        return -1

    # Send special keyboard:
    send_keyboard(bot, user_id)

    while True:
        try:
            updates = bot.get_updates(offset=last_id).wait()

            for update in updates:
                id = update.message.message_id
                update_id = update.update_id
                user = update.message.sender

                chat_id = update.message.chat.id
                text = update.message.text

                if int(update_id) > last_id:
                    last_id = update_id
                    save_last_id(last_id)
                    save_log(id, update_id, chat_id, text)

                    #text = regex.sub('', text)
                    words = text.split()

                    for word in words:
                        # Process commands:
                        if word == '/start':
                            print "New user started the app: " + str(user)

                        # Restricted API
                        if int(user_id) == user.id:
                            if 'Play' in word:
                                print '[+] Play command'
                                player.play()
                            elif 'Pause' in word:
                                print '[+] Pause command'
                                player.pause()
                            elif 'Previous' in word:
                                print '[+] Previous command'
                                player.previous()
                            elif 'Next' in word:
                                print '[+] Next command'
                                player.next()

        except (KeyboardInterrupt, SystemExit):
            print '\nkeyboardinterrupt caught (again)'
            print '\n...Program Stopped Manually!'
            raise
Esempio n. 21
0
class RepeaterStatusBot(object):
    def __init__(self, tg_group, tg_credentials,
                 repeater_info_url, repeater_json_stream_url):
        self.logger = logging.getLogger(__name__)
        self.tg_group = tg_group
        self.tg_credentials = tg_credentials
        self.repeater_json_stream_url = repeater_json_stream_url
        self.repeater_info_url = repeater_info_url
        self.rx_status = {}
        self.statuses = {
            True: 'in',
            False: 'uit',
        }
        self.last_updated = datetime(1970, 1, 1)
        self.RXes = {}
        self.update_rxes()
        self.last_message_send = datetime(1970, 1, 1)
        self._init_telegram()

    def _init_telegram(self):
        self.telegram = TelegramBot(self.tg_credentials)
        self.telegram.update_bot_info().wait()

    def update_rxes(self):
        if datetime.now() - self.last_updated > timedelta(minutes=60):
            self.logger.info('Updating repeater info')
            try:
                repeater_info = requests.get(self.repeater_info_url).json()
            except ValueError:
                repeater_info = {}
            self.last_updated = datetime.now()
            self.RXes = repeater_info.get('rx', {})

    def signal_telegram(self, message, retry=3):
        self.logger.info('Sending via TGL: {msg}'.format(msg=message))
        if retry < 1:
            self.logger.error('Failed sending message, exceeded retries')
            return False
        try:
            result = self.telegram.send_message(self.tg_group, message).wait()
            if not result:
                new_retry = retry - 1
                self.signal_telegram(message, retry=new_retry)
            else:
                return True
        except Exception as error:
            self.logger.error('Caught exception while transmitting message: {type}: {message}'.format(
                type=type(error),
                message=str(error)
            ))
            self._init_telegram()
            new_retry = retry - 1
            return self.signal_telegram(message, retry=new_retry)

    def queue_message(self, receiver, enabled):
        if receiver in self.RXes:
            receiver = self.RXes[receiver]['name']
        msg = '"{receiver} is {status}geschakeld"'.format(
            receiver=receiver, status=self.statuses[enabled]
        )
        self.logger.info('Queueing: {msg}'.format(msg=msg))
        result = self.signal_telegram(msg)

    def run(self):
        for line in requests.get(self.repeater_json_stream_url,
                                 stream=True).iter_lines(1):
            self.logger.debug('Received: {data}'.format(data=line))
            if line.startswith('data: '):
                data = line.split('data: ')[1].strip()
                try:
                    line_json = json.loads(data)
                except Exception as e:
                    self.logger.warn('FAILED (%s): %s', data, e.message)
                else:
                    self.update_rxes()
                    if line_json.get('event') == 'Voter:sql_state':
                        for rx in line_json.get('rx', []).keys():
                            if rx not in self.rx_status:
                                self.rx_status[rx] = None
                            status = line_json['rx'][rx]['sql'] != "off"
                            if self.rx_status[rx] is not None and \
                                    self.rx_status[rx] != status:
                                self.queue_message(rx, status)
                            self.rx_status[rx] = status
Esempio n. 22
0
def main():
    bot = TelegramBot(token)  #Connect with the bot
    bot.update_bot_info().wait()
    print("botUsername: "******"\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)

    def layer9(bot, last_update_id, usr, pwd, dest, sub, content,
               filesToSend):  # Send mail with or without files
        print("\n Layer 9\n")
        while True:
            updates = bot.get_updates(offset=last_update_id).wait()
            try:
                for update in updates:
                    if int(update.update_id) > int(last_update_id):
                        last_update_id = update.update_id
                        print("last_update_id: ", last_update_id)
                        process_message_layer9(bot, update, last_update_id,
                                               usr, pwd, dest, sub, content,
                                               filesToSend)
                        continue
                continue
            except Exception:
                ex = None
                print(traceback.format_exc())
                continue

    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)

    def layer8(bot, last_update_id, usr, pwd, dest, sub,
               content):  # Send mail with or without files
        print("\n Layer 8\n")
        while True:
            updates = bot.get_updates(offset=last_update_id).wait()
            try:
                for update in updates:
                    if int(update.update_id) > int(last_update_id):
                        last_update_id = update.update_id
                        print("last_update_id: ", last_update_id)
                        process_message_layer8(bot, update, last_update_id,
                                               usr, pwd, dest, sub, content)
                        continue
                continue
            except Exception:
                ex = None
                print(traceback.format_exc())
                continue

    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)

    def layer7(bot, last_update_id, usr, pwd, dest, sub):  # Content
        print("\n Layer 7\n")
        while True:
            updates = bot.get_updates(offset=last_update_id).wait()
            try:
                for update in updates:
                    if int(update.update_id) > int(last_update_id):
                        last_update_id = update.update_id
                        print("last_update_id: ", last_update_id)
                        process_message_layer7(bot, update, last_update_id,
                                               usr, pwd, dest, sub)
                        continue
                continue
            except Exception:
                ex = None
                print(traceback.format_exc())
                continue

    def process_message_layer6(bot, u, last_update_id, usr, pwd, dest):

        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 6")
                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("Send me the body, Layer 6")
                keyboard = [['Back']]
                reply_markup = ReplyKeyboardMarkup.create(keyboard)
                bot.send_message(chat_id,
                                 'Send me the body',
                                 reply_markup=reply_markup).wait()
                layer7(bot, last_update_id, usr, pwd, dest, message)

        else:
            print("Select an option, Layer 6")
            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)

    def layer6(bot, last_update_id, usr, pwd, dest):  #Subject
        print("\n Layer 6\n")
        while True:
            updates = bot.get_updates(offset=last_update_id).wait()
            try:
                for update in updates:
                    if int(update.update_id) > int(last_update_id):
                        last_update_id = update.update_id
                        print("last_update_id: ", last_update_id)
                        process_message_layer6(bot, update, last_update_id,
                                               usr, pwd, dest)
                        continue
                continue
            except Exception:
                ex = None
                print(traceback.format_exc())
                continue

    def process_message_layer5(bot, u, last_update_id, usr, pwd):

        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 5")
                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("Send me the subject, Layer 5")
                keyboard = [['Back']]
                reply_markup = ReplyKeyboardMarkup.create(keyboard)
                bot.send_message(chat_id,
                                 'Send me the subject',
                                 reply_markup=reply_markup).wait()
                layer6(bot, last_update_id, usr, pwd, message)

        else:
            print("Select an option, Layer 5")
            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)

    def layer5(bot, last_update_id, usr, pwd):  #Insert mail address
        print("\n Layer 5\n")
        while True:
            updates = bot.get_updates(offset=last_update_id).wait()
            try:
                for update in updates:
                    if int(update.update_id) > int(last_update_id):
                        last_update_id = update.update_id
                        print("last_update_id: ", last_update_id)
                        process_message_layer5(bot, update, last_update_id,
                                               usr, pwd)
                        continue
                continue
            except Exception:
                ex = None
                print(traceback.format_exc())
                continue

    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 layer4(bot, last_update_id, usr,
               pwd):  #Show emails, send email and back
        print("\n Layer 4\n")
        while True:
            updates = bot.get_updates(offset=last_update_id).wait()
            try:
                for update in updates:
                    if int(update.update_id) > int(last_update_id):
                        last_update_id = update.update_id
                        print("last_update_id: ", last_update_id)
                        process_message_layer4(bot, update, last_update_id,
                                               usr, pwd)
                        continue
                continue
            except Exception:
                ex = None
                print(traceback.format_exc())
                continue

    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)

    def layer3(bot, last_update_id):  # Loggin
        print("\n Layer 3\n")
        while True:
            updates = bot.get_updates(offset=last_update_id).wait()
            try:
                for update in updates:
                    if int(update.update_id) > int(last_update_id):
                        last_update_id = update.update_id
                        print("last_update_id: ", last_update_id)
                        process_message_layer3(bot, update, last_update_id)
                        continue
                continue
            except Exception:
                ex = None
                print(traceback.format_exc())
                continue

    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()

    def layer2(bot, last_update_id):  # Loggin or loggout
        print("\n Layer 2\n")
        while True:
            updates = bot.get_updates(offset=last_update_id).wait()
            try:
                for update in updates:
                    if int(update.update_id) > int(last_update_id):
                        last_update_id = update.update_id
                        print("\nlast_update_id: ", last_update_id)
                        process_message_layer2(bot, update, last_update_id)
                        continue
                continue
            except Exception:
                ex = None
                print(traceback.format_exc())
                continue

    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()

    def layer1(bot, last_update_id):  #Welcome layer
        print("\n Layer 1\n")
        while True:  # While for message from this layer, because the user can insert bad text
            updates = bot.get_updates(offset=last_update_id).wait()
            try:
                for update in updates:  #get message data
                    if int(update.update_id) > int(
                            last_update_id):  #if the message is new, process
                        last_update_id = update.update_id
                        print("\nlast_update_id: ", last_update_id)
                        process_message_layer1(
                            bot, update,
                            last_update_id)  # call process message
                        continue
                continue
            except Exception:
                ex = None
                print(traceback.format_exc())
                continue

    layer1(bot, last_update_id)  # Start first layer
Esempio n. 23
0
            elif f['actualFermataType'] == 0:
                output.append(station + "data not available\n")
            else:
                output.append(description)

    message=''
    for s in output:
        message=message+' '+s
    write(message)

"""
Setup the bot
"""

bot = TelegramBot('204368082:AAEfHT1b1pXmBJM3OfbSHUaL5Th30zdsmtI')
bot.update_bot_info().wait()
print(bot.username)

"""
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'],
class AdapterTelegram2Channel(AbstractChannel):

    def __init__(self, token, bot_id, my_user):
        self.token = token.strip()
        self.bot_id = int(bot_id)
        self.my_user = int(my_user)

        self.bot = TelegramBot(self.token)
        self.bot.update_bot_info().wait()

        self.queue = deque()
        self.offset = 0  # Needed for the bot.get_updates method to avoid getting duplicate updates

    def send_text(self, text):
        """
        Send a message to the user
        """
        # Removing the wait method will make sending multiple messages faster, of course, however in practice
        # it is too fast. It gives a better UX with the wait
        self.bot.send_message(self.my_user, text).wait()

    def get_user_messages(self):
        """
        Get updates sent to the bot
        """
        # Because many updates can happen in a short interval, we are going to store them in a queue
        # because to stick to the interface we need to return just one update by function call
        updates = self.bot.get_updates(offset=self.offset).wait()
        [self.queue.append(update) for update in updates if (update and update.message.sender.id != self.bot_id)]

        if len(updates):
            # Re-compute the offset
            self.offset = max([elem.update_id for elem in updates]) + 1

        if len(self.queue):
            # Get the oldest element in the queue
            first_update = self.queue.popleft()
            return first_update.message.text, first_update.message.sender.id
        else:
            return None, None

    def send_pic(self, path2pic):

        with open(path2pic, 'rb') as finput:
            file_info = InputFileInfo(os.path.basename(path2pic), finput, 'image/jpeg')
            input_file = InputFile('photo', file_info)
            self.bot.send_photo(self.my_user, input_file)
            time.sleep(0.5)

    def allowed_user(self, user_id):
        return user_id == self.my_user

    def close(self):
        pass

    def flush(self):
        """
        The purpose of this method is to clean the channel at the beginning of the execution.
        This is to fix a known issue with the usr_cmd_finish command that was left in the channel
        and causes the closing of Alfred every execution. This happens because at the beginning,
        self.offset it's initialized to 0 and many of the previous messages are recovered again
        """

        updates = self.bot.get_updates(offset=self.offset).wait()

        if len(updates):
            # Re-compute the offset
            self.offset = max([elem.update_id for elem in updates]) + 1
Esempio n. 25
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")
Esempio n. 26
0
def main():
    print '[+] Starting bot...'

    # Read the config file
    print '[+] Reading config file...'
    config = ConfigParser.ConfigParser()
    config.read([os.path.expanduser('./config')])

    # Read data
    bot_name = config.get('bot', 'name')
    bot_token = config.get('bot', 'token')
    user_id = config.get('user', 'allowed')

    # Last mssg id:
    last_id = int(load_last_id())
    print '[+] Last id: %d' % last_id

    # Configure regex
    regex = re.compile('[%s]' % re.escape(string.punctuation))

    # Create bot
    print '[+] Connecting bot...'
    bot = TelegramBot(bot_token)
    bot.update_bot_info().wait()

    print '\tBot connected! Bot name: %s' % bot.username

    # Connect to hardware
    interface = SerialInterface()
    if platform.system() == 'Windows' :
        interface.connect('COM3', 19200)
    else:
        interface.connect('/dev/ttyUSB0', 19200)

    # Send special keyboard:
    send_keyboard(bot, user_id)

    print bot

    while True:
        try:
            updates = bot.get_updates(offset=last_id).wait()
            #print updates[0].message.sender
            #print updates[0].message.message_id
            #print "-------------------------------"

            itera = 0
            for update in updates:

                #print len(update.message)
                if update.message is not None:

                    #print update.message.text
                    #print "*************************** iteration: "

                    id = update.message.message_id
                    update_id = update.update_id
                    user = update.message.sender

                    chat_id = update.message.chat.id
                    text = update.message.text

                    if int(update_id) > last_id:
                        last_id = update_id
                        save_last_id(last_id)
                        save_log(id, update_id, chat_id, text)

                        #text = regex.sub('', text)
                        if text:
                            words = text.split()

                            for i, word in enumerate(words):

                                print word

                                # Process commands:
                                if word == '/start':
                                    print "New user started the app: " + str(user)
                                    send_keyboard(bot, chat_id)
                                elif word == '/flag':
                                    if update.message.sender.username  == 'paclema' : interface.sendFlagWave(1)
                                    bot.send_message(chat_id, "Moviendo la bandera " + get_user_name(update.message.sender) + "!")
                                elif word == '/rainbow':
                                    interface.sendRainbow()
                                    break
                                elif word == '/foto':
                                    #interface.sendFlagWave(1)
                                    interface.sendStripColor(0,0,0)
                                    for a in range(30):
                                        interface.sendStripBarColor(0, 2*a, 8.5*a, 0, 0)
                                        t.sleep(0.03)

                                    interface.sendStripColor(0,0,0)
                                    t.sleep(0.2)
                                    interface.sendStripColor(0,0,0)
                                    cam.start()
                                    bot.send_message(chat_id, get_user_name(update.message.sender) + " quiere una foto!")

                                    if platform.system() == 'Windows' :
                                        img = pygame.Surface((640,480))
                                        cam.get_image(img)
                                    else:
                                        img = cam.get_image()

                                    pygame.image.save(img,"./snap_photo.jpg")
                                    pygame.mixer.music.load("./camera_shutter.mp3")
                                    interface.sendStripColor(255,255,255)
                                    pygame.mixer.music.play()

                                    fp = open('snap_photo.jpg', 'rb')
                                    file_info = InputFileInfo('snap_photo.jpg', fp, 'image/jpg')

                                    f = InputFile('photo', file_info)

                                    bot.send_photo(chat_id, photo=f)

                                    cam.stop()
                                    print "[" + t.strftime("%c") + "]" + " Foto enviada de " + get_user_name(update.message.sender, True, True) + "!"
                                    t.sleep(0.3)
                                    interface.sendStripColor(0,0,0)

                                    break
                                else:
                                    bot.send_message(chat_id, "Bad syntax!")
                                    break

                                # Restricted API
                                if int(user_id) == user.id:
                                    if word == '/move':
                                        try:
                                            interface.sendMove(int(words[i+1]))
                                            break
                                        except Exception, e:
                                            print e


        except (KeyboardInterrupt, SystemExit):
            print '\nkeyboardinterrupt caught (again)'
            print '\n...Program Stopped Manually!'
            raise
Esempio n. 27
0
from twx.botapi import TelegramBot

with open('.tokenfile') as inf:
    API_TOKEN = inf.readline().split('=')[1]

print API_TOKEN
bot = TelegramBot(API_TOKEN)
print(bot.update_bot_info().wait())
print(bot)
print "I am a bot : " + str(bot.username)

what_i_can_do = ['/start', '/size']

initial_offset = 0
offsets = []
while offsets == []:
    updates = bot.get_updates(offset=initial_offset).wait()
    for update in updates:
        offsets.append(update.update_id)

chat_start_offset = max(offsets) + 1


def reply_to_chat(bot, chat_id, with_message=''):
    result = bot.send_message(chat_id, with_message).wait()
    return result


def get_dir_size(hdfs_dir):
    with open('size.csv') as inf:
        for line in inf:
Esempio n. 28
0
from twx.botapi import TelegramBot
from random import randint
import re, setup_photos

token = str((open("token.txt", "r")).read()) # get API token

bot = TelegramBot(token) # create bot with the given authorization token
bot.update_bot_info().wait() # setup bot

photos = setup_photos.setup() # defined in setup_photos module

def send_input_location(message) :
	_, longitude, latitude = cur_message.text.split() # unpack array into variables for sending
	bot.send_location(cur_message.chat, float(latitude), float(longitude))
	print "Location sent"

def send_help_text(message) :
	bot.send_message(message.chat, "This is a basic telegram bot. This bot will send a photo if \"dank\" is in the message")
	print "Help message sent"

def send_about_text(message) :
	bot.send_message(message.chat, "This bot is written in Python using a wrapper for the Telegram API written by datamachine")
	print "About message sent"

def send_author_info(message) :
	bot.send_message(message.chat, "Created by: GMCtree")
	print "Author info sent"

def send_meme(message) :
	bot.send_photo(message.chat, photos[randint(0, (len(photos) - 1))])
	print "Photo sent"
def main():

    prewarning_counter = 0
    warning_counter = 0
    alert_counter = 0

    print "[+] Starting bot..."

    # Read the config file
    print "[+] Reading config file..."
    config = ConfigParser.ConfigParser()
    config.read([os.path.expanduser("./config")])

    # Read data
    bot_name = config.get("bot", "name")
    bot_token = config.get("bot", "token")
    user_id = config.get("user", "allowed")

    # Last mssg id:
    last_id = int(load_last_id())
    print "[+] Last id: %d" % last_id

    # Configure regex
    regex = re.compile("[%s]" % re.escape(string.punctuation))

    # Create bot
    print "[+] Conectando tu bot..."
    bot = TelegramBot(bot_token)
    bot.update_bot_info().wait()

    print "\tBot conectado! El nombre de tu bot es: %s" % bot.username

    # Connect to hardware
    interface = SerialInterface()
    if platform.system() == "Windows":
        interface.connect(config.get("system", "port_Windows"), 115200)
    if platform.system() == "Darwin":
        interface.connect(config.get("system", "port_Mac"), 115200)
    else:
        interface.connect(config.get("system", "port_Ubuntu"), 115200)

    # Send special keyboard:
    send_keyboard(bot, user_id)

    print bot

    while True:
        try:
            updates = bot.get_updates(offset=last_id).wait()
            # print updates[0].message.sender
            # print "-------------------------------"

            for update in updates:

                id = update.message.message_id
                update_id = update.update_id
                user = update.message.sender

                chat_id = update.message.chat.id
                text = update.message.text

                if int(update_id) > last_id:
                    last_id = update_id
                    save_last_id(last_id)
                    save_log(id, update_id, chat_id, text)

                    # text = regex.sub('', text)
                    if text:
                        words = text.split()

                        for i, word in enumerate(words):
                            # Process commands:
                            if word == "/start":
                                print "New user started the app: " + str(user)
                                send_keyboard(bot, chat_id)
                            elif word == "/pollution":

                                # Acceso al html
                                d = pq(
                                    url="http://www.mambiente.munimadrid.es/opencms/opencms/calaire/consulta/Gases_y_particulas/informegaseshorarios.html?__locale=es"
                                )

                                # Selection of data date
                                date_data = d("span[class=tabla_titulo_fecha]")
                                date_data = date_data.text()
                                # print (date_data)

                                # Selection of station name
                                station_name = d('td[class="primertd"]')
                                station_name = station_name.append("**")
                                station_name = station_name.text()
                                station_name = station_name.split("**")
                                # print(station_name)

                                del station_name[0]  # Delete the first empty element of  the list

                                # Selection of all the N02 data
                                no2rawdata = d('td[headers="NO2"]')
                                no2data = no2rawdata.text()
                                no2data = no2data.replace("-", "0")  # Replaces no data with a 0
                                no2data = no2data.split(" ")
                                no2data = map(int, no2data)  # int conversion

                                # Info output
                                print ("Contaminacion de NO2 en Madrid-Fecha: " + date_data)
                                bot.send_message(chat_id, "\n\nContaminacion de NO2 en Madrid-Fecha: " + date_data)
                                t.sleep(3)

                                for x in range(len(no2data)):
                                    if no2data[x] > 400:
                                        print ("\n")
                                        print (
                                            station_name[x]
                                            + ": "
                                            + str(no2data[x])
                                            + " microgramos/metro cubico"
                                            + "-POSIBLE ALERTA POR POLUCION"
                                        )
                                        bot.send_message(
                                            chat_id,
                                            station_name[x]
                                            + ": "
                                            + str(no2data[x])
                                            + " microgramos/metro cubico"
                                            + "-POSIBLE ALERTA POR POLUCION",
                                        )
                                        alert_counter = alert_counter + 1
                                    elif no2data[x] > 250:
                                        print ("\n")
                                        print (
                                            station_name[x]
                                            + ": "
                                            + str(no2data[x])
                                            + " microgramos/metro cubico"
                                            + "-POSIBLE AVISO POR POLUCION"
                                        )
                                        bot.send_message(
                                            chat_id,
                                            station_name[x]
                                            + ": "
                                            + str(no2data[x])
                                            + " microgramos/metro cubico"
                                            + "-POSIBLE AVISO POR POLUCION",
                                        )
                                        warning_counter = warning_counter + 1
                                    elif no2data[x] > 200:
                                        print ("\n")
                                        print (
                                            station_name[x]
                                            + ": "
                                            + str(no2data[x])
                                            + " microgramos/metro cubico"
                                            + "-POSIBLE PREAVISO POR POLUCION"
                                        )
                                        bot.send_message(
                                            chat_id,
                                            station_name[x]
                                            + ": "
                                            + str(no2data[x])
                                            + " microgramos/metro cubico"
                                            + "-POSIBLE PREAVISO POR POLUCION",
                                        )
                                        prewarning_counter = prewarning_counter + 1
                                    else:
                                        print ("\n")
                                        print (station_name[x] + ": " + str(no2data[x]) + " microgramos/metro cubico")
                                        bot.send_message(
                                            chat_id,
                                            station_name[x] + ": " + str(no2data[x]) + " microgramos/metro cubico",
                                        )

                                        # Zowi pollution reaction
                                if alert_counter > 0:
                                    interface.gestureZowi("sad")
                                elif warning_counter > 0:
                                    interface.gestureZowi("angry")
                                elif prewarning_counter > 0:
                                    interface.gestureZowi("nervous")
                                else:
                                    interface.gestureZowi("superhappy")

                                    # interface.testZowi()
                                    # bot.send_message(chat_id, "Probando el bot!")
                                break

        except (KeyboardInterrupt, SystemExit):
            print "\nkeyboardinterrupt caught (again)"
            print "\n...Program Stopped Manually!"
            raise
Esempio n. 30
0
def main():
    print "[+] Starting bot..."

    # Read the config file
    print "[+] Reading config file..."
    config = ConfigParser.ConfigParser()
    config.read([os.path.expanduser("./config")])

    # Read data
    bot_name = config.get("bot", "name")
    bot_token = config.get("bot", "token")
    user_id = config.get("user", "allowed")

    # Last mssg id:
    last_id = int(load_last_id())
    print "[+] Last id: %d" % last_id

    # Configure regex
    regex = re.compile("[%s]" % re.escape(string.punctuation))

    # Create bot
    print "[+] Connecting bot..."
    bot = TelegramBot(bot_token)
    bot.update_bot_info().wait()
    print "\tBot connected! Bot name: %s" % bot.username

    # Connect to hardware
    interface = SerialInterface()
    interface.connect("/dev/ttyUSB0", 9600)

    # Send special keyboard:
    send_keyboard(bot, user_id)

    while True:
        try:
            updates = bot.get_updates(offset=last_id).wait()

            for update in updates:
                id = update.message.message_id
                update_id = update.update_id
                user = update.message.sender

                chat_id = update.message.chat.id
                text = update.message.text

                if int(update_id) > last_id:
                    last_id = update_id
                    save_last_id(last_id)
                    save_log(id, update_id, chat_id, text)

                    # text = regex.sub('', text)
                    if text:
                        words = text.split()

                        for i, word in enumerate(words):
                            # Process commands:
                            if word == "/start":
                                print "New user started the app: " + str(user)
                                send_keyboard(bot, chat_id)
                            elif word == "/flag":
                                if words[i + 1] == "up":
                                    interface.sendMove(90)
                                    break
                                elif words[i + 1] == "down":
                                    interface.sendMove(0)
                                    break
                                else:
                                    bot.send_message(chat_id, "Bad syntax!")
                                    break

                            # Restricted API
                            if int(user_id) == user.id:
                                if word == "/move":
                                    try:
                                        interface.sendMove(int(words[i + 1]))
                                        break
                                    except Exception, e:
                                        print e

        except (KeyboardInterrupt, SystemExit):
            print "\nkeyboardinterrupt caught (again)"
            print "\n...Program Stopped Manually!"
            raise
Esempio n. 31
0
def init_bot(init_token):
    bot = TelegramBot(init_token)
    bot.update_bot_info().wait()
    return bot
Esempio n. 32
0
from twx.botapi import TelegramBot

with open('.tokenfile') as inf:
    API_TOKEN = inf.readline().split('=')[1]

print API_TOKEN
bot = TelegramBot(API_TOKEN)
print(bot.update_bot_info().wait())
print(bot)
print "I am a bot : " + str(bot.username)

what_i_can_do = ['/start', '/size']

initial_offset = 0
offsets = []
while offsets == []:
    updates = bot.get_updates(offset=initial_offset).wait()
    for update in updates:
        offsets.append(update.update_id)

chat_start_offset = max(offsets) + 1


def reply_to_chat(bot, chat_id, with_message=''):
    result = bot.send_message(chat_id, with_message).wait()
    return result

def get_dir_size(hdfs_dir):
    with open('size.csv') as inf:
        for line in inf:
            if line.startwith(hdfs_dir + ','):
def main():

    prewarning_counter=0
    warning_counter=0
    alert_counter=0
    day_alert_flag=False

    print '[+] Starting bot...'

    # Read the config file
    print '[+] Reading config file...'
    config = ConfigParser.ConfigParser()
    config.read([os.path.expanduser('./config')])

    # Read data
    bot_name = config.get('bot', 'name')
    bot_token = config.get('bot', 'token')
    #user_id=[]
    #user_id.append(config.get('user', 'allowed'))
    #for x in user_id:
    #	print(x)

    #misiones.append(nuevo_elemento)
    user_id= config.get('user', 'allowed')

    # Last mssg id:
    last_id = int(load_last_id())
    print '[+] Last id: %d' % last_id

    # Configure regex
    regex = re.compile('[%s]' % re.escape(string.punctuation))

    # Create bot
    print '[+] Conectando tu bot...'
    bot = TelegramBot(bot_token)
    bot.update_bot_info().wait()

    print '\tBot conectado! El nombre de tu bot es: %s' % bot.username

    # Send special keyboard:
    send_keyboard(bot, user_id)
    print bot

    global chat_id
    chat_id=[]

    while True:
        try:
            updates = bot.get_updates(offset=last_id).wait()
            #print updates[0].message.sender
            #print "-------------------------------"

	    time_notify=t.asctime(t.localtime(t.time()) )
	    #print(time_notify)
	    time_notify=time_notify.split(" ");
	    #print(time_notify)
	    main_hour=time_notify[3]
	    main_hour=main_hour.split(":")
	    main_hour=map(int, main_hour)
	    #print(main_hour)


            for update in updates:#arroja un error de tiempo

                id = update.message.message_id
                update_id = update.update_id
                user = update.message.sender


		#file_chat_id=open('chat_id.txt','r')
		#chat_id_aux=file_chat_id.read()
		#print(chat_id_aux)
		#chat_id.append(update.message.chat.id)
		#for x in chat_id:
		#	print (x)
                active_chat_id = update.message.chat.id
                #chat_id=8999128
		#chat_id2=97335854
		text = update.message.text


		#if main_hour[0]==00 and main_hour[1]==00 and main_hour[2]==00:#Reset the day_alert_flag
		#if main_hour[2]==50:#Reset the day_alert_flag
			#day_alert_flag=False
			#print("FLAG RESETEADA A FALSE")
		if (main_hour[0]==9 and main_hour[1]==30 and main_hour[2]==00) or (main_hour[0]==12 and main_hour[1]==30 and main_hour[2]==00) or (main_hour[0]==14 and main_hour[1]==30 and main_hour[2]==00) :
		#if main_hour[2]==00: #and main_hour[2]==00 :# and main_hour[2]==00:
				#day_alert_flag=True #This day the alert is done

				#Acceso al html
				d = pq(url='http://www.mambiente.munimadrid.es/opencms/opencms/calaire/consulta/Gases_y_particulas/informegaseshorarios.html?__locale=es')

				#Selection of data date
				date_data=d('span[class=tabla_titulo_fecha]')
				date_data=date_data.text()
				#print (date_data)

				#Selection of station name
				station_name=d('td[class="primertd"]')
				station_name=station_name.append("**")
				station_name=station_name.text()
				station_name=station_name.split("**")
				#print(station_name)
				del station_name[0] #Delete the first empty element of  the list

				#Selection of all the N02 data
				no2rawdata=d('td[headers="NO2"]')
				no2data=no2rawdata.text()
				no2data=no2data.replace("-","0")#Replaces no data with a 0
				no2data=no2data.split(" ")
				no2data = map(int, no2data) #int conversion


				#Info output
				print(date_data+" Buenos dias la media de NO2 en Madrid es: ")
				#bot.send_message(chat_id, "\n\n"+date_data+"\n\nBuenos dias la media de NO2 en Madrid es: ")
				for x in chat_id:
					bot.send_message(x, "\n\n"+date_data+"\n\nLa media de NO2 en Madrid es: ")

				t.sleep(3);
				#print(no2data[-1])

				if no2data[-1]>400:
					print("\n")
					print(station_name[-2]+": "+str(no2data[-1])+" microgramos/metro cubico"+"-POSIBLE ALERTA POR POLUCION")
					for x in chat_id:
						bot.send_message(x, station_name[-2]+": "+str(no2data[-1])+" microgramos/metro cubico"+"-POSIBLE ALERTA POR POLUCION")
					alert_counter=alert_counter+1
				elif no2data[-1]>250:
					print("\n")
					print(station_name[-2]+": "+str(no2data[-1])+" microgramos/metro cubico"+"-POSIBLE AVISO POR POLUCION")
					for x in chat_id:
						bot.send_message(x, station_name[-2]+": "+str(no2data[-1])+" microgramos/metro cubico"+"-POSIBLE AVISO POR POLUCION")
					warning_counter=warning_counter+1
				elif no2data[-1]>200:
					print("\n")
					print(station_name[-2]+": "+str(no2data[-1])+" microgramos/metro cubico"+"-POSIBLE PREAVISO POR POLUCION")
					for x in chat_id:
						bot.send_message(x, station_name[-2]+": "+str(no2data[-1])+" microgramos/metro cubico"+"-POSIBLE PREAVISO POR POLUCION")
					prewarning_counter=prewarning_counter+1
				else:
					print("\n")
					print(station_name[-2]+": "+str(no2data[-1])+" microgramos/metro cubico")
					for x in chat_id:
						bot.send_message(x, station_name[-2]+": "+str(no2data[-1])+" microgramos/metro cubico")
                if int(update_id) > last_id:
                    last_id = update_id
                    save_last_id(last_id)
                    save_log(id, update_id, chat_id, text) #chat_id pertece al usuario ultimo almacenado

                    #text = regex.sub('', text)
                    if text:
                        words = text.split()

                        for i, word in enumerate(words):
                            # Process commands:
                            if word == '/start':
                                print "New user started the app: " + str(user)
				vara=user[0]
				#print("vara: "+str(vara))
				chat_id.append(vara)

				for x in chat_id:
					print(x)

				send_keyboard(bot, active_chat_id)
				#send_keyboard(bot, chat_id)
				#send_keyboard(bot, chat_id2)
                            elif word == '/polution':
				#Acceso al html
				d = pq(url='http://www.mambiente.munimadrid.es/opencms/opencms/calaire/consulta/Gases_y_particulas/informegaseshorarios.html?__locale=es')

				#Selection of data date
				date_data=d('span[class=tabla_titulo_fecha]')
				date_data=date_data.text()
				#print (date_data)

				#Selection of station name
				station_name=d('td[class="primertd"]')
				station_name=station_name.append("**")
				station_name=station_name.text()
				station_name=station_name.split("**")
				#print(station_name)
				del station_name[0] #Delete the first empty element of  the list

				#Selection of all the N02 data
				no2rawdata=d('td[headers="NO2"]')
				no2data=no2rawdata.text()
				no2data=no2data.replace("-","0")#Replaces no data with a 0
				no2data=no2data.split(" ")
				no2data = map(int, no2data) #int conversion


				#Info output
				print("Contaminacion de NO2 en Madrid-Fecha: "+date_data)

				bot.send_message(active_chat_id, "\n\nContaminacion de NO2 en Madrid-Fecha: "+date_data)
				t.sleep(3);

				for x in range(len(no2data)):
					if no2data[x]>400:
						print("\n")
						print(station_name[x]+": "+str(no2data[x])+" microgramos/metro cubico"+"-POSIBLE ALERTA POR POLUCION")
						bot.send_message(active_chat_id, station_name[x]+": "+str(no2data[x])+" microgramos/metro cubico"+"-POSIBLE ALERTA POR POLUCION")
						alert_counter=alert_counter+1
					elif no2data[x]>250:
						print("\n")
						print(station_name[x]+": "+str(no2data[x])+" microgramos/metro cubico"+"-POSIBLE AVISO POR POLUCION")
						bot.send_message(active_chat_id, station_name[x]+": "+str(no2data[x])+" microgramos/metro cubico"+"-POSIBLE AVISO POR POLUCION")
						warning_counter=warning_counter+1
					elif no2data[x]>200:
						print("\n")
						print(station_name[x]+": "+str(no2data[x])+" microgramos/metro cubico"+"-POSIBLE PREAVISO POR POLUCION")
						prewarning_counter=prewarning_counter+1
					else:
						print("\n")
						print(station_name[x]+": "+str(no2data[x])+" microgramos/metro cubico")
						bot.send_message(active_chat_id, station_name[x]+": "+str(no2data[x])+" microgramos/metro cubico")
				break


        except (KeyboardInterrupt, SystemExit):
            print '\nkeyboardinterrupt caught (again)'
            print '\n...Program Stopped Manually!'
	    #main()
            raise
Esempio n. 34
0
def main():
    print '[+] Starting bot...'

    # Read the config file
    print '[+] Reading config file...'
    config = ConfigParser.ConfigParser()
    config.read([os.path.expanduser('./config')])

    # Read data
    bot_name = config.get('bot', 'name')
    bot_token = config.get('bot', 'token')
    user_id = config.get('user', 'allowed')

    # Last mssg id:
    last_id = int(load_last_id())
    print '[+] Last id: %d' % last_id

    # Configure regex
    regex = re.compile('[%s]' % re.escape(string.punctuation))

    # Create bot
    print '[+] Connecting bot...'
    bot = TelegramBot(bot_token)
    bot.update_bot_info().wait()
    print '\tBot connected! Bot name: %s' % bot.username

    # Create media player controllers:
    player = MediaPlayer()
    if not player.connect_to_player():
        print 'Error connecting to player. Exiting...'
        return -1

    # Send special keyboard:
    send_keyboard(bot, user_id)

    while True:
        try:
            updates = bot.get_updates(offset=last_id).wait()

            for update in updates:
                id = update.message.message_id
                update_id = update.update_id
                user = update.message.sender

                chat_id = update.message.chat.id
                text = update.message.text

                if int(update_id) > last_id:
                    last_id = update_id
                    save_last_id(last_id)
                    save_log(id, update_id, chat_id, text)

                    #text = regex.sub('', text)
                    words = text.split()

                    for word in words:
                        # Process commands:
                        if word == '/start':
                            print "New user started the app: " + str(user)

                        # Restricted API
                        if int(user_id) == user.id:
                            if 'Play' in  word:
                                print '[+] Play command'
                                player.play()
                            elif 'Pause' in word:
                                print '[+] Pause command'
                                player.pause()
                            elif 'Previous' in word:
                                print '[+] Previous command'
                                player.previous()
                            elif 'Next' in word:
                                print '[+] Next command'
                                player.next()

        except (KeyboardInterrupt, SystemExit):
            print '\nkeyboardinterrupt caught (again)'
            print '\n...Program Stopped Manually!'
            raise
Esempio n. 35
0
from twx.botapi import TelegramBot
import cfg

token = cfg.readcfg('config.yml')['token']
channel = cfg.readcfg('config.yml')['channel']
bot = TelegramBot(token)
bot.update_bot_info()


def sendtextonly(message):
    try:
        bot.send_message(channel, message, disable_web_page_preview=True)
    except Exception:
        sendtextonly(message)


def sendtextandphoto(photourl, message):
    try:
        bot.send_photo(channel, photourl).wait()
        bot.send_message(channel, message, disable_web_page_preview=True)
    except Exception:
        sendtextandphoto(photourl, message)


def sendtextandvideo(message):
    try:
        bot.send_message(channel, message, parse_mode='HTML')
    except Exception:
        sendtextandvideo(message)

Esempio n. 36
0
class AssisBot:
    def __init__(self):
        config = ConfigObj(fileInit)
        self.Listen = False
        self.IA = AssisIA()
        self.apikey = config['bot']['apikey']
        self.name = config['bot']['name']
        self.adminChatId = config['bot']['adminChatId']
        self.updatesDelay = float(config['bot']['delay'])
        self.Telegram = TelegramBot(self.apikey)
        self.Telegram.update_bot_info().wait()
        self.ListenerUsers = threading.Thread(target=self.listeningUser,
                                              daemon=True)

    def changeApiKey(self, apikey):
        self.Telegram = TelegramBot(apikey)
        self.Telegram.update_bot_info().wait()

    def startToListen(self):
        self.Listen = True
        if (not self.ListenerUsers.is_alive()):
            self.ListenerUsers.start()
        logging.info('Corriendo programa: ' +
                     str(self.ListenerUsers.is_alive()))

    def stopToListen(self):
        if self.ListenerUsers.is_alive():
            self.Listen = False
            logging.info('Deja de escuchar')
        else:
            logging.info("No hay programa que detener")

    def listeningUser(self):
        logging.info("Inicio subproceso de escucha")
        updates = self.Telegram.get_updates().wait()
        last_updateId = (updates[-1].update_id) if (len(updates) > 0) else 0
        while True:
            try:
                updates = self.Telegram.get_updates(offset=last_updateId + 1,
                                                    timeout=100).wait()
                logging.info("Updates: " + str(len(updates)))
                if len(updates) > 0:
                    if self.Listen:  #debería responder? (Es una bandera)
                        res = self.IA.getResponse(updates[0])
                        if (res['Options'] == False):
                            self.Telegram.send_message(
                                updates[0].message.chat.id,
                                res['Text']).wait()
                            if (res['Image']):
                                fp = open(res['ImagePath'], 'rb')
                                file_info = InputFileInfo(
                                    'NOCData.png', fp, 'image/png')
                                chart = InputFile('photo', file_info)
                                self.Telegram.send_photo(
                                    updates[0].message.chat.id,
                                    photo=chart).wait()
                            if (res['Document']):
                                doc = open(res['DocumentPath'], 'rb')
                                file_info = InputFileInfo(
                                    'Details.csv', doc, 'csv')
                                document = InputFile('document', file_info)
                                self.Telegram.send_document(
                                    updates[0].message.chat.id,
                                    document=document).wait()

                        else:
                            keyboard = res['Options']
                            reply_markup = ReplyKeyboardMarkup.create(keyboard)
                            msg = 'Seleccione el grupo para ver los detalles'
                            self.Telegram.send_message(
                                updates[0].message.chat.id,
                                msg,
                                reply_markup=reply_markup).wait()

                        dataLoadDelta = (datetime.now() - datetime.strptime(
                            res['UpdateTime'], '%a %b %d %H:%M:%S %Y'))
                        dataLoadTimeHours = dataLoadDelta.seconds / 3600
                        maxHours = 3
                        if (dataLoadTimeHours >= maxHours):
                            msg = "Carga de Datos igual a " + str(
                                dataLoadDelta
                            ) + " horas. Revisar BD desactualizada"
                            self.Telegram.send_message(self.adminChatId,
                                                       msg).wait()
                            msg = "Última actualización mayor a 02:30 horas. BD desactualizada, contactar a Administrador"
                            self.Telegram.send_message(
                                updates[0].message.chat.id, msg).wait()

                    logging.info('Nuevo mensaje: ' + updates[0].message.text)
                    last_updateId = updates[0].update_id
            except Exception as ex:
                template = "Un error del tipo {0} ha ocurrido, por favor contactar Administrador. Detalles:\n{1!r}"
                excepMsg = template.format(type(ex).__name__, ex.args)
                logging.error("Error generado en el Bot")
                logging.error(excepMsg)
                if (
                        type(ex).__name__ == "FileNotFoundError"
                ):  #Error no se ha encontrado el archivo, contestar con el error
                    self.Telegram.send_message(updates[0].message.chat.id,
                                               excepMsg).wait()
                    self.Telegram.send_message(self.adminChatId,
                                               excepMsg).wait()
                    last_updateId = updates[0].update_id
                time.sleep(10)
Esempio n. 37
0
nse = Nse()
q = nse.get_quote('infy')

#pprint(q)

str1 = str(q)

r = api.request('statuses/update', {'status': TWEET_TEXT})

print('SUCCESS' if r.status_code == 200 else 'FAILURE')
"""
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)
"""
Esempio n. 38
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")
Esempio n. 39
0
from time import sleep
from twx.botapi import TelegramBot, ReplyKeyboardMarkup #Telegram BotAPI
import traceback
from pyowm import OWM #Weather API

from config import Config

"""
Setup the bot and the Weather API
"""
c = Config()
TOKEN = c.getToken()
OWMKEY = c.getOWMKEY()

bot = TelegramBot(TOKEN) 
bot.update_bot_info().wait()  #wait for a message
print bot.username 
last_update_id = 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: 
Esempio n. 40
0
class DevopsBot:
    authenticated = False
    auth_token = None
    MESSAGE_TYPE_START = "/start"

    def __init__(self):
        self.bot = None
        self.conn = None
        self.c = None
        self.mem_alert = False
        self.disk_alert = False

        # Initialize DB
        self.conn = sqlite3.connect('telegram.db')
        self.c = self.conn.cursor()

        # Create tables
        self.c.execute(
            '''create table if not exists Telegram (name STRING, last_name STRING, userid STRING UNIQUE)'''
        )

        # Initialize bot
        self.bot = TelegramBot('TELEGRAM_BOT_UNIQUE_ID_GOES_HERE')
        self.bot.update_bot_info().wait()

    def new_user(self, name, lastname, userid):
        # Insert a row of data
        print "DEBUG: %s , %s , %s " % (name, lastname, userid)
        strr = "INSERT INTO Telegram VALUES (\"" + name + "\",\"" + lastname + "\",\"" + str(
            userid) + "\")"
        print(strr)
        # Save (commit) the changes
        try:
            self.c.execute(strr)
            self.conn.commit()
            self._send_message(userid, "Welcome, " + name + " " + lastname)
        except:  # sqlite3.IntegrityError:
            self._send_message(
                userid,
                "Thanks, " + name + " " + lastname + ". No need to reregister")

    def _subproc_run(self, cmd, decode=True):
        print(cmd)
        log = subprocess.Popen(cmd,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.STDOUT)
        if not decode:
            return log.communicate()[0]
        return log.communicate()[0].strip()

    def _handle_message(self, message):
        print(str(message.text))
        if message.text == self.MESSAGE_TYPE_START:
            from random import randint
            rand_seed = randint(1000, 1999)
            send_factor.two_factor_authenticate(rand_seed,
                                                str(message.sender.id))
            self._send_message(
                message.sender.id,
                "Please enter the number token your received via SMS")
            self.auth_token = str(rand_seed)
            return
        if not self.authenticated and message.text.isdigit():
            if self.auth_token == message.text:
                self.new_user(message.sender.first_name,
                              message.sender.last_name, message.sender.id)
                self.authenticated = True
                return
            else:
                self._send_message(message.sender.id,
                                   'Wrong token, try again.')
                return
        if not self.authenticated:
            if message.sender.id in self._get_users_list():
                self.authenticated = True
            else:
                self._send_message(message.sender.id,
                                   "Please authenticate using /start first.")
                return

        res = "Command not understood"
        try:
            cmd_list = message.text.split()
            print(cmd_list)
            print(cmd_list[0])
            print(commands.allowable_commands)
            cmd = commands.allowable_commands[cmd_list[0]]
            cmd_list[0] = cmd
            print "DEBUG: %s" % cmd
            print("FINAL:" + cmd + "END")
            res = self._subproc_run(cmd_list)
            self._send_message(message.sender.id, res)
        except:
            self._send_message(message.sender.id, res)

    def _send_message(self, uid, message):
        self.bot.send_message(int(uid), message)

    def operation_loop(self):
        offset = 0
        while (True):
            print(offset)
            updates = self.bot.get_updates(offset).wait()
            for cnt, update in enumerate(updates):
                self._handle_message(update.message)
                offset = update.update_id + 1
            self._fire_alert()

    def _get_users_list(self):
        userslist = []
        self.c.execute("SELECT userid FROM Telegram")
        for row in self.c.fetchall():
            userslist.append(row[0])
        return userslist

    def _fire_alert(self):
        self.userlist = self._get_users_list()
        self.memory = os.path.isfile("/tmp/memfile")
        if self.memory is True and self.mem_alert is False:
            self.mem_alert = True
            for user in self.userlist:
                self._send_message(
                    int(user),
                    "Your system is unstable, check out Memory by typing /mem -m"
                )

        if self.memory is False and self.mem_alert is True:
            for user in self.userlist:
                self._send_message(int(user),
                                   "Your system is now OK, Memory-wise")
                self.mem_alert = False

        self.disk_space = os.path.isfile("/tmp/diskfile")
        if self.disk_space is True and self.disk_alert is False:
            self.disk_alert = True
            for user in self.userlist:
                self._send_message(
                    int(user),
                    "Your system is unstable, check out disk_space by typing /df -h"
                )

        if self.disk_space is False and self.disk_alert is True:
            for user in self.userlist:
                self._send_message(int(user),
                                   "Your system is now OK, Disk-wise")
                self.disk_alert = False