Beispiel #1
0
def local_counties():
    stats = database.get_stats(slug=SLUG["romania"])
    if not stats or not stats.get("Judete"):
        return "Nu sunt date despre județe pentru ziua de azi"
    deserialized = DLZArchiveSerializer.deserialize(stats)
    stats = deserialized["Judete"]
    counties = list(reversed(sorted(stats, key=stats.get)))

    max_key_len = len(counties[0])
    max_val_len = len(str(stats[counties[0]]))

    top_three = counties[:3]
    remaining = list(sorted(counties[3:]))
    return formatters.parse_global(
        title=f"🇷🇴Top cazuri confirmate",
        stats=[
            f"🦠 `{name:<{max_key_len}}: {stats[name]:<{max_val_len}}`"
            for name in top_three
        ],
        items=["\nRestul județelor"]
        + [
            " ".join(
                [
                    f"`{name:<{max_key_len}}: {stats[name]:<{max_val_len}}`"
                    for name in judete
                ]
            )
            for judete in chunks(remaining, 15)
        ],
        emoji="🦠",
        footer=f"\n`Actualizat la: {deserialized['Data']}`",
    )
Beispiel #2
0
 def test_update_with_no_game(self, fetch_mock):
     assert self.game.update("+", "foo") == parse_global(
         stats=self.get_does_not_exist_result(),
         items={},
         title="Foo_game_name",
     )
     fetch_mock.asssert_called_once_with()
Beispiel #3
0
def local_latest_article():
    stats = database.get_stats(slug=SLUG["stiri-oficiale"])
    if not stats:
        return "Nu sunt stiri salvate pentru ziua de azi"
    items = {stats.pop("descriere"): [stats.pop("url")]}
    return formatters.parse_global(
        title=f"🔵 {stats.pop('titlu')}", stats=stats, items=items, emoji="❗"
    )
Beispiel #4
0
 def respond(self, stats, title=None):
     return (
         parse_global(
             title=title or self.name.capitalize(),
             stats=stats,
             items={},
         )
         if stats
         else self.does_not_exist
     )
Beispiel #5
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
Beispiel #6
0
def local_age():
    stats = database.get_stats(slug=SLUG["romania"])
    if not stats:
        return "Nu sunt statistici de vârstă pentru ziua de azi"
    deserialized = DLZArchiveSerializer.deserialize(stats)
    stats = deserialized["Categorii de vârstă"]
    categories = list(reversed(sorted(stats)))

    max_key_len = len(categories[0])
    max_val_len = len(str(stats[categories[0]]))
    return formatters.parse_global(
        title=f"🇷🇴Categorii de vârstă",
        stats=[
            f"🦠 `{k:<{max_key_len}}: {stats[k]:<{max_val_len}}`" for k in stats
        ],
        items=[],
        emoji="🦠",
        footer=f"\n`Actualizat la: {deserialized['Data']}`",
    )
Beispiel #7
0
def local_global_stats():
    top_stats = database.get_stats(
        collection=COLLECTION["global"], slug=SLUG["global"]
    )
    if not top_stats:
        return "Nu sunt statistici globale pentru ziua de azi"
    countries = list(
        database.get_many(COLLECTION["country"], order_by="total_cases")[:3]
    )
    for item in countries:
        del item["_id"]
    last_updated = top_stats.pop("last_updated")
    return formatters.parse_global(
        title="🌎 Global Stats",
        stats=top_stats,
        items=prepare_items("country", countries),
        emoji="🦠",
        footer=f"\n`{last_updated}`\n[Source: worldometers.info](https://worldometers.info/)",
    )
Beispiel #8
0
def analyze_sentiment(text, **kwargs):
    """
    Analyzing Sentiment in a String

    Args:
      text_content The text content to analyze
    """

    if not text:
        return "Syntax: /analyze_sentiment <your text here>"

    client = language_v1.LanguageServiceClient()

    # Available types: PLAIN_TEXT, HTML
    doc = {"content": text, "type": language_v1.Document.Type.PLAIN_TEXT}
    encoding_type = language_v1.EncodingType.UTF8
    try:
        response = client.analyze_sentiment(doc, encoding_type=encoding_type)
    except InvalidArgument as error:
        return error.message

    stats = OrderedDict()
    stats["Overall score"] = response.document_sentiment.score
    stats["Overall magnitude"] = response.document_sentiment.magnitude
    stats["Language"] = response.language

    sentences = {}
    for sentence in response.sentences:
        title = sentence.text.content
        sentences[title] = OrderedDict()
        sentences[title]["Score"] = sentence.sentiment.score
        sentences[title]["Magnitute"] = sentence.sentiment.magnitude

    if "json" in kwargs:
        return {"sentences": sentences, **stats}

    return parse_global(
        title="💔 Sentiment analysis",
        stats=stats,
        items=sentences,
        footer=get_footer(),
    )
Beispiel #9
0
    def test_formatted(self, lang):
        resp = self.mock_analyze()
        lang.return_value.analyze_sentiment.return_value = resp
        assert analyze_sentiment("foo") == parse_global(
            title="💔 Sentiment analysis",
            stats={
                "Overall score": 1,
                "Overall magnitude": 2,
                "Language": 3
            },
            items={"foo_content": {
                "Score": 6,
                "Magnitute": 7
            }},
            footer="""===================================
Clearly Positive:   "score": 0.8,  "magnitude": 3.0
Clearly Negative: "score": -0.6, "magnitude": 4.0
Neutral:                 "score": 0.1,  "magnitude": 0.0
Mixed:                   "score": 0.0,  "magnitude": 4.0
""",
        )
Beispiel #10
0
def test_parse_global():
    assert formatters.parse_global(
        {"foo": "bar"},
        {"bar": ["cux"]}) == ("\n*🦠 Romania*\n└ Foo: bar\n\n➡️ bar\n└ cux\n\n")
Beispiel #11
0
 def test_respond_with_no_stats_calls_does_not_exists(self):
     assert self.game.respond({}, title="cux") == parse_global(
         stats=self.get_does_not_exist_result(),
         items={},
         title="Foo_game_name",
     )
Beispiel #12
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}")
Beispiel #13
0
def local_quick_stats():
    stats = database.get_stats(slug=SLUG["romania"])
    if not stats:
        return "Nu sunt statistici salvate pentru ziua de azi"
    stats = DLZSerializer.deserialize(stats)
    return formatters.parse_global(title="🔴 Cazuri noi", stats=stats, items={})