Ejemplo n.º 1
0
def set_warn_limit(update: Update, context: CallbackContext) -> str:
    if not check_perms(update, 1):
        return
    bot, args = context.bot, context.args
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    msg = update.effective_message  # type: Optional[Message]

    if args:
        if args[0].isdigit():
            if int(args[0]) < 3:
                msg.reply_text("The minimum warn limit is 3!")
            else:
                sql.set_warn_limit(chat.id, int(args[0]))
                msg.reply_text("Updated the warn limit to {}".format(args[0]))
                return ("<b>{}:</b>"
                        "\n#SET_WARN_LIMIT"
                        "\n<b>Admin:</b> {}"
                        "\nSet the warn limit to <code>{}</code>".format(
                            html.escape(chat.title),
                            mention_html(user.id, user.first_name),
                            args[0],
                        ))
        else:
            msg.reply_text("Give me a number as an arg!")
    else:
        limit, soft_warn = sql.get_warn_setting(chat.id)

        msg.reply_text("The current warn limit is {}".format(limit))
    return ""
Ejemplo n.º 2
0
def add_warn_filter(update: Update, context: CallbackContext):
    if not check_perms(update, 1):
        return
    bot = context.bot
    chat = update.effective_chat  # type: Optional[Chat]
    msg = update.effective_message  # type: Optional[Message]

    args = msg.text.split(
        None,
        1)  # use python's maxsplit to separate Cmd, keyword, and reply_text

    if len(args) < 2:
        return

    extracted = split_quotes(args[1])

    if len(extracted) >= 2:
        # set trigger -> lower, so as to avoid adding duplicate filters with different cases
        keyword = extracted[0].lower()
        content = extracted[1]

    else:
        return

    # Note: perhaps handlers can be removed somehow using sql.get_chat_filters
    for handler in dispatcher.handlers.get(WARN_HANDLER_GROUP, []):
        if handler.filters == (keyword, chat.id):
            dispatcher.remove_handler(handler, WARN_HANDLER_GROUP)

    sql.add_warn_filter(chat.id, keyword, content)

    update.effective_message.reply_text(
        "Warn handler added for '{}'!".format(keyword))
    raise DispatcherHandlerStop
Ejemplo n.º 3
0
def add_blacklist(update: Update, context: CallbackContext):
    if not check_perms(update, 1):
        return
    bot = context.bot
    msg = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]
    words = msg.text.split(None, 1)

    if len(words) > 1:
        text = words[1]
        if "**" in text:
            msg.reply_text(
                "Can't set blacklist, please don't use consecutive multiple \"*\"."
            )
            return
        to_blacklist = list(
            set(trigger.strip() for trigger in text.split("\n")
                if trigger.strip()))
        for trigger in to_blacklist:
            sql.add_to_blacklist(chat.id, trigger.lower())

        if len(to_blacklist) == 1:
            msg.reply_text("Added <code>{}</code> to the blacklist!".format(
                html.escape(to_blacklist[0])),
                           parse_mode=ParseMode.HTML)

        else:
            msg.reply_text(
                "Added <code>{}</code> triggers to the blacklist.".format(
                    len(to_blacklist)),
                parse_mode=ParseMode.HTML)

    else:
        msg.reply_text(
            "Tell me which words you would like to add to the blacklist.")
Ejemplo n.º 4
0
def pin(update: Update, context: CallbackContext) -> str:
    if not check_perms(update, 2):
        return
    bot = context.bot
    args = context.args
    user = update.effective_user  # type: Optional[User]
    chat = update.effective_chat  # type: Optional[Chat]

    is_group = chat.type != "private" and chat.type != "channel"

    prev_message = update.effective_message.reply_to_message

    is_silent = True
    if len(args) >= 1:
        is_silent = not (args[0].lower() == 'notify' or args[0].lower()
                         == 'loud' or args[0].lower() == 'violent')

    if prev_message and is_group:
        try:
            bot.pinChatMessage(chat.id,
                               prev_message.message_id,
                               disable_notification=is_silent)
        except BadRequest as excp:
            if excp.message == "Chat_not_modified":
                pass
            else:
                raise
        return "<b>{}:</b>" \
               "\n#PINNED" \
               "\n<b>Admin:</b> {}".format(html.escape(chat.title), mention_html(user.id, user.first_name))

    return ""
Ejemplo n.º 5
0
def remove_warns(update: Update, context: CallbackContext) -> str:
    if not check_perms(update, 1):
        return
    bot, args = context.bot, context.args
    message = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]

    user_id = extract_user(message, args)

    if user_id:
        sql.remove_warn(user_id, chat.id)
        message.reply_text("Last warn has been removed!")
        warned = chat.get_member(user_id).user
        return ("<b>{}:</b>"
                "\n#UNWARN"
                "\n<b>• Admin:</b> {}"
                "\n<b>• User:</b> {}"
                "\n<b>• ID:</b> <code>{}</code>".format(
                    html.escape(chat.title),
                    mention_html(user.id, user.first_name),
                    mention_html(warned.id, warned.first_name),
                    warned.id,
                ))
    message.reply_text("No user has been designated!")
    return ""
