Esempio n. 1
0
def parse_request(request, for_bakchod, og_bakchod, tg_update):

    try:
        set_type = request[1]
    except IndexError:
        response = "❔ Please include what you want to set"
        return response

    if set_type.lower() == "rokda":

        try:
            rokda_to_set = float(request[2])
        except IndexError:
            response = "Please include rokda to set - `/set rokda 1337`"
            return response

        if util.is_admin(og_bakchod):
            set_reponse = set_bakchod_rokda(rokda_to_set, for_bakchod)
            response = set_reponse
        else:
            response = "❌ Not allowed to set rokda."

    else:

        response = "❌ Can't set that."

    logger.info(response)
    return response
Esempio n. 2
0
def handle(update, context):

    util.log_chat("reset", update)

    try:

        # Extract query...
        query = update.message.text
        query = query.split(" ")

        target = None

        if not util.is_admin(update.message.from_user["id"]):
            return

        # Request includes the username as a mention
        if update.message.entities:
            for entity in update.message.entities:
                if entity.type == "text_mention" and entity.user is not None:
                    target = dao.get_bakchod_by_id(entity.user.id)

        # Last attempt... try to lookup username in DB
        if target is None:

            receiver_username = query[1]

            # Remove the "@" prefix
            if receiver_username.startswith("@"):
                receiver_username = receiver_username[1:]

            target = dao.get_bakchod_by_username(receiver_username)

        if target is not None:
            logger.info("[reset] target={}",
                        util.extract_pretty_name_from_bakchod(target))
            target.modifiers = {}
            dao.insert_bakchod(target)
            update.message.reply_text(
                "Reset - " + util.extract_pretty_name_from_bakchod(target))
            return

    except Exception as e:
        logger.error(
            "Caught Error in reset.handle - {} \n {}",
            e,
            traceback.format_exc(),
        )
Esempio n. 3
0
def handle(update, context):

    try:

        util.log_chat("purge", update)

        end_message_id = update.message.message_id

        if not util.is_admin(update.message.from_user["id"]):
            safe_delete_message(context.bot, end_message_id,
                                update.message.chat_id)
            return

        start_message_id = extract_start_message_id(update)
        if start_message_id is None:
            logger.info("[purge] end_message_id was None!")
            return

        logger.info(
            "[purge] start_message_id={} end_message_id={}",
            start_message_id,
            end_message_id,
        )

        for purge_message_id in range(start_message_id, end_message_id):
            logger.debug(
                "[purge] deleting message_id={} group_id={}",
                purge_message_id,
                update.message.chat_id,
            )
            break_the_loop = safe_delete_message(context.bot, purge_message_id,
                                                 update.message.chat_id)

            if break_the_loop:
                break

    except Exception as e:
        logger.error(
            "Caught Error in default.handle - {} \n {}",
            e,
            traceback.format_exc(),
        )
Esempio n. 4
0
def handle(update, context):

    util.log_chat("roll", update)

    try:
        command = extract_command_from_update(update)

        if command == "start":

            create_new_roll = False

            group_id = get_group_id_from_update(update)
            if group_id is None:
                update.message.reply_text(text="Roll only be used in a group!")
                return

            current_roll = dao.get_roll_by_id(group_id)
            if current_roll is None:
                create_new_roll = True
            else:
                # Pre-exisitng roll... check if expired
                roll_expiry = ciso8601.parse_datetime(current_roll["expiry"])
                if roll_expiry <= datetime.datetime.now():
                    create_new_roll = True

            # Allow admins to create new rolls
            if util.is_admin(update.message.from_user["id"]):
                create_new_roll = True

            if create_new_roll:

                roll = generate_new_roll(update, group_id)
                if roll is None:
                    update.message.reply_text(text="Couldn't start a new roll :(")
                    return

                metrics.rolls_started.inc()

                pretty_roll = generate_pretty_roll(roll)
                response = "<b>Started new roulette!</b> " + pretty_roll
                update.message.reply_text(
                    text=response, parse_mode=telegram.ParseMode.HTML
                )
                return

            else:
                # Handle when not create_new_roll
                update.message.reply_text("Chal kat re bsdk!")
                return

        elif command == "reset":

            if util.is_admin(update.message.from_user["id"]):

                # Remove schedule reset job
                for job in context.job_queue.jobs():
                    if (
                        job.name == "reset_roll_effects"
                        and job.context == update.message.chat_id
                    ):
                        logger.info(
                            "[roll] Removing pre-scheduled reset_roll_effects job..."
                        )
                        job.schedule_removal()

                # Schedule callback for resetting roll effects
                context.job_queue.run_once(
                    reset_roll_effects, 1, context=update.message.chat_id
                )
                return

            else:
                update.message.reply_text("Chal kat re bsdk!")
                return

        else:

            # Return roll status for anything else

            group_id = get_group_id_from_update(update)
            if group_id is None:
                update.message.reply_text(text="Roll can only be used in a group!")
                return

            current_roll = dao.get_roll_by_id(group_id)

            if current_roll is None:
                update.message.reply_text(
                    text="No active roulette right now. <code>/roll start</code> to start one!",
                    parse_mode=telegram.ParseMode.HTML,
                )
                return
            else:
                # Handle expired roll
                roll_expiry = ciso8601.parse_datetime(current_roll["expiry"])
                if roll_expiry <= datetime.datetime.now():
                    update.message.reply_text(
                        text="No active roulette right now. <code>/roll start</code> to start one!",
                        parse_mode=telegram.ParseMode.HTML,
                    )
                    return
                else:
                    pretty_roll = generate_pretty_roll(current_roll)
                    response = "<b>Current active roulette:</b> {}".format(pretty_roll)
                    update.message.reply_text(
                        text=response, parse_mode=telegram.ParseMode.HTML
                    )
                    return

    except Exception as e:
        logger.error(
            "Caught Error in roll.handle - {} \n {}", e, traceback.format_exc(),
        )
