def setupBot(apitoken): """ Setup the bot """ bot = TelegramBot(apitoken) bot.update_bot_info().wait() return bot
def start(self): self.logger.info("%s started" % self.serviceName) self.retrieveHomeSettings() if (self.botToken is None): self.logger.error ("The Telegram Token is not valid") self.stop() else: self.bot = TelegramBot(self.botToken) self.homeUpdateThread = Thread (target = self.homeUpdate) self.homeUpdateThread.start() # serving clients try: while self.isRunning: try: #The get_updates method returns the earliest 100 unconfirmed updates updates = self.bot.get_updates(offset = self.lastUpdateID + 1).wait() if (updates is not None): cont1=len(updates) if cont1 != 0: replyThread = Thread (target = self.reply, args=[updates[-1]]) replyThread.start() self.lastUpdateID = updates[-1].update_id time.sleep(1) except Exception, e: self.logger.error('Something wrong occurred in telegram communication: %s. restoring the bot' % (e)) self.bot = TelegramBot(self.botToken) except KeyboardInterrupt: self.stop()
def 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 MessageServer(object): def __init__(self): self.thread_map = {} self.bot = TelegramBot(API_TOKEN) self.updates = set(self.bot.get_updates().wait()) def poll(self): while True: del_list = [] for name in self.thread_map: thread = self.thread_map[name] if thread.finished_event.isSet(): del_list.append(name) for x in del_list: del self.thread_map[x] print("<{time}> Waiting....".format(time=datetime.now().time())) updates = set(self.bot.get_updates().wait()) new_updates = updates.difference(self.updates) for update in new_updates: print("<{time}> Received new message....".format(time=datetime.now().time())) user = update.message.sender.id if user in self.thread_map: print("<{time}> Dispatching message to thread....".format(time=datetime.now().time())) self.thread_map[user]._add_to_queue(update.message.text) else: print("<{time}> Creating new thread....".format(time=datetime.now().time())) user_thread = Worker(user) self.thread_map[user] = user_thread print("<{time}> Dispatching message to thread....".format(time=datetime.now().time())) user_thread._add_to_queue(update.message.text) self.updates.add(update)
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(): try: with open('API_KEY', 'r') as f: api_key = f.read().replace('\n', '') except IOError: print "please write the api key in file `API_KEY`" exit(1) bot = TelegramBot(api_key) bot.update_bot_info().wait() print(bot.username) last_update_id = int(0) while True: try: updates = bot.get_updates(offset=last_update_id+1, timeout=5).wait() for update in updates: last_update_id = update.update_id #print(update) process_update(bot, update) except KeyboardInterrupt: # Allow ctrl-c. raise KeyboardInterrupt except Exception as e: print "---\nException: " print e traceback.print_exc() pass
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 __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 __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 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 start(): bot = TelegramBot(token) bot.update_bot_info().wait() print(bot.username) #foto belle -33909375 #user_id = int(23263342) #result = bot.send_message(user_id, 'Salve ragazzi').wait() #XXX WebHook automatico non funzionante result = bot.set_webhook(token) print('*****Il risultato:' % (result)) return "ok"
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 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)
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')
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)
def retrieve_telegram_id(self, data): api_token = dict(data)['value'][0] auth = dict(data)['auth_code'][0] bot = TelegramBot(api_token) bot.update_bot_info().wait() if bot.username is not None: updates = bot.get_updates().wait() data = dict() for update in updates: id = update._asdict()['message']._asdict()['sender']._asdict( )['id'] text = update._asdict()['message']._asdict()['text'] data[id] = text if auth in list(data.values()): user_id = list(data.keys())[list(data.values()).index(auth)] return 'er1' # Send a welcome message welcome_message = """Welcome to HealthChecks B Notifications via Telegram Messanger.""" bot.send_message(user_id, welcome_message).wait() return user_id return 'er2'
def crawl(self, user): tb = Telegram(user.get_telegram_credentials()) seen_tg = user.get_seen_tg() try: updates = tb.get_updates(offset=seen_tg + 1, allowed_updates="message").wait() except TypeError: updates = tb.get_updates().wait() reports = [] if updates == None: return reports for update in updates: # return when telegram returns an error code if update in [303, 404, 420, 500, 502]: return reports if isinstance(update, int): try: logger.error("City " + str(user.uid) + ": Unknown Telegram error code: " + str(update) + " - " + str(updates[1])) except TypeError: logger.error("Unknown Telegram error code: " + str(update)) return reports user.save_seen_tg(update.update_id) if update.message.text.lower() == "/start": user.add_telegram_subscribers(update.message.sender.id) tb.send_message( update.message.sender.id, "You are now subscribed to report notifications.") # TODO: /start message should be set in frontend elif update.message.text.lower() == "/stop": user.remove_telegram_subscribers(update.message.sender.id) tb.send_message( update.message.sender.id, "You are now unsubscribed from report notifications.") # TODO: /stop message should be set in frontend elif update.message.text.lower() == "/help": tb.send_message( update.message.sender.id, "Send reports here to share them with other users. Use /start and /stop to get reports or not.") # TODO: /help message should be set in frontend else: # set report.author to "" to avoid mailbot crash sender_name = update.message.sender.username if sender_name is None: sender_name = "" reports.append(Report(sender_name, self, update.message.text, None, update.message.date)) return reports
def __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 run(self): try: json_data = open("settings.json").read() self.settings = json.loads(json_data) """ Setup the bot """ self.bot = TelegramBot(self.settings["tg-apiKey"]) self.dsf = DatasheetFinder(self.settings["el14-apiKey"]) self.bot.update_bot_info().wait() self.db = {} logging.info("username is %s" % self.bot.username) for update in self.get_updates_cont(): self.handleUpdate(update) except KeyboardInterrupt: logging.info("halting due to KeyboardInterrupt")
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 __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 __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 __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
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 __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 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"
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 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 __init__(self, user, *args, **kwargs): super(Worker, self).__init__(*args, **kwargs) if "timeout" in kwargs: self.max_timeout = kwargs["timeout"] else: self.max_timeout = 600 # 10 minute timeout by default. self._queue = Queue() self.awaiting_command = True self.user = user self.bot = TelegramBot(API_TOKEN) self.affirmative = ["yes", "yup", "yeah", "yea"] self.negative = ["no", "nope", "none", "negative"] self.finished_event = threading.Event() self.last_message_time = datetime.now()
def init(self): # init Telegram bot through API token = os.environ.get('TELEGRAM_TOKEN') if not token: f = open(TELEGRAM_TOKEN_FILE) token = f.read() f.close() bot = TelegramBot(token) if not bot: self.error_message = 'Cannot initialize Bot' return False self.initialized = True self.bot = bot return True
def main(): try: with open('API_KEY', 'r') as f: api_key = f.read().replace('\n', '') except IOError: print "please write the api key in file `API_KEY`" exit(1) bot = TelegramBot(api_key) bot.update_bot_info().wait() print(bot.username) last_update_id = int(0) last_fortune = (datetime.now() - timedelta(minutes=31)) while True: try: updates = bot.get_updates(offset=last_update_id+1, timeout=5).wait() for update in updates: last_update_id = update.update_id print(update) process_update(bot, update) global rems for rem in rems: if rem.when < datetime.now(): bot.send_message(rem.chatid, "=== RAPPEL ===\n\n" + unicode(rem.what)) print "removing reminder " + str(rem.id) rems = [r for r in rems if r.id != rem.id] print "rems = " + str(rems) odd = random.randint(0, 100) thirty_minutes = (datetime.now() - datetime.timedelta(minutes=5)) if last_fortune < thirty_minutes and 50 < odd: last_fortune = datetime.datetime.now() msg = subprocess.check_output("fortune") + ' #fortune' bot.send_message(update.message.chat.id, msg) except KeyboardInterrupt: # Allow ctrl-c. raise KeyboardInterrupt except Exception as e: print "---\nException: " print e traceback.print_exc() pass
def __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()
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 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 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)
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 __init__(self, token, plugins=[], no_command=None, db_url=None): self._token = token self.tg = TelegramBot(token) self._last_id = None self.cmds = {} self.pcmds = {} self._no_cmd = no_command self._msgs = {} self._plugins = plugins if no_command is not None: if not isinstance(no_command, TGPluginBase): raise NotImplementedError("%s does not subclass tgbot.TGPluginBase" % type(no_command).__name__) for p in self._plugins: if not isinstance(p, TGPluginBase): raise NotImplementedError("%s does not subclass tgbot.TGPluginBase" % type(p).__name__) for cmd in p.list_commands(): if not isinstance(cmd, TGCommandBase): raise NotImplementedError("%s does not subclass tgbot.TGCommandBase" % type(cmd).__name__) if cmd in self.cmds or cmd in self.pcmds: raise Exception( "Duplicate command %s: both in %s and %s" % (cmd.command, type(p).__name__, self.cmds.get(cmd.command) or self.pcmds.get(cmd.command)) ) if cmd.prefix: self.pcmds[cmd.command] = cmd else: self.cmds[cmd.command] = cmd if db_url is None: self.db = connect("sqlite:///:memory:") models.database_proxy.initialize(self.db) self.setup_db() else: self.db = connect(db_url) self.db.autorollback = True models.database_proxy.initialize(self.db)
def __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 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
import sys from time import sleep from twx.botapi import TelegramBot, ReplyKeyboardMarkup #Telegram BotAPI import traceback from pyowm import OWM #Weather API from config import Config """ Setup the bot and the Weather API """ c = Config() TOKEN = c.getToken() OWMKEY = c.getOWMKEY() bot = TelegramBot(TOKEN) bot.update_bot_info().wait() #wait for a message print bot.username last_update_id = 0 def process_message(bot, u): #This is what we'll do when we get a message #Use a custom keyboard keyboard = [['Get Weather']] #Setting a Button to Get the Weather reply_markup = ReplyKeyboardMarkup.create(keyboard) #And create the keyboard if u.message.sender and u.message.text and u.message.chat: #if it is a text message then get it chat_id = u.message.chat.id user = u.message.sender.username message = u.message.text print chat_id print message if message == 'Get Weather': #if the user is asking for the weather then we ask the location bot.send_message(chat_id, 'please send me your location')
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 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())
nse = Nse() q = nse.get_quote('infy') #pprint(q) str1 = str(q) r = api.request('statuses/update', {'status': TWEET_TEXT}) print('SUCCESS' if r.status_code == 200 else 'FAILURE') """ Setup the bot """ bot = TelegramBot('332101015:AAFy9vC_d4Dj5GK7bkIQa5kETnudMqZWUhY') bot.update_bot_info().wait() print(bot.username) """ Send a message to a user """ user_id = int(185350524) result = bot.send_message(user_id, str1).wait() print(result) """ Get updates sent to the bot """ updates = bot.get_updates().wait() for update in updates: print(update)
def main(): bot = TelegramBot(token) #Connect with the bot bot.update_bot_info().wait() print("botUsername: "******"\n chat_id: ", chat_id) print("user: \n", user) if u.message.document: print(" \n BOT.MESSAGE.DOCUMENT, Layer 9") print(u.message.document) print("\n") # Get file info file_Info = botto.get_file(u.message.document.file_id) # Download locally to manipulate later file_Info.download(u.message.document.file_name) filesToSend.append(u.message.document.file_name) print("\n Layer 9: Esperando por archivo o Send") keyboard = [['Send'], ['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message( chat_id, "Do you have another file? or do you want to send email?", reply_markup=reply_markup).wait() layer9(bot, last_update_id, usr, pwd, dest, sub, content, filesToSend) elif u.message.photo: print(" \n BOT.MESSAGE.PHOTO, Layer 9") print(u.message.photo) print("\n") # Get file info file_Info = botto.get_file(u.message.photo[3].file_id) # Download locally to manipulate later tofu = u.message.photo[3].file_id file_Info.download(tofu) filesToSend.append(tofu) print("\n Layer 9: Esperando por archivo o Send") keyboard = [['Send'], ['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message( chat_id, "Do you have another file? or do you want to send email?", reply_markup=reply_markup).wait() layer9(bot, last_update_id, usr, pwd, dest, sub, content, filesToSend) elif u.message.text: if u.message.text == 'Send': print("Sending mail, Layer 9") bot.send_message(chat_id, 'Sending email') if sendMessage(dest, sub, content, filesToSend, usr, pwd, chat_id) == 0: bot.send_message(chat_id, 'Email send') print("Select an option, Layer 9") keyboard = [['Show unseen emails'], ['Send a email'], ['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(chat_id, 'Select an option', reply_markup=reply_markup).wait() layer4(bot, last_update_id, usr, pwd) elif u.message.text == 'Back': print("Select an option, Layer 9") keyboard = [['Show unseen emails'], ['Send a email'], ['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(chat_id, 'Select an option', reply_markup=reply_markup).wait() layer4(bot, last_update_id, usr, pwd) else: print("Select an option, Layer 9") keyboard = [['Send'], ['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(chat_id, 'Select an option', reply_markup=reply_markup).wait() else: print("Select an option, Layer 9") keyboard = [['Show unseen emails'], ['Send a email'], ['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(u.message.chat.id, 'Select an option', reply_markup=reply_markup).wait() layer4(bot, last_update_id, usr, pwd) def layer9(bot, last_update_id, usr, pwd, dest, sub, content, filesToSend): # Send mail with or without files print("\n Layer 9\n") while True: updates = bot.get_updates(offset=last_update_id).wait() try: for update in updates: if int(update.update_id) > int(last_update_id): last_update_id = update.update_id print("last_update_id: ", last_update_id) process_message_layer9(bot, update, last_update_id, usr, pwd, dest, sub, content, filesToSend) continue continue except Exception: ex = None print(traceback.format_exc()) continue def process_message_layer8(bot, u, last_update_id, usr, pwd, dest, sub, content): if u.message.sender and u.message.text and u.message.chat: # if the message is text chat_id = u.message.chat.id # Extract data of message user = u.message.sender.id message = u.message.text print("\n chat_id: ", chat_id) print("user: "******"message: ", message) print("\n") if message == 'Back': print("Select an option, Layer 8") keyboard = [['Show unseen emails'], ['Send a email'], ['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(chat_id, 'Select an option', reply_markup=reply_markup).wait() layer4(bot, last_update_id, usr, pwd) elif message == 'Attach files': print("Enviame los archivos, Layer 8") keyboard = [['Send'], ['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(chat_id, 'Send me your files', reply_markup=reply_markup).wait() layer9(bot, last_update_id, usr, pwd, dest, sub, content, []) elif message == 'Do not attach files': print("Sending mail, Layer 8") bot.send_message(chat_id, 'Sending email') if sendMessage(dest, sub, content, [], usr, pwd, chat_id) == 0: bot.send_message(chat_id, 'Email send') print("Select an option, Layer 8") keyboard = [['Show unseen emails'], ['Send a email'], ['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(chat_id, 'Select an option', reply_markup=reply_markup).wait() layer4(bot, last_update_id, usr, pwd) else: print("Select an option, Layer 8") keyboard = [['Attach files'], ['Do not attach files'], ['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(chat_id, 'Select an option', reply_markup=reply_markup).wait() layer8(bot, last_update_id, usr, pwd, dest, sub, content) else: print("Select an option, Layer 8") keyboard = [['Show unseen emails'], ['Send a email'], ['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(u.message.chat.id, 'Select an option', reply_markup=reply_markup).wait() layer4(bot, last_update_id, usr, pwd) def layer8(bot, last_update_id, usr, pwd, dest, sub, content): # Send mail with or without files print("\n Layer 8\n") while True: updates = bot.get_updates(offset=last_update_id).wait() try: for update in updates: if int(update.update_id) > int(last_update_id): last_update_id = update.update_id print("last_update_id: ", last_update_id) process_message_layer8(bot, update, last_update_id, usr, pwd, dest, sub, content) continue continue except Exception: ex = None print(traceback.format_exc()) continue def process_message_layer7(bot, u, last_update_id, usr, pwd, dest, sub): if u.message.sender and u.message.text and u.message.chat: # if the message is text chat_id = u.message.chat.id # Extract data of message user = u.message.sender.id message = u.message.text print("\n chat_id: ", chat_id) print("user: "******"message: ", message) print("\n") if message == 'Back': print("Select an option, Layer 7") keyboard = [['Show unseen emails'], ['Send a email'], ['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(chat_id, 'Select an option', reply_markup=reply_markup).wait() layer4(bot, last_update_id, usr, pwd) else: print("Select an option, Layer 7") keyboard = [['Attach files'], ['Do not attach files'], ['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(chat_id, 'Select an option', reply_markup=reply_markup).wait() layer8(bot, last_update_id, usr, pwd, dest, sub, message) else: print("Select an option, Layer 7") keyboard = [['Show unseen emails'], ['Send a email'], ['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(u.message.chat.id, 'Select an option', reply_markup=reply_markup).wait() layer4(bot, last_update_id, usr, pwd) def layer7(bot, last_update_id, usr, pwd, dest, sub): # Content print("\n Layer 7\n") while True: updates = bot.get_updates(offset=last_update_id).wait() try: for update in updates: if int(update.update_id) > int(last_update_id): last_update_id = update.update_id print("last_update_id: ", last_update_id) process_message_layer7(bot, update, last_update_id, usr, pwd, dest, sub) continue continue except Exception: ex = None print(traceback.format_exc()) continue def process_message_layer6(bot, u, last_update_id, usr, pwd, dest): if u.message.sender and u.message.text and u.message.chat: # if the message is text chat_id = u.message.chat.id # Extract data of message user = u.message.sender.id message = u.message.text print("\n chat_id: ", chat_id) print("user: "******"message: ", message) print("\n") if message == 'Back': print("Select an option, Layer 6") keyboard = [['Show unseen emails'], ['Send a email'], ['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(chat_id, 'Select an option', reply_markup=reply_markup).wait() layer4(bot, last_update_id, usr, pwd) else: print("Send me the body, Layer 6") keyboard = [['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(chat_id, 'Send me the body', reply_markup=reply_markup).wait() layer7(bot, last_update_id, usr, pwd, dest, message) else: print("Select an option, Layer 6") keyboard = [['Show unseen emails'], ['Send a email'], ['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(u.message.chat.id, 'Select an option', reply_markup=reply_markup).wait() layer4(bot, last_update_id, usr, pwd) def layer6(bot, last_update_id, usr, pwd, dest): #Subject print("\n Layer 6\n") while True: updates = bot.get_updates(offset=last_update_id).wait() try: for update in updates: if int(update.update_id) > int(last_update_id): last_update_id = update.update_id print("last_update_id: ", last_update_id) process_message_layer6(bot, update, last_update_id, usr, pwd, dest) continue continue except Exception: ex = None print(traceback.format_exc()) continue def process_message_layer5(bot, u, last_update_id, usr, pwd): if u.message.sender and u.message.text and u.message.chat: # if the message is text chat_id = u.message.chat.id # Extract data of message user = u.message.sender.id message = u.message.text print("\n chat_id: ", chat_id) print("user: "******"message: ", message) print("\n") if message == 'Back': print("Select an option, Layer 5") keyboard = [['Show unseen emails'], ['Send a email'], ['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(chat_id, 'Select an option', reply_markup=reply_markup).wait() layer4(bot, last_update_id, usr, pwd) else: print("Send me the subject, Layer 5") keyboard = [['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(chat_id, 'Send me the subject', reply_markup=reply_markup).wait() layer6(bot, last_update_id, usr, pwd, message) else: print("Select an option, Layer 5") keyboard = [['Show unseen emails'], ['Send a email'], ['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(u.message.chat.id, 'Select an option', reply_markup=reply_markup).wait() layer4(bot, last_update_id, usr, pwd) def layer5(bot, last_update_id, usr, pwd): #Insert mail address print("\n Layer 5\n") while True: updates = bot.get_updates(offset=last_update_id).wait() try: for update in updates: if int(update.update_id) > int(last_update_id): last_update_id = update.update_id print("last_update_id: ", last_update_id) process_message_layer5(bot, update, last_update_id, usr, pwd) continue continue except Exception: ex = None print(traceback.format_exc()) continue def process_message_layer4(bot, u, last_update_id, usr, pwd): global run if u.message.sender and u.message.text and u.message.chat: # if the message is text chat_id = u.message.chat.id # Extract data of message user = u.message.sender.id message = u.message.text print("\n chat_id: ", chat_id) print("user: "******"message: ", message) print("\n") if message == 'Back': run = False print("Select a option, Layer 4") keyboard = [['Loggin account'], ['Exit']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(chat_id, 'Select a option', reply_markup=reply_markup).wait() layer2(bot, last_update_id) elif message == 'Show unseen emails': print('Showing emails, Layer 4') bot.send_message(chat_id, 'Showing emails') run = True th = threading.Thread(target=analizerMail, args=( usr, pwd, chat_id, bot, last_update_id, )) th.start() elif message == 'Send a email': run = False print( 'Send me the emails of the destinations (separate with \',\'), Layer 4' ) keyboard = [['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message( chat_id, 'Send me the emails of the destinations (separate with \',\')', reply_markup=reply_markup).wait() layer5(bot, last_update_id, usr, pwd) else: print("Select an option, Layer 4") keyboard = [['Show unseen emails'], ['Send a email'], ['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(chat_id, 'Select an option', reply_markup=reply_markup).wait() else: print("Select an option, Layer 4") keyboard = [['Show unseen emails'], ['Send a email'], ['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(u.message.chat.id, 'Select an option', reply_markup=reply_markup).wait() def layer4(bot, last_update_id, usr, pwd): #Show emails, send email and back print("\n Layer 4\n") while True: updates = bot.get_updates(offset=last_update_id).wait() try: for update in updates: if int(update.update_id) > int(last_update_id): last_update_id = update.update_id print("last_update_id: ", last_update_id) process_message_layer4(bot, update, last_update_id, usr, pwd) continue continue except Exception: ex = None print(traceback.format_exc()) continue def process_message_layer3(bot, u, last_update_id): if u.message.sender and u.message.text and u.message.chat: # if the message is text chat_id = u.message.chat.id # Extract data of message user = u.message.sender.id message = u.message.text print("\n chat_id: ", chat_id) print("user: "******"message: ", message) print("\n") if message == 'Back': print("Select an option, Layer 3") keyboard = [['Loggin account'], ['Exit']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(chat_id, 'Select an option', reply_markup=reply_markup).wait() layer2(bot, last_update_id) else: if len(message.split()) != 2: print("Incorrect input, Layer 3") keyboard = [['Loggin account'], ['Exit']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(chat_id, 'Incorrect input', reply_markup=reply_markup).wait() bot.send_sticker(chat_id, 'CAADAgAD1wgAAgi3GQJjq91gSNeyaQI', reply_markup=reply_markup).wait() layer2(bot, last_update_id) else: user = message.split()[0] pwd = message.split()[1] # connecting to the gmail imap server imapMail = imaplib.IMAP4_SSL("imap.gmail.com") # Login try: imapMail.login(user, pwd) except: print("User or password incorrect <Sticker>, Layer 3") keyboard = [['Loggin account'], ['Exit']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(chat_id, 'User or password incorrect', reply_markup=reply_markup).wait() bot.send_sticker(chat_id, 'CAADAgAD8wgAAgi3GQKHdYrrN-Wt_QI', reply_markup=reply_markup).wait() layer2(bot, last_update_id) print("Logging successful <Sticker>, Layer 3") bot.send_message(chat_id, 'Loggin successful').wait() bot.send_sticker(chat_id, 'CAADAgADsggAAgi3GQITL8y1531UoQI').wait() imapMail.logout() print("Select an option, Layer 3") keyboard = [['Show unseen emails'], ['Send a email'], ['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(chat_id, 'Select an option', reply_markup=reply_markup).wait() layer4(bot, last_update_id, user, pwd) else: print("Incorrect input, Layer 3") keyboard = [['Loggin account'], ['Exit']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(u.message.chat.id, 'Incorrect input', reply_markup=reply_markup).wait() bot.send_sticker(chat_id, 'CAADAgAD1wgAAgi3GQJjq91gSNeyaQI', reply_markup=reply_markup).wait() layer2(bot, last_update_id) def layer3(bot, last_update_id): # Loggin print("\n Layer 3\n") while True: updates = bot.get_updates(offset=last_update_id).wait() try: for update in updates: if int(update.update_id) > int(last_update_id): last_update_id = update.update_id print("last_update_id: ", last_update_id) process_message_layer3(bot, update, last_update_id) continue continue except Exception: ex = None print(traceback.format_exc()) continue def process_message_layer2(bot, u, last_update_id): if u.message.sender and u.message.text and u.message.chat: # if the message is text chat_id = u.message.chat.id # Extract data of message user = u.message.sender.id message = u.message.text print("\n chat_id: ", chat_id) print("user: "******"message: ", message) print("\n") if message == 'Loggin account': print( "Send me your User and Password (separate with space), Layer 2" ) keyboard = [['Back']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message( chat_id, 'Send me your User and Password (separate with space)', reply_markup=reply_markup).wait() layer3(bot, last_update_id) elif message == 'Exit': print("See you later, Layer 2") keyboard = [['Start LambderBot']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(chat_id, 'See you later', reply_markup=reply_markup).wait() layer1(bot, last_update_id) else: print("Select an option, Layer 2") keyboard = [['Loggin account'], ['Exit']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(chat_id, 'Select an option', reply_markup=reply_markup).wait() else: print("Select an option, Layer 2") keyboard = [['Loggin account'], ['Exit']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(u.message.chat.id, 'Select an option', reply_markup=reply_markup).wait() def layer2(bot, last_update_id): # Loggin or loggout print("\n Layer 2\n") while True: updates = bot.get_updates(offset=last_update_id).wait() try: for update in updates: if int(update.update_id) > int(last_update_id): last_update_id = update.update_id print("\nlast_update_id: ", last_update_id) process_message_layer2(bot, update, last_update_id) continue continue except Exception: ex = None print(traceback.format_exc()) continue def process_message_layer1(bot, u, last_update_id): if u.message.sender and u.message.text and u.message.chat: # if the message is text chat_id = u.message.chat.id # Extract data of message user = u.message.sender.id message = u.message.text print("\n chat_id: ", chat_id) print("user: "******"message: ", message) print("\n") if message == 'Start LambderBot': # if message is ... keyboard = [['Loggin account'], ['Exit']] # Buttons Loggin account and Exit reply_markup = ReplyKeyboardMarkup.create( keyboard) # Create Button # welcome according to the time if int(time.strftime("%H")) >= 4 and int( time.strftime("%H") ) < 12: #If the time is between 4 and 12 noon then the bot will say 'Good morning' greeting = 'Good Morning' print("Good Morning") elif int(time.strftime("%H")) >= 12 and int( time.strftime("%H") ) < 16: #If the time is between 12 noon and 6 then the bot will say 'Good Afternoon' greeting = 'Good Afternoon' print("Good Afternoon") else: greeting = 'Good Nigth' #Else say 'Good Nigth' print("Good Nigth") bot.send_message(chat_id, greeting + '\nSelect an option', reply_markup=reply_markup).wait( ) # Show message and Button bot.send_sticker(chat_id, 'CAADAgAD5QgAAgi3GQLR-yMPZfVRlAI', reply_markup=reply_markup).wait() print('Hello, Select an option, Layer 1') layer2(bot, last_update_id) # Call Second Layer elif message == '/start': print("Select an option, Layer 1") keyboard = [['Start LambderBot']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(chat_id, 'Select an option', reply_markup=reply_markup).wait( ) # update buttons and stay in this layer else: print("Select an option, Layer 1") keyboard = [['Start LambderBot']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(chat_id, 'Select an option', reply_markup=reply_markup).wait() else: print("Select an option, Layer 1") keyboard = [['Start LambderBot']] reply_markup = ReplyKeyboardMarkup.create(keyboard) bot.send_message(u.message.chat.id, 'Select an option', reply_markup=reply_markup).wait() def layer1(bot, last_update_id): #Welcome layer print("\n Layer 1\n") while True: # While for message from this layer, because the user can insert bad text updates = bot.get_updates(offset=last_update_id).wait() try: for update in updates: #get message data if int(update.update_id) > int( last_update_id): #if the message is new, process last_update_id = update.update_id print("\nlast_update_id: ", last_update_id) process_message_layer1( bot, update, last_update_id) # call process message continue continue except Exception: ex = None print(traceback.format_exc()) continue layer1(bot, last_update_id) # Start first layer
from twx.botapi import TelegramBot import datetime bot = TelegramBot('489053214:AAHub_fZo0OdP-SWy1aRFiyfxHZM4HinqDQ') log_ = open("log.txt", "r") log = log_.read() log_.close() updates = bot.get_updates().wait() pan = len(updates) i = 0 mulai = 0 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))
# -*- 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)
sec_state[user]['stage'] * sec_state[user]['stage'] ^ 1337) % 10 sec_state[user]['mode'] = sec_state[user]['mode'] - 1 if sec_state[user]['mode'] < 0: sec_state[user]['mode'] = 0 if sec_state[user]['mode'] == 0: bot.send_message(chat_id, 'Secret mode enabled!', reply_markup=reply_hide).wait() else: print 'NO', num, sec_state[user]['stage'] bot.send_message(chat_id, 'Invalid password!', reply_markup=reply_hide).wait() sec_state[user]['mode'] = 15 bot = TelegramBot(config.token) bot.update_bot_info().wait() print bot.username last_update_id = 0 while True: updates = bot.get_updates(offset=last_update_id).wait() try: for update in updates: if int(update.update_id) > int(last_update_id): last_update_id = update.update_id process_message(bot, update) except Exception as ex: print traceback.format_exc()
import os from flask import Flask from twx.botapi import TelegramBot bot_api_key = os.environ.get('TELEGRAM_BOT_APIKEY') bot = TelegramBot(bot_api_key) application = Flask(__name__) from app import views if os.environ.get('HEROKU') is not None: import logging stream_handler = logging.StreamHandler() application.logger.addHandler(stream_handler) application.logger.setLevel(logging.DEBUG)
output.append(station + "cancelled\n") elif f['actualFermataType'] == 0: output.append(station + "data not available\n") else: output.append(description) message='' for s in output: message=message+' '+s write(message) """ Setup the bot """ bot = TelegramBot('204368082:AAEfHT1b1pXmBJM3OfbSHUaL5Th30zdsmtI') bot.update_bot_info().wait() print(bot.username) """ Send a message to a user """ user_id = int(153170813) result = bot.send_message(user_id, bot.username + " is Online!").wait() print(result) """ Use a custom keyboard """ keyboard = [[':joy:', '8', '9'],
from twx.botapi import TelegramBot, ReplyKeyboardMarkup def get_me(**kwargs): """ A simple method for testing your bot's auth token. Requires no parameters. Returns basic information about the bot in form of a User object. :param \*\*kwargs: Args that get passed down to :class:`TelegramBotRPCRequest` :returns: Returns basic information about the bot in form of a User object. :rtype: User """ return TelegramBotRPCRequest('getMe', on_result=User.from_result, **kwargs) # Token Constants bot = TelegramBot('125579945:AAGjgsLLGeSqSILvfky71QjuMcZpeIBpuho') #bot.update_bot_info().wait() #print(bot.username) json_file = 'data.json' json_data = open(json_file) data = json.load(json_data) json_data.close() #print data['result'][0]['message']['text'] # Renaming the JSON objects as string variables so that I don't have to # type "data['x'][0]['y']['z']" all the time: