예제 #1
0
def add_mute(upd: Updater, handlers_group: int):
    logger.info("registering mute handlers")
    dp = upd.dispatcher
    dp.add_handler(
        CommandHandler(
            "mute",
            mute,
            filters=Filters.chat(username=get_group_chat_id().strip("@"))
            & admin_filter,
            run_async=True,
        ),
        handlers_group,
    )
    dp.add_handler(CommandHandler("mute", mute_self, run_async=True),
                   handlers_group)
    dp.add_handler(
        CommandHandler(
            "unmute",
            unmute,
            filters=Filters.chat(username=get_group_chat_id().strip("@"))
            & admin_filter,
            run_async=True,
        ),
        handlers_group,
    )
예제 #2
0
def random_cough(bot: Bot, queue: JobQueue):
    users = _db.find_all()

    message = ''

    for user in users:
        _rng = random()

        # todo: move "_get_username" to commons
        full_name = _get_username(user)

        lethaled = _db.is_lethaled(user['_id'])

        if 'infected_since' in user and 'cured_since' not in user and lethaled is None:
            chance = RANDOM_COUGH_INFECTED_CHANCE
            delta_seconds = (datetime.now() -
                             user['infected_since']).total_seconds()
            delta_days_float = delta_seconds / (60 * 60 * 24)

            if _rng <= RANDOM_CURE_RATE**(2 - delta_days_float):
                chance = .0
                _db.cure(user['_id'])
                message += f"{full_name} излечился от коронавируса\n"

            if _rng <= LETHALITY_RATE * (delta_days_float**delta_days_float):
                chance = .0
                try:
                    _db.add_lethality(user['_id'], datetime.now())
                    # TODO: Extract it more properly
                    mute_perm = ChatPermissions(
                        can_add_web_page_previews=False,
                        can_send_media_messages=False,
                        can_send_other_messages=False,
                        can_send_messages=False)
                    bot.restrict_chat_member(get_group_chat_id(), user['_id'],
                                             mute_perm)
                    message += f"{full_name} умер от коронавируса, F\n"

                except BadRequest as err:
                    err_msg = f"can't restrict user: {err}"
                    logger.warning(err_msg)
        else:
            chance = RANDOM_COUGH_UNINFECTED_CHANCE

        if _rng <= chance:
            message += f"{full_name} чихнул в пространство \n"

    if message:
        bot.send_message(get_group_chat_id(), message)
예제 #3
0
def is_avatar_has_mask(img: bytearray, user: User, context: CallbackContext) -> bool:
    if (img is None) or len(img) < 100:
        return False

    # lookup existing value in cache
    cache_key = "avatar_mask_cache"
    hash_ = hash_img(img)
    if cache_key in context.bot_data.keys():
        is_good = context.bot_data[cache_key].get(hash_)
        if is_good is not None:
            return is_good

    try:
        is_good = container_predict(img, hash_)

        if cache_key not in context.bot_data.keys():
            context.bot_data[cache_key] = {}

        context.bot_data[cache_key][hash_] = is_good
        mask_message = "has" if is_good else "does not have"
        message = f"User {user.full_name} {mask_message} mask on"
        context.bot.send_message(get_group_chat_id(), message)
        return is_good

    except TelegramError as err:
        logger.error("can't check mask: %s", err)
        return False
예제 #4
0
def cure_all(queue: JobQueue, bot: Bot) -> None:
    # wipe db and ununrestrict all infected users
    for user in _db.find_all():
        # unrestrict all except admins (they are so good)
        try:
            # TODO: extract it more properly
            unmute_perm = ChatPermissions(
                can_add_web_page_previews=True,
                can_send_media_messages=True,
                can_send_other_messages=True,
                can_send_messages=True,
            )
            bot.restrict_chat_member(get_group_chat_id(), user.id, unmute_perm)
            logger.debug("user: %s was unrestrict", _get_username(user))
        except TelegramError as err:
            logger.warning("can't unrestrict %s: %s", _get_username(user), err)
    _db.remove_all()

    # clean up the jobs queue
    covid_daily_infection_job: Tuple = queue.get_jobs_by_name(
        JOB_QUEUE_DAILY_INFECTION_KEY
    )

    if covid_daily_infection_job:
        covid_daily_infection_job[0].schedule_removal()

    covid_repeating_coughing_job: Tuple = queue.get_jobs_by_name(
        JOB_QUEUE_REPEATING_COUGHING_KEY
    )

    if covid_repeating_coughing_job:
        covid_repeating_coughing_job[0].schedule_removal()