Ejemplo n.º 6
0
def unlock(update: Update, context: CallbackContext) -> str:
    if not check_perms(update, 1):
        return
    bot, args = context.bot, context.args
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    message = update.effective_message  # type: Optional[Message]

    if is_user_admin(chat, message.from_user.id):
        if len(args) >= 1:
            if args[0] in LOCK_TYPES:
                sql.update_lock(chat.id, args[0], locked=False)
                message.reply_text("Unlocked {} for everyone!".format(args[0]))
                return ("<b>{}:</b>"
                        "\n#UNLOCK"
                        "\n<b>Admin:</b> {}"
                        "\nUnlocked <code>{}</code>.".format(
                            html.escape(chat.title),
                            mention_html(user.id, user.first_name),
                            args[0],
                        ))

            if args[0] in RESTRICTION_TYPES:
                sql.update_restriction(chat.id, args[0], locked=False)
                """
                            members = users_sql.get_chat_members(chat.id)
                            if args[0] == "messages":
                                unrestr_members(bot, chat.id, members, media=False, other=False, previews=False)

                            elif args[0] == "media":
                                unrestr_members(bot, chat.id, members, other=False, previews=False)

                            elif args[0] == "other":
                                unrestr_members(bot, chat.id, members, previews=False)

                            elif args[0] == "previews":
                                unrestr_members(bot, chat.id, members)

                            elif args[0] == "all":
                                unrestr_members(bot, chat.id, members, True, True, True, True)
                            """
                message.reply_text("Unlocked {} for everyone!".format(args[0]))

                return ("<b>{}:</b>"
                        "\n#UNLOCK"
                        "\n<b>Admin:</b> {}"
                        "\nUnlocked <code>{}</code>.".format(
                            html.escape(chat.title),
                            mention_html(user.id, user.first_name),
                            args[0],
                        ))
            message.reply_text(
                "What are you trying to unlock...? Try /locktypes for the list of lockables"
            )

        else:
            bot.sendMessage(chat.id, "What are you trying to unlock...?")

    return ""
Ejemplo n.º 7
0
def promote(update: Update, context: CallbackContext, check="restrict") -> str:
    if not check_perms(update, 3):
        return
    bot = context.bot
    args = context.args
    chat_id = update.effective_chat.id
    message = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]

    user_id, title = extract_user_and_text(message, args)

    if not user_id or int(user_id) == 777000 or int(user_id) == 1087968824:
        message.reply_text("You don't seem to be referring to a user.")
        return ""

    user_member = chat.get_member(user_id)
    if user_member.status == 'administrator' or user_member.status == 'creator':
        message.reply_text(
            "How am I meant to promote someone that's already an admin?")
        return ""

    if user_id == bot.id:
        message.reply_text(
            "I can't promote myself! Get an admin to do it for me.")
        return ""

    # set same perms as bot - bot can't assign higher perms than itself!
    bot_member = chat.get_member(bot.id)

    bot.promoteChatMember(
        chat_id,
        user_id,
        can_change_info=bot_member.can_change_info,
        can_post_messages=bot_member.can_post_messages,
        can_edit_messages=bot_member.can_edit_messages,
        can_delete_messages=bot_member.can_delete_messages,
        can_invite_users=bot_member.can_invite_users,
        can_restrict_members=bot_member.can_restrict_members,
        can_promote_members=bool(False if user_id not in SUDO_USERS else
                                 bot_member.can_restrict_members),
        can_pin_messages=bot_member.can_pin_messages)

    text = ""
    if title:
        bot.set_chat_administrator_custom_title(chat_id, user_id, title[:16])
        text = " with title <code>{}</code>".format(title[:16])

    message.reply_text("Successfully promoted {}".format(
        mention_html(user_member.user.id, user_member.user.first_name)) +
                       text + "!",
                       parse_mode=ParseMode.HTML)
    return "<b>{}:</b>" \
           "\n#PROMOTED" \
           "\n<b>Admin:</b> {}" \
           "\n<b>User:</b> {}".format(html.escape(chat.title),
                                      mention_html(user.id, user.first_name),
                                      mention_html(user_member.user.id, user_member.user.first_name))
Ejemplo n.º 8
0
def unmute(update: Update, context: CallbackContext) -> str:
    if not check_perms(update, 1):
        return
    bot, args = context.bot, context.args
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    message = update.effective_message  # type: Optional[Message]

    user_id = extract_user(message, args)
    if not user_id:
        message.reply_text(
            "You'll need to either give me a username to unmute, or reply to someone to be unmuted."
        )
        return ""

    member = chat.get_member(int(user_id))

    if member:
        if is_user_admin(chat, user_id, member=member):
            message.reply_text(
                "This is an admin, what do you expect me to do?")
            return ""

        if member.status not in ("kicked", "left"):
            if (member.can_send_messages and member.can_send_media_messages
                    and member.can_send_other_messages
                    and member.can_add_web_page_previews):
                message.reply_text("This user already has the right to speak.")
                return ""
            bot.restrict_chat_member(
                chat.id,
                int(user_id),
                permissions=ChatPermissions(
                    can_send_messages=True,
                    can_send_media_messages=True,
                    can_send_other_messages=True,
                    can_add_web_page_previews=True,
                ),
            )
            message.reply_text("Unmuted!")
            return ("<b>{}:</b>"
                    "\n#UNMUTE"
                    "\n<b>Admin:</b> {}"
                    "\n<b>User:</b> {}".format(
                        html.escape(chat.title),
                        mention_html(user.id, user.first_name),
                        mention_html(member.user.id, member.user.first_name),
                    ))
    else:
        message.reply_text(
            "This user isn't even in the chat, unmuting them won't make them talk more than they "
            "already do!")

    return ""