Esempio n. 5
0
def handle(update, context):

    util.log_chat("quotes", update)

    try:

        # Extract query...
        query = update.message.text
        query = query.split(" ")

        command = None

        try:
            command = query[1].lower()
        except:
            command = "random"

        if command == "add":
            if update.message.reply_to_message.text:
                response = add_quote(update)
                update.message.reply_text(text=response, parse_mode=ParseMode.MARKDOWN)

        elif command == "remove":
            if util.is_admin(update.message.from_user["id"]):
                try:
                    id_to_remove = query[2]
                except:
                    update.message.reply_text(
                        text="Please include the Quote ID you want to remove!",
                        parse_mode=ParseMode.MARKDOWN,
                    )
                    return
                response = remove_quote(id_to_remove)
            else:
                response = "Chal kat re bsdk!"

            update.message.reply_text(text=response, parse_mode=ParseMode.MARKDOWN)

        elif command == "get":

            response = ""

            try:
                quote_id = query[2]
            except:
                update.message.reply_text(
                    text="Please include the Quote ID you want to get!",
                    parse_mode=ParseMode.MARKDOWN,
                )
                return

            quote = get_quote_by_id(quote_id)

            if quote is None:

                group_id = util.get_group_id_from_update(update)
                if group_id is None:
                    update.message.reply_text(text="Can't run this command here!")
                    return

                # Return a random quote
                random_quote = get_random_quote(group_id)

                if random_quote is None:
                    logger.info("[quotes] No quotes found! - group_id={}", group_id)
                    update.message.reply_text(
                        text="No quotes found for this Group! You can add quotes with `/quotes add`",
                        parse_mode=ParseMode.MARKDOWN,
                    )
                    return

                response = "Couldn't find quote with ID `{}`... but here's a random one - \n".format(
                    quote_id
                )

            pretty_quote = generate_pretty_quote(quote)
            response = response + pretty_quote
            update.message.reply_text(text=response, parse_mode=ParseMode.MARKDOWN)

        elif command == "join":

            response = ""

            try:
                quote_id = query[2]
            except:
                update.message.reply_text(
                    text="Please include the Quote ID you want to join!",
                    parse_mode=ParseMode.MARKDOWN,
                )
                return

            quote = get_quote_by_id(quote_id)

            if quote is None:
                update.message.reply_text(
                    text="Couldn't find quote with ID `{}`!".format(quote_id),
                    parse_mode=ParseMode.MARKDOWN,
                )
                return

            response = join_quotes(quote, update)

            update.message.reply_text(text=response, parse_mode=ParseMode.MARKDOWN)

        else:

            # Enforce rate limiting on getting random quotes
            bakchod = dao.get_bakchod_by_id(update.message.from_user.id)
            history = bakchod.history

            if history is None:
                history = {}

            two_min_ago = datetime.datetime.now() - datetime.timedelta(minutes=2)

            if "random_quote_get" in history:
                last_time_get = ciso8601.parse_datetime(history["random_quote_get"])
                if last_time_get > two_min_ago:
                    logger.info("[quotes] request random quote too soon... skipping")
                    update.message.reply_text(
                        "Quotes ki dukan band hai... come back later!"
                    )
                    return

            history["random_quote_get"] = datetime.datetime.now()
            bakchod.history = history
            dao.insert_bakchod(bakchod)

            group_id = util.get_group_id_from_update(update)
            if group_id is None:
                update.message.reply_text(text="Can't run this command here!")
                return

            # Return a random quote
            random_quote = get_random_quote(group_id)

            if random_quote is None:
                logger.info("[quotes] No quotes found! - group_id={}", group_id)
                update.message.reply_text(
                    text="No quotes found for this Group! You can add quotes with `/quotes add`",
                    parse_mode=ParseMode.MARKDOWN,
                )
                return

            logger.info("[quotes] Got a random quote '{}", random_quote)
            pretty_quote = generate_pretty_quote(random_quote)
            update.message.reply_text(text=pretty_quote, parse_mode=ParseMode.MARKDOWN)
            return

    except Exception as e:
        logger.error(
            "Caught Error in quotes.handle - {} \n {}", e, traceback.format_exc(),
        )
