def getUpdates(self, offset=None, limit=100, timeout=0): """Use this method to receive incoming updates using long polling. Args: offset: Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id. limit: Limits the number of updates to be retrieved. Values between 1—100 are accepted. Defaults to 100. timeout: Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Returns: A list of telegram.Update objects are returned. """ url = "%s/getUpdates" % (self.base_url) data = {} if offset: data["offset"] = offset if limit: data["limit"] = limit if timeout: data["timeout"] = timeout json_data = self._requestUrl(url, "POST", data=data) data = self._parseAndCheckTelegram(json_data) return [Update.de_json(x) for x in data]
def webhook(): """Webhook view which receives the updates from Telegram""" #create update object from json-format request data, we use the request library of the flask module as well update = Update.de_json(request.get_json(), bot) #process the update dp.process_update(update) return "Ok"
def webhook(hashsum): if hashsum != app.config['BOT_HASHSUM']: abort(403) from app.telegram.handlers import bot update = Update.de_json(request.json, bot()) bot().dispatcher.process_update(update) return 'Ok'
def lambda_handler(event, context): input_data = json.loads(event["body"]) update = Update.de_json(input_data, bot) dispatcher.process_update(update) return {"statusCode": 200, "body": ""}
def _telegram_update(): telegram_json = telegram_json_message_without_surname() bot = Bot(env('TELEGRAM_API_TOKEN')) update = Update.de_json(json.loads(telegram_json), bot) return update
def tg_webhook(): update = Update.de_json(request.get_json(), tg.bot) if not update.inline_query: return "" query = update.inline_query.query images = None if query: nmsp = Namespace.get(Namespace.slug == query) if nmsp: images = [e.image for e in nmsp.emotes] print(images) else: images = Image.select().where(Image.emote_id == None) rszimgs = [] for image in images: if image: if image.original.split(".")[-1] != "gif": rszimgs.append(image.size(256, 256, webp=1)) results = [ InlineQueryResultCachedSticker(id=uuid4(), sticker_file_id=rszimg.tg_file_id, title="z") for rszimg in rszimgs ] update.inline_query.answer(results) return ""
def webhook(): """Webhook for the telegram bot. Args: request: A flask.Request object. Returns: Response text. """ logger.info("In webhook handler") global bot_lang if request.method == "POST": global update update = Update.de_json(request.get_json(force=True), bot) # your bot can receive updates without messages if update.message: if timeout(update.message): return "Timeout" bot.send_chat_action(chat_id=update.message.chat_id, action=ChatAction.TYPING) if update.message.text in ("/start", "/Start"): start() return "ok" # default keyboard_handler() return "ok"
def webhook(): try: logger.info(request.data) params = request.data.decode('utf-8') logger.info(params) json_params = json.loads(params) logger.info(json_params) update = Update.de_json(json_params, None) info = UpdateInfo(update) logger.info(info) api.process_request(info) return 'ok' except Exception as ex: # _, _, exc_tb = sys.exc_info() # fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1] # logger.error('{file} line {line} - {error}'.format(file=fname, line=exc_tb.tb_lineno, error=ex)) tb = traceback.format_exc() logger.error(ex) logger.error(tb) abort(500)
def webhook(): update = Update.de_json(request.get_json(force=True), telebot) logger.debug("webhook update: {}".format(update)) utils.set_update(update) # bot_dispatcher.process_update(update) return "OK"
def Telegram_POST(): if request.method == 'POST': update = Update.de_json(request.get_json(force=True), bot) dp.process_update(update) return Response('POST success', status=200) elif request.method == 'GET': return 'Server is running'
def webhook(): """webhook view which recieves update from telegram""" update = Update.de_json(request.get_json(), bot) dp.process_update(update) return "ok"
async def post(self) -> None: """Handle incoming POST request""" self._logger.debug("Webhook triggered") self._validate_post() json_string = self.request.body.decode() data = json.loads(json_string) self.set_status(HTTPStatus.OK) self._logger.debug("Webhook received data: %s", json_string) try: update = Update.de_json(data, self.bot) except Exception as exc: self._logger.critical( "Something went wrong processing the data received from Telegram. " "Received data was *not* processed!", exc_info=exc, ) if update: self._logger.debug("Received Update with ID %d on Webhook", update.update_id) # handle arbitrary callback data, if necessary if isinstance(self.bot, ExtBot): self.bot.insert_callback_data(update) await self.update_queue.put(update)
def post(self, request, *args, **kwargs): req = request.data dispatcher = setup() update = Update.de_json(req, dispatcher.bot) dispatcher.process_update(update) return Response({'status': 'Messages sent'})
def lambda_handler(event, context): # Create bot, update queue and dispatcher instances bot: Bot = OBJ_GRAPH.provide(Bot) dispatcher: Dispatcher = Dispatcher(bot, None, workers=0, use_context=True) dispatcher.bot_data = {"event": event} gsc: GameStateCommands = OBJ_GRAPH.provide(GameStateCommands) gsc.register_handlers(dispatcher) ah: AnsweringHandlers = OBJ_GRAPH.provide(AnsweringHandlers) ah.register_handlers(dispatcher) def error_callback(update, context): error: Exception = context.error traceback.print_exception(type(error), error, error.__traceback__) traceback.print_tb(error.__traceback__) context.bot.send_message( chat_id=update.effective_chat.id, text=f"An error occurred: {context.error}" ) dispatcher.add_error_handler(error_callback) input_data = json.loads(event["body"]) update = Update.de_json(input_data, bot) dispatcher.process_update(update) return {"statusCode": 200, "body": ""}
def webhook(): """webhook view which receives updates from telegram""" # create update object from json-format request data update = Update.de_json(request.get_json(), bot) # process update dp.process_update(update) return "ok"
def webhook(): update = request.get_json() current_app.bot_instance.update_queue.put( Update.de_json(update, current_app.bot_instance.bot)) return ("", 204)
def test_de_json_default_quote(self, bot): json_dict = {'update_id': TestUpdate.update_id} json_dict['message'] = message.to_dict() json_dict['default_quote'] = True update = Update.de_json(json_dict, bot) assert update.message.default_quote is True
def process_update(self, request, token): if 'message' in request.data or 'edited_message' in request.data: serializer = UpdateSerializer(data=request.data) elif 'channel_post' in request.data or 'edited_channel_post' in request.data: serializer = ChannelUpdateSerializer(data=request.data) else: logger.info( 'request contains unsupported telegram update type. It will not be handled' ) return if serializer.is_valid(): serializer.save() try: bot = Bot.objects.get(token=token) bot.handle(APIUpdate.de_json(request.data, APIBot(token))) # return Response(status=status.HTTP_200_OK) return except Bot.DoesNotExist: logger.warning("Token %s not associated to a bot" % token) # return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND) except: exc_info = sys.exc_info() traceback.print_exception(*exc_info) logger.error("Error processing %s for token %s" % (request.data, token)) # return Response(serializer.errors, status=status.HTTP_500_INTERNAL_SERVER_ERROR) logger.error("Validation error: %s from message %s" % (serializer.errors, request.data)) # return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return
async def handle_request(request: Request): try: data = await request.json() update = Update.de_json(data, updater.bot) updater.dispatcher.process_update(update) except Exception as e: pass
async def message(request: Request) -> Any: if request.method == "POST": if not out_channel.get_me()["username"] == self.verify: logger.debug( "Invalid access token, check it matches Telegram") return response.text("failed") update = Update.de_json(request.json, out_channel) if self._is_button(update): msg = update.callback_query.message text = update.callback_query.data else: msg = update.message if self._is_user_message(msg): text = msg.text.replace("/bot", "") elif self._is_location(msg): text = '{{"lng":{0}, "lat":{1}}}'.format( msg.location.longitude, msg.location.latitude) else: return response.text("success") sender_id = msg.chat.id metadata = self.get_metadata(request) try: if text == (INTENT_MESSAGE_PREFIX + USER_INTENT_RESTART): await on_new_message( UserMessage( text, out_channel, sender_id, input_channel=self.name(), metadata=metadata, )) await on_new_message( UserMessage( "/start", out_channel, sender_id, input_channel=self.name(), metadata=metadata, )) else: await on_new_message( UserMessage( text, out_channel, sender_id, input_channel=self.name(), metadata=metadata, )) except Exception as e: logger.error( "Exception when trying to handle message.{0}".format( e)) logger.debug(e, exc_info=True) if self.debug_mode: raise pass return response.text("success")
def tg_webhook(): logging.info("tg_webhook") data = request.get_json(force=True) logging.info(data) update = Update.de_json(data, bot=bot) dp.process_update(update) return "OK"
def answer_telegram(): data = request.get_data().decode("utf-8") app.logger.info(f'{data}') update = Update.de_json(json.loads(data), b) dispatcher.process_update(update) return ''
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)
def webhook(): update = Update.de_json(request.get_json(), bot) dp.process_update(update) return "Ok!"
def process_event(self, event: dict) -> None: update = Update.de_json(event, self._bot) chat_id = update.message.chat.id text = update.message.text.encode('utf-8').decode() if text not in self._get_commands(): self.invalid_command(chat_id) return if text == '/start': self.start(chat_id) return if text == '/about': self.about(chat_id) return try: gorrion = self._build_gorrion(False, False) if text == '/playing': self.playing(chat_id, gorrion) return if text == '/lyric': self.playing_with_lyrics(chat_id, gorrion) return if text == '/album': self.playing_album(chat_id, gorrion) return except SpotifyApiError as error: self._bot.send_message( chat_id=chat_id, text=f'{error}', )
def getUpdates(self, offset=None, limit=100, timeout=0): """Use this method to receive incoming updates using long polling. Args: offset: Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id. limit: Limits the number of updates to be retrieved. Values between 1—100 are accepted. Defaults to 100. timeout: Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Returns: A list of telegram.Update objects are returned. """ url = '%s/getUpdates' % (self.base_url) data = {} if offset: data['offset'] = offset if limit: data['limit'] = limit if timeout: data['timeout'] = timeout json_data = self._requestUrl(url, 'POST', data=data) data = self._parseAndCheckTelegram(json_data) return [Update.de_json(x) for x in data]
def update(token, params): bot_data = _bot_updaters.get(token) if bot_data: updater = bot_data['updater'] bot_key = bot_data['key'] send_utils.collect_chat_id() updater.dispatcher.process_update(Update.de_json(params, updater.bot))
def update_for_command(self, bot, command, args="", user_id=None, chat_id=None): """Creates a telegram.Update instance""" mock_data = copy.deepcopy(self.data['req_template_command_01']) # set command if args: mock_data['message']['text'] = "/{} {}".format(command, args) else: mock_data['message']['text'] = "/{}".format(command) mock_data['message']['entities'][0]['length'] = len(command) + 1 # set chat_id if (chat_id): mock_data['message']['chat']['id'] = chat_id # set user_id if (user_id): mock_data['message']['from']['id'] = user_id update = Update.de_json(mock_data, bot) return update
def webhook(req: HttpRequest, token: str): bot = Bot(token=token) update = Update.de_json(json.loads(req.body), bot) MrPishbiniBot.update(bot, update) return HttpResponse('')
def webhook(): #Webhook view which recieves updates from telegram #Create update object from json-format request data update = Update.de_json(request.get_json(), bot) #process update dp.process_update(update) return "Okay!"
def webhook(request: Request): logging.info("access_route: %s", ",".join(request.access_route)) logging.info("args: %s", request.args) logging.info("data: %s", request.data) logging.info("form: %s", request.form) if request.args.get("apikey") != apikey and request.form.get("apikey") != apikey: return make_response("", 404) if "version" in request.args: return str(os.environ.get("X_GOOGLE_FUNCTION_VERSION")) + "\n" if "title" in request.form: return post_np(request.form["title"], request.form.get("show")) if request.form.get("group") in group_ids: pin = request.form.get("pin") if pin in ["true", "1"]: pin = True elif pin in ["false", "0"]: pin = False notify = True if request.form.get("notify") in ["true", "1"] else False forward = True if request.form.get("forward") in ["true", "1"] else False return post_pin( bot, request.form["group"], request.form.get("message"), pin, notify, forward, ) update = Update.de_json(request.get_json(force=True), bot) dispatcher.process_update(update)
def post(self, request, token): dispatcher = self.get_dispatcher(token) if not dispatcher: return Http404() json_string = request.body.decode('utf-8') update = Update.de_json(json.loads(json_string)) dispatcher.process_update(update) return HttpResponse()
def __init__(self): update = Update.de_json(request.get_json(force=True)) if getattr(update, 'message', None): for t, c in self.types.items(): if getattr(update.message, t): m = c() m.update = update m.parse() m.run() m.respond()
def getUpdates(self, offset=None, limit=100, timeout=0, network_delay=.2): """Use this method to receive incoming updates using long polling. Args: offset: Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id. limit: Limits the number of updates to be retrieved. Values between 1-100 are accepted. Defaults to 100. timeout: Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. network_delay: Additional timeout in seconds to allow the response from Telegram to take some time when using long polling. Defaults to 2, which should be enough for most connections. Increase it if it takes very long for data to be transmitted from and to the Telegram servers. Returns: list[:class:`telegram.Update`]: A list of :class:`telegram.Update` objects are returned. Raises: :class:`telegram.TelegramError` """ url = '{0}/getUpdates'.format(self.base_url) data = {'timeout': timeout} if offset: data['offset'] = offset if limit: data['limit'] = limit urlopen_timeout = timeout + network_delay result = request.post(url, data, timeout=urlopen_timeout) if result: self.logger.debug( 'Getting updates: %s', [u['update_id'] for u in result]) else: self.logger.debug('No new updates found.') return [Update.de_json(x) for x in result]
def webhook(): if request.method == "POST": # retrieve the message in JSON and then transform it to Telegram object update = Update.de_json(request.get_json(force=True)) logger.info("Update received! "+ update.message.text) dp.process_update(update) update_queue.put(update) return "OK" else: return redirect("https://telegram.me/links_forward_bot", code=302)
def send_message(self, text, from_user_id=0, skip_answer=True): update = { 'update_id': 0, 'message': { 'message_id': 0, 'text': text, 'from': { 'id': from_user_id, 'first_name': 'Jack' }, 'date': int(time.time()) } } self.updater.dispatcher.processUpdate(Update.de_json(update)) if skip_answer and len(self.bot.messages) > 0: self.bot.pop_message()
def application(environ, start_response): print "app" # the environment variable CONTENT_LENGTH may be empty or missing try: request_body_size = int(environ.get('CONTENT_LENGTH', 0)) except (ValueError): request_body_size = 0 # When the method is POST the variable will be sent # in the HTTP request body which is passed by the WSGI server # in the file like wsgi.input environment variable. buf = environ['wsgi.input'].read(request_body_size) global job_queue updater = Updater("207443777:AAGuMP5nIJMqbFKILRmVuuAz8in7PfiWdjA") job_queue = updater.job_queue # Get the dispatcher to register handlers dp = updater.dispatcher # on different commands - answer in Telegram dp.addHandler(CommandHandler("start", start)) dp.addHandler(CommandHandler("help", start)) dp.addHandler(CommandHandler("set", set)) dp.addHandler(InlineQueryHandler(inlinequery)) # log all errors dp.addErrorHandler(error) updater.bot.setWebhook("https://afternoon-shelf-83103.herokuapp.com") # Start the Bot #updater.start_polling() json_string = bytes_to_native_str(buf) update = Update.de_json(json.loads(json_string)) dp.processUpdate(update) start_response('200 OK', [('Content-Type', 'text/plain')]) return [''] # Block until the you presses Ctrl-C or the process receives SIGINT, # SIGTERM or SIGABRT. This should be used most of the time, since # start_polling() is non-blocking and will stop the bot gracefully. import time
def post(self, request, token): serializer = UpdateSerializer(data=request.data) if serializer.is_valid(): serializer.save() try: bot = Bot.objects.get(token=token) bot.handle(Update.de_json(request.data)) except Bot.DoesNotExist: logger.warning("Token %s not associated to a bot" % token) return Response(serializer.errors, status=status.HTTP_404_NOT_FOUND) except: exc_info = sys.exc_info() traceback.print_exception(*exc_info) logger.error("Error processing %s for token %s" % (request.data, token)) return Response(serializer.errors, status=status.HTTP_500_INTERNAL_SERVER_ERROR) else: return Response(serializer.data, status=status.HTTP_200_OK) logger.error("Validation error: %s from message %s" % (serializer.errors, request.data)) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def getUpdates(self, offset=None, limit=100, timeout=0): """Use this method to receive incoming updates using long polling. Args: offset: Identifier of the first update to be returned. Must be greater by one than the highest among the identifiers of previously received updates. By default, updates starting with the earliest unconfirmed update are returned. An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id. limit: Limits the number of updates to be retrieved. Values between 1-100 are accepted. Defaults to 100. timeout: Timeout in seconds for long polling. Defaults to 0, i.e. usual short polling. Returns: A list of telegram.Update objects are returned. """ url = '%s/getUpdates' % self.base_url data = {} if offset: data['offset'] = offset if limit: data['limit'] = limit if timeout: data['timeout'] = timeout result = request.post(url, data) if result: self.logger.info( 'Getting updates: %s', [u['update_id'] for u in result]) else: self.logger.info('No new updates found.') return [Update.de_json(x) for x in result]
def message(): if request.method == 'POST': if not out_channel.get_me()['username'] == self.verify: logger.debug("Invalid access token, check it " "matches Telegram") return "failed" update = Update.de_json(request.get_json(force=True), out_channel) if self._is_button(update): message = update.callback_query.message text = update.callback_query.data else: message = update.message if self._is_user_message(message): text = message.text.replace('/bot', '') elif self._is_location(message): text = ('{{"lng":{0}, "lat":{1}}}' ''.format(message.location.longitude, message.location.latitude)) else: return "success" sender_id = message.chat.id try: if text == '_restart' or text == '/restart': on_new_message(UserMessage(text, out_channel, sender_id)) on_new_message(UserMessage('/start', out_channel, sender_id)) else: on_new_message(UserMessage(text, out_channel, sender_id)) except Exception as e: logger.error("Exception when trying to handle " "message.{0}".format(e)) logger.error(e, exc_info=True) if self.debug_mode: raise pass return "success"
def do_POST(self): self.logger.debug("Webhook triggered") try: self._validate_post() clen = self._get_content_len() except _InvalidPost as e: self.send_error(e.http_code) self.end_headers() else: buf = self.rfile.read(clen) json_string = bytes_to_native_str(buf) self.send_response(200) self.end_headers() self.logger.debug("Webhook received data: " + json_string) update = Update.de_json(json.loads(json_string)) self.logger.info("Received Update with ID %d on Webhook" % update.update_id) self.server.update_queue.put(update)
def do_POST(self): self.logger.debug("Webhook triggered") if self.path == self.server.webhook_path and \ 'content-type' in self.headers and \ 'content-length' in self.headers and \ self.headers['content-type'] == 'application/json': json_string = \ n(self.rfile.read(int(self.headers['content-length']))) self.send_response(200) self.end_headers() self.logger.debug("Webhook received data: " + json_string) update = Update.de_json(json.loads(json_string)) self.logger.info("Received Update with ID %d on Webhook" % update.update_id) self.server.update_queue.put(update) else: self.send_error(403) self.end_headers()
def telegramWebHook(): update = Update.de_json(request.get_json(force=True)) text = None if getattr(update.message, 'document'): gallery = Gallery().search(tgid = update.message.chat.id) if gallery: newfile = bot.getFile(update.message.document.file_id) file_name = update.message.document.file_id newfile.download(file_name) writed = False if os.path.exists(file_name): writed = write_file(file_name, read_file(file_name, storage = 'local', append_path = False), acl = 'public-read', mime_type = update.message.document.mime_type) thumbnail(file_name) os.remove(file_name) write_file('%s.json' % file_name, update.to_json()) if writed: file_id = File(gallery_eid = gallery.eid, file_id = update.message.document.file_id) file_id.save() sendLink = getattr(gallery, 'sendLink', None) if sendLink == 'True': text = 'File URL: %s' % url_for('image', file_id = file_id.eid, _external = True, disable_web_page_preview = True) else: text = 'Failed to download file' else: text = 'Gallery does not exist, please create first' pass if getattr(update.message, 'text'): args = update.message.text.split(' ', 2) if args[0] == '/register': text = 'Username:'******'Complete register: https://telegram.me/ACSGalleryBot?start=%s' % update.message.from_user.id else: text = 'User added to gallery' # set gallery permission at this point because i have chat id elif args[0] == '/start': if len(args) > 1 and int(args[1]) == int(update.message.chat.id): text = 'Username:'******'force_reply' : True }) else: text = update.to_json() elif getattr(update.message, 'reply_to_message'): if update.message.reply_to_message.text == 'Username:'******'Password:'******'force_reply' : True }) return 'ok' elif update.message.reply_to_message.text == 'Password:'******'User succesfuly registered' elif args[0] == '/create': if hasattr(update.message.chat, 'title'): gallery = Gallery().search(tgid = update.message.chat.id) if not gallery: gallery = Gallery(tgid = update.message.chat.id, title = update.message.chat.title).save() text = 'Gallery URL: %s' % url_for('gallery', id = gallery.eid, _external = True, _scheme = 'https') else: text = 'Bot only works in groups' elif args[0] == '/remove': gallery = Gallery().search(tgid = update.message.chat.id) if gallery: gallery.delete() text = 'Gallery deleted' else: text = 'Gallery is not registered' # TODO: Confirm elif args[0] == '/config': args.pop(0) gallery = Gallery.search(tgid = update.message.chat.id) if gallery: if len(args) == 0: text = g.config(update.message.chat.id) elif len(args) == 1: text = 'get one' text = g.config(update.message.chat.id, args[0]) else: text = g.config(update.message.chat.id, args[0], args[1]) else: text = 'Gallery is not registered' #else: # text = update.to_json() if text: bot.sendMessage(update.message.chat.id, text, disable_web_page_preview=True) return ""
def telegram_hook(token): if token != WEBHOOK_TOKEN: abort(401, 'Unauthorized') update = Update.de_json(request.json, bot) if update.callback_query: return process_callback(update.callback_query) elif update.message: return process_message(update.message)