Ejemplo n.º 9
0
def set_flood(update: Update, context: CallbackContext) -> str:
    bot, args = context.bot, context.args
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    message = update.effective_message  # type: Optional[Message]

    if not check_perms(update, 1):
        return

    if len(args) >= 1:
        val = args[0].lower()
        if val in ("off", "no", "0"):
            sql.set_flood(chat.id, 0)
            message.reply_text("Anti-flood has been disabled.")

        elif val.isdigit():
            amount = int(val)
            if amount <= 0:
                sql.set_flood(chat.id, 0)
                message.reply_text("Anti-flood has been disabled.")
                return ("<b>{}:</b>"
                        "\n#SETFLOOD"
                        "\n<b>Admin:</b> {}"
                        "\nDisabled Anti-flood.".format(
                            html.escape(chat.title),
                            mention_html(user.id, user.first_name)))

            if amount < 1:
                message.reply_text(
                    "Anti-flood has to be either 0 (disabled) or least 1")
                return ""
            sql.set_flood(chat.id, amount)
            message.reply_text(
                "Anti-flood has been updated and set to {}".format(amount))
            return ("<b>{}:</b>"
                    "\n#SETFLOOD"
                    "\n<b>Admin:</b> {}"
                    "\nSet anti-flood to <code>{}</code>.".format(
                        html.escape(chat.title),
                        mention_html(user.id, user.first_name),
                        amount,
                    ))

        else:
            message.reply_text(
                "Unrecognised argument - please use a number, 'off', or 'no'.")
    else:
        message.reply_text(
            "Give me an argument! Set a number to enforce against consecutive spams.\n"
            "i.e `/setflood 5`: to control consecutive of messages.",
            parse_mode=ParseMode.MARKDOWN,
        )
    return ""
Ejemplo n.º 10
0
def set_flood_strength(update: Update, context: CallbackContext):
    if not check_perms(update, 1):
        return
    bot, args = context.bot, context.args
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    msg = update.effective_message  # type: Optional[Message]

    if args:
        if args[0].lower() in ("on", "yes"):
            sql.set_flood_strength(chat.id, False)
            msg.reply_text(
                "Exceeding consecutive flood limit will result in a ban!")
            return (
                "<b>{}:</b>\n"
                "<b>• Admin:</b> {}\n"
                "Has enabled strong flood and users will be banned.".format(
                    html.escape(chat.title),
                    mention_html(user.id, user.first_name)))

        if args[0].lower() in ("off", "no"):
            sql.set_flood_strength(chat.id, True)
            msg.reply_text(
                "Exceeding consecutive flood limit will result in a kick, Users will able to join back."
            )
            return ("<b>{}:</b>\n"
                    "<b>• Admin:</b> {}\n"
                    "Has disabled strong flood and users will only be kicked.".
                    format(html.escape(chat.title),
                           mention_html(user.id, user.first_name)))
        msg.reply_text("I only understand on/yes/no/off!")
    else:
        soft_flood = sql.get_flood_strength(chat.id)
        if soft_flood is True:
            msg.reply_text(
                "Flood strength is currently set to *kick* users when they exceed the limits. ",
                parse_mode=ParseMode.MARKDOWN,
            )

        elif soft_flood:
            msg.reply_text(
                "The default configuration for flood control is currently set as a ban.",
                parse_mode=ParseMode.MARKDOWN,
            )

        elif soft_flood is False:
            msg.reply_text(
                "Flood strength is currently set to *ban* users when they exceed the limits, "
                "user will be banned.",
                parse_mode=ParseMode.MARKDOWN,
            )
    return ""
Ejemplo n.º 11
0
def unblacklist(update: Update, context: CallbackContext):
    if not check_perms(update, 0):
        return
    bot = context.bot
    msg = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]
    words = msg.text.split(None, 1)

    if len(words) > 1:
        text = words[1]
        to_unblacklist = list(
            set(trigger.strip() for trigger in text.split("\n")
                if trigger.strip()))
        successful = 0
        for trigger in to_unblacklist:
            success = sql.rm_from_blacklist(chat.id, trigger.lower())
            if success:
                successful += 1

        if len(to_unblacklist) == 1:
            if successful:
                msg.reply_text(
                    "Removed <code>{}</code> from the blacklist!".format(
                        html.escape(to_unblacklist[0])),
                    parse_mode=ParseMode.HTML)
            else:
                msg.reply_text("This isn't a blacklisted trigger...!")

        elif successful == len(to_unblacklist):
            msg.reply_text(
                "Removed <code>{}</code> triggers from the blacklist.".format(
                    successful),
                parse_mode=ParseMode.HTML)

        elif not successful:
            msg.reply_text(
                "None of these triggers exist, so they weren't removed.".
                format(successful,
                       len(to_unblacklist) - successful),
                parse_mode=ParseMode.HTML)

        else:
            msg.reply_text(
                "Removed <code>{}</code> triggers from the blacklist. {} did not exist, "
                "so were not removed.".format(successful,
                                              len(to_unblacklist) -
                                              successful),
                parse_mode=ParseMode.HTML)
    else:
        msg.reply_text(
            "Tell me which words you would like to remove from the blacklist.")