Esempio n. 6
0
def handle(update, context):

    util.log_chat("roll", update)

    try:
        command = extract_command_from_update(update)

        if command == "start":

            create_new_roll = False

            group_id = get_group_id_from_update(update)
            if group_id is None:
                update.message.reply_text(text="Roll only be used in a group!")
                return

            current_roll = dao.get_roll_by_id(group_id)
            if current_roll is None:
                create_new_roll = True
            else:
                # Pre-exisitng roll... check if expired
                roll_expiry = ciso8601.parse_datetime(current_roll["expiry"])
                if roll_expiry <= datetime.datetime.now():
                    create_new_roll = True

            # Allow admins to create new rolls
            if util.is_admin(update.message.from_user["id"]):
                create_new_roll = True

            if create_new_roll:

                # Create new roll...

                # Set roll rule type
                rule = get_random_roll_type()

                # Set the number to required to win
                roll_number = random.randint(1, 6)

                # Extract victim from command param...
                victim = None
                parsed_victim_username = extract_param_from_update(update)
                if parsed_victim_username is not None:
                    victim = dao.get_bakchod_by_username(
                        parsed_victim_username)
                    if victim is not None:
                        logger.info(
                            "[roll] Found passed Bakchod username={} in DB",
                            parsed_victim_username,
                        )

                # Or else get a Random Bakchod
                if victim is None:
                    victim = get_random_bakchod(group_id)

                if victim is None:
                    update.message.reply_text(
                        text="Couldn't get a random Bakchod :(")
                    return

                # Set the roll winrar to None
                winrar = None

                expiry = datetime.datetime.now() + datetime.timedelta(hours=1)

                dao.insert_roll(group_id, rule, roll_number, victim.id, winrar,
                                expiry)

                roll = dao.get_roll_by_id(group_id)
                if roll is None:
                    update.message.reply_text(
                        text="Couldn't start a new roll :(")
                    return

                pretty_roll = generate_pretty_roll(roll)
                response = "<b>Started new roulette!</b> " + pretty_roll
                update.message.reply_text(text=response,
                                          parse_mode=telegram.ParseMode.HTML)
                return

            else:
                # Handle when not create_new_roll
                update.message.reply_text("Chal kat re bsdk!")
                return

        elif command == "reset":

            if util.is_admin(update.message.from_user["id"]):

                # Remove schedule reset job
                for job in context.job_queue.jobs():
                    if (job.name == "reset_roll_effects"
                            and job.context == update.message.chat_id):
                        logger.info(
                            "[roll] Removing pre-scheduled reset_roll_effects job..."
                        )
                        job.schedule_removal()

                # Schedule callback for resetting roll effects
                context.job_queue.run_once(reset_roll_effects,
                                           1,
                                           context=update.message.chat_id)
                return

            else:
                update.message.reply_text("Chal kat re bsdk!")
                return

        else:

            # Return roll status for anything else

            group_id = get_group_id_from_update(update)
            if group_id is None:
                update.message.reply_text(
                    text="Roll can only be used in a group!")
                return

            current_roll = dao.get_roll_by_id(group_id)

            if current_roll is None:
                update.message.reply_text(
                    text=
                    "No active roulette right now. <code>/roll start</code> to start one!",
                    parse_mode=telegram.ParseMode.HTML,
                )
                return
            else:
                # Handle expired roll
                roll_expiry = ciso8601.parse_datetime(current_roll["expiry"])
                if roll_expiry <= datetime.datetime.now():
                    update.message.reply_text(
                        text=
                        "No active roulette right now. <code>/roll start</code> to start one!",
                        parse_mode=telegram.ParseMode.HTML,
                    )
                    return
                else:
                    pretty_roll = generate_pretty_roll(current_roll)
                    response = "<b>Current active roulette:</b> {}".format(
                        pretty_roll)
                    update.message.reply_text(
                        text=response, parse_mode=telegram.ParseMode.HTML)
                    return

    except Exception as e:
        logger.error(
            "Caught Error in roll.handle - {} \n {}",
            e,
            traceback.format_exc(),
        )