class MessageServer(object): def __init__(self): self.thread_map = {} self.bot = TelegramBot(API_TOKEN) self.updates = set(self.bot.get_updates().wait()) def poll(self): while True: del_list = [] for name in self.thread_map: thread = self.thread_map[name] if thread.finished_event.isSet(): del_list.append(name) for x in del_list: del self.thread_map[x] print("<{time}> Waiting....".format(time=datetime.now().time())) updates = set(self.bot.get_updates().wait()) new_updates = updates.difference(self.updates) for update in new_updates: print("<{time}> Received new message....".format(time=datetime.now().time())) user = update.message.sender.id if user in self.thread_map: print("<{time}> Dispatching message to thread....".format(time=datetime.now().time())) self.thread_map[user]._add_to_queue(update.message.text) else: print("<{time}> Creating new thread....".format(time=datetime.now().time())) user_thread = Worker(user) self.thread_map[user] = user_thread print("<{time}> Dispatching message to thread....".format(time=datetime.now().time())) user_thread._add_to_queue(update.message.text) self.updates.add(update)
def crawl(self, user): tb = Telegram(user.get_telegram_credentials()) seen_tg = user.get_seen_tg() try: updates = tb.get_updates(offset=seen_tg + 1, allowed_updates="message").wait() except TypeError: updates = tb.get_updates().wait() reports = [] if updates == None: return reports for update in updates: # return when telegram returns an error code if update in [303, 404, 420, 500, 502]: return reports if isinstance(update, int): try: logger.error("City " + str(user.uid) + ": Unknown Telegram error code: " + str(update) + " - " + str(updates[1])) except TypeError: logger.error("Unknown Telegram error code: " + str(update)) return reports user.save_seen_tg(update.update_id) if update.message.text.lower() == "/start": user.add_telegram_subscribers(update.message.sender.id) tb.send_message( update.message.sender.id, "You are now subscribed to report notifications.") # TODO: /start message should be set in frontend elif update.message.text.lower() == "/stop": user.remove_telegram_subscribers(update.message.sender.id) tb.send_message( update.message.sender.id, "You are now unsubscribed from report notifications.") # TODO: /stop message should be set in frontend elif update.message.text.lower() == "/help": tb.send_message( update.message.sender.id, "Send reports here to share them with other users. Use /start and /stop to get reports or not.") # TODO: /help message should be set in frontend else: # set report.author to "" to avoid mailbot crash sender_name = update.message.sender.username if sender_name is None: sender_name = "" reports.append(Report(sender_name, self, update.message.text, None, update.message.date)) return reports
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 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
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)
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
class YoutubeBot(object): api_token = '' def __init__(self): self.bot = TelegramBot(self.api_token) self.bot.get_me() last_updates = self.bot.get_updates(offset=0).wait() try: self.last_update_id = list(last_updates)[-1].update_id except IndexError: self.last_update_id = None print 'last update id: {}'.format(self.last_update_id) def process_message(self, message): text = message.message.text chat = message.message.chat text = text.strip().split('&')[0] msg = 'Could not download {}'.format(text) print 'Got message: \33[0;32m{}\33[0m'.format(text) try: self.bot.send_message(chat.id, 'Staring to download') with youtube_dl.YoutubeDL(YDL_OPTS) as ydl: r_code = ydl.download([text]) if r_code == 0: msg = '{} download successfully'.format(text) except Exception: pass self.bot.send_message(chat.id, msg) def run(self): print 'Main loop started' while True: updates = self.bot.get_updates( offset=self.last_update_id).wait() try: for update in updates: if update.update_id > self.last_update_id: self.last_update_id = update.update_id self.process_message(update) except Exception as ex: print traceback.format_exc()
class YoutubeBot(object): api_token = '' def __init__(self): self.bot = TelegramBot(self.api_token) self.bot.get_me() last_updates = self.bot.get_updates(offset=0).wait() try: self.last_update_id = list(last_updates)[-1].update_id except IndexError: self.last_update_id = None print 'last update id: {}'.format(self.last_update_id) def process_message(self, message): text = message.message.text chat = message.message.chat text = text.strip().split('&')[0] msg = 'Could not download {}'.format(text) print 'Got message: \33[0;32m{}\33[0m'.format(text) try: self.bot.send_message(chat.id, 'Staring to download') with youtube_dl.YoutubeDL(YDL_OPTS) as ydl: r_code = ydl.download([text]) if r_code == 0: msg = '{} download successfully'.format(text) except Exception: pass self.bot.send_message(chat.id, msg) def run(self): print 'Main loop started' while True: updates = self.bot.get_updates(offset=self.last_update_id).wait() try: for update in updates: if update.update_id > self.last_update_id: self.last_update_id = update.update_id self.process_message(update) except Exception as ex: print traceback.format_exc()
class Telegram(object): def __init__(self, config, interpreter): super().__init__() self.__interpreter = interpreter self.__logger = logging.getLogger('telegram') logHandler = StreamHandler() logHandler.setLevel(logging.DEBUG) self.__logger.addHandler(logHandler) self.__bot = TelegramBot(config['Telegram']['token']) self.__logger.warning("Bot details: " + str(self.__bot.get_me().wait())) self.__updateOffset = None def send_msg(self, telegram_id, text): self.__bot.send_message(telegram_id, text).wait() def getUpdates(self, dbSession): updates = None try: if self.__updateOffset is not None: updates = self.__bot.get_updates(offset=self.__updateOffset + 1).wait() else: updates = self.__bot.get_updates().wait() if updates is None: raise Exception("No updates have been received due to an error") except: return for update in updates: if hasattr(update, 'message'): self.__logger.warning(str(update.message.sender) + ": " + update.message.text) self.__interpreter.interpret(dbSession, self, update.message.sender, update.message.text.split(' ')) if hasattr(update, 'update_id'): self.__updateOffset = update.update_id def shutdown(self): pass
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)
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
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
# update=update #print("update: ", update) #message_id = update.message.message_id; #first_name = update.message.sender.first_name; #print( "message_id: ", message_id) #print( "name: ", first_name) reply_markup = ForceReply(True, False) #messageFlush(bot) updates = bot.get_updates().wait() while(updates == []): time.sleep(0.5) updates = bot.get_updates().wait() for update in updates: update=update print(update) update_id = update.update_id + 1; print(update_id) print("-------------------------------------------") chat_id = update.message.chat.id; #bot.send_message(chat_id, "Hi Arturo. How are you feeling today?").wait() #bot.send_message(chat_id, "Well Buddy... you could imagine. I am stuck in Adam's laptop. You're out there breathing fresh air, and chcking out the girls.").wait()
class BullsAndCowsNumbersBot(object): token = config.token def __init__(self): self.bot = TelegramBot(self.token) self.bot.get_me() last_updates = self.bot.get_updates(offset=0).wait() try: self.last_update_id = list(last_updates)[-1].update_id except IndexError: self.last_update_id = None print('last update id: {0}'.format(self.last_update_id)) def check_user_answer(self, text): nums = '0123456789' if len(text)!=4: return False else: if not(text[0] in nums) or not(text[1] in nums) or not(text[2] in nums) or not(text[3] in nums): return False else: return True def answer_for_attempt(self, number_for_solve, number_attempt): indexes_in_number_for_solve = [0, 1, 2, 3] indexes_in_number_attempt = [0, 1, 2, 3] number_of_bulls = 0 number_of_cows = 0 # посчитаем количество быков i = 0 while i < 4: if number_for_solve[i] == number_attempt[i]: number_of_bulls = number_of_bulls + 1 indexes_in_number_for_solve.remove(i) indexes_in_number_attempt.remove(i) i = i + 1 # посчитаем количество коров i = 0 while i < 4: if i in indexes_in_number_attempt: for j in indexes_in_number_for_solve: if number_for_solve[j] == number_attempt[i]: number_of_cows = number_of_cows + 1 indexes_in_number_for_solve.remove(j) break i = i + 1 return {'number_of_bulls': number_of_bulls, 'number_of_cows': number_of_cows} def check_is_repeat(self, list_of_attempts, text): for element in list_of_attempts: if element[0] == text: return True return False def process_message(self, message): text = message.message.text chat = message.message.chat text = text.strip() print('{2} Got message: \33[0;32m{0}\33[0m from chat: {1}'.format(text, chat, strftime("%Y-%m-%d %H:%M:%S", gmtime()))) try: if text == '/start': bot_answer = 'Это игра "Быки и коровы"\nИгра состоит в том, что я загадал число, а вам нужно его отгадать за меньшее число попыток.\n\ Чтобы прочитать правила воспользуйтесь командой /help\nИтак, я загадал число. Угадывайте' try: result = mariadb_connector.read_current_game_state(chat.id) num1 = str(random.randint(0, 9)) num2 = str(random.randint(0, 9)) num3 = str(random.randint(0, 9)) num4 = str(random.randint(0, 9)) number_for_solve = ''.join([num1, num2, num3, num4]) if (result == None): mariadb_connector.write_new_user(chat.id, number_for_solve) else: mariadb_connector.write_current_game_state(chat.id, number_for_solve, None) self.bot.send_message(chat.id, bot_answer) except Exception: self.bot.send_message(chat.id, 'Unknow error. Sorry.') elif text == '/help': bot_answer = 'Это игра "Быки и Коровы"\n\ Я загадываю число из 4 цифр. Цифры могут повторяться, число может начинаться с нуля, т.е. я могу загадать даже такое число: 0103.\n\ Вам нужно отгадать число. Чем меньше попыток - тем лучше.\nДля того чтобы сделать попытку, просто напечатайте в ответ 4 цифры, например: 1234.\n\ После каждой вашей попытки я даю подсказку: количество быков и коров в вашем числе.\n\ Бык - это цифра, которая присутствует в загаданном числе и стоит на своем месте.\n\ Корова - это цифра, которая пристуствует в загаданном числе но стоит на другом месте.\n\ Т.е. например я загадал число 1234, вы отвечаете 1458: 1Б 1К (1 бык и 1 корова).\n\ Цифра 1 в вашем ответе это бык, т.к. в загаданном числе на первом месте тоже 1.\n \ Цифра 4 в вашем ответе это корова, т.к. в загаданном числе она есть, но должна стоять на четвертом месте.\n \ Цифры 5 и 8 в вашем ответе животными не являются, т.к. отсутствуют в загаданном числе.\n \ Чтобы прочитать более подробное объяснение как считаются быки и коровы, с пояснением сложных примеров, воспользуйтесь командой /rules' try: self.bot.send_message(chat.id, bot_answer) except Exception: self.bot.send_message(chat.id, 'Unknow error. Sorry.') elif text == '/rules': bot_answer = 'Подробнее о том как определется число быков и коров.\n\ Пример: загадано 0250, ваш ответ 0202.\n\ 1) Считаем количество быков, для этого смотрим цифры вашего ответа по порядку.\n\ -первая цифра 0 - бык, т.к. в 0250 на первом месте тоже 0\n\ -вторая цифра 2 - бык, т.к. в 0250 на втором месте тоже 2\n\ -третья цифра 0 - не бык, т.к. в 0250 на третьем месте 5\n\ -четвертая цифра 2 - не бык, т.к. в 0250 на четвертом месте 0\n\ Итого 2 быка. 2Б\n\ 2) Считаем количество коров, для этого смотрим цифры вашего ответа по порядку,\n\ но только те которые не являются быками:\n\ -первая цифра 0 - уже бык, поэтому не может быть коровой, хотя в загаданном числе она есть еще и на третьем месте\n\ -вторая цифра 2 - уже бык, не может быть коровой\n\ -третья цифра 0 - корова, т.к. не бык и при этом есть в 0250 на четвертом месте\n\ -четвертая цифра 2 - не бык и не корова. Она присутствует в 0250, но первые две цифры уже заняты быками, т.е. мы проверяем есть ли 2 среди последних цифр __50.\n\ иными словами каждая цифра в загаданном числе и в ответе может соответствовать только одному животному.\n\ Итого 1 корова. 1К\n\ Ответ будет 0202 2Б 1К\n\ Ещё примеры:\n\ 1) загадано 1111 ответ 1214 - 2Б 0К\n\ 2) загадано 2342 ответ 3222 - 1Б 2К\n\ 3) загадано 5678 ответ 6587 - 0Б 4К\n\ 4) загадано 1234 ответ 1111 - 1Б 0К' try: self.bot.send_message(chat.id, bot_answer) except Exception: self.bot.send_message(chat.id, 'Unknow error. Sorry.') elif text == '/newgame': bot_answer = 'В прошлой игре было загадано число: {}\nСыграем ещё? Я загадал новое число\nУгадывайте.' try: result = mariadb_connector.read_current_game_state(chat.id) num1 = str(random.randint(0, 9)) num2 = str(random.randint(0, 9)) num3 = str(random.randint(0, 9)) num4 = str(random.randint(0, 9)) number_for_solve = ''.join([num1, num2, num3, num4]) if (result == None): mariadb_connector.write_new_user(chat.id, number_for_solve) self.bot.send_message(chat.id, bot_answer.format('...')) else: mariadb_connector.write_current_game_state(chat.id, number_for_solve, None) self.bot.send_message(chat.id, bot_answer.format(result['number_for_solve'])) except Exception: self.bot.send_message(chat.id, 'Unknow error. Sorry.') else: try: start_new_game = False if self.check_user_answer(text): result = mariadb_connector.read_current_game_state(chat.id) if result == None: num1 = str(random.randint(0, 9)) num2 = str(random.randint(0, 9)) num3 = str(random.randint(0, 9)) num4 = str(random.randint(0, 9)) number_for_solve = ''.join([num1, num2, num3, num4]) mariadb_connector.write_new_user(chat.id, number_for_solve) result = mariadb_connector.read_current_game_state(chat.id) bulls_and_cows = self.answer_for_attempt(result['number_for_solve'], text) if bulls_and_cows['number_of_bulls'] == 4: start_new_game = True if result['current_game'] == None: result['current_game'] = [[text, str(bulls_and_cows['number_of_bulls']), str(bulls_and_cows['number_of_cows'])]] mariadb_connector.write_current_game_state(chat.id, result['number_for_solve'], result['current_game']) bot_answer = '' for attempt in result['current_game']: bot_answer = bot_answer + attempt[0] + ' ' + str(attempt[1]) + 'Б ' + str(attempt[2]) + 'К\n' else: if self.check_is_repeat(result['current_game'], text): bot_answer = 'Вы уже писали число {}'.format(text) else: result['current_game'].append([text, str(bulls_and_cows['number_of_bulls']), str(bulls_and_cows['number_of_cows'])]) mariadb_connector.write_current_game_state(chat.id, result['number_for_solve'], result['current_game']) bot_answer = '' for attempt in result['current_game']: bot_answer = bot_answer + attempt[0] + ' ' + str(attempt[1]) + 'Б ' + str(attempt[2]) + 'К\n' if bulls_and_cows['number_of_bulls'] == 4: if result['current_game'] == None: mariadb_connector.write_statistics(chat.id, True, 0) else: mariadb_connector.write_statistics(chat.id, True, len(result['current_game'])) else: if result['current_game'] == None: mariadb_connector.write_statistics(chat.id, False, 0) else: mariadb_connector.write_statistics(chat.id, False, len(result['current_game'])) else: bot_answer = "Ошибка при обработке ответа. В вашем ответе должны быть четыре цифры. Число может начинаться с нуля, цифры могут повторяться, например: 0373. Если хотите прочитать о правилах игры подробно, воспользуйтесь командой /help" if start_new_game: bot_answer_victory = 'Вы угадали! Это было число: {}\nСыграем ещё? Я загадал новое число\nУгадывайте.'.format(text) try: num1 = str(random.randint(0, 9)) num2 = str(random.randint(0, 9)) num3 = str(random.randint(0, 9)) num4 = str(random.randint(0, 9)) number_for_solve = ''.join([num1, num2, num3, num4]) mariadb_connector.write_current_game_state(chat.id, number_for_solve, None) bot_answer = bot_answer + '\n' + bot_answer_victory except Exception: self.bot.send_message(chat.id, 'Unknow error. Sorry.') self.bot.send_message(chat.id, bot_answer) except Exception: self.bot.send_message(chat.id, 'Unknow error. Sorry.') except Exception: pass def run(self): print('Main loop started') while True: updates = self.bot.get_updates(offset=self.last_update_id).wait() try: for update in updates: if int(update.update_id) > int(self.last_update_id): self.last_update_id = update.update_id self.process_message(update) except Exception as ex: print(traceback.format_exc())
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 + ','):
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
else: return ("Чтобы начать заново введите /start, чтобы продолжить игру введите /continue", ReplyKeyboardMarkup.create([['🔄 Начать заново'],['▶️ Продолжить игру']],resize_keyboard=True)) bot = TelegramBot('203607471:AAGIXeoretNObpGdN8lh1ecOQWUa5xY12c8') bot.update_bot_info().wait() print (bot.username) last_update_id = 0 try: while True: updates = bot.get_updates(last_update_id+1).wait() for update in updates: last_update_id = update.update_id reply, keyboard = get_message_reply(update.message) bot.send_message(update.message.sender.id, reply, reply_markup = keyboard, parse_mode = 'Markdown') # print ("sended "+reply) time.sleep(0.5) users = User.getAll(True, round(time.time())+1) #up to -5 for user in users: if (user.progressKey == -1): scenario.progress = (user.progressLabel, 0) else: scenario.progress = (user.progressLabel, user.progressKey) if scenario.get_current().__class__.__name__ != "NodeMenu" and scenario.get_current().__class__.__name__ != "NodeReturn":
from twx.botapi import TelegramBot token = '<>' bot = TelegramBot(token) while True: updates = bot.get_updates().wait() for update in updates: if update.message.text.startswith('/start'): bot.send_message(update.message.chat.id, 'test message body')
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)
continue else: #len(responses) - 1 update_id = updates[0][0] last_update_id = update_id + 1 for i in range(len(updates)): # probably range(len(updates[0][0])) # Process commands: message = updates[i][1] chat_id = updates[i][1][3][0] username = updates[i][1][1][3] text = updates[i][1][7] print text i = i + 1 if '/question' in text: bot.send_message(user_id, QuestionsList[i]).wait()''' updates = bot.get_updates(offset=None,limit=2,timeout=None).wait() for update in updates: gaga = updates[0][0] print(gaga)
""" bot = TelegramBot('173036865:AAGTS4HpLglqlLULSG3odoeYZr87d2GG9U0') print bot bot.update_bot_info().wait() last_id = 0 print(bot.username) TELEGRAM_MSGID=0; TELEGRAM_MSG=1; """ Send a message to a user """ #create objects first updates = bot.get_updates(offset= last_id, timeout=600).wait() msg = updates[len(updates)-1][TELEGRAM_MSG] #result = bot.send_message(user_id, 'test message body').wait() #print(result) """ Get updates sent to the bot """ pmsg = 'jbufs' while True: updates = bot.get_updates(offset= last_id, timeout=600).wait() #for update in updates: # print(update[TELEGRAM_MSGID])
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
class DigestBot(object): token = '146027849:AAGY5g94uLZRfURyEZrkOuh5Kvn23GnFZC4' #Super secret bot token stack_list = [] admin = 'Pablozzz' #admin name def __init__(self): self.bot = TelegramBot(self.token) self.bot.get_me() last_updates = self.bot.get_updates(offset=0).wait() try: self.last_update_id = list(last_updates)[-1].update_id except IndexError: self.last_update_id = None print('last update id: {0}'.format(self.last_update_id)) def process_message(self, message): #function for chech messages and send answers text = message.message.text chat = message.message.chat text = text.strip() bot_name = "zaurtox_bot" #Substrings in messages = commands Toxa = "/Toxa" Zaur = "/Zaur" News = "/News" Help = "/Help" Valuta = "/Valuta" Start = "/Start" Slogan = "/Pogovorka" Leha = "/Leha" Igor = "/Igor" Pasha = "/Pasha" Photo = "/Photo" Sticker = "/Sticker" Bash = "/Bash" #logger : print susbstr if catch that in message print('Got message: \33[0;32m{0}\33[0m from chat: {1}'.format(text, chat)) try: # commands #Help : print all supported commands if Help in text: bot_answer = 'Команды /Help /News /Zaur /Toxa /Valuta /Pogovorka /Photo /Sticker /Bash\n' try: self.bot.send_message(chat.id, bot_answer) except Exception: self.bot.send_message(chat.id, 'Unknow error. Sorry.') #Start command it's nessesary for telegramm rules complete if Start in text: bot_answer = 'Это эмоциональный бот, который может помочь с новостями и комментариями к ним /Help \n' try: self.bot.send_message(chat.id, bot_answer) except Exception: self.bot.send_message(chat.id, 'Unknow error. Sorry.') #News parse news from rbc.ru rss and send in chat if News in text: d = feedparser.parse('http://static.feed.rbc.ru/rbc/internal/rss.rbc.ru/rbc.ru/news.rss') bot_answer =d['entries'][0]['title']+" "+d.entries[0]['link'] try: self.bot.send_message(chat.id, bot_answer) except Exception: self.bot.send_message(chat.id, 'Unknow error. Sorry.') #Parse currenty rate and send in chat if Valuta in text: speaker=["Как заявил Антон Силуанов", "Как заявил Алексей Улюкаев", "Как заявила Эльвира Набиулина"] i = random.randrange(0,3,1) sentense = speaker[i] +", обоснованным курсом рубля явлеется: " HOST = "www.sberometer.ru" PORT = 80 conn = http.client.HTTPConnection(HOST, PORT) conn.request("GET", "/") res = conn.getresponse() data = res.read() conn.close() answer = str(data) pos = answer.find("cursNow") bot_answer= sentense + answer[(pos+11):(pos+34):1] try: self.bot.send_message(chat.id, bot_answer) except Exception: self.bot.send_message(chat.id, 'Unknow error. Sorry.') #Parse strory from bach.org rss and print in chat if Bash in text: d = feedparser.parse('http://bash.im/rss/') bot_answer =d['entries'][0]['title']+" "+d.entries[0]['link'] try: self.bot.send_message(chat.id, bot_answer) except Exception: self.bot.send_message(chat.id, 'Unknow error. Sorry.') #Select random slogan from file "pogovorki.txt" and send in chat if Slogan in text: fp = open("pogovorki.txt") lines = fp.readlines() fp.close() phrase = ["Как говорил мой дед: ", "Как говорят у нас в народе: ", "Народная мудрость: ", "Как мы все знаем: "] a = random.randrange(0,4,1) i = random.randrange(0,1353,1) slogan = (lines[i].strip()) bot_answer = phrase[a] + slogan try: self.bot.send_message(chat.id, bot_answer) except Exception: self.bot.send_message(chat.id, 'Unknow error. Sorry.') #Send strickers in chat if (text == Sticker): stikers = ["BQADAgADeAcAAlOx9wOjY2jpAAHq9DUC"] try: self.bot.send_sticker(chat.id, stikers[0]) except Exception: self.bot.send_photo(chat.id, 'Unknow error. Sorry.') #Send photo from /photo path if (text == Photo): photos = ["photo/photo1.jpg"] #"photo/photo2.jpg", #"photo/photo3.jpg"] #i = random.randrange(0,3,1) fp = open(photos[0], "rb") file_info = InputFileInfo(photos[0], fp, 'image/jpg') a = InputFile('photo', file_info) self.bot.send_photo(chat.id, a) fp.close() #Send comment from Toxa.txt file if Toxa in text: fp = open("Toxa.txt") lines = fp.readlines() fp.close() i = random.randrange(0,len(lines)-1,1) slogan = (lines[i].strip()) bot_answer = slogan + '\n' try: self.bot.send_message(chat.id, bot_answer) except Exception: self.bot.send_message(chat.id, 'Unknow error. Sorry.') #Send comment from Zaur.txt file if Zaur in text: fp = open("Zaur.txt") lines = fp.readlines() fp.close() i = random.randrange(0,len(lines)-1,1) slogan = (lines[i].strip()) bot_answer = slogan + '\n' try: self.bot.send_message(chat.id, bot_answer) except Exception: self.bot.send_message(chat.id, 'Unknow error. Sorry.') #Send comment from Leha.txt file if Leha in text: fp = open("Leha.txt") lines = fp.readlines() fp.close() i = random.randrange(0,len(lines)-1,1) slogan = (lines[i].strip()) bot_answer = slogan + '\n' try: self.bot.send_message(chat.id, bot_answer) except Exception: self.bot.send_message(chat.id, 'Unknow error. Sorry.') #Send comment from Igor.txt file if Igor in text: fp = open("igor.txt") lines = fp.readlines() fp.close() i = random.randrange(0,len(lines)-1,1) slogan = (lines[i].strip()) bot_answer = slogan + '\n' try: self.bot.send_message(chat.id, bot_answer) except Exception: self.bot.send_message(chat.id, 'Unknow error. Sorry.') #Send comment from Pasha.txt file if Pasha in text: fp = open("pasha.txt") lines = fp.readlines() fp.close() i = random.randrange(0,len(lines)-1,1) slogan = (lines[i].strip()) bot_answer = slogan + '\n' try: self.bot.send_message(chat.id, bot_answer) except Exception: self.bot.send_message(chat.id, 'Unknow error. Sorry.') except Exception: pass def run(self): print('Main loop started') while True: updates = self.bot.get_updates(offset=self.last_update_id).wait() #update status try: for update in updates: if int(update.update_id) > int(self.last_update_id): self.last_update_id = update.update_id self.process_message(update) except Exception as ex: print(traceback.format_exc())
class DigestBot(object): token = '309819985:AAE03f1oaX1VvfeqxKtcghq7aoNZSEuYTEw' stack_list = [] admin = 'Greg' userID = 0 def __init__(self): self.bot = TelegramBot(self.token) self.bot.get_me() last_updates = self.bot.get_updates(offset=0).wait() try: self.last_update_id = list(last_updates)[-1].update_id except IndexError: self.last_update_id = None print('last update id: {0}'.format(self.last_update_id)) def process_message(self, message): text = message.message.text chat = message.message.chat text = text.strip() digest_tag = '#digest' print('Got message: \33[0;32m{0}\33[0m from chat: {1}'.format( text, chat)) try: if text == '/digest': bot_answer = 'There is your digest:\n' try: for struct in self.stack_list: if struct['chat_id'] == chat.id: bot_answer += struct['chat_message'] bot_answer += '\n' bot_answer = bot_answer[:-1] bot_answer += '.' self.bot.send_message(chat.id, bot_answer) except Exception: self.bot.send_message(chat.id, 'Unknow error. Sorry.') if text == '/stackView': list_answer = 'There is my stack list:\n' try: if message.message.sender.username == self.admin: for (index, d) in enumerate(self.stack_list): list_answer += str(index + 1) list_answer += ' ' + str(d['chat_id']) list_answer += ' ' + d['chat_message'] list_answer += '\n' list_answer = list_answer[:-1] self.bot.send_message(chat.id, list_answer) else: raise Exception('You do not access for this function.') except Exception as ex_acc: answer = ex_acc.args self.bot.send_message(chat.id, answer) if re.match(r'[0-9]', text) and len(text) == 11: self.userID = text print(self.userID) if text == '/getJobs': if self.userID != 0: print(self.userID) response = requests.get( 'https://test.periodix.net/get-jobs.php?id=' + self.userID).json() print(response['JobTitle']) bot_answer = 'There is your job: \n' + ( response['JobTitle']) try: self.bot.send_message(chat.id, bot_answer) except Exception: self.bot.send_message(chat.id, 'Unknow error. Sorry.') if digest_tag in text: try: text = text.replace(digest_tag, '') text = text.strip() struct = {'chat_id': chat.id, 'chat_message': text} self.stack_list.append(struct.copy()) self.bot.send_message( chat.id, 'Done. I append your digest-message in my stack list.') except Exception: self.bot.send_message(chat.id, 'There is error. Sorry.') except Exception: pass def run(self): print('Main loop started') while True: updates = self.bot.get_updates(offset=self.last_update_id).wait() try: for update in updates: if int(update.update_id) > int(self.last_update_id): self.last_update_id = update.update_id self.process_message(update) except Exception as ex: print(traceback.format_exc())
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 + ','): return line.split(',')[1]
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
class SmartHomeBot(AbstractServiceClass): def __init__ (self, serviceName, logLevel): super(SmartHomeBot, self).__init__(serviceName, logLevel) self.lastUpdateID = 0 self.validUsers = [] self.keyboards = { #"start": [["Rooms" , "All Devices"], ["Switch off all devices", "Rules"]], "start": [["Rooms" , "All Devices"], ["Switch off all devices"]], "Rooms": [], "All Devices": [] , "Rules": []} self.keybordForUsers = {} self.allDevicesList = {} self.alldevicesFunctionsList = {} self.allRoomsList = {} self.upnp = miniupnpc.UPnP() self.upnp.discoverdelay = 200 self.minUPnPPort = 1024 self.maxUPnPPort = self.minUPnPPort + 20 def stop(self): super(SmartHomeBot, self).stop() # Starts the communication with the bot def start(self): self.logger.info("%s started" % self.serviceName) self.retrieveHomeSettings() if (self.botToken is None): self.logger.error ("The Telegram Token is not valid") self.stop() else: self.bot = TelegramBot(self.botToken) self.homeUpdateThread = Thread (target = self.homeUpdate) self.homeUpdateThread.start() # serving clients try: while self.isRunning: try: #The get_updates method returns the earliest 100 unconfirmed updates updates = self.bot.get_updates(offset = self.lastUpdateID + 1).wait() if (updates is not None): cont1=len(updates) if cont1 != 0: replyThread = Thread (target = self.reply, args=[updates[-1]]) replyThread.start() self.lastUpdateID = updates[-1].update_id time.sleep(1) except Exception, e: self.logger.error('Something wrong occurred in telegram communication: %s. restoring the bot' % (e)) self.bot = TelegramBot(self.botToken) except KeyboardInterrupt: self.stop() def makeKeyboards(self): # Rooms keyboard keyboard = [] keyoardRow = [] self.allRoomsList = {} for count, room in enumerate(self.myhome["rooms"]): if ((count+1) % 3 != 0): label = "%s - %s" % (room["roomID"], room["description"]) keyoardRow.append (label) self.allRoomsList[label] = room else: label = "%s - %s" % (room["roomID"], room["description"]) keyoardRow.append (label) keyboard.append(keyoardRow) keyoardRow = [] self.allRoomsList[label] = room toBeAppend = False if (len(keyboard[-1:]) % 3 != 0 ): keyoardRow.append ("Back") toBeAppend = True else: keyoardRow.append ("Back") keyboard.append(keyoardRow) keyoardRow = [] toBeAppend = False if (len(keyboard[-1:]) % 3 != 0 ): keyoardRow.append ("Start") toBeAppend = True else: keyoardRow.append ("Start") keyboard.append(keyoardRow) keyoardRow = [] toBeAppend = False if (toBeAppend): keyboard.append(keyoardRow) self.keyboards["Rooms"] = keyboard # allDevices keyboard keyboard = [] keyoardRow = [] self.allDevicesList = {} for i, room in enumerate(self.myhome["rooms"]): for count, device in enumerate(room["devices"]): label = "%s (%s)" % (device["description"], device["deviceID"]) self.allDevicesList[label] = device keyoardRow.append (label) keyboard.append(keyoardRow) keyoardRow = [] keyboard.sort() keyoardRow = ["Back", "Start"] keyboard.append(keyoardRow) self.keyboards["All Devices"] = keyboard # Rules keyboard keyboard = [] keyoardRow = [] for count, rule in enumerate(self.myhome["rules"]): keyoardRow.append (rule["ruleSID"]) keyboard.append(keyoardRow) keyoardRow = [] keyoardRow = ["Back", "Start"] keyboard.append(keyoardRow) self.keyboards["Rules"] = keyboard def retrieveDeviceInfo(self, deviceID): replyMsg = ("This is %s\n" % (deviceID)) if (deviceID.lower().startswith("http://") or deviceID.lower().startswith("https://")): deviceUri = deviceID else: deviceUri = self.allDevicesList[deviceID]["protocol"][0]["uri"] if (len(self.allDevicesList[deviceID]["thingspeakChannels"]) > 0): replyMsg += ("Thingspeak Channels:\n") for tsfeed in self.allDevicesList[deviceID]["thingspeakChannels"]: replyMsg += ("%s %s\n\n" % (tsfeed["measureType"], tsfeed["readFeed"])) resp, isOk = self.invokeWebService (deviceUri) reply_markup = None keyboard = [] if (isOk): deviceInfo = json.loads (resp) for function in deviceInfo["functions"]: if (function["configuredAs"].lower() == "switch"): if (function["status"] == "0"): status = "off" nextStatus = "switch on" elif (function["status"] == "1"): status = "on" nextStatus = "switch off" else: status = "unknown" replyMsg += "%s is %s\n" % (function["type"], status) label = "%s %s (%s)" % (nextStatus, function["type"], deviceInfo["ip"]) self.alldevicesFunctionsList[label] = function["ws"] keyboard.append([label]) elif (function["configuredAs"].lower() == "button"): replyMsg += "%s\n" % (function["type"]) label = "%s (%s)" % (function["type"], deviceInfo["ip"]) self.alldevicesFunctionsList[label] = function["ws"] keyboard.append([label]) elif (function["configuredAs"].lower() == "sensor"): replyMsg += "%s is %s%s\n" % (function["type"], function["status"], function["unit"]) if (len(keyboard)>0): keyboard.append(["Back", "Start"]) #reply_markup = ReplyKeyboardMarkup.create(keyboard, one_time_keyboard= False, selective=True) else: replyMsg += 'Devices %s is unreachable: %s' % (deviceID, resp) return replyMsg, keyboard def openPort(self, localIP, localPort, externalPort, protocol): ndevices = self.upnp.discover() igd = self.upnp.selectigd() msg = "" errormsg = "Error: host and/or router port must be an integer between %d and %d" % (self.minUPnPPort, self.maxUPnPPort) isOk = True if (protocol.upper() == 'TCP'): protocol = 'TCP' elif (protocol.upper() == 'UDP'): protocol = 'UDP' else: protocol = 'TCP' msg += "Protocol not valid, using TCP by default\n" if (localIP is None): localIP = self.upnp.lanaddr isOk = isOk and True else: try: #ip = ipaddress.ip_address(unicode(localIP, 'utf8')) ip = ipaddress.ip_address(localIP) isOk = isOk and True except Exception, e: msg += str(e) + "\n" isOk = isOk and False try: localPort = int(localPort) externalPort = int(externalPort) if (localPort > 1 and localPort < 65536): isOk = isOk and True else: isOk = isOk and False msg += errormsg + "\n" if (externalPort > self.minUPnPPort and externalPort < self.maxUPnPPort): isOk = isOk and True else: isOk = isOk and False msg += errormsg + "\n" except Exception, e: isOk = isOk and False msg += errormsg + "\n"
file_info = InputFileInfo('gattino.jpg', fp, 'image/jpg') input = InputFile('photo', file_info) bot.send_photo(chat_id=update.message.chat.id,photo=input) if "pene" in update.message.text: fp = open('p.jpg', 'rb') file_info = InputFileInfo('p.jpg', fp, 'image/jpg') input = InputFile('photo', file_info) bot.send_photo(chat_id=update.message.chat.id,photo=input) if "treno" in update.message.text: number=update.message.text[5:] trainInfo(int(number), update.message.chat.id) var = 1 offset = 0 while(var == 1): updates = bot.get_updates(offset).wait() for update in updates: offset = update.update_id + 1 print(update.message.sender.id) reply(update) bot.send_message(user_id, 'please enter a number', reply_markup=reply_markup).wait()
class BotServer(object): TORRENT = { "category": { "movies": CATEGORY.MOVIES, "tv": CATEGORY.TV, "music": CATEGORY.MUSIC, "books": CATEGORY.BOOKS, "games": CATEGORY.GAMES, "applications": CATEGORY.APPLICATIONS, "xxx": CATEGORY.XXX, }, "order": { "size": ORDER.SIZE, "files_count": ORDER.FILES_COUNT, "time_add": ORDER.AGE, "seeders": ORDER.SEED, "leechers": ORDER.LEECH, "asc": ORDER.ASC, "desc": ORDER.DESC, }, } MODES = ["torrent.search"] def __init__(self): self.bot = TelegramBot(API_TOKEN) self.updates = set(bot.get_updates().wait()) self.users_mode = {} self.thread = Thread(target=self.call_factory) def call_factory(self): pass @staticmethod def isqrt(n): print(n) x = n y = (x + 1) // 2 last_x = x while y < x: x = y y = (x + n // x) // 2 last_x = x print(last_x + 1) return last_x + 1 def search_torrent(self, search_term, options): page = 1 category = None order = None for option, value in options: if option.split("-")[0] == "page": page = value elif option.split("-")[0] == "category": category = self.TORRENT["category"][value] elif option.split("-")[0] == "order": order = self.TORRENT["order"][value] torrents = Search(search_term, page=page, category=category, order=order) return torrents def download_torrent(self, number, torrents): torrent = torrents[int(number)] print(torrent["magnet_link"]) def build_keyboard(self, xy, iterable_obj): print("Building Base keyboard") keyboard = [] count = 0 r_count = 0 len_itter = len(iterable_obj) print("Building Custom keyboard") for row in range(xy): c_count = 0 print(keyboard) print(r_count) keyboard.append([]) for col in range(xy): if count < len_itter: keyboard[r_count].append(count) # for i, x in enumerate(iterable_obj): # if i == count: # print("Modifying keyboard at %s, %s from value %s" % (r_count, c_count, x)) # keyboard[r_count][c_count] = x['name'] count += 1 c_count += 1 r_count += 1 return keyboard def build_message(self, style, result, _id=None): if _id: if style == "torrent.search": print("Building Message") msg = "We have found several torents for you.\nThey are:\n%s\n\nPleas" % "\n".join( [str(i) + ". %s" % x.name for i, x in enumerate(result)] ) print("Building keyboard") keyboard = self.build_keyboard(self.isqrt(len(result)), result) print("Building Markup") pprint(keyboard) reply_markup = ReplyKeyboardMarkup.create(keyboard, one_time_keyboard=True) print("Sending Message") self.bot.send_message(_id, msg, reply_markup=reply_markup).wait() def start(self): COMMANDS = {"TORRENT": self.search_torrent} while True: print("Waiting....") updates = set(self.bot.get_updates().wait()) new_updates = updates.difference(self.updates) for update in new_updates: text = update.message.text if str(update.message.sender.id) in self.users_mode: command = self.users_mode[str(update.message.sender.id)]["command"] torrents = self.users_mode[str(update.message.sender.id)]["data"] command(update.message.text, torrents) if text.startswith("/"): # Look for command command, arg, optional = BotWorker.tokenize(text) if command[1:].upper() in COMMANDS: # I understand this function = COMMANDS[command[1:].upper()] result = function(arg, optional) print("Got results") if result: self.users_mode[str(update.message.sender.id)] = { "command": self.download_torrent, "data": result, } print("Updating user status") self.build_message("torrent.search", result, _id=update.message.sender.id)
""" Setup the bot """ bot = TelegramBot('332101015:AAFy9vC_d4Dj5GK7bkIQa5kETnudMqZWUhY') bot.update_bot_info().wait() print(bot.username) """ Send a message to a user """ user_id = int(185350524) result = bot.send_message(user_id, str1).wait() print(result) """ Get updates sent to the bot """ updates = bot.get_updates().wait() for update in updates: print(update) """ Use a custom keyboard """ keyboard = [['7', '8', '9'], ['4', '5', '6'], ['1', '2', '3'], ['0']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(user_id, 'please enter a number', reply_markup=reply_markup).wait() print reply_markup
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
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
if random.random() > random.choice( [0.9992, 0.9993, 0.9994, 0.9995, 0.9996, 0.9997, 0.9998, 0.9999]): new += chr( int(ord(c) + random.random() * random.choice(range(100))) % 256) else: new += c fw = open("/tmp/teleglitched.jpg", 'w') fw.write(new) fw.close() return "/tmp/teleglitched.jpg" answered = pickle.load(open('answered.pkl', 'r')) updates = bot.get_updates().wait() #Flush first updates for pos, update in enumerate(updates): answered.append(update.message.message_id) while True: print("Getting updates".center(50, '-')) updates = bot.get_updates().wait() for pos, update in enumerate(updates): #print str(update) msg = update.message.text if update.message.chat: user = update.message.chat.id else: user = update.message.sender.id if update.message.message_id in answered:
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)
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
while True: try: if sleepers is not None: # ********** STAGE ONE - check current timers db_connection() tm_now = datetime.now() #print("Now " + tm_now.strftime("%A, %d. %B %Y %I:%M:%S%p")) for sleeping_chat in sleepers: tm = sleepers[sleeping_chat] if tm is not None: print("Chat " + str(sleeping_chat) + " " + tm.strftime("%A, %d. %B %Y %I:%M:%S%p")) if tm_now >= tm: print("It's time to move out of room for chat " + str(sleeping_chat)) parse_scene(None, sleeping_chat) updates = bot.get_updates(offset).wait() if updates is None: # ********** STAGE TWO - check new updates continue db_connection() for update in updates: print(update) offset = update.update_id + 1 msg = update.message if msg is not None: fromuser = msg.sender txt = msg.text check_new_chat(msg.chat.id) if txt is not None: humanname = fromuser.first_name userid = fromuser.id username = fromuser.username
chat_id = upd.message.chat.id try: message = upd.message.text if message == "/get_history": bot.send_message(chat_id, 'Que titulo quieres consultar?') try: BOT_OPTIONS[message.lower()](bot, chat_id) except Exception: print(traceback.format_exc()) except Exception: print(traceback.format_exc()) while True: # print last_update_id 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 process_message(bot, update) continue continue except Exception: ex = None print(traceback.format_exc()) continue
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
TELEGRAM_MSG = 1 """ Socket """ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #replace localhost with server dns or ip address; choose a high port to use server_address = ('localhost', 10003) print >> sys.stderr, 'starting up on %s port %s' % server_address sock.bind(server_address) sock.listen(1) bufferdata = "" while True: #create objects for bot updates = bot.get_updates(offset=last_id, timeout=600).wait() #if updates is not None: #if len(updates) > 0: msg = updates[len(updates) - 1][TELEGRAM_MSG] #bufferdata = "" #wait for a connection from Sensesurround # chat = msg.chat # encodedteext = msg.text #if encodedtext is not None: # encodedtext.encode(encoding='utf-8',errors='ignore') #encodedpmsg = pmsg #if encodedpmsg is not None: # encodedtext.encode(encoding='utf-8',errors='ignore') if updates is not None: print >> sys.stderr, 'waiting for a connection' connection, client_address = sock.accept()
def send_meme(message) : bot.send_photo(message.chat, photos[randint(0, (len(photos) - 1))]) print "Photo sent" def command_response(message) : # respond to commands typed by the user commands = {"/help" : send_help_text, "/about" : send_about_text, "/author" : send_author_info } if message.text in commands : commands[message.text](message) else : bot.send_message(message.chat, "That is not a command that this bot knows") print "Bot running..." updates = bot.get_updates(1, None, None).wait() # get first update if len(updates) == 0 : print "There must be at least 1 message in the current chat" elif len(updates) == 1 : # account for bot's first update current = updates[0] else : current = updates[-1] dank_pattern = re.compile('(\w\sdank\s\w)|(dank\s\w)|(\w\sdank)|(Dank)') command_pattern = re.compile('/\w') location_pattern = re.compile('(location -?\d\d -?\d\d)') try : while True : # use long polling prev = current.update_id
sec_state[user]['stage'] * sec_state[user]['stage'] ^ 1337) % 10 sec_state[user]['mode'] = sec_state[user]['mode'] - 1 if sec_state[user]['mode'] < 0: sec_state[user]['mode'] = 0 if sec_state[user]['mode'] == 0: bot.send_message(chat_id, 'Secret mode enabled!', reply_markup=reply_hide).wait() else: print 'NO', num, sec_state[user]['stage'] bot.send_message(chat_id, 'Invalid password!', reply_markup=reply_hide).wait() sec_state[user]['mode'] = 15 bot = TelegramBot(config.token) bot.update_bot_info().wait() print bot.username last_update_id = 0 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 process_message(bot, update) except Exception as ex: print traceback.format_exc()
class TGBot(object): def __init__(self, token, plugins=[], no_command=None, db_url=None): self._token = token self.tg = TelegramBot(token) self._last_id = None self.cmds = {} self.pcmds = {} self._no_cmd = no_command self._msgs = {} self._plugins = plugins if no_command is not None: if not isinstance(no_command, TGPluginBase): raise NotImplementedError("%s does not subclass tgbot.TGPluginBase" % type(no_command).__name__) for p in self._plugins: if not isinstance(p, TGPluginBase): raise NotImplementedError("%s does not subclass tgbot.TGPluginBase" % type(p).__name__) for cmd in p.list_commands(): if not isinstance(cmd, TGCommandBase): raise NotImplementedError("%s does not subclass tgbot.TGCommandBase" % type(cmd).__name__) if cmd in self.cmds or cmd in self.pcmds: raise Exception( "Duplicate command %s: both in %s and %s" % (cmd.command, type(p).__name__, self.cmds.get(cmd.command) or self.pcmds.get(cmd.command)) ) if cmd.prefix: self.pcmds[cmd.command] = cmd else: self.cmds[cmd.command] = cmd if db_url is None: self.db = connect("sqlite:///:memory:") models.database_proxy.initialize(self.db) self.setup_db() else: self.db = connect(db_url) self.db.autorollback = True models.database_proxy.initialize(self.db) def update_bot_info(self): # re-implement update_bot_info to make it synchronous if self.tg.username is None: self.tg._bot_user = self.tg.get_me().wait() def process_update(self, update): # noqa not complex at all! self.update_bot_info() message = update.message try: models.User.create( id=message.sender.id, first_name=message.sender.first_name, last_name=message.sender.last_name ) except peewee.IntegrityError: pass # ignore, already exists if message.left_chat_participant is not None and message.left_chat_participant.username == self.tg.username: models.GroupChat.delete().where(models.GroupChat.id == message.chat.id).execute() elif isinstance(message.chat, GroupChat): try: models.GroupChat.create(id=message.chat.id, title=message.chat.title) except peewee.IntegrityError: pass if message.new_chat_participant is not None and message.new_chat_participant != self.me: try: models.User.create( id=message.new_chat_participant.id, first_name=message.new_chat_participant.first_name, last_name=message.new_chat_participant.last_name, ) except peewee.IntegrityError: pass # ignore, already exists if message.contact is not None: try: models.User.create( id=message.contact.user_id, first_name=message.contact.first_name, last_name=message.contact.last_name, ) except peewee.IntegrityError: pass # ignore, already exists if message.text is not None and message.text.startswith("/"): spl = message.text.find(" ") if spl < 0: cmd = message.text[1:] text = "" else: cmd = message.text[1:spl] text = message.text[spl + 1 :] spl = cmd.find("@") if spl > -1: cmd = cmd[:spl] self.process(message, cmd, text) else: was_expected = False for p in self._plugins: was_expected = p.is_expected(self, message) if was_expected: break if self._no_cmd is not None and not was_expected: self._no_cmd.chat(self, message, message.text) def setup_db(self): models.create_tables(self.db) def run(self, polling_time=2): from time import sleep # make sure all webhooks are disabled self.tg.set_webhook().wait() while True: ups = self.tg.get_updates(offset=self._last_id).wait() if isinstance(ups, Error): print "Error: ", ups else: for up in ups: self.process_update(up) self._last_id = up.update_id + 1 sleep(polling_time) def run_web(self, hook_url, **kwargs): from .webserver import run_server url = hook_url if url[-1] != "/": url += "/" self.tg.set_webhook(url + "update/" + self._token) run_server(self, **kwargs) def list_commands(self): return self.cmds.values() + self.pcmds.values() def print_commands(self, out=sys.stdout): """ utility method to print commands and descriptions for @BotFather """ cmds = self.list_commands() for ck in cmds: if ck.printable: out.write("%s\n" % ck) def process(self, message, cmd, text): if cmd in self.cmds: self.cmds[cmd].method(self, message, text) elif cmd in self.pcmds: self.pcmds[cmd].method(self, message, text) else: for pcmd in self.pcmds: if cmd.startswith(pcmd): ntext = cmd[len(pcmd) :] if text: ntext += " " + text self.pcmds[pcmd].method(self, message, ntext) break
class NimBot(object): token = config.token def __init__(self): self.bot = TelegramBot(self.token) self.bot.get_me() last_updates = self.bot.get_updates(offset=0).wait() try: self.last_update_id = list(last_updates)[-1].update_id except IndexError: self.last_update_id = None print('last update id: {0}'.format(self.last_update_id)) def read_current_state(self, chat_id): connection = pymysql.connect(host=config.sql_host, user=config.sql_user, password=config.sql_user_password, db=config.sql_db, charset=config.sql_charset, cursorclass=pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: sql = "SELECT chat_id, num1, num2, num3 FROM data WHERE chat_id = {}".format(chat_id) cursor.execute(sql) row = cursor.fetchone() finally: cursor.close() connection.close() return row def write_new_user(self, chat_id, num1, num2, num3): connection = pymysql.connect(host=config.sql_host, user=config.sql_user, password=config.sql_user_password, db=config.sql_db, charset=config.sql_charset, cursorclass=pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: sql = "INSERT INTO data (chat_id, num1, num2, num3) VALUES({}, {}, {}, {})".format(chat_id, num1, num2, num3) cursor.execute(sql) connection.commit() finally: cursor.close() connection.close() def write_current_state(self, chat_id, num1, num2, num3): connection = pymysql.connect(host=config.sql_host, user=config.sql_user, password=config.sql_user_password, db=config.sql_db, charset=config.sql_charset, cursorclass=pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: sql = "UPDATE data SET num1={1}, num2={2}, num3={3} WHERE chat_id = {0}".format(chat_id, num1, num2, num3) cursor.execute(sql) connection.commit() finally: cursor.close() connection.close() def write_message(self, chat_id, title, username, first_name, last_name, text): connection = pymysql.connect(host=config.sql_host, user=config.sql_user, password=config.sql_user_password, db=config.sql_db, charset=config.sql_charset, cursorclass=pymysql.cursors.DictCursor) try: with connection.cursor() as cursor: sql = "INSERT INTO messages (chat_id, title, username, first_name, last_name, text) VALUES({}, '{}', '{}', '{}', '{}', '{}')".format(chat_id, title, username, first_name, last_name, text) cursor.execute(sql) connection.commit() finally: cursor.close() connection.close() def check_user_numbers(self, list_from_db, list_from_user): list_from_db_work = list(list_from_db) list_from_user_work = list(list_from_user) for number in list_from_user: if number in list_from_db_work: list_from_db_work.remove(number) list_from_user_work.remove(number) if len(list_from_db_work)!=1 or len(list_from_user_work)!=1: return -1 elif list_from_db_work[0] < list_from_user_work[0]: return -2 else: return 0 def make_a_move(self, list_from_user): random_decision = random.randint(0,100) if random_decision>30: return self.make_a_move_smart(list_from_user) elif random_decision<=30: return self.make_a_move_random(list_from_user) def make_a_move_random(self, list_from_user): list_from_user_work = list(list_from_user) indexes_for_change = [0,1,2] for i, number in enumerate(list_from_user_work): if number==0: indexes_for_change.remove(i) if len(indexes_for_change)>0: index_for_change = random.choice(indexes_for_change) list_from_user_work[index_for_change] = list_from_user_work[index_for_change] - random.randint(1,list_from_user_work[index_for_change]) return list_from_user_work else: return -1 def make_a_move_smart(self, list_from_user): num1 = list_from_user[0] num2 = list_from_user[1] num3 = list_from_user[2] if num1==0 and num2==0 and num3==0: return -1 elif (num1^num2^num3)==0: return self.make_a_move_random(list_from_user) else: list_from_user_work = list(list_from_user) list_of_right_answers = [] indexes_for_change= [0,1,2] for i, number in enumerate(list_from_user_work): if number==0: indexes_for_change.remove(i) if len(indexes_for_change)>0: index_for_change = random.choice(indexes_for_change) i = 1 while i <= list_from_user_work[index_for_change]: if index_for_change==0: num1 = list_from_user[0] - i num2 = list_from_user[1] num3 = list_from_user[2] if (num1^num2^num3)==0: list_of_right_answers.append([num1, num2, num3]) elif index_for_change==1: num1 = list_from_user[0] num2 = list_from_user[1] - i num3 = list_from_user[2] if (num1^num2^num3)==0: list_of_right_answers.append([num1, num2, num3]) elif index_for_change==2: num1 = list_from_user[0] num2 = list_from_user[1] num3 = list_from_user[2] - i if (num1^num2^num3)==0: list_of_right_answers.append([num1, num2, num3]) i = i + 1 if len(list_of_right_answers)==0: indexes_for_change.remove(index_for_change) if len(indexes_for_change)>0: index_for_change = random.choice(indexes_for_change) i = 1 while i <= list_from_user_work[index_for_change]: if index_for_change==0: num1 = list_from_user[0] - i num2 = list_from_user[1] num3 = list_from_user[2] if (num1^num2^num3)==0: list_of_right_answers.append([num1, num2, num3]) elif index_for_change==1: num1 = list_from_user[0] num2 = list_from_user[1] - i num3 = list_from_user[2] if (num1^num2^num3)==0: list_of_right_answers.append([num1, num2, num3]) elif index_for_change==2: num1 = list_from_user[0] num2 = list_from_user[1] num3 = list_from_user[2] - i if (num1^num2^num3)==0: list_of_right_answers.append([num1, num2, num3]) i = i + 1 if len(list_of_right_answers)==0: indexes_for_change.remove(index_for_change) if len(indexes_for_change)>0: index_for_change = random.choice(indexes_for_change) i = 1 while i <= list_from_user_work[index_for_change]: if index_for_change==0: num1 = list_from_user[0] - i num2 = list_from_user[1] num3 = list_from_user[2] if (num1^num2^num3)==0: list_of_right_answers.append([num1, num2, num3]) elif index_for_change==1: num1 = list_from_user[0] num2 = list_from_user[1] - i num3 = list_from_user[2] if (num1^num2^num3)==0: list_of_right_answers.append([num1, num2, num3]) elif index_for_change==2: num1 = list_from_user[0] num2 = list_from_user[1] num3 = list_from_user[2] - i if (num1^num2^num3)==0: list_of_right_answers.append([num1, num2, num3]) i = i + 1 if len(list_of_right_answers)==0: return self.make_a_move_random(list_from_user) else: return random.choice(list_of_right_answers) else: return random.choice(list_of_right_answers) else: return random.choice(list_of_right_answers) def process_message(self, message): text = message.message.text chat = message.message.chat text = text.strip() print('Got message: \33[0;32m{0}\33[0m from chat: {1}'.format(text, chat)) try: if text == '/start': bot_answer = 'Это игра Ним.\nПеред вами три числа.\nКаждый ход вы должны уменьшить одно из чисел.\nЧтобы сделать ход просто напечатайте три числа, разделенные пробелом.\nПропустить ход нельзя.\nМожно изменить только одно число за ход.\nТот кто сделает ход 0 0 0 - победил. Т.е. нужно взять последнюю монету.\nИтак, числа:\n{} {} {}\nВаш ход.' try: row = self.read_current_state(chat.id) num1 = random.randint(config.min_random,config.max_random) num2 = random.randint(config.min_random,config.max_random) num3 = random.randint(config.min_random,config.max_random) if (row == None): self.write_new_user(chat.id, num1, num2, num3) else: self.write_current_state(chat.id, num1, num2, num3) self.bot.send_message(chat.id, bot_answer.format(num1, num2, num3)) except Exception: self.bot.send_message(chat.id, 'Unknow error. Sorry.') elif text == '/help': bot_answer = 'Это игра Ним.\nПеред вами три числа.\nКаждый ход вы должны уменьшить одно из чисел.\nЧтобы сделать ход просто напечатайте три числа, разделенные пробелом.\nПропустить ход нельзя.\nМожно изменить только одно число за ход.\nТот кто сделает ход 0 0 0 - победил. Т.е. нужно взять последнюю монету.\n/newgame - новая игра.\n/send2admin [message] - отправить сообщение админу (140 симв.)\n' try: self.bot.send_message(chat.id, bot_answer) except Exception: self.bot.send_message(chat.id, 'Unknow error. Sorry.') elif text == '/newgame': bot_answer = 'Ок, начинаем новую игру:\n{} {} {}\nВаш ход.' try: row = self.read_current_state(chat.id) num1 = random.randint(config.min_random,config.max_random) num2 = random.randint(config.min_random,config.max_random) num3 = random.randint(config.min_random,config.max_random) if (row == None): self.write_new_user(chat.id, num1, num2, num3) else: self.write_current_state(chat.id, num1, num2, num3) self.bot.send_message(chat.id, bot_answer.format(num1, num2, num3)) except Exception: self.bot.send_message(chat.id, 'Unknow error. Sorry.') elif '/send2admin' in text: bot_answer = 'Сообщение "{}" передано администратору, когда-нибудь он его обязательно прочитает.\nНапомню числа:\n{} {} {}\nВаш ход.' try: row = self.read_current_state(chat.id) num1 = random.randint(config.min_random,config.max_random) num2 = random.randint(config.min_random,config.max_random) num3 = random.randint(config.min_random,config.max_random) if (row == None): self.write_new_user(chat.id, num1, num2, num3) else: row = self.read_current_state(chat.id) num1 = row["num1"] num2 = row["num2"] num3 = row["num3"] if text[int(text.find('/send2admin'))+12:]=='': self.bot.send_message(chat.id, 'После /send2admin нужно что-нибудь написать. Сообщение не передано.\nНапомню числа:\n{} {} {}\nВаш ход.'.format(num1, num2, num3)) else: self.write_message(chat.id, str(chat.title), str(chat.username), str(chat.first_name), str(chat.last_name), str(text[int(text.find('/send2admin'))+12:])) self.bot.send_message(chat.id, bot_answer.format(text[int(text.find('/send2admin'))+12:], num1, num2, num3)) except Exception: self.bot.send_message(chat.id, 'Unknow error. Sorry.') else: bot_answer = '{} {} {}\n' try: result = re.split(r'[\s]', text) numcount = len(result) if (numcount == 3): num1 = int(result[0]) num2 = int(result[1]) num3 = int(result[2]) list_from_user = [num1, num2, num3] row = self.read_current_state(chat.id) if (row == None): new_list = self.make_a_move(list_from_user) self.write_new_user(chat.id, new_list[0], new_list[1], new_list[2]) self.bot.send_message(chat.id, bot_answer.format(self.bot.send_message(chat.id, bot_answer.format(num1, num2, num3)))) else: list_from_db = [row["num1"], row["num2"], row["num3"]] result_of_check = self.check_user_numbers(list_from_db, list_from_user) if result_of_check == -1: self.bot.send_message(chat.id, "Error. Ошибка при обработке ответа. Нужно изменть одно число. Нельзя изменять больше, чем одно число.") elif result_of_check == -2: self.bot.send_message(chat.id, "Error. Ошибка при обработке ответа. Число можно изменять только в меньшую сторону.") elif result_of_check == 0: if list_from_user[0]==0 and list_from_user[1]==0 and list_from_user[2]==0: num1 = random.randint(config.min_random,config.max_random) num2 = random.randint(config.min_random,config.max_random) num3 = random.randint(config.min_random,config.max_random) self.write_current_state(chat.id, num1, num2, num3) self.bot.send_message(chat.id, "Вы победили! Сыграем еще? Вот новые числа:\n{} {} {}".format(num1, num2, num3)) else: new_list = self.make_a_move(list_from_user) if new_list[0]==0 and new_list[1]==0 and new_list[2]==0: num1 = random.randint(config.min_random,config.max_random) num2 = random.randint(config.min_random,config.max_random) num3 = random.randint(config.min_random,config.max_random) self.write_current_state(chat.id, num1, num2, num3) self.bot.send_message(chat.id, "0 0 0\nЯ победил!\nСыграем еще? Вот новые числа:\n{} {} {}".format(num1, num2, num3)) else: num1 = new_list[0] num2 = new_list[1] num3 = new_list[2] self.write_current_state(chat.id, num1, num2, num3) self.bot.send_message(chat.id, bot_answer.format(str(num1), str(num2), str(num3))) else: self.bot.send_message(chat.id, "Error. Ошибка при обработке ответа. Вы должны прислать три числа, разделенные одинарным пробелом. Если вы хотите написать администратору, используйте команду /send2admin") except Exception: self.bot.send_message(chat.id, 'Unknow error. Sorry.') except Exception: pass def run(self): print('Main loop started') while True: updates = self.bot.get_updates(offset=self.last_update_id).wait() try: for update in updates: if int(update.update_id) > int(self.last_update_id): self.last_update_id = update.update_id self.process_message(update) except Exception as ex: print(traceback.format_exc())
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
elif u.message.location: #if the message contains a location then get the weather on that latitude/longitude print u.message.location chat_id = u.message.chat.id owm = OWM(OWMKEY) #initialize the Weather API obs = owm.weather_at_coords(u.message.location.latitude, u.message.location.longitude) #Create a weather observation w = obs.get_weather() #create the object Weather as w print(w) # <Weather - reference time=2013-12-18 09:20, status=Clouds> l = obs.get_location() #create a location related to our already created weather object And send the parameters status = str(w.get_detailed_status()) placename = str(l.get_name()) wtime = str(w.get_reference_time(timeformat='iso')) temperature = str(w.get_temperature('celsius').get('temp')) bot.send_message(chat_id, 'Weather Status: ' +status +' At '+placename+' ' +wtime+' Temperature: '+ temperature+ 'C') #send the anwser bot.send_message(chat_id, 'please select an option', reply_markup=reply_markup).wait() #send the options again else: print u bot.send_message(chat_id, 'please select an option', reply_markup=reply_markup).wait() while True: #a loop to wait for messages updates = bot.get_updates(offset = last_update_id).wait() #we wait for a message try: for update in updates: #get the messages if int(update.update_id) > int(last_update_id): #if it is a new message then get it last_update_id = update.update_id process_message(bot, update) #send it to the function continue continue except Exception: ex = None print traceback.format_exc() continue
class TelegramForeignDataWrapper(ForeignDataWrapper): def __init__(self, options, columns): super(TelegramForeignDataWrapper, self).__init__(options, columns) self.bot = TelegramBot(options['bot_id']) self.columns = columns self._row_id_column = options['primary_key'] def execute(self, quals, columns): updates = self.bot.get_updates().wait() for update in updates: line = {} line['update_id'] = update.update_id line['chat_id'] = update.message.chat.id line['message'] = update.message.text line['payload'] = json.dumps({ "update": { "update_id": update.update_id, "message": { "message_id": update.message.message_id, "sender": update.message.sender.__dict__, "date": update.message.date, "chat": update.message.chat.__dict__, "forward_from": update.message.forward_from, "forward_date": update.message.forward_date, "reply_to_message": update.message.reply_to_message, "text": update.message.text, "audio": update.message.audio, "document": update.message.document, "photo": update.message.photo, "sticker": update.message.sticker, "video": update.message.video, "voice": update.message.voice, "caption": update.message.caption, "contact": update.message.contact, "location": update.message.location, "new_chat_participant": update.message.new_chat_participant, "left_chat_participant": update.message.left_chat_participant, "new_chat_title": update.message.new_chat_title, "new_chat_photo": update.message.new_chat_photo, "delete_chat_photo": update.message.delete_chat_photo, "group_chat_created": update.message.group_chat_created } } }) yield line def insert(self, values): result = self.bot.send_message(int(values['chat_id']), values['message']).wait() @property def rowid_column(self): if self._row_id_column is None: log_to_postgres( 'You need to declare a primary key option in order ' 'to use the write features') return self._row_id_column