Ejemplo n.º 12
0
def unban(update: Update, context: CallbackContext):
    if not check_perms(update, 1):
        return
    bot, args = context.bot, context.args
    message = update.effective_message  # type: Optional[Message]
    user = update.effective_user  # type: Optional[User]
    chat = update.effective_chat  # type: Optional[Chat]

    user_id, reason = extract_user_and_text(message, args)

    if not user_id or int(user_id) == 777000 or int(user_id) == 1087968824:
        message.reply_text("You don't seem to be referring to a user.")
        return ""

    try:
        member = chat.get_member(user_id)
    except BadRequest as excp:
        if excp.message == "User not found":
            message.reply_text("404 - user not found")
            return ""
        raise

    if user_id == bot.id:
        message.reply_text("How would I unban myself if I wasn't here...?")
        return ""

    if is_user_in_chat(chat, user_id):
        message.reply_text("User is already in the chat...")
        return ""

    chat.unban_member(user_id)
    message.reply_text(
        "Yep, {} can join!".format(
            mention_html(member.user.id, member.user.first_name)),
        parse_mode=ParseMode.HTML,
    )

    log = ("<b>{}:</b>"
           "\n#UNBANNED"
           "\n<b>Admin:</b> {}"
           "\n<b>User:</b> {} (<code>{}</code>)".format(
               html.escape(chat.title),
               mention_html(user.id, user.first_name),
               mention_html(member.user.id, member.user.first_name),
               member.user.id,
           ))
    if reason:
        log += "\n<b>Reason:</b> {}".format(reason)

    return log
Ejemplo n.º 13
0
def mute(update: Update, context: CallbackContext) -> str:
    if not check_perms(update, 1):
        return
    bot, args = context.bot, context.args
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    message = update.effective_message  # type: Optional[Message]

    user_id = extract_user(message, args)
    if not user_id:
        message.reply_text(
            "You'll need to either give me a username to mute, or reply to someone to be muted."
        )
        return ""

    if user_id == bot.id:
        message.reply_text("I'm not muting myself!")
        return ""

    member = chat.get_member(int(user_id))

    if member:
        if is_user_admin(chat, user_id, member=member):
            message.reply_text("Afraid I can't stop an admin from talking!")

        elif member.can_send_messages is None or member.can_send_messages:
            bot.restrict_chat_member(
                chat.id,
                user_id,
                permissions=ChatPermissions(can_send_messages=False))
            message.reply_text("Muted!")
            return ("<b>{}:</b>"
                    "\n#MUTE"
                    "\n<b>Admin:</b> {}"
                    "\n<b>User:</b> {}".format(
                        html.escape(chat.title),
                        mention_html(user.id, user.first_name),
                        mention_html(member.user.id, member.user.first_name),
                    ))

        else:
            message.reply_text("This user is already muted!")
    else:
        message.reply_text("This user isn't in the chat!")

    return ""
Ejemplo n.º 14
0
def set_warn_strength(update: Update, context: CallbackContext):
    if not check_perms(update, 1):
        return
    bot, args = context.bot, context.args
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    msg = update.effective_message  # type: Optional[Message]

    if args:
        if args[0].lower() in ("on", "yes"):
            sql.set_warn_strength(chat.id, False)
            msg.reply_text("Too many warns will now result in a ban!")
            return ("<b>{}:</b>\n"
                    "<b>Admin:</b> {}\n"
                    "Has enabled strong warns. Users will be banned.".format(
                        html.escape(chat.title),
                        mention_html(user.id, user.first_name)))

        if args[0].lower() in ("off", "no"):
            sql.set_warn_strength(chat.id, True)
            msg.reply_text(
                "Too many warns will now result in a kick! Users will be able to join again after."
            )
            return (
                "<b>{}:</b>\n"
                "<b>Admin:</b> {}\n"
                "Has disabled strong warns. Users will only be kicked.".format(
                    html.escape(chat.title),
                    mention_html(user.id, user.first_name)))
        msg.reply_text("I only understand on/yes/no/off!")
    else:
        limit, soft_warn = sql.get_warn_setting(chat.id)
        if soft_warn:
            msg.reply_text(
                "Warns are currently set to *kick* users when they exceed the limits.",
                parse_mode=ParseMode.MARKDOWN,
            )
        else:
            msg.reply_text(
                "Warns are currently set to *ban* users when they exceed the limits.",
                parse_mode=ParseMode.MARKDOWN,
            )
    return ""
Ejemplo n.º 15
0
def del_message(update: Update, context: CallbackContext) -> str:
    if not check_perms(update, 0):
        return
    bot = context.bot
    if update.effective_message.reply_to_message:
        user = update.effective_user  # type: Optional[User]
        chat = update.effective_chat  # type: Optional[Chat]

        if can_delete(chat, bot.id):
            update.effective_message.reply_to_message.delete()
            update.effective_message.delete()
            return "<b>{}:</b>" \
                   "\n#DEL" \
                   "\n<b>Admin:</b> {}" \
                   "\nMessage deleted.".format(html.escape(chat.title),
                                               mention_html(user.id, user.first_name))
    else:
        update.effective_message.reply_text("Whadya want to delete?")

    return ""
Ejemplo n.º 16
0
def warn_user(update: Update, context: CallbackContext) -> str:
    if not check_perms(update, 1):
        return
    bot, args = context.bot, context.args
    message = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]
    warner = update.effective_user  # type: Optional[User]

    user_id, reason = extract_user_and_text(message, args)

    if user_id:
        if message.reply_to_message and message.reply_to_message.from_user.id == user_id:
            return warn(message.reply_to_message.from_user, chat, reason,
                        message.reply_to_message, warner)
        else:
            return warn(
                chat.get_member(user_id).user, chat, reason, message, warner)
    else:
        message.reply_text("No user was designated!")
    return ""
