def webhook(event, context): """ Runs the Telegram webhook. """ bot = configure_telegram() dispatcher = Dispatcher(bot, None, workers=0) dispatcher.add_handler(CommandHandler('start', start_callback)) dispatcher.add_handler(CommandHandler('version', version_callback)) dispatcher.add_handler(CommandHandler('gasprice', gas_price_callback)) dispatcher.add_handler( CommandHandler('refratio', refratio_callback, pass_args=True)) dispatcher.add_handler( CommandHandler('predict', predict_callback, pass_args=True)) dispatcher.add_handler( CommandHandler('stats', user_stats_callback, pass_args=True)) logger.info('Event: {}'.format(event)) if event.get('httpMethod') == 'POST' and event.get('body'): logger.info('Message received') update = telegram.Update.de_json(json.loads(event.get('body')), bot) dispatcher.process_update(update) logger.info('Message sent') return OK_RESPONSE return ERROR_RESPONSE
def run(message): bot = Bot(config.bot_token) dp = Dispatcher(bot, None, workers=0) # on different commands - answer in Telegram dp.add_handler(CommandHandler("ranking", ranking, pass_args=True)) dp.add_handler(CommandHandler("players", players, pass_args=True)) dp.add_handler(CommandHandler("player", player, pass_args=True)) dp.add_handler(CommandHandler("matchday", matchday, pass_args=True)) dp.add_handler(CommandHandler("scorers", scorers)) dp.add_handler(CommandHandler("help", help)) dp.add_handler( CommandHandler('info', info, filters=Filters.user(username='******'))) # on noncommand i.e message - echo the message on Telegram dp.add_handler(MessageHandler(Filters.text, echo)) # log all errors dp.add_error_handler(error) # inline inline_handler = InlineQueryHandler(inline) dp.add_handler(inline_handler) # decode update and try to process it update = Update.de_json(message, bot) dp.process_update(update)
class TelegramInterface(BotInterface): API_TOKEN = os.environ.get('TELEGRAM_BOT_TOKEN') def __init__(self): self.bot = Bot(self.API_TOKEN) self.dispatcher = Dispatcher(self.bot, None, workers=0) self._init_handlers() def _init_handlers(self): handlers = [ MessageHandler( Filters.text & (Filters.entity(MessageEntity.URL) | Filters.entity(MessageEntity.TEXT_LINK)), self._handle_message) ] for handler in handlers: self.dispatcher.add_handler(handler) def _handle_message(self, bot, update): text = update.message.text response = process_message(text) if response: update.message.reply_markdown( response, quote=True, disable_web_page_preview=True, disable_notification=True, ) def process_message(self, message_data): update = Update.de_json(message_data, self.bot) self.dispatcher.process_update(update)
class BotComm: exposed = True def __init__(self, TOKEN, NAME): super().__init__() self.TOKEN = TOKEN self.NAME = NAME self.bot = telegram.Bot(self.TOKEN) try: self.bot.set_webhook( f"https://{self.NAME}.herokuapp.com/{self.TOKEN}") except: raise RuntimeError("Failed to set the webhook") self.update_queue = Queue() self.dp = Dispatcher(self.bot, self.update_queue) self.dp.add_handler(CommandHandler("start", self._start)) self.dp.add_handler( MessageHandler(Filters.text & ~Filters.command, self._echo)) @cherrypy.tools.json_in() def POST(self, *args, **kwargs): update = cherrypy.request.json update = telegram.Update.de_json(update, self.bot) self.dp.process_update(update) def _start(self, update, context): update.effective_message.reply_text("Hi!") def _echo(self, update, context): update.effective_message.reply_text(update.effective_message.text)
class BotComm(object): exposed = True def __init__(self, TOKEN, NAME): super(BotComm, self).__init__() self.TOKEN = TOKEN self.NAME=NAME self.bot = telegram.Bot(self.TOKEN) try: self.bot.setWebhook("https://{}.herokuapp.com/{}".format(self.NAME, self.TOKEN)) except: raise RuntimeError("Failed to set the webhook") self.update_queue = Queue() self.dp = Dispatcher(self.bot, self.update_queue) self.dp.add_handler(CommandHandler("start", self._start)) self.dp.add_handler(MessageHandler(Filters.text, self._echo)) self.dp.add_error_handler(self._error) @cherrypy.tools.json_in() def POST(self, *args, **kwargs): update = cherrypy.request.json update = telegram.Update.de_json(update, self.bot) self.dp.process_update(update) def _error(self, error): cherrypy.log("Error occurred - {}".format(error)) def _start(self, bot, update): update.effective_message.reply_text("Hi!") def _echo(self, bot, update): update.effective_message.reply_text(update.effective_message.text)
class LambdaSantaBot(SantaBot): def __init__(self, dbConnection): super().__init__(dbConnection) self.read_config() # TODO Replace with Environment Variables try: self.bot_id = int(self.token.split(":")[0]) except Exception: self.bot_id = None self.bot = Bot(self.token) self.dispatcher = Dispatcher(self.bot, None, workers=0, use_context=True) for handler in self.handlers: self.dispatcher.add_handler(handler) def read_config(self): # TODO Replace with Environment Variables config = ConfigParser() configPath = os.path.normpath('config/config.ini') config.read(configPath) self.token = config.get('auth', 'token') def process_message(self, updateText): print('incoming message') print(updateText) decodedUpdate = Update.de_json(updateText, self.bot) self.dispatcher.process_update(decodedUpdate) self.session.close()
def main(update, bot): print("User: %s" % update.effective_user.name) dispatcher = Dispatcher(bot=bot, update_queue=None, use_context=True) dispatcher.add_handler(CommandHandler("start", start_command)) dispatcher.add_handler(CommandHandler("help", help_command)) dispatcher.add_handler(MessageHandler(Filters.photo, photo_callback)) dispatcher.add_handler(MessageHandler(Filters.text, default_message)) dispatcher.process_update(update)
def webhook(request): bot = Bot(token=os.environ["TELEGRAM_TOKEN"]) dispatcher = Dispatcher(bot, None, 0) dispatcher.add_handler(CommandHandler("cs", cs_callback)) if request.method == "POST": update = Update.de_json(request.get_json(force=True), bot) dispatcher.process_update(update) return "ok"
class BotComm(object): exposed = True def __init__(self, TOKEN, NAME): super(BotComm, self).__init__() self.TOKEN = TOKEN self.NAME = NAME self.bot = telegram.Bot(self.TOKEN) try: self.bot.setWebhook("https://{}.herokuapp.com/{}".format( self.NAME, self.TOKEN)) except: raise RuntimeError("Failed to set the webhook") self.update_queue = Queue() self.dp = Dispatcher(self.bot, self.update_queue) self.dp.add_handler(CommandHandler("start", self._start)) self.dp.add_handler(MessageHandler(Filters.text, self._handler)) self.dp.add_error_handler(self._error) @cherrypy.tools.json_in() def POST(self, *args, **kwargs): update = cherrypy.request.json update = telegram.Update.de_json(update, self.bot) self.dp.process_update(update) def _error(self, error): cherrypy.log("Error occurred - {}".format(error)) def _start(self, bot, update): update.effective_message.reply_text("Hi!") def _handler(self, bot, update): global TOPIC global TOPIC_STATUS print("MESSAGE", update.message.chat_id, update.message.text) if update.message.text == 'kb' or update.message.text == 'keyboard': send_KB_() elif text_ON in update.message.text and text_topic[ 0] in update.message.text: mqttc.publish(TOPIC[0], "ON", 0, True) TOPIC_CHANGES[0] = 1 elif text_OFF in update.message.text and text_topic[ 0] in update.message.text: mqttc.publish(TOPIC[0], "OFF", 0, True) TOPIC_CHANGES[0] = 1 elif text_ON in update.message.text and text_topic[ 1] in update.message.text: mqttc.publish(TOPIC[1], "ON", 0, True) TOPIC_CHANGES[1] = 1 elif text_OFF in update.message.text and text_topic[ 1] in update.message.text: mqttc.publish(TOPIC[1], "OFF", 0, True) TOPIC_CHANGES[1] = 1 else: update.message.reply_text(text=update.message.text)
def run_prod(message): bot = Bot(env.str("BOT_KEY")) # noinspection PyTypeChecker dp = Dispatcher(bot, None, workers=0) configure_bot(dp) # decode update and try to process it update = Update.de_json(message, bot) dp.process_update(update)
def handle_request(bot, update): dispatcher = Dispatcher(bot, None) dispatcher.add_handler(CommandHandler('start', start)) dispatcher.add_handler(CommandHandler('help', help)) dispatcher.add_handler(CommandHandler('subscribe', subscribe)) dispatcher.add_handler(CommandHandler('unsubscribe', unsubscribe)) dispatcher.add_handler(CallbackQueryHandler(button)) dispatcher.add_error_handler(error) dispatcher.add_handler(MessageHandler(Filters.command, unknown)) dispatcher.process_update(update)
class BotDispatcher: def __init__(self): self.dispatcher = Dispatcher(bot, None, workers=0) self.dispatcher.add_handler(CommandHandler('start', start)) self.dispatcher.add_handler(CommandHandler('help', help)) self.dispatcher.add_handler(CallbackQueryHandler(button)) self.dispatcher.add_error_handler(error) def process_update(self, update): self.dispatcher.process_update(update)
class Telegram(object): """connect to Telegram""" def __init__(self, app, host, token, cert=None, unknown_command_text=None, port='443', name='tg_callback'): self.app = app self.app.add_url_rule('/'+token, name, self.callback, methods=['POST']) self.bot = telegram.Bot(token) self.bot.setWebhook(webhook_url='https://%s:%s/%s' % (host, port, token), **({'certificate':open(cert, 'rb')} if cert is not None else {})) self.dispatcher = Dispatcher(self.bot, None, workers=0) self.unknown_command_text = "Ummm... This command not found." self._stop = True self._inited = False def __exit__(self): self.stop() def callback(self): if self._stop: abort(404) update = telegram.update.Update.de_json(request.get_json(force=True), self.bot) logging.debug(update) self.dispatcher.process_update(update) return 'OK' def Command(self, command, func, pass_args=False): handler = CommandHandler(command, CommandCall(command, func), pass_args=pass_args) self.dispatcher.add_handler(handler) def Start(self): if not self._inited: self.dispatcher.add_handler(MessageHandler(Filters.text, self.got_text)) self.dispatcher.add_handler(MessageHandler(Filters.command, self.unknown_command)) self._inited = True self._stop = False def Stop(self): self._stop = True def unknown_command(self, bot, update): if update.message.chat.type not in ('supergroup', 'group'): update.message.reply_text(self.unknown_command_text) def got_text(self, bot, update): if type(self.text_message) in (str, unicode): if update.message.chat.type not in ('supergroup', 'group'): bot.sendMessage(chat_id=update.message.chat_id, text=self.text_message) else: msg = Message('Telegram') msg.setEvent(bot=bot, update=update, type='text') self.text_message(msg) def Push(self, to, data, type='text'): if type == 'text': self.bot.sendMessage(chat_id=to, text=data)
class BotDispatcher: def __init__(self): self.dispatcher = Dispatcher(telegram_bot, None, workers=0) self.dispatcher.add_handler(CommandHandler('register', register)) self.dispatcher.add_handler(CommandHandler('unregister', unregister)) self.dispatcher.add_handler(CommandHandler('mute', mute)) self.dispatcher.add_handler(CommandHandler('unmute', unmute)) self.dispatcher.add_handler(CommandHandler('about', about)) self.dispatcher.add_handler(CommandHandler('uptime', uptime)) def process_update(self, update): self.dispatcher.process_update(update)
def vika(event, context): logger.debug(event) update_queue = None bot = telegram.Bot(TOKEN) dispatcher = Dispatcher(bot, update_queue, use_context=True) setup_dispatcher(dispatcher=dispatcher) update = telegram.Update.de_json(json.loads(event['body']), bot) dispatcher.process_update(update) return { "statusCode": 200, }
def webhook(request): bot = Bot(token=os.environ["TELEGRAM_TOKEN"]) dispatcher = Dispatcher(bot, None, 0) dispatcher.add_handler(CommandHandler('coronamundo', world)) dispatcher.add_handler(CommandHandler('coronabrasil', brazil)) if request.method == 'POST': update = Update.de_json(request.get_json(force=True), bot) dispatcher.process_update(update) return 'ok'
class BotComm: exposed = True def __init__(self, TOKEN, NAME): super(BotComm, self).__init__() self.TOKEN = TOKEN self.NAME = NAME self.bot = telegram.Bot(self.TOKEN) try: self.bot.setWebhook("https://{}.herokuapp.com/{}".format( self.NAME, self.TOKEN)) except: raise RuntimeError("Failed to set the webhook") self.update_queue = Queue() self.dp = Dispatcher(self.bot, self.update_queue) self.dp.add_handler(CommandHandler("start", self._start)) self.dp.add_handler(MessageHandler(Filters.text, self._process_update)) self.dp.add_error_handler(self._error) @cherrypy.tools.json_in() def POST(self, *args, **kwargs): update = cherrypy.request.json update = telegram.Update.de_json(update, self.bot) self.dp.process_update(update) def _error(self, error): cherrypy.log("Error occurred - {}".format(error)) def _start(self, bot, update): update.effective_message.reply_text( 'Милые девушки. Этот бот создан специально для вас. Сделайте заказ, например, "латте без сахара" или "черный чай с одним кусочком сахара и печенькой". А мы обеспечим оперативную доставку вашего желания прямо на ваше рабочее место' ) def _accept_order(self, bot, update): order_text = update.effective_message.text order_user = update.effective_message.from_user order_user_first_name = order_user.first_name order_user_last_name = order_user.last_name order_user_username = order_user.username text = "{first_name} {last_name} ({username}) " \ "желает: {order}".format(first_name=order_user_first_name, last_name=order_user_last_name, username=order_user_username, order=order_text) self.bot.send_message(chat_id=CHAT_ID, text=text) update.effective_message.reply_text("Ваш заказ принят!") def _process_update(self, bot, update): chat_id = update.effective_message.chat.id if not chat_id == CHAT_ID: self._accept_order(bot, update)
def webhook(botname, arg_token): settings = get_bot_settings(botname) if not settings: raise abort(404,f"No bot {botname} known.") if arg_token != settings['token']: abort(403, "Wrong token") bot = Bot(token = settings['token']) # decode update and try to process it dp = Dispatcher(bot, None, workers=0, use_context = True) add_handlers(botname, dp) update = Update.de_json(request.json, bot) dp.process_update(update) return ""
def run(message): """Receive a message, handle it, and send a response""" bot = Bot(config.bot_token) dp = Dispatcher(bot, None, workers=0) # add your handlers here dp.add_handler(CommandHandler("test", test)) dp.add_handler(MessageHandler(Filters.text, echo)) # decode update and try to process it update = Update.de_json(message, bot) dp.process_update(update)
def webhook(request): bot = Bot(token=os.environ["TELEGRAM_TOKEN"]) dispatcher = Dispatcher(bot, None, 0) dispatcher.add_handler(CommandHandler("intercomp", intercomp_callback)) dispatcher.add_handler(CommandHandler("contagem", contagem_callback)) dispatcher.add_handler(CommandHandler("mackenzie", mackenzie_callback)) dispatcher.add_handler(CommandHandler("cidade", cidade_callback)) dispatcher.add_handler(CommandHandler("mochila", mochila_callback)) if request.method == "POST": update = Update.de_json(request.get_json(force=True), bot) dispatcher.process_update(update) return "ok"
def main(): dp = Dispatcher(bot, None, workers=0) if request.method == "POST": print('POST') update = telegram.Update.de_json(request.get_json(force=True), bot) dp.add_handler(CommandHandler('start', start)) dp.add_handler(MessageHandler(Filters.text, hi)) dp.process_update(update) return 'ok'
def webhook(request): bot = Bot(token=os.environ["TELEGRAM_TOKEN"]) dispatcher = Dispatcher(bot, None, 0) dispatcher.add_handler(CommandHandler('start', start)) dispatcher.add_handler(CommandHandler('kotlin', msg)) dispatcher.add_handler(MessageHandler(Filters.command, unknown)) if request.method == 'POST': update = Update.de_json(request.get_json(force=True), bot) dispatcher.process_update(update) return 'ok'
def webhook(request): bot = Bot(token=os.environ["TELEGRAM_TOKEN"]) dispatcher = Dispatcher(bot, None, 0) dispatcher.add_handler(CommandHandler("start", start)) dispatcher.add_handler(CommandHandler("ajuda", help)) dispatcher.add_handler(CommandHandler("entrar", key_in)) dispatcher.add_handler(CommandHandler("sair", key_out)) dispatcher.add_handler(CommandHandler("lista", list_key_owners)) dispatcher.add_handler(CommandHandler("resetlist", reset_list)) dispatcher.add_handler(MessageHandler(Filters.text, invalid_message)) if request.method == "POST": update = Update.de_json(request.get_json(force=True), bot) dispatcher.process_update(update) return "ok"
class TelegramBot(object): """docstring for TelegramBot""" _instance = None def __init__(self, **kwargs): super(TelegramBot, self).__init__() self.dispatcher.add_handler(CommandHandler('start', _start)) self.dispatcher.add_handler(CommandHandler('help', _help)) self.dispatcher.add_handler(CommandHandler('stop', _stop)) self.dispatcher.add_handler(CommandHandler('dm', _dm)) self.dispatcher.add_handler(MessageHandler([Filters.text], msg_handler)) self.dispatcher.add_handler(CommandHandler('block', _block_unblock)) self.dispatcher.add_handler(CallbackQueryHandler(_button_handler)) # self.dispatcher.add_handler(MessageHandler([Filters.text], _custom_messagehandler)) self.dispatcher.add_error_handler(error) def __new__(self): if not self._instance: self._instance = super(TelegramBot, self).__new__(self) self.bot = Bot(settings.TG_TOKEN) self.dispatcher = Dispatcher(self.bot, None, workers=0) return self._instance def webhook_request(self, update): dis = self.dispatcher.process_update(update)
def webhook_handler(data): bot = TelegramBot(TG_TOKEN) dispatcher = Dispatcher(bot, None) # Handlers dispatcher.add_handler(CommandHandler('ni', callbacks.ni)) dispatcher.add_handler(CommandHandler('list', callbacks.ni_list)) dispatcher.add_handler(CommandHandler('add', callbacks.add)) dispatcher.add_handler(CommandHandler('edit', callbacks.edit)) dispatcher.add_handler(CommandHandler('delete', callbacks.delete)) dispatcher.add_handler(CommandHandler('cancel', callbacks.cancel)) dispatcher.add_handler(MessageHandler(Filters.text, callbacks.text_message)) # NOQA # Process update update = Update.de_json(data, bot) dispatcher.process_update(update)
def main(): bot = Bot(BOT_TOKEN) dp = Dispatcher(bot, None, 0) set_handlers(dp) update_queue = Queue() httpd = WebhookServer(('127.0.0.1', WEBHOOK_PORT), WebhookHandler, update_queue, WEBHOOK_URI, bot) while True: try: httpd.handle_request() if not update_queue.empty(): update = update_queue.get() dp.process_update(update) except KeyboardInterrupt: exit(0)
def webcomic_bot(event, context): """Entrypoint for AWS Lambda""" logger.info('Event: %s', event) logger.info("Request ID: %s", context.aws_request_id) try: bot = telegram.Bot(TOKEN) dispatcher = Dispatcher(bot, None, workers=0) data = json.loads(event["body"]) update = telegram.update.Update.de_json(data, bot) dispatcher.add_handler(CommandHandler('get', get, pass_args=True)) dispatcher.process_update(update) except Exception as error: logger.exception(error) return {"statusCode": 200}
class MyBot: def __init__(self): self.bot = telegram.Bot(TOKEN) self.codes = dict() self.dispatcher = Dispatcher(self.bot, None, workers=0) self.add_handlers() self.set_webhook() def add_handlers(self): self.dispatcher.add_handler(CommandHandler("start", start, pass_args=True)) self.dispatcher.add_handler(CommandHandler("help", help_)) self.dispatcher.add_handler(CommandHandler("gettasks", tasks)) self.dispatcher.add_handler(MessageHandler(Filters.text, echo)) self.dispatcher.add_error_handler(error) def process_msg(self, msg): update = telegram.update.Update.de_json(msg, self.bot) self.dispatcher.process_update(update) def send_message(self, chat_id, text): self.bot.sendMessage(chat_id=chat_id, text=text, disable_web_page_preview=True) def send_mime_msg(self, chat_id, mime_msg): text_msg = repr_mime_msg(mime_msg) if len(text_msg) > 4096: text_msg = "TEXT IS TOO LONG\n\n" + text_msg log_line("Mime message was TOO LONG!") while len(text_msg) > 0: self.bot.sendMessage(chat_id=chat_id, text=text_msg[:4000], disable_web_page_preview=True, parse_mode=telegram.ParseMode.MARKDOWN) text_msg = text_msg[4000:] self.bot.sendMessage(chat_id=chat_id, text=text_msg, disable_web_page_preview=True, parse_mode=telegram.ParseMode.MARKDOWN) log_line("Mime message was sent!") def set_webhook(self): if not bool(self.bot.get_webhook_info().url): try: self.bot.setWebhook("https://{}.herokuapp.com/{}".format(NAME, TOKEN)) log_line("Webhook was set") except telegram.error.RetryAfter: log_line("telegram.error.RetryAfter WAS ENCOUNTERED :(") sleep(2) self.set_webhook()
def telegram_bot(request): """View bot telegram.""" # Create the bot's token. bot = Bot(token=settings.TELEGRAM_TOKEN) update = Update.de_json(json.loads(request.body), bot) print(json.loads(request.body)) dispatcher = Dispatcher(bot=bot, update_queue=Queue(), workers=1) # on different commands - answer in Telegram dispatcher.add_handler(CommandHandler("start", start)) dispatcher.add_handler(CommandHandler("cadastro", register)) dispatcher.add_handler(CommandHandler("help", help_command)) # on noncommand i.e message - echo the message on Telegram dispatcher.add_handler( MessageHandler(Filters.text & ~Filters.command, echo)) dispatcher.process_update(update) return HttpResponse()
def webhook_handler(data): bot = TelegramBot(settings.TG_TOKEN) dispatcher = Dispatcher(bot, None) # Handlers dispatcher.add_handler(CommandHandler('start', callbacks.start)) dispatcher.add_handler(CommandHandler('website', callbacks.website)) dispatcher.add_handler(CommandHandler('help', callbacks.help)) dispatcher.add_handler(CommandHandler('event', callbacks.get_event)) dispatcher.add_handler(CommandHandler('login', callbacks.login)) dispatcher.add_handler(CommandHandler('meeting', callbacks.meeting)) dispatcher.add_handler(CommandHandler('subscribe', callbacks.calendar)) dispatcher.add_handler( MessageHandler(Filters.text, callbacks.calendarSubscribe), ) dispatcher.add_handler(CallbackQueryHandler(callbacks.meeting_callback)) # Process update update = Update.de_json(data, bot) dispatcher.process_update(update)