Ejemplo n.º 1
0
def event(requests):
    print requests
    json_list = json.loads(requests.body)
    print json_list
    chat_id = json_list['message']['chat']['id']
    command = json_list['message']['text']
    output = process_message(command)
    send_message(output, chat_id)
    return HttpResponse()
Ejemplo n.º 2
0
def event(requests):
    try:
        json_list = json.loads(requests.body)
        chat_id = json_list['message']['chat']['id']
        command = json_list['message']['text']
        output = process_message(command)
        send_message(output, chat_id)
    except Exception as ex:
        print('erro: %s'%ex)
    return HttpResponse()
Ejemplo n.º 3
0
def check_quick_stats():
    client = DateLaZiClient()
    client.sync()

    quick_stats = DLZSerializer.deserialize(client.serialized_data)
    last_updated = quick_stats.pop("Data")

    db_stats = client._local_data
    if db_stats and quick_stats.items() <= db_stats.items():
        msg = "No updates to quick stats"
        logger.info(msg)
        return msg

    diff = parse_diff(quick_stats, db_stats)
    diff["Actualizat la"] = last_updated

    incidence = client.serialized_data["Incidență"]
    infections = client.serialized_data["Judete"]
    items = {
        "*Incidențe*":
        split_in_chunks(incidence, limit=5),
        "*Infectări*":
        split_in_chunks(infections, limit=5),
        "*Vaccinări*": [
            f"`Total: {client.serialized_data['Total doze administrate']}`",
        ],
        **{
            f"*{company.title()} (24h)*": {
                "Total": f'+{data["total_administered"]}',
                "Rapel": f'+{data["immunized"]}',
            }
            for company, data in client.serialized_data.get("Vaccinări", {}).items(
            ) if data["total_administered"] or data["immunized"]
        },
    }
    send_message(
        bot=telegram.Bot(token=os.environ["TOKEN"]),
        text=parse_global(
            title="🔴 Cazuri noi",
            stats=diff,
            items=items,
            footer="\nDetalii: https://coronavirus.pradan.dev/",
            emoji="🔸",
        ),
        chat_id=os.environ["CHAT_ID"],
    )
    msg = "Quick stats updated"
    logger.info(msg)
    return msg
Ejemplo n.º 4
0
def test_send_message_unauthorized_bad_request():
    bot = MagicMock()
    bot.send_message.side_effect = [
        telegram.error.BadRequest("err"),
        telegram.error.Unauthorized("unauth"),
    ]
    assert send_message(bot, text="hey foo!") == "unauth"
Ejemplo n.º 5
0
def test_send_message_bad_request():
    bot = MagicMock()
    second_call = MagicMock()
    second_call.to_json.return_value = "foo"
    bot.send_message.side_effect = [
        telegram.error.BadRequest("err"),
        second_call,
    ]
    assert send_message(bot, text="hey foo!") == "foo"
Ejemplo n.º 6
0
def test_send_message_without_chat_id():
    bot = MagicMock()
    bot.send_message.return_value.to_json.return_value = "sent..."
    assert send_message(bot, text="hey foo!") == "sent..."
    bot.send_message.assert_called_once_with(
        chat_id=os.getenv("DEBUG_CHAT_ID"),
        text="hey foo!",
        disable_notification=True,
        parse_mode="Markdown",
    )
    bot.send_message.return_value.to_json.assert_called_once_with()
Ejemplo n.º 7
0
def webhook():
    json = request.get_json()
    if not json:
        raise ValueError("No payload")

    bot = telegram.Bot(token=TOKEN)
    update = telegram.Update.de_json(json, bot)

    command_text, status_code = handlers.validate_components(update)

    if command_text == "inline":
        chat_id = update.callback_query.message.chat_id
        if status_code in ["more", "back", "end"]:
            return getattr(inline, status_code)(update)
        if status_code.startswith("games_"):
            status_code = status_code.replace("games_", "")
            return inline.refresh_data(update,
                                       Games(chat_id, status_code).get())
        return inline.refresh_data(update, getattr(local_data, status_code)())

    if status_code == 1337:
        if command_text == "skip-debug":
            return "ok"
        text = f"{command_text}.\nUpdate: {update.to_dict()}"
        return utils.send_message(bot, text=text)

    chat_id = update.message.chat.id
    if status_code != "valid-command":
        return utils.send_message(bot, text=command_text, chat_id=chat_id)

    if command_text == "start":
        return inline.start(update)

    if command_text == "games" and not update.message.text.split(" ")[1:]:
        return inline.start(update, games=True)

    if command_text in GOOGLE_CLOUD_COMMANDS:
        chat_type = update.message.chat.type
        if str(chat_id) not in GOOGLE_CLOUD_WHITELIST[chat_type]:
            return utils.send_message(bot, "Unauthorized", chat_id)

        arg = " ".join(update.message.text.split(" ")[1:])
        if command_text == "translate":
            return utils.send_message(bot, translate_text(arg), chat_id)
        if command_text == "analyze_sentiment":
            return utils.send_message(bot, analyze_sentiment(arg), chat_id)

    if command_text in GAME_COMMANDS:
        chat_type = update.message.chat.type
        if str(chat_id) not in GOOGLE_CLOUD_WHITELIST[chat_type]:
            return utils.send_message(bot, "Unauthorized", chat_id)

        if command_text == "games":
            args = update.message.text.split(" ")[1:]
            if len(args) not in (2, 3) or len(args) == 2 and args[1] != "new":
                return utils.send_message(
                    bot,
                    parse_global(
                        title="Syntax",
                        stats=[
                            "/games => scores",
                            "/games <game_name> new => new game",
                            "/games <game_name> new_player <player_name>"
                            " => new player",
                            "/games <game_name> + <player_name>"
                            " => increase <player_name>'s score by 1",
                            "/games <game_name> - <player_name>"
                            " => decrease <player_name>'s score by 1",
                        ],
                        items={},
                    ),
                    chat_id,
                )
            name, *args = args
            games = Games(chat_id, name)
            if len(args) == 1:
                return utils.send_message(bot, games.new_game(), chat_id)
            return utils.send_message(bot, games.update(*args), chat_id)

        if command_text == "randomize":
            args = update.message.text.split(" ")[1:]
            if len(args) not in range(2, 51):
                return utils.send_message(
                    bot,
                    "Must contain a list of 2-50 items separated by space",
                    chat_id,
                )
            random.shuffle(args)
            return utils.send_message(
                bot,
                "\n".join(f"{i+1}. {item}" for i, item in enumerate(args)),
                chat_id,
            )
    raise ValueError(f"Unhandled command: {command_text}, {status_code}")
Ejemplo n.º 8
0
def test_send_message_unauthorized():
    bot = MagicMock()
    bot.send_message.side_effect = Unauthorized("err")
    assert send_message(bot, text="hey foo!") == "err"