Ejemplo n.º 17
0
def unpinall(update: Update, context: CallbackContext) -> str:
    if not check_perms(update, 2):
        return
    bot = context.bot
    chat = update.effective_chat
    user = update.effective_user  # type: Optional[User]

    try:
        bot.unpinAllChatMessages(chat.id)
        update.effective_message.reply_text(
            "Successfully unpinned all messages!")
    except BadRequest as excp:
        if excp.message == "Chat_not_modified":
            pass
        else:
            raise

    return "<b>{}:</b>" \
           "\n#UNPINNED" \
           "\n<b>Admin:</b> {}".format(html.escape(chat.title),
                                       mention_html(user.id, user.first_name))
Ejemplo n.º 18
0
def unpin(update: Update, context: CallbackContext) -> str:
    if not check_perms(update, 2):
        return
    bot = context.bot
    chat = update.effective_chat
    user = update.effective_user  # type: Optional[User]
    args = {}

    if update.effective_message.reply_to_message:
        args[
            "message_id"] = update.effective_message.reply_to_message.message_id

    try:
        bot.unpinChatMessage(chat.id, **args)
    except BadRequest as excp:
        if excp.message == "Chat_not_modified":
            pass
        else:
            raise

    return "<b>{}:</b>" \
           "\n#UNPINNED" \
           "\n<b>Admin:</b> {}".format(html.escape(chat.title),
                                       mention_html(user.id, user.first_name))
Ejemplo n.º 19
0
def remove_warn_filter(update: Update, context: CallbackContext):
    if not check_perms(update, 1):
        return
    bot = context.bot
    chat = update.effective_chat  # type: Optional[Chat]
    msg = update.effective_message  # type: Optional[Message]

    args = msg.text.split(
        None,
        1)  # use python's maxsplit to separate Cmd, keyword, and reply_text

    if len(args) < 2:
        return

    extracted = split_quotes(args[1])

    if len(extracted) < 1:
        return

    to_remove = extracted[0]

    chat_filters = sql.get_chat_warn_triggers(chat.id)

    if not chat_filters:
        msg.reply_text("No warning filters are active here!")
        return

    for filt in chat_filters:
        if filt == to_remove:
            sql.remove_warn_filter(chat.id, to_remove)
            msg.reply_text("Yep, I'll stop warning people for that.")
            raise DispatcherHandlerStop

    msg.reply_text(
        "That's not a current warning filter - run /warnlist for all active warning filters."
    )
Ejemplo n.º 20
0
def reset_warns(update: Update, context: CallbackContext) -> str:
    if not check_perms(update, 1):
        return
    bot, args = context.bot, context.args
    message = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]

    user_id = extract_user(message, args)

    if user_id:
        sql.reset_warns(user_id, chat.id)
        message.reply_text("Warnings have been reset!")
        warned = chat.get_member(user_id).user
        return "<b>{}:</b>" \
               "\n#RESETWARNS" \
               "\n<b>Admin:</b> {}" \
               "\n<b>User:</b> {} (<code>{}</code>)".format(html.escape(chat.title),
                                                            mention_html(user.id, user.first_name),
                                                            mention_html(warned.id, warned.first_name),
                                                            warned.id)
    else:
        message.reply_text("No user has been designated!")
    return ""
Ejemplo n.º 21
0
def purge(update: Update, context: CallbackContext) -> str:
    if not check_perms(update, 0):
        return
    bot = context.bot
    args = context.args
    msg = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]

    if msg.reply_to_message:
        if can_delete(chat, bot.id):
            message_id = msg.reply_to_message.message_id
            delete_to = msg.message_id - 1
            if args and args[0].isdigit():
                new_del = message_id + int(args[0])
                # No point deleting messages which haven't been written yet.
                if new_del < delete_to:
                    delete_to = new_del

            for m_id in range(delete_to, message_id - 1,
                              -1):  # Reverse iteration over message ids
                try:
                    bot.deleteMessage(chat.id, m_id)
                except BadRequest as err:
                    if err.message == "Message can't be deleted":
                        bot.send_message(
                            chat.id,
                            "Cannot delete all messages. The messages may be too old, I might "
                            "not have delete rights, or this might not be a supergroup."
                        )

                    elif err.message != "Message to delete not found":
                        LOGGER.exception("Error while purging chat messages.")

            try:
                msg.delete()
            except BadRequest as err:
                if err.message == "Message can't be deleted":
                    bot.send_message(
                        chat.id,
                        "Cannot delete all messages. The messages may be too old, I might "
                        "not have delete rights, or this might not be a supergroup."
                    )

                elif err.message != "Message to delete not found":
                    LOGGER.exception("Error while purging chat messages.")

            del_msg = bot.send_message(chat.id, "Purge complete.")
            time.sleep(5)
            del_msg.delete()
            return "<b>{}:</b>" \
                   "\n#PURGE" \
                   "\n<b>Admin:</b> {}" \
                   "\nPurged <code>{}</code> messages.".format(html.escape(chat.title),
                                                               mention_html(user.id, user.first_name),
                                                               delete_to - message_id)

    else:
        msg.reply_text(
            "Reply to a message to select where to start purging from.")

    return ""
