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(): 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
#!/usr/bin/env python3 from twx.botapi import TelegramBot, ReplyKeyboardMarkup, InputFileInfo, InputFile import os import sys import time 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) fp = open(os.path.expanduser(sys.argv[1]), 'rb') file_info = InputFileInfo(sys.argv[1], fp, 'image/png') inputfile=InputFile('photo', file_info) bot.send_photo(chat_id=my_user_id, photo=inputfile)
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)
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
print("started") bot = TelegramBot('157665031:AAHaeUoydRVxbisOrx-yA3542NYlmA0XOdo') bot.update_bot_info().wait() print(bot.username) """ Send a message to a user """ user_id = int(122012260) fp = open('0005-006-TSypljonok-ostalsja-u-zabora-odin.png', 'rb') file_info = InputFileInfo('0005-006-TSypljonok-ostalsja-u-zabora-odin.png', fp, 'image/png') i = InputFile('photo', file_info) bot.send_photo(chat_id=79434866, photo=i) #result = bot.send_message(user_id, 'ddd').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'],
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())
#SENDP.PY from twx.botapi import TelegramBot, ReplyKeyboardMarkup f = open('photo2.jpg', 'r+') jpgdata = f.read() bot = TelegramBot('232181922:AAG5L_UGt9pEvfhL4LqZFTu3Hyjk8srYR-0') bot.update_bot_info().wait() user_id = int(148942492) bot.send_photo(user_id, '/home/debian/photo2.jpg') f.close()
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