예제 #5
0
def random_fate(bot: Bot):
    """health or death"""

    users = _db.find_all()

    message = ""

    for user in users:
        _rng = random()

        # todo: move "_get_username" to commons
        full_name = _get_username(user)

        lethaled = _db.is_lethaled(user["_id"])

        if "infected_since" in user and "cured_since" not in user and lethaled is None:
            delta_seconds = (datetime.now() - user["infected_since"]).total_seconds()
            delta_days_float = delta_seconds / (60 * 60 * 24)

            if _rng <= RANDOM_CURE_RATE ** (2 - delta_days_float):
                _db.cure(user["_id"])
                message += f"{full_name} has recovered from coronavirus!\n"
                continue

            if _rng <= LETHALITY_RATE * (delta_days_float ** delta_days_float):
                try:
                    _db.add_lethality(user["_id"], datetime.now())
                    # TODO: Extract it more properly
                    mute_perm = ChatPermissions(
                        can_add_web_page_previews=False,
                        can_send_media_messages=False,
                        can_send_other_messages=False,
                        can_send_messages=False,
                    )
                    until = datetime.now() + RESPAWN_TIME
                    bot.restrict_chat_member(
                        get_group_chat_id(), user["_id"], mute_perm, until
                    )
                    message += f"{full_name} died from coronavirus F (time to respawn: {RESPAWN_TIME}) 🧟\n"

                except BadRequest as err:
                    err_msg = f"can't restrict user: {err}"
                    logger.warning(err_msg)

    if message:
        bot.send_message(get_group_chat_id(), message)
예제 #6
0
def add_roll(upd: Updater, handlers_group: int):
    logger.info("registering roll handlers")
    dp = upd.dispatcher
    dp.add_handler(MessageHandler(Filters.dice, roll), handlers_group)
    dp.add_handler(
        MessageHandler(Filters.regex(MEME_REGEX), roll, run_async=True), handlers_group
    )
    dp.add_handler(
        CommandHandler(
            "gdpr_me",
            satisfy_GDPR,
            filters=Filters.chat(username=get_group_chat_id().strip("@")),
            run_async=True,
        ),
        handlers_group,
    )
    dp.add_handler(
        CommandHandler(
            "hussars",
            show_hussars,
            filters=~Filters.chat(username=get_group_chat_id().strip("@"))
            | admin_filter,
            run_async=True,
        ),
        handlers_group,
    )
    dp.add_handler(
        CommandHandler(
            "htop",
            show_active_hussars,
            filters=admin_filter
            & Filters.chat(username=get_group_chat_id().strip("@")),
            run_async=True,
        ),
        handlers_group,
    )
    dp.add_handler(
        CommandHandler(
            "wipe_hussars",
            wipe_hussars,
            filters=admin_filter
            & Filters.chat(username=get_group_chat_id().strip("@")),
            run_async=True,
        ),
        handlers_group,
    )
예제 #7
0
def set_handlers(queue: JobQueue, bot: Bot):
    queue.run_daily(lambda _: daily_infection(get_group_chat_id(), bot),
                    DAILY_INFECTION_TIME,
                    name=JOB_QUEUE_DAILY_INFECTION_KEY)

    queue.run_repeating(lambda _: random_cough(bot, queue),
                        REPEATING_COUGHING_INTERVAL,
                        name=JOB_QUEUE_REPEATING_COUGHING_KEY)