Ejemplo n.º 22
0
def demote(update: Update, context: CallbackContext) -> str:
    if not check_perms(update, 3):
        return
    bot = context.bot
    args = context.args
    chat = update.effective_chat  # type: Optional[Chat]
    message = update.effective_message  # type: Optional[Message]
    user = update.effective_user  # type: Optional[User]

    user_id = extract_user(message, args)

    if not user_id or int(user_id) == 777000 or int(user_id) == 1087968824:
        message.reply_text("You don't seem to be referring to a user.")
        return ""

    user_member = chat.get_member(user_id)
    if user_member.status == 'creator':
        message.reply_text(
            "This person CREATED the chat. He's IMMORTAL, how would I demote them?🤦‍♀️"
        )
        return ""

    if not user_member.status == 'administrator':
        message.reply_text(
            "Can't demote what wasn't promoted! Tho we can kick them 😉")
        return ""

    if user_id == bot.id:
        message.reply_text(
            "I can't demote myself! 🤷‍♀️ Get an admin to do it for me (please don't 😔)."
        )
        return ""

    try:
        bot.restrict_chat_member(chat.id,
                                 int(user_id),
                                 permissions=ChatPermissions(
                                     can_send_messages=True,
                                     can_send_media_messages=True,
                                     can_send_other_messages=True,
                                     can_add_web_page_previews=True)
                                 )  #restrict incase you're demoting a bot
        bot.promoteChatMember(int(chat.id),
                              int(user_id),
                              can_change_info=False,
                              can_post_messages=False,
                              can_edit_messages=False,
                              can_delete_messages=False,
                              can_invite_users=False,
                              can_restrict_members=False,
                              can_pin_messages=False,
                              can_promote_members=False)

        message.reply_text(
            "Successfully demoted {}, He's now mortal lmao!".format(
                mention_html(user_member.user.id,
                             user_member.user.first_name)),
            parse_mode=ParseMode.HTML)
        return "<b>{}:</b>" \
               "\n#DEMOTED" \
               "\n<b>Admin:</b> {}" \
               "\n<b>User:</b> {}".format(html.escape(chat.title),
                                          mention_html(user.id, user.first_name),
                                          mention_html(user_member.user.id, user_member.user.first_name))

    except BadRequest:
        message.reply_text(
            "Could not demote. I might not be admin, or the admin status was appointed by another "
            "user, so I can't act upon them!")
        return ""
Ejemplo n.º 23
0
def kick(update: Update, context: CallbackContext):
    if not check_perms(update, 1):
        return
    bot = context.bot
    args = context.args
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    message = update.effective_message  # type: Optional[Message]

    banType = 0
    userIds = extract_multiple_users(message, args)
    allTrue = True
    for id in userIds:
        if id is None or not isinstance(id, int) or id == "":
            allTrue = False
    if len(userIds) > 1 and allTrue:
        banType = 1

    if banType == 1:
        if len(userIds) == 0:
            message.reply_text("There was a problem parsing the user IDs")
            return ""
        log = "#KICK_MUL\n Admin: " + user.first_name + "\n"
        for id in userIds:
            try:
                integerID = int(id)
                member = chat.get_member(integerID)
                if is_user_ban_protected(chat, integerID, member):
                    message.reply_text("Can't kick " + str(integerID) +
                                       ", user is ban protected.")
                    continue
                if integerID == bot.id:
                    message.reply_text("I wont ban myself... " +
                                       str(integerID) + " is my ID.")
                    continue
                if integerID == 777000 or integerID == 1087968824:
                    message.reply_text(
                        str(integerID) +
                        " is an account reserved for telegram, I cannot kick it"
                    )
                    continue
                res = chat.unban_member(integerID)
                if res:
                    #bot.send_sticker(chat.id, BAN_STICKER)  # ban sticker
                    reply = "{} has been kicked!".format(
                        mention_html(member.user.id, member.user.first_name))
                    message.reply_text(reply, parse_mode=ParseMode.HTML)
                    log += "ID: " + str(member.user.id) + "\n"
                else:
                    message.reply_text("Well damn, I can't kick that user.")
            except ValueError:
                message.reply_text("Error parsing the ID: " + id +
                                   " is not a valid user ID")
            except BadRequest as excp:
                if excp.message == "User not found":
                    message.reply_text("User " + str(integerID) +
                                       "has not been found")
                    continue
                else:
                    raise
        return log
    else:
        user_id, reason = extract_user_and_text(message, args)
        if not user_id or int(user_id) == 777000 or int(user_id) == 1087968824:
            message.reply_text("You don't seem to be referring to a user.")
            return ""
        try:
            member = chat.get_member(user_id)
        except BadRequest as excp:
            if excp.message == "User not found":
                message.reply_text("404 - user not found")
                return ""
            else:
                raise

        if is_user_ban_protected(chat, user_id):
            message.reply_text(
                "I'm not gonna kick an admin... Though I reckon it'd be pretty funny."
            )
            return ""

        if user_id == bot.id:
            message.reply_text("hahahahahahaha nice try.. nope")
            return ""

        res = chat.unban_member(user_id)  # unban on current user = kick
        if res:
            bot.send_sticker(chat.id, BAN_STICKER)  # ban sticker
            reply = "{} has been kicked!".format(
                mention_html(member.user.id, member.user.first_name))
            reply += "\nReason: <code>{}</code>".format(
                reason) if reason else ""
            message.reply_text(reply, parse_mode=ParseMode.HTML)

            log = "<b>{}:</b>" \
                  "\n#KICKED" \
                  "\n<b>Admin:</b> {}" \
                  "\n<b>User:</b> {} (<code>{}</code>)".format(html.escape(chat.title),
                                                               mention_html(user.id, user.first_name),
                                                               mention_html(member.user.id, member.user.first_name),
                                                               member.user.id)
            if reason:
                log += "\n<b>Reason:</b> {}".format(reason)

            return log

        else:
            message.reply_text("Well damn, I can't kick that user.")

        return ""
