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'
class NotificationSender: def __init__(self, bot_token, user_id): self.bot = TelegramBot(bot_token) self.user_id = user_id def send_message(self, message): self.bot.send_message(self.user_id, message).wait()
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
def notify(self, check): bot = TelegramBot(self.channel.value) bot.update_bot_info().wait() if bot.username is not None: # Send a welcome message notification = 'The check with name:' + check.name + \ 'and code:' + str(check.code) + ' has gone ' + check.status bot.send_message(self.channel.telegram_id, notification).wait()
def post(self, user, report): tb = Telegram(user.get_telegram_credentials()) text = report.text if len(text) > 4096: text = text[:4096 - 4] + u' ...' try: for subscriber_id in user.get_telegram_subscribers(): tb.send_message(subscriber_id, text).wait() except Exception: logger.error('Error telegramming: ' + user.get_city() + ': ' + str(report.id), exc_info=True)
def telegram_bot(url, regexs): bot = TelegramBot(BOT_API_TOKEN) bot.update_bot_info().wait() print(bot.username) bot.send_message(CHAT_ID, "[%s] Bot Starting" % str(datetime.now())).wait() while (True): diff = diff_html(url, regexs) if diff: for diff_message in diff: ticket = ["Ticket", "ticket"] print diff_message for t in ticket: print t if t in diff_message: bot.send_message( CHAT_ID, "TICKET WORD APPEARED IN A DIFF!!1111").wait() sleep(2) bot.send_message( CHAT_ID, "TICKET WORD APPEARED IN A DIFF!!1111").wait() bot.send_message(CHAT_ID, "Last updates:\n %s" % diff_message).wait() else: print("LOG: No diff") sleep(CYCLE_TIME)
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 update(): bot = TelegramBot(token) bot.update_bot_info().wait() if 'chat' in request.json['message']: chat = request.json['message']['chat']['id'] if 'text' in request.json['message']: text = request.json['message']['text'] if text.find('vice') != -1: bot.send_message(chat, vice()).wait() if text.find('drink') != -1: bot.send_photo(chat,bill()).wait() #Print in console for fast Debugging print(json.dumps(request.json)) return "ok"
def update(): bot = TelegramBot(token) bot.update_bot_info().wait() if 'chat' in request.json['message']: chat = request.json['message']['chat']['id'] if 'text' in request.json['message']: text = request.json['message']['text'] if text.find('vice') != -1: bot.send_message(chat, vice()).wait() if text.find('drink') != -1: bot.send_photo(chat, bill()).wait() #Print in console for fast Debugging print(json.dumps(request.json)) return "ok"
def main(): last_post_date, tgm_data = load_settings() rss = feedparser.parse(settings.RSS_URL) logging.debug("last_post_date: %s", last_post_date.isoformat()) # find new entries in feed new_entries = [] for entry in rss.entries: try: entry_published = datetime.utcfromtimestamp( calendar.timegm(entry.published_parsed)) if entry_published > last_post_date: new_entries.append(entry) except AttributeError as e: logging.error("%s\n%s", e, entry) logging.info('The number of new entries: %s\nEntries: %s', len(new_entries), [(item.get('id'), item.get('published_parsed')) for item in new_entries]) date = datetime.now() if not new_entries: logging.info('New entries are not found') save_settings(date.isoformat()) return # sort new entries by published date new_entries.sort(key=lambda item: item.published_parsed) # send to telegram channel tgm_bot = TelegramBot(settings.TGM_BOT_ACCESS_TOKEN) for entry in new_entries: try: logging.debug("Raw message:\n%s\n", entry.description) text = entry.title + '\n\n' + entry.link + '\n\n' + entry.description message = remove_tags(text) logging.debug("message:\n%s\n", message) except AttributeError as e: logging.error("%s\n%s", e, entry) continue answer = tgm_bot.send_message(settings.TGM_CHANNEL, message).wait() if isinstance(answer, twx.botapi.Error): logging.error("error code: %s\nerror description: %s\n", answer.error_code, answer.description) break else: date = max( datetime.utcfromtimestamp( calendar.timegm(entry.published_parsed)), date ) time.sleep(1) save_settings(date.isoformat())
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 pub_to_telegram(text, bot_token, tg_channel): tgm_bot = TelegramBot(bot_token) answer = tgm_bot.send_message(tg_channel, text).wait() if isinstance(answer, twx.botapi.Error): print('error code: %s\nerror description: %s\n', answer.error_code, answer.description) else: print('OK')
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
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()
def send_telegram(pdf): """ Отсылается сообщение через telegram bot. Получатель определяется по полю user.employee.sms_notify :param pdf: :return: """ d = shelve.open('shelve.db') import_mode = d['IMPORT_MODE'] d.close() logger.info('') logger.info('――> Telegram:') if import_mode: logger.info('····skip due import mode') return None if pdf.upload_to_ctpbureau_status: if pdf.ctpbureau.name == 'Admin': # TODO прибито гвоздями; можно сделать в настройках что-то вроде, - пропускать, если есть стоп-слова в названии. Но опять таки - что пропускать? Аплоад? Смс? Нотификации? Если все пропускать, тогда дебажить не получится # debugging purpose; if outputter is Admin then telegram send only to first superuser receivers = Employee.objects.filter(user__is_superuser=True) else: receivers = Employee.objects.filter(telegram_notify=True) for each in receivers: telegram_id = each.telegram_id bot = TelegramBot(settings.TELEGRAM_API_KEY) message = """ №{} {} Плит: {}, Машина: {}, Вывод: {} """.format(pdf.order, pdf.ordername, str(pdf.plates),pdf.machines[1].name, pdf.ctpbureau.name) # logger.debug('telegram_id={}'.format(telegram_id)) # logger.debug('username={}'.format(each.user.username)) responce = bot.send_message(chat_id=telegram_id, text=message).wait() if isinstance(responce, twx.botapi.botapi.Message): logger.info('··· {} receive notify'.format(responce.chat.username)) elif isinstance(responce, twx.botapi.botapi.Error): logger.error(responce) else: logger.error('Critical telegram twx bug:') logger.error(responce) else: # если по какой-то причине у нас не софрмирован upload_to_ctpbureau_status logger.warning('····telegram NOT sent. Reason: failed upload')
def run(self): init_logging() """ TODO: create directory for archive if it does not excist already """ bot = TelegramBot(BOT_ID) bot.update_bot_info().wait() print(bot.username) logging.info("Bot %s running", bot.username) page_source = download(URL) old_titles = titles(page_source) logging.info("First set of titles parsed") minutes = 60 * INTERVAL # Disabled sending messages to the channel to decrease spam result = bot.send_message(DEV_PERSONAL_ID, "The blog will be watched").wait() # print("Sending channel: " + str(result)) logging.info("Sending channel: " + str(result)) while True: time.sleep(minutes) try: page_source = download(URL) new_titles = titles(page_source) diff = new_titles.has_changed(old_titles) except socket.error: diff = -2 if (diff == -2): print("No internet connection") logging.info("No internet connection") elif (diff < 0): print("no changes were made") logging.info("No changes were made") else: print("Changes on target") logging.info("Changes on target") save_index(page_source) message = message_hj() old_titles = new_titles try: message.add_title_in_cleartxt(new_titles.get_title(diff)) message.send_to_telegram(bot) except: fallback_msg = message_hj() fallback_msg.fallback_without_title() fallback_msg.send_to_telegram(bot)
class TelegramBroadcaster(): """ Setup the bot """ def __init__(self): self.bot = TelegramBot('<BOT_KEY>') self.bot.update_bot_info().wait() self.user_id = int(<CHANNEL_KEY>) # channel goyanglib print(self.bot.username) def send(self, message): result = self.bot.send_message(self.user_id, message).wait() print(result)
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 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
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
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)
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')
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 if fromuser.last_name is not None: humanname += ' ' + fromuser.last_name print('From ' + humanname + ' ' + txt + ' (id ' + str(userid) + '): ' + txt) if username == botmaster: command_text = parse_command(txt) if command_text is not None: bot.send_message(msg.chat.id, command_text) continue parse_scene(txt, msg.chat.id) except Exception as e: print(e) sleep(sleep_time) db_conn.close()
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)
if path.exists(DUMP_FILE): # Se existe, carregar a lista de mensagens respondidas pkl_file = open(DUMP_FILE) answered_messages = pickle.load(pkl_file) else: answered_messages = [] bot_message = "Oi, eu sou um bot do BRAZIL" while (True): print ("Getting updates".center(50, '-')) updates = bot.get_updates().wait() for pos, update in enumerate(updates): print(str(pos) +" "+ str(update) + "n") update_id = update.update_id if (update_id not in answered_messages): # Se a mensagem não foi respondida, responda o usuário sender_id = update.message.sender.id result = bot.send_message(sender_id, bot_message).wait() print(result) if (result): answered_messages.append(update_id) output = open(DUMP_FILE, 'wb') pickle.dump(answered_messages, output) # persiste a lista de mensagens respondidas sleep(30)
# -*- coding: utf-8 -*- from twx.botapi import TelegramBot BOT_TOKEN = '261616344:AAG7mO1GEA6KDwPYFV6V3hiXv1PMfKYlcvM' bot = TelegramBot(BOT_TOKEN) if __name__ == '__main__': a = bot.send_message(u'@helloworldru', u'Hellorld barowold!').wait() print(a)
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() bot.send_message(chat_id, "These Spanish dudez you know...").wait() while(True): time.sleep(1) updates = bot.get_updates(update_id).wait() while(updates == []): time.sleep(0.5) updates = bot.get_updates().wait() for update in updates: update=update print("==========") print(update_id) tmp_update_id = update.update_id; if(True):
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())
from twilio.rest import Client client = Client(account_sid, auth_token) #sms message = client.messages \ .create( body=text_body, from_='+1', to=hp '+65' ) #whatsapp message = client.messages.create( body=text_body, from_='whatsapp:+1', to='whatsapp:'+hp ) #tele from twx.botapi import TelegramBot, ReplyKeyboardMarkup bot = TelegramBot('706256156:AAFjCPB4IsmMxrh8u6GheEzAbNldb9Znhuo') bot.update_bot_info().wait() user_id = int(tele) result = bot.send_message(user_id, text_body).wait()
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 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 send_notification(token, user_id, message): bot = TelegramBot(token) bot.send_message(user_id, message).wait()
#print(jam_jadw-1) if jam in range(jam_jadw - 1, jam_jadw + 5): #print(log, jam_jadw) #print('y') #print('iii', iii) if not str(log) == str(jam_jadw): save_ = open("time_log.txt", "w+") save = save_.write(str(jam_jadw)) save_.close() jam_jadw_ = str(jam_jadw)[:2] + ':' + str( jam_jadw)[2:] jwl = 'hayoo, kakak ada jadwal hari ini loh, \njam : ' + jam_jadw_ + '\nmakul : ' + str( j['jadwal'][hari]['jam'][iii] ['makul']) + '\ndiruang : ' + str( j['jadwal'][hari]['jam'][iii]['ruang']) result = bot.send_message(user_id, jwl).wait() #print('hayoo, kakak ada jadwal hari ini loh, ') #print(jwl) iii += 1 else: ii -= 1 ii += 1 i += 1 except KeyError: #print('x') jam_ = datetime.datetime.now() tambah = datetime.timedelta(hours=7) jam_ = (jam_ + tambah).time() jam = int(str(jam_.time())[:2] + str(jam_.time())[3:5]) jams = str(jam_.time())[:2] + str(jam_.time())[3:5] if jams == '0800':
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() bot.send_message(chat_id, "Thank god it's Friday!").wait() while(True): time.sleep(1) updates = bot.get_updates(update_id).wait() while(updates == []): time.sleep(0.5) updates = bot.get_updates().wait() for update in updates: update=update print("==========") print(update_id) tmp_update_id = update.update_id; if(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": scenario.load(user) reply, menu = scenario.next() user.load(scenario) user.lastMessage = round(time.time())
#!/usr/bin/env python3 from twx.botapi import TelegramBot, ReplyKeyboardMarkup import sys import os import time print "spam spawned" with open(os.path.expanduser("~/arantgbot.api_token"), 'r') as _file: api_token = _file.readline().strip() with open(os.path.expanduser("~/arantgbot.my_user_id"), 'r') as _file: my_user_id = int(_file.readline().strip()) bot = TelegramBot(api_token) for i in range(100): time.sleep(1) msg = str(i) + " " + " ".join(sys.argv[1:]) print "spammm:", msg bot.send_message(my_user_id, msg).wait()
encodedtext.encode(encoding='utf-8', errors='ignore') #print encodedtext.encode('utf-8') encodedpmsg = pmsg if encodedpmsg is not None: encodedpmsg.encode(encoding='utf-8', errors='ignore') #print encodedpmsg.encode('utf-8') if pmsg is not msg.text: #if encodedpmsg is not None: #print encodedpmsg.encode('utf-8') if len(updates) >= 0: last_id = int(updates[len(updates) - 1][TELEGRAM_MSGID]) + 1 if msg.text is not None: if "adding" in msg.text: bot.send_message(msg.chat.id, random.choice(welcome_list)) elif "Adding" in msg.text: bot.send_message(msg.chat.id, random.choice(welcome_list)) elif "Let's welcome" in msg.text: bot.send_message(msg.chat.id, random.choice(welcome_list)) elif "lets welcome" in msg.text: bot.send_message(msg.chat.id, random.choice(welcome_list)) elif "Lets welcome" in msg.text: bot.send_message(msg.chat.id, random.choice(welcome_list)) elif "let's welcome" in msg.text: bot.send_message(msg.chat.id, random.choice(welcome_list)) elif "Welcome " in msg.text: bot.send_message(msg.chat.id, random.choice(welcome_list)) elif "All the best" in msg.text: bot.send_message(msg.chat.id, "Good Luck..." + "\xF0\x9F\x98\x94")
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 CloudLog(object): """ Lets you duplicate console logs in a locally stored file, folder on Dropbox and receive updates in a Telegram chat. """ def __init__(self, root_path, dropbox_token=None, telegram_token=None, telegram_chat_id=None): """ Initialises a new logger instance. Parameters ---------- root_path : Local log root path. dropbox_token : Dropbox access token. telegram_token : Telegram Bot API access token. telegram_chat_id : Telegram chat ID. """ self.telegram_chat_id = int(telegram_chat_id) if telegram_chat_id is not None else None self.cloud_log_writer = dropbox.Dropbox(dropbox_token) if dropbox_token is not None else None self.notification_bot = TelegramBot(telegram_token) if telegram_token is not None else None self.log_file = time.strftime('%Y-%m-%d_%H-%M-%S') + '_log.txt' self.root = root_path os.makedirs(root_path, exist_ok=True) def __call__(self, string): """ Logs the value to console and appends the same string to the log file. Parameters ---------- string : string Value to be logged. """ print(string) with open(os.path.join(self.root, self.log_file), 'a') as file: file.write(string + '\n') def add_plot(self, notify=False, caption=None): """ Saves current `pyplot` plot as a .png, uploads it to Dropbox and optionally notifies via Telegram chat. Parameters ---------- notify : Flag indicating if we need to send a Telegram notification. caption : Optional plot caption. """ plot_file = time.strftime('%Y-%m-%d_%H-%M-%S') + '.png' plot_path = os.path.join(self.root, plot_file) pyplot.savefig(plot_path) self.cloud_upload_plot(plot_file) if notify: self.bot_send_plot(plot_file, caption) def sync(self, notify=False, message=None): """ Synchronises local log with Dropbox. Parameters ---------- notify : Flag indicating if we need to send a Telegram notification. message : Optional notification message. """ self.cloud_sync_log() if notify: self.bot_send_message(message) self.bot_send_log() # Dropbox routines def cloud_sync_log(self): """ Syncs local log with the one in Dropbox App's folder (e.g. overwrtites it). """ if self.cloud_log_writer is None: return with open(os.path.join(self.root, self.log_file), 'rb') as file: try: self.cloud_log_writer.files_upload( file.read(), '/' + self.log_file, mode=dropbox.files.WriteMode('overwrite', None) ) except Exception as e: self('Failed to sync log: ' + str(e)) pass def cloud_upload_plot(self, filename): """ Uploads plot to Dropbox app's folder. Parameters ---------- filename : Plot filename or relative path. """ if self.cloud_log_writer is None: return plot_path = os.path.join(self.root, filename) with open(plot_path, 'rb') as file: try: self.cloud_log_writer.files_upload( file.read(), '/' + filename, mode=dropbox.files.WriteMode('overwrite', None) ) except Exception as e: self('Failed to upload plot: ' + str(e)) pass # Telegram routines def bot_send_message(self, message, mode="Markdown"): """ Sends a text message to default Telegram chat. Parameters ---------- message : Message to send. mode : Message parsing mode. Defaults to `Markdown`. """ if self.notification_bot is None or self.telegram_chat_id is None: return try: self.notification_bot.send_message( self.telegram_chat_id, message, parse_mode=mode ).wait() except Exception as e: self('Failed to send notification: ' + str(e)) pass def bot_send_plot(self, filename, caption=None): """ Sends plot saved as `filename` to default Telegram chat with optional caption. Parameters ---------- filename : Plot filename or path relative to current directory. caption : Optional plot caption. """ if self.notification_bot is None or self.telegram_chat_id is None: return plot_path = os.path.join(self.root, filename) with open(plot_path, 'rb') as file: try: self.notification_bot.send_photo( self.telegram_chat_id, InputFile('photo', InputFileInfo(filename, file, 'image/png')), caption=caption, disable_notification=True ).wait() except Exception as e: self('Failed to send plot: ' + str(e)) pass def bot_send_log(self): """ Sends current log file to default Telegram chat. Does not notify the user about this message, send a separate message if you want the notification to hit user's device. """ if self.notification_bot is None or self.telegram_chat_id is None: return with open(os.path.join(self.root, self.log_file), 'rb') as file: try: self.notification_bot.send_document( self.telegram_chat_id, InputFile('document', InputFileInfo(self.log_file, file, 'text/plain')), disable_notification=True ).wait() except Exception as e: self('Failed to send log: ' + str(e)) pass
#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() try: print >> sys.stderr, 'connection from', client_address #Receive data in 16 bytes chunk while True: data = connection.recv(16) print >> sys.stderr, 'received "%s"' % data if data: bufferdata = bufferdata + data elif "" in data: bot.send_message(msg.chat.id, bufferdata) bufferdata = "" connection.close() break else: #send message to Telegram bot.send_message(msg.chat.id, bufferdata) bufferdata = "" connection.close() break finally: bufferedata = "" connection.close()
'Who killed Joffrey?', 'Why did Jaime tell Tyrion that caused him to kill Tywin?', 'What species were the first humanoid creatures to walk on Westeros?', 'Which famous man bought down almost all Westeros to heel?' ] arrayEnd = len(QuestionsList) - 1 i = random.randint(0, arrayEnd) user_id = int(########) last_update_id = 0 #last processed command bot.send_message(user_id, 'Hello, please use the /question command to start the trivia!').wait() '''while True: updates = bot.get_updates(offset = last_update_id + 1, limit = None, timeout=None).wait() r = requests.get('https://api.telegram.org/bot125579945:AAGjgsLLGeSqSILvfky71QjuMcZpeIBpuho/getUpdates') if r.status_code == 200: if not updates: continue else: #len(responses) - 1 update_id = updates[0][0]
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
write(message) """ Setup the bot """ bot = TelegramBot('204368082:AAEfHT1b1pXmBJM3OfbSHUaL5Th30zdsmtI') bot.update_bot_info().wait() print(bot.username) """ Send a message to a user """ user_id = int(153170813) result = bot.send_message(user_id, bot.username + " is Online!").wait() print(result) """ Use a custom keyboard """ keyboard = [[':joy:', '8', '9'], ['4', '5', '6'], ['1', '2', '3'], ['0']] reply_markup = ReplyKeyboardMarkup.create(keyboard) """ Get updates sent to the bot """
""" Send a message to a user """ chat_id = update.message.chat.id;x print("chat_id: ", chat_id) print("----------") reply_markup = ForceReply(True, False) result = bot.send_message(chat_id, Menu.menu(), reply_markup=reply_markup).wait() print(">>>>" + str(result)) sys.exit(0) """ Get updates sent to the bot """ updates = bot.get_updates().wait() for update in updates: print('---') print(update) """ Use a custom keyboard """
for updates_ in updates: #print(log, updates[i].update_id) if str(updates[i].update_id) == str(log): break mulai = i+1 i += 1 while True: tambah = datetime.timedelta(hours=7) jam_ = datetime.datetime.now() hari_ = datetime.datetime.now() jam_ = (jam_+tambah).time() hari = hari_.strftime("%A") updates = bot.get_updates().wait() info = str(jam_)+' '+str(hari)+' waktu sekarang\n' pan = len(updates) if pan > mulai: #print(pan, '>', mulai) if not log == str(updates[pan-1].update_id): save = open('log.txt', 'w+') save.write(str(updates[mulai].update_id)) save.close() user_id = updates[mulai].message.chat.id #print(user_id) if updates[mulai].message.text == '/start': result = bot.send_message(user_id, 'terimakasih telah memulai').wait() elif updates[mulai].message.text == '/info': result = bot.send_message(user_id, info).wait() else: result = bot.send_message(user_id, 'command kamu salah kakak :P').wait() mulai += 1 #print([u.message.sender.id for u in updates])
from twx.botapi import TelegramBot, ReplyKeyboardMarkup """ Setup the bot """ bot = TelegramBot('194930793:AAGgpd3CP6On1GN0xY3gNhJUdg1XOUCfVNQ') bot.update_bot_info().wait() print(bot.username) """ Send a message to a user """ user_id = int(196123754) result = bot.send_message(user_id, 'test message body').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'],
r = api.request('statuses/update', {'status': TWEET_TEXT}) print('SUCCESS' if r.status_code == 200 else 'FAILURE') """ Setup the bot """ bot = TelegramBot('332101015:AAFy9vC_d4Dj5GK7bkIQa5kETnudMqZWUhY') bot.update_bot_info().wait() print(bot.username) """ Send a message to a user """ user_id = int(185350524) result = bot.send_message(user_id, str1).wait() print(result) """ Get updates sent to the bot """ updates = bot.get_updates().wait() for update in updates: print(update) """ 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()
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() 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 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