예제 #8
0
def add_prism(upd: Updater, handlers_group: int):
    logger.info("register words handlers")
    dp = upd.dispatcher
    dp.add_handler(
        CommandHandler(
            "top",
            show_top,
            filters=Filters.chat(username=get_group_chat_id().strip("@"))
            & admin_filter,
            run_async=True,
        ),
        handlers_group,
    )
    dp.add_handler(
        MessageHandler(
            Filters.text & Filters.chat(username=get_group_chat_id().strip("@")),
            extract_words,
            run_async=True,
        ),
        handlers_group,
    )
예제 #9
0
def add_since_mode(upd: Updater, handlers_group: int):
    logger.info("register since-mode handlers")
    dp = upd.dispatcher
    dp.add_handler(
        CommandHandler(
            "since",
            since_callback,
            filters=Filters.chat(username=get_group_chat_id().strip("@")),
            run_async=True,
        ),
        handlers_group,
    )
    dp.add_handler(
        CommandHandler(
            "since_list",
            since_list_callback,
            filters=Filters.chat(username=get_group_chat_id().strip("@")),
            run_async=True,
        ),
        handlers_group,
    )
예제 #10
0
def add_nya(upd: Updater, handlers_group: int):
    logger.info("registering nya handlers")
    dp = upd.dispatcher
    dp.add_handler(
        CommandHandler(
            "nya",
            nya,
            filters=Filters.chat(username=get_group_chat_id().strip("@"))
            & admin_filter,
            run_async=True,
        ),
        handlers_group,
    )
예제 #11
0
def add_fools_mode(upd: Updater, handlers_group: int):
    logger.info("registering fools handlers")
    dp = upd.dispatcher

    dp.add_handler(
        MessageHandler(
            ~Filters.status_update
            & Filters.chat(username=get_group_chat_id().strip("@")),
            mesaĝa_traduko,
            run_async=True,
        ),
        handlers_group,
    )
예제 #12
0
def add_length(upd: Updater, handlers_group: int):
    logger.info("registering length handlers")
    dp = upd.dispatcher
    dp.add_handler(
        CommandHandler(
            "length",
            _length,
            filters=Filters.chat(username=get_group_chat_id().strip("@")),
            run_async=True,
        ),
        handlers_group,
    )

    dp.add_handler(
        CommandHandler(
            "longest",
            _longest,
            filters=Filters.chat(username=get_group_chat_id().strip("@")),
            run_async=True,
        ),
        handlers_group,
    )
예제 #13
0
def _add_version(upd: Updater, version_handlers_group: int):
    logger.info("register version handlers")
    dp = upd.dispatcher
    dp.add_handler(
        CommandHandler(
            "version",
            _version,
            filters=Filters.chat(username=get_group_chat_id().strip("@"))
            & admin_filter,
            run_async=True,
        ),
        version_handlers_group,
    )
예제 #14
0
def add_trusted_mode(upd: Updater, handlers_group: int):
    logger.info("register trusted-mode handlers")
    dp = upd.dispatcher
    dp.add_handler(
        CommandHandler(
            "trust",
            trust_callback,
            filters=Filters.chat(username=get_group_chat_id().strip("@"))
            & admin_filter,
            run_async=True,
        ),
        handlers_group,
    )
    dp.add_handler(
        CommandHandler(
            "untrust",
            untrust_callback,
            filters=Filters.chat(username=get_group_chat_id().strip("@"))
            & admin_filter,
            run_async=True,
        ),
        handlers_group,
    )
예제 #15
0
def random_cough(bot: Bot):
    users = _db.find_all()

    message = ""

    for user in users:
        # todo: move "_get_username" to commons
        full_name = _get_username(user)

        if random() <= RANDOM_COUGH_UNINFECTED_CHANCE:
            message += f"{full_name} чихнул в пространство \n"

    if message:
        bot.send_message(get_group_chat_id(), message)
