예제 #1
0
        msg_id = msgdb.insert(request.query)
        keyboard = InlineKeyboardBuilder()
        keyboard.add_row().add(lang['decrypt'], callback_data=msg_id)
        for processor in reversible_processors:
            transform_query(processor, reply_markup=keyboard.build())

    request.answer(results.build_list())


@bot.callback
def decrypt(_, callback_query: CallbackQuery) -> None:
    not_found_msg = localizations.get_phrase(
        callback_query.src['from'].get('language_code'),
        'missing_original_text')
    message = msgdb.select(callback_query.data) or not_found_msg
    callback_query.answer(text=message, cache_time=DECRYPT_BUTTON_CACHE_TIME)


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    if DEBUG:
        loop.run_until_complete(bot.delete_webhook())
        bot.run(debug=True)
    else:
        webhook_future = bot.set_webhook("https://{}:{}/{}/{}".format(
            HOST, SERVER_PORT, NAME, TOKEN))
        loop.run_until_complete(webhook_future)
        app = bot.create_webhook_app('/{}/{}'.format(NAME, TOKEN), loop)
        os.umask(0o137)  # rw-r----- for the unix socket
        web.run_app(app, path=UNIX_SOCKET)
예제 #2
0
def main():
    """Main app"""
    logger = init_logger()

    # Loading settings
    try:
        setting = {
            "token": os.environ["FWD_TOKEN"],
            "keys_path": os.environ["FWD_KEYS_PATH"],
            "salt": int(os.environ["FWD_SALT"]),
            "webhook_url": os.environ["FWD_WEBHOOK_URL"],
            "listen_addr": os.environ.get("FWD_LISTEN_ADDR", "127.0.0.1"),
            "listen_port": int(os.environ.get("FWD_LISTEN_PORT", 8080)),
        }
    except KeyError as err:
        logger.critical("Setting %s not found. Exit!", err)
        sys.exit(1)
    except ValueError:
        logger.critical(
            "Invalid setting value. Check `FWD_SALT` or `FWD_LISTEN_PORT`. Exit!"
        )
        sys.exit(1)

    # Init token module
    base_dir = os.path.realpath(setting["keys_path"])
    if not os.path.isdir(base_dir):
        logger.critical("Invalid directory in `FWD_KEYS_PATH`: %s", base_dir)
        sys.exit(1)

    token = Token(pub_key_path=os.path.join(base_dir, "fwd_pub.pem"),
                  priv_key_path=os.path.join(base_dir, "fwd_priv.pem"),
                  salt=setting["salt"])

    # Init bot module
    parsed_url = urlparse(setting["webhook_url"])
    bot = Bot(api_token=setting["token"])
    bot_handlers = BotHandlers(
        token=token,
        base_api_url="{p.scheme}://{p.netloc}".format(p=parsed_url))

    bot.add_command("token", bot_handlers.token_handler)
    bot.add_command("ping", bot_handlers.ping_handler)
    bot.add_command("help", bot_handlers.help_handler)

    try:
        logger.info("Register webhook...")
        bot.set_webhook(setting["webhook_url"])
        logger.info("Register webhook... OK!")
    except BotApiError as err:
        logger.error("Register webhook... ERROR!")
        logger.critical("Unable to register webhook: %s", err)
        sys.exit(2)

    # Init web app
    app = web.Application()
    app["bot"] = bot
    app.on_cleanup.append(bot_shutdown)

    web_handlers = RestHandlers(token=token, bot=bot)
    app.add_routes([
        web.post("/in", web_handlers.incomming_message),
        web.get("/v1/message", web_handlers.send_message),
        web.post("/v1/message", web_handlers.send_message),
        web.put("/v1/message", web_handlers.update_message),
        web.delete("/v1/message", web_handlers.delete_message),
    ])

    web.run_app(app,
                host=setting["listen_addr"],
                port=setting["listen_port"],
                access_log=logger)

    logger.info("Web application closed. Exit!")