Ejemplo n.º 24
0
def temp_mute(update: Update, context: CallbackContext) -> str:
    if not check_perms(update, 1):
        return
    bot = context.bot
    args = context.args
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    message = update.effective_message  # type: Optional[Message]

    user_id, reason = extract_user_and_text(message, args)

    if not user_id:
        message.reply_text("You don't seem to be referring to a user.")
        return ""

    try:
        member = chat.get_member(user_id)
    except BadRequest as excp:
        if excp.message == "User not found":
            message.reply_text("I can't seem to find this user")
            return ""
        else:
            raise

    if is_user_admin(chat, user_id, member):
        message.reply_text("I really wish I could mute admins...")
        return ""

    if user_id == bot.id:
        message.reply_text("I'm not gonna MUTE myself, are you crazy?")
        return ""

    if not reason:
        message.reply_text(
            "You haven't specified a time to mute this user for!")
        return ""

    split_reason = reason.split(None, 1)

    time_val = split_reason[0].lower()
    if len(split_reason) > 1:
        reason = split_reason[1]
    else:
        reason = ""

    mutetime = extract_time(message, time_val)

    if not mutetime:
        return ""

    log = "<b>{}:</b>" \
          "\n#TEMP MUTED" \
          "\n<b>Admin:</b> {}" \
          "\n<b>User:</b> {}" \
          "\n<b>Time:</b> {}".format(html.escape(chat.title), mention_html(user.id, user.first_name),
                                     mention_html(member.user.id, member.user.first_name), time_val)
    if reason:
        log += "\n<b>Reason:</b> {}".format(reason)

    try:
        if member.can_send_messages is None or member.can_send_messages:
            bot.restrict_chat_member(
                chat.id,
                user_id,
                until_date=mutetime,
                permissions=ChatPermissions(can_send_messages=False))
            message.reply_text("Muted for {}!".format(time_val))
            return log
        else:
            message.reply_text("This user is already muted.")

    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            message.reply_text("Muted for {}!".format(time_val), quote=False)
            return log
        else:
            LOGGER.warning(update)
            LOGGER.exception("ERROR muting user %s in chat %s (%s) due to %s",
                             user_id, chat.title, chat.id, excp.message)
            message.reply_text("Well damn, I can't mute that user.")

    return ""
Ejemplo n.º 25
0
def temp_ban(update: Update, context: CallbackContext):
    if not check_perms(update, 1):
        return
    bot, args = context.bot, context.args
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    message = update.effective_message  # type: Optional[Message]

    user_id, reason = extract_user_and_text(message, args)

    if not user_id or int(user_id) == 777000 or int(user_id) == 1087968824:
        message.reply_text("You don't seem to be referring to a user.")
        return ""

    try:
        member = chat.get_member(user_id)
    except BadRequest as excp:
        if excp.message == "User not found":
            message.reply_text("404 - user not found")
            return ""
        raise

    if is_user_ban_protected(chat, user_id, member):
        message.reply_text("Can't do that, user is admin..")
        return ""

    if user_id == bot.id:
        message.reply_text("hahahahahahaha nice try.. nope")
        return ""

    if not reason:
        message.reply_text(
            "You haven't specified a time to ban this user for!")
        return ""

    split_reason = reason.split(None, 1)

    time_val = split_reason[0].lower()
    if len(split_reason) > 1:
        reason = split_reason[1]
    else:
        reason = ""

    bantime = extract_time(message, time_val)

    if not bantime:
        return ""

    log = ("<b>{}:</b>"
           "\n#TEMP BANNED"
           "\n<b>Admin:</b> {}"
           "\n<b>User:</b> {} (<code>{}</code>)"
           "\n<b>Time:</b> {}".format(
               html.escape(chat.title),
               mention_html(user.id, user.first_name),
               mention_html(member.user.id, member.user.first_name),
               member.user.id,
               time_val,
           ))
    if reason:
        log += "\n<b>Reason:</b> {}".format(reason)

    try:
        chat.ban_member(user_id, until_date=bantime)
        bot.send_sticker(chat.id, BAN_STICKER)  # ban sticker
        reply = "\nReason: <code>{}</code>".format(reason) if reason else ""
        message.reply_text(
            "Banned! {} will be banned for {}.".format(
                mention_html(member.user.id, member.user.first_name), time_val)
            + reply,
            parse_mode=ParseMode.HTML,
        )
        return log

    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            message.reply_text(
                "Banned! User will be banned for {}.".format(time_val),
                quote=False)
            return log
        LOGGER.warning(update)
        LOGGER.exception(
            "ERROR banning user %s in chat %s (%s) due to %s",
            user_id,
            chat.title,
            chat.id,
            excp.message,
        )
        message.reply_text("Well damn, I can't ban that user.")

    return ""