예제 #16
0
def process_aoc_update(data, bot: Bot):
    cached_data = _db.get()

    # It is okay for a first mode run, just store this one
    if cached_data is None:
        # Return?
        cached_data = {"members": {}}

    _db.update(data)

    current_day = int(aoc_day_from_datetime(datetime.utcnow())) + 1
    logger.info("Current AOC day is %d", current_day)

    day_solved_by = calculate_solved_by(cached_data["members"], current_day)
    updated_day_solved_by = calculate_solved_by(data["members"], current_day)

    solved_both = False
    for _, tasks in day_solved_by.items():
        if len(tasks) == 2:
            solved_both = True

    logger.info(day_solved_by)
    logger.info(updated_day_solved_by)

    if len(updated_day_solved_by) > 0 and solved_both is False:
        # someone has done both current day task
        # find out who was first from sorted array
        first_one = None

        for memberId, tasks in updated_day_solved_by.items():
            if len(tasks) == 2:
                first_one = (memberId, tasks)
                break

        logger.info(first_one)
        if first_one is not None:
            member = data["members"][first_one[0]]
            max_delta = max(
                aoc_time_since_day_start(first_one[1][0]),
                aoc_time_since_day_start(first_one[1][1]),
            )

            message = (
                f"Wow! @{member['name']} just solves Day {current_day}"
                f" problem in {str(max_delta)}, gaining {member['stars']} ⭐️!"
                " Gut Gemacht! 🔥🔥🔥")

            bot.send_message(get_group_chat_id(), message)
예제 #17
0
def random_cough(bot: Bot, queue: JobQueue):
    users = _db.find_all()

    message = ""

    for user in users:
        # todo: move "_get_username" to commons
        full_name = _get_username(user)

        if random() <= RANDOM_COUGH_UNINFECTED_CHANCE:
            message += f"{full_name} чихнул в пространство \n"

    if message:
        result = bot.send_message(get_group_chat_id(), message)
        cleanup_queue_update(
            queue, None, result, 30, remove_cmd=True, remove_reply=False
        )
예제 #18
0
def start_pandemic(queue: JobQueue, bot: Bot) -> None:
    set_handlers(queue, bot)

    bot.send_message(get_group_chat_id(), "ALARM!!! CORONAVIRUS IS SPREADING")
예제 #19
0
def add_covid_mode(upd: Updater, handlers_group: int):
    logger.info("registering covid handlers")
    dp = upd.dispatcher
    dp.add_handler(
        CommandHandler(
            "check",
            test,
            filters=Filters.chat(username=get_group_chat_id().strip("@"))
            & admin_filter,
            run_async=True,
        ),
        handlers_group,
    )

    dp.add_handler(
        CommandHandler(
            "infect",
            infect_admin,
            filters=Filters.chat(username=get_group_chat_id().strip("@"))
            & admin_filter,
            run_async=True,
        ),
        handlers_group,
    )

    dp.add_handler(CommandHandler("cough", cough, run_async=True), handlers_group)

    dp.add_handler(
        CommandHandler(
            "quarantine",
            quarantine,
            filters=Filters.chat(username=get_group_chat_id().strip("@"))
            & admin_filter,
            run_async=True,
        ),
        handlers_group,
    )

    dp.add_handler(
        CommandHandler(
            "stats",
            stats,
            filters=Filters.chat(username=get_group_chat_id().strip("@"))
            & admin_filter,
            run_async=True,
        ),
        handlers_group,
    )

    dp.add_handler(
        CommandHandler(
            "temp",
            temp,
            filters=only_admin_on_others
            & Filters.chat(username=get_group_chat_id().strip("@")),
            run_async=True,
        ),
        handlers_group,
    )

    # We must do this, since bot api doesnt present a way to get all members
    # of chat at once
    dp.add_handler(
        MessageHandler(
            Filters.chat(username=get_group_chat_id().strip("@")),
            callback=catch_message,
        ),
        handlers_group,
    )