def webhook_for_bot(): if request.is_json: data = request.data.decode('utf-8') update = Update.de_json(data) bot.process_new_updates([update]) return '' abort(403)
def handle_webhook(): if request.headers.get('content-type') == 'application/json': json_string = request.get_data().decode('utf-8') update = Update.de_json(json_string) bot.process_new_updates([update]) return '' abort(403)
def handler(event: dict, _context): update = Update.de_json(event['body']) print(update) bot.process_new_updates([update]) return { 'statusCode': 200, }
def webhook(): if request.headers.get('contetnt-type') == 'application/json': json_string = request.data().decode('utf-8') update = Update.de_json(json_string) bot.process_new_update([update]) else: abort(403)
async def post(self, bot: str, token: str): super().authenticate_channel(token, bot, self.request) telegram = ChatDataProcessor.get_channel_config("telegram", bot, mask_characters=False) out_channel = TelegramOutput(telegram['config']['access_token']) request_dict = json_decode(self.request.body) update = Update.de_json(request_dict) if not out_channel.get_me().username == telegram['config'].get("username_for_bot"): logger.debug("Invalid access token, check it matches Telegram") self.write("failed") return if self._is_button(update): msg = update.callback_query.message text = update.callback_query.data elif self._is_edited_message(update): msg = update.edited_message text = update.edited_message.text 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: self.write("success") return sender_id = msg.chat.id metadata = {"out_channel": out_channel.name()} try: if text == (INTENT_MESSAGE_PREFIX + USER_INTENT_RESTART): await self.process_message(bot, UserMessage( text, out_channel, sender_id, input_channel=self.name(), metadata=metadata, )) await self.process_message(bot, UserMessage( "/start", out_channel, sender_id, input_channel=self.name(), metadata=metadata, )) else: await self.process_message(bot, UserMessage( text, out_channel, sender_id, input_channel=self.name(), metadata=metadata, )) except Exception as e: logger.error(f"Exception when trying to handle message.{e}") logger.debug(e, exc_info=True) self.write("success") return
def receive_message(): if request.headers.get('content-type') == 'application/json': json_string = request.get_data().decode('utf-8') update = Update.de_json(json_string) bot.process_new_updates([update]) return '' else: abort(400)
def handle_webhook(): if request.content_type == 'application/json': json_string = request.get_data().decode('utf-8') update = Update.de_json(json_string) bot.process_new_updates([update]) return 'OK' else: abort(403)
def handle_update(): if(flask.request.headers.get("content-type") == "application/json"): json_string = flask.request.get_data().decode("utf-8") update = Update.de_json(json_string) bot.process_new_updates([update]) return '' else: flask.abort(403)
def process_method(): if request.headers.get('content-type') == 'application/json': json_string = request.get.data().decode('ulf-8') update = Update.de_json(json_string) bot.process_new_updates([update]) return '' else: abort(status=403)
async def handle(request: web.Request) -> web.Response: if request.match_info.get('token') != bot.token: return web.Response(status=403) request_body_dict = await request.json() update = Update.de_json(request_body_dict) bot.process_new_updates([update]) return web.Response(status=200)
def webhook(): if request.headers.get("content-type") == "application/json": json_string = request.get_data().decode('utf-8') update = Update.de_json(json_string) bot.process_new_updates([update]) return '' else: abort(403)
async def webhook_handle(request): if request.path.replace('/', '') == bot.token: request_body_dict = await request.json() update = Update.de_json(request_body_dict) bot.process_new_updates([update]) return web.Response() else: return web.Response(status=403)
def post(self, request: HttpRequest, *args, **kwargs): if request.content_type != 'application/json': return HttpResponseBadRequest() json_string = request.body.decode('utf-8') update = Update.de_json(json_string) from bot import telegram_bot telegram_bot.process_new_updates([update]) return HttpResponse('')
def post(request): bot.process_new_updates( [ Update.de_json( request.body.decode('UTF-8') ) ] ) return JsonResponse({'code': 200})
def post(self): json_string = request.get_json() if json_string: _bot.process_new_updates([Update.de_json(json_string)]) return '' else: abort(403, error_message= 'Knock knock, open up the door, it\'s query! (C) DMX')
def telegram_update(): request_data = request.stream.read().decode("utf-8") update = Update.de_json(request_data) redis_response = redis.sadd("telegramChatUpdates", str(update.update_id)) if redis_response: handle_bot_update(update) return "!", 200
def webhook(): if flask.request.headers.get('content-type') == 'application/json': json_string = flask.request.get_data().decode('utf-8') update = Update.de_json(json_string) log_update(update) bot.process_new_updates([update]) return '' else: flask.abort(403)
def post(self, webhook_url): # opens the file for dynamic url with open("webhook_url", "r") as f: temp = f.read() if webhook_url == temp: bot.process_new_updates( [Update.de_json(request.stream.read().decode("utf-8"))]) return "!", 200
def telegram_web_hook(): """This route get new updates from Telegram server next this updates sends to handlers defined in handlers.py """ update = Update.de_json(request.stream.read().decode('utf-8')) bot.process_new_updates([update]) return Response('ok', 200)
def bot_endpoint(request, token): bot_registry = apps.get_app_config('bot').bot_registry bot = bot_registry.get(token) if bot is None: return HttpResponse(status=404) update = Update.de_json(request.body.decode('utf-8')) bot.process_update(update) return HttpResponse(status=200)
def webhook(): if request.headers.get("content-type") == "application/json": # Запускать бота фоновым процессом в RQ? run_bot( update=Update.de_json( json_type=request.get_data().decode("utf-8") ) ) return "OK", 200 else: abort(403)
def webhook(): if request.headers.get("content-type") == "application/json": print(request.headers) print(datetime.now()) # length = request.headers["content-length"] json_string = request.get_data().decode("utf-8") update = Update.de_json(json_string) print(update) bot.process_new_updates([update]) return "OK", 200 return abort(403)
def post(self): if _bot is None: raise ValueError("Bot hasn't been set up yet") json_string = request.get_json() if json_string: _bot.process_new_updates([Update.de_json(json_string)]) return "" else: abort( 403, error_message= "Knock knock, open up the door, it's query! (C) DMX", )
def webhook(): """ Function process webhook call """ if request.headers.get('content-type') == 'application/json': json_string = request.get_data().decode('utf-8') update = Update.de_json(json_string) bot.process_new_updates([update]) return '' else: abort(403)
def web_hook_view(request: HttpRequest, *args, **kwargs) -> HttpResponse: """ Accepts and processes updates from Telegram. @endpoint /{TOKEN} """ # Return 403 if the request is not in JSON if request.content_type != "application/json": return HttpResponse(status=403) json_string = json.loads(request.body) update = Update.de_json(json_string) bot_instance.process_new_updates([update]) return HttpResponse(status=200)
def process_update(self, request: Request, update: dict): """ Processes updates. :meta private: """ # header containsX-Telegram-Bot-Api-Secret-Token if request.headers.get( 'X-Telegram-Bot-Api-Secret-Token') != self._secret_token: # secret token didn't match return JSONResponse(status_code=403, content={"error": "Forbidden"}) if request.headers.get('content-type') == 'application/json': self._bot.process_new_updates([Update.de_json(update)]) return JSONResponse('', status_code=200) return JSONResponse(status_code=403, content={"error": "Forbidden"})
async def endpoint_for_bots(request: Request, userid: UUID4, token: str): user = await user_db.find_one({"id": UUID4(f"{userid}".replace("-", ""))}) user_tokens = lambda: list(map(lambda x: x["token"], user["bots"])) if (user is not None) and (token in user_tokens()): sas = await request.body() decoded = json.loads(sas.decode()) telegram_bot = TeleBot(token) @telegram_bot.message_handler() def echo(m: Message): telegram_bot.send_message(m.chat.id, m.text) telegram_bot.process_new_updates([Update.de_json(decoded)]) return sas.decode() else: raise HTTPException(status_code=403, detail="This bot is not allowed here!")
def webhook(): if request.headers.get("content-type") == "application/json": json_string = request.get_data().decode("utf-8") update = Update.de_json(json_string) was_error = False tic = time() try: bot.process_new_updates([update]) except Exception as err: answer = "Кажется, произошла ошибка.\n" \ "Возможно, информация по этому поводу есть в нашем " \ "канале - @Spbu4u_news\nИ ты всегда можешь связаться с " \ "<a href='https://t.me/eeonedown'>разработчиком</a>" was_error = True if update.message is not None: try: bot.send_message(update.message.chat.id, answer, disable_web_page_preview=True, parse_mode="HTML") bot.send_message(ids["my"], str(err) + "\n\nWas sent: True") except ApiException as ApiExcept: json_err = loads(ApiExcept.result.text) if json_err["description"] == "Forbidden: bot was " \ "blocked by the user": delete_user(update.message.chat.id) logging.info("USER LEFT {0}".format( update.message.chat.id)) else: logging.info("ERROR: {0}".format( json_err["description"])) else: pass finally: write_log(update, time() - tic, was_error) return "OK", 200 else: abort(403)
def post(self, request, *args, **kwargs): if len(request.data) == 0: return Response({'error': 'no data'}, status=HTTP_400_BAD_REQUEST) from bot.handlers import tgbot message_id = tg_id = '' try: update = Update.de_json(request.data) if update.message: assert isinstance(update.message, Message) message_id = update.message.message_id tg_id = update.message.from_user.id elif update.callback_query: assert isinstance(update.callback_query, CallbackQuery) message_id = update.callback_query.id tg_id = update.callback_query.from_user.id tgbot.process_new_updates([update]) except Exception as e: if settings.TESTING: raise e base_utils.error_log_to_group_chat() logger.exception(e) if settings.TELEGRAM_RESPONSE_ERROR_ON_EXCEPTION: return Response({'error': 'exception'}, status=HTTP_500_INTERNAL_SERVER_ERROR) return Response({'status': 'OK'}, status=HTTP_200_OK)
def fake_update(fake_update_dict): """Return a fake Telegram update with message.""" return Update.de_json(fake_update_dict)
def telegram_web_hook(): update = Update.de_json(request.stream.read().decode('utf-8')) bot.process_new_updates([update]) return 'ok', 200