Ejemplo n.º 26
0
def ban(update: Update, context: CallbackContext):
    if not check_perms(update, 1):
        return
    bot, args = context.bot, context.args
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    message = update.effective_message  # type: Optional[Message]

    banType = 0
    userIds = extract_multiple_users(message, args)
    allTrue = True
    for id in userIds:
        if id is None or not isinstance(id, int) or id == "":
            allTrue = False
    if len(userIds) > 1 and allTrue:
        banType = 1
    if banType == 1:
        if len(userIds) == 0:
            message.reply_text("There was a problem parsing the user IDs")
            return ""
        log = "#BAN MUL\n Admin: " + user.first_name + "\n"
        for id in userIds:
            try:
                integerID = int(id)
                member = chat.get_member(integerID)
                if integerID == bot.id:
                    message.reply_text("I wont ban myself... " +
                                       str(integerID) + " is my ID.")
                    continue
                if integerID in (777000, 1087968824):
                    message.reply_text(
                        str(integerID) +
                        " is an account reserved for telegram, I cannot ban it"
                    )
                    continue
                if is_user_ban_protected(chat, integerID, member):
                    message.reply_text("Can't ban " + str(integerID) +
                                       ", user is ban protected.")
                    continue
                try:
                    chat.ban_member(integerID)
                    # bot.send_sticker(update.effective_chat.id, BAN_STICKER)  # ban sticker
                    reply = "{} has been banned!".format(
                        mention_html(member.user.id, member.user.first_name))
                    message.reply_text(reply, parse_mode=ParseMode.HTML)
                    log += "ID: " + str(member.user.id) + "\n"
                except BadRequest as excp:
                    LOGGER.warning(update)
                    LOGGER.exception(
                        "ERROR banning user %s in chat %s (%s) due to %s",
                        integerID,
                        chat.title,
                        chat.id,
                        excp.message,
                    )
                    message.reply_text("Well damn, I can't ban " +
                                       str(integerID))
            except ValueError:
                message.reply_text("Error parsing the ID: " + id +
                                   " is not a valid user ID")
            except BadRequest as excp:
                if excp.message == "User not found":
                    message.reply_text("User " + str(integerID) +
                                       "has not been found")
                    continue
                raise
        return log
    user_id, reason = extract_user_and_text(message, args)
    if not user_id or int(user_id) == 777000 or int(user_id) == 1087968824:
        message.reply_text("You don't seem to be referring to a user.")
        return ""
    try:
        member = chat.get_member(user_id)
    except BadRequest as excp:
        if excp.message == "User not found":
            message.reply_text("404 - user not found")
            return ""
        raise
    if user_id == bot.id:
        message.reply_text("hahahahahahaha nice try.. nope")
        return ""
    if is_user_ban_protected(chat, user_id, member):
        message.reply_text("Can't do that, user is admin..")
        return ""
    log = ("<b>{}:</b>"
           "\n#BANNED"
           "\n<b>Admin:</b> {}"
           "\n<b>User:</b> {} (<code>{}</code>)".format(
               html.escape(chat.title),
               mention_html(user.id, user.first_name),
               mention_html(member.user.id, member.user.first_name),
               member.user.id,
           ))
    if reason:
        log += "\n<b>Reason:</b> {}".format(reason)
    try:
        chat.ban_member(user_id)
        bot.send_sticker(update.effective_chat.id, BAN_STICKER)  # ban sticker
        reply = "{} has been banned!".format(
            mention_html(member.user.id, member.user.first_name))
        reply += "\nReason: <code>{}</code>".format(reason) if reason else ""

        message.reply_text(reply, parse_mode=ParseMode.HTML)
        return log
    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            message.reply_text("Banned!", quote=False)
            return log
        LOGGER.warning(update)
        LOGGER.exception(
            "ERROR banning user %s in chat %s (%s) due to %s",
            user_id,
            chat.title,
            chat.id,
            excp.message,
        )
        message.reply_text("Well damn, I can't ban that user.")
    return ""
Ejemplo n.º 27
0
def lock(update: Update, context: CallbackContext) -> str:
    if not check_perms(update, 1):
        return
    bot, args = context.bot, context.args
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    message = update.effective_message  # type: Optional[Message]

    if can_delete(chat, bot.id):
        if len(args) >= 1:
            if args[0] in LOCK_TYPES:
                sql.update_lock(chat.id, args[0], locked=True)
                message.reply_text(
                    "Locked {} messages for all non-admins!".format(args[0]))

                return "<b>{}:</b>" \
                       "\n#LOCK" \
                       "\n<b>Admin:</b> {}" \
                       "\nLocked <code>{}</code>.".format(html.escape(chat.title),
                                                          mention_html(user.id, user.first_name), args[0])

            elif args[0] in RESTRICTION_TYPES:
                sql.update_restriction(chat.id, args[0], locked=True)
                if args[0] == "previews":
                    members = users_sql.get_chat_members(str(chat.id))
                    restr_members(bot,
                                  chat.id,
                                  members,
                                  messages=True,
                                  media=True,
                                  other=True)
                    bot.restrict_chat_member(
                        chat.id,
                        int(777000),
                        permissions=ChatPermissions(
                            can_send_messages=True,
                            can_send_media_messages=True,
                            can_send_other_messages=True,
                            can_add_web_page_previews=True))

                    bot.restrict_chat_member(
                        chat.id,
                        int(1087968824),
                        permissions=ChatPermissions(
                            can_send_messages=True,
                            can_send_media_messages=True,
                            can_send_other_messages=True,
                            can_add_web_page_previews=True))

                message.reply_text("Locked {} for all non-admins!".format(
                    args[0]))
                return "<b>{}:</b>" \
                       "\n#LOCK" \
                       "\n<b>Admin:</b> {}" \
                       "\nLocked <code>{}</code>.".format(html.escape(chat.title),
                                                          mention_html(user.id, user.first_name), args[0])

            else:
                message.reply_text(
                    "What are you trying to lock...? Try /locktypes for the list of lockables"
                )

    else:
        message.reply_text(
            "I'm not an administrator, or haven't got delete rights.")

    return ""