Ejemplo n.º 1
0
def runmute(bot: Bot, update: Update, args: List[str]):
    message = update.effective_message
    chat = update.effective_chat

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

    user_id, chat_id = extract_user_and_text(message, args)

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

    try:
        chat = bot.get_chat(chat_id.split()[0])
    except BadRequest as excp:
        if excp.message == "Chat not found":
            message.reply_text(
                "Chat not found! Make sure you entered a valid chat ID and I'm part of that chat."
            )
            return
        else:
            raise

    if chat.type == 'private':
        message.reply_text("I'm sorry, but that's a private chat!")
        return

    if not is_bot_admin(chat, bot.id) or not chat.get_member(
            bot.id).can_restrict_members:
        message.reply_text(
            "I can't unrestrict people there! Make sure I'm admin and can unban users."
        )
        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 there")
            return
        else:
            raise

    if is_user_in_chat(chat, user_id):
        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 in that chat.")
            return

    if user_id == bot.id:
        message.reply_text("I'm not gonna UNMUTE myself, I'm an admin there!")
        return

    try:
        bot.restrict_chat_member(chat.id,
                                 int(user_id),
                                 can_send_messages=True,
                                 can_send_media_messages=True,
                                 can_send_other_messages=True,
                                 can_add_web_page_previews=True)
        message.reply_text("Yep, this user can talk in that chat!")
    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            message.reply_text('Unmuted!', quote=False)
        elif excp.message in RUNMUTE_ERRORS:
            message.reply_text(excp.message)
        else:
            LOGGER.warning(update)
            LOGGER.exception(
                "ERROR unmnuting 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 unmute that user.")
Ejemplo n.º 2
0
def help_button(bot: Bot, update: Update):
    query = update.callback_query
    chat = update.effective_chat  # type: Optional[Chat]
    mod_match = re.match(r"help_module\((.+?)\)", query.data)
    prev_match = re.match(r"help_prev\((.+?)\)", query.data)
    next_match = re.match(r"help_next\((.+?)\)", query.data)
    back_match = re.match(r"help_back", query.data)
    try:
        if mod_match:
            module = mod_match.group(1)
            mod_name = tld(chat.id, HELPABLE[module].__mod_name__)
            help_txt = tld_help(chat.id, HELPABLE[module].__mod_name__)

            if help_txt == False:
                help_txt = HELPABLE[module].__help__

            text = tld(chat.id,
                       "Here is the help for the *{}* module:\n{}").format(
                           mod_name, help_txt)
            query.message.reply_text(text=text,
                                     parse_mode=ParseMode.MARKDOWN,
                                     reply_markup=InlineKeyboardMarkup([[
                                         InlineKeyboardButton(
                                             text=tld(chat.id, "Back"),
                                             callback_data="help_back")
                                     ]]))

        elif prev_match:
            curr_page = int(prev_match.group(1))
            query.message.reply_text(tld(chat.id, "send-help").format(
                dispatcher.bot.first_name, "" if not ALLOW_EXCL else tld(
                    chat.id,
                    "\nAll commands can either be used with `/` or `!`.\n")),
                                     parse_mode=ParseMode.MARKDOWN,
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(
                                             chat.id, curr_page - 1, HELPABLE,
                                             "help")))

        elif next_match:
            next_page = int(next_match.group(1))
            query.message.reply_text(tld(chat.id, "send-help").format(
                dispatcher.bot.first_name, "" if not ALLOW_EXCL else tld(
                    chat.id,
                    "\nAll commands can either be used with `/` or `!`.\n")),
                                     parse_mode=ParseMode.MARKDOWN,
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(
                                             chat.id, next_page + 1, HELPABLE,
                                             "help")))

        elif back_match:
            query.message.reply_text(text=tld(chat.id, "send-help").format(
                dispatcher.bot.first_name, "" if not ALLOW_EXCL else tld(
                    chat.id,
                    "\nAll commands can either be used with `/` or `!`.\n")),
                                     parse_mode=ParseMode.MARKDOWN,
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(
                                             chat.id, 0, HELPABLE, "help")))

        # ensure no spinny white circle
        bot.answer_callback_query(query.id)
        query.message.delete()
    except BadRequest as excp:
        if excp.message == "Message is not modified":
            pass
        elif excp.message == "Query_id_invalid":
            pass
        elif excp.message == "Message can't be deleted":
            pass
        else:
            LOGGER.exception("Exception in help buttons. %s", str(query.data))
Ejemplo n.º 3
0
def temp_mute(bot: Bot, update: Update, args: List[str]) -> str:
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    message = update.effective_message  # type: Optional[Message]

    conn = connected(bot, update, chat, user.id)
    if not conn == False:
        chatD = dispatcher.bot.getChat(conn)
    else:
        if chat.type == "private":
            exit(1)
        else:
            chatD = chat

    user_id, reason = extract_user_and_text(message, args)

    if not user_id:
        message.reply_text(
            tld(chat.id,
                "tunjuk orangnya yang mau lu mute! reply /mute ke pesannya."))
        return ""

    try:
        member = chat.get_member(user_id)
    except BadRequest as excp:
        if excp.message == "User not found":
            message.reply_text(tld(chat.id, "weh gua gabisa nemuin itu orang"))
            return ""
        else:
            raise

    if is_user_admin(chat, user_id, member):
        message.reply_text(
            tld(chat.id,
                "hmmm pengennya si gua bisa ngemut dia, tttapi...dia admin"))
        return ""

    if user_id == bot.id:
        message.reply_text(tld(chat.id, "egk!"))
        return ""

    if not reason:
        message.reply_text(tld(chat.id, "masukin format waktu yang bener!"))
        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,
                                     can_send_messages=False)
            message.reply_text(
                tld(chat.id,
                    "Muted for {} in {}!").format(time_val, chatD.title))
            return log
        else:
            message.reply_text(
                tld(chat.id,
                    "This user is already muted in {}!").format(chatD.title))

    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            message.reply_text(tld(chat.id, "Muted for {} in {}!").format(
                time_val, chatD.title),
                               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(tld(chat.id, "sial, gua gabisa ngemut dia."))

    return ""
Ejemplo n.º 4
0
def get(bot, update, notename, show_none=True, no_format=False):
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    conn = connected(bot, update, chat, user.id, need_admin=False)
    if not conn == False:
        chat_id = conn
        send_id = user.id
    else:
        chat_id = update.effective_chat.id
        send_id = chat_id

    note = sql.get_note(chat_id, notename)
    message = update.effective_message  # type: Optional[Message]

    if note:
        # If we're replying to a message, reply to that message (unless it's an error)
        if message.reply_to_message:
            reply_id = message.reply_to_message.message_id
        else:
            reply_id = message.message_id

        if note.is_reply:
            if MESSAGE_DUMP:
                try:
                    bot.forward_message(chat_id=chat_id,
                                        from_chat_id=MESSAGE_DUMP,
                                        message_id=note.value)
                except BadRequest as excp:
                    if excp.message == "Message to forward not found":
                        message.reply_text(
                            "This message seems to have been lost - I'll remove it "
                            "from your notes list.")
                        sql.rm_note(chat_id, notename)
                    else:
                        raise
            else:
                try:
                    bot.forward_message(chat_id=chat_id,
                                        from_chat_id=chat_id,
                                        message_id=note.value)
                except BadRequest as excp:
                    if excp.message == "Message to forward not found":
                        message.reply_text(
                            "Looks like the original sender of this note has deleted "
                            "their message - sorry! Get your bot admin to start using a "
                            "message dump to avoid this. I'll remove this note from "
                            "your saved notes.")
                        sql.rm_note(chat_id, notename)
                    else:
                        raise
        else:
            text = note.value
            keyb = []
            parseMode = ParseMode.MARKDOWN
            buttons = sql.get_buttons(chat_id, notename)
            if no_format:
                parseMode = None
                text += revert_buttons(buttons)
            else:
                keyb = build_keyboard(buttons)

            keyboard = InlineKeyboardMarkup(keyb)

            try:
                if note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT):
                    bot.send_message(send_id,
                                     text,
                                     reply_to_message_id=reply_id,
                                     parse_mode=parseMode,
                                     disable_web_page_preview=True,
                                     reply_markup=keyboard)
                else:
                    ENUM_FUNC_MAP[note.msgtype](send_id,
                                                note.file,
                                                caption=text,
                                                reply_to_message_id=reply_id,
                                                parse_mode=parseMode,
                                                disable_web_page_preview=True,
                                                reply_markup=keyboard)

            except BadRequest as excp:
                print(excp.message)
                if excp.message == "Entity_mention_user_invalid":
                    message.reply_text(
                        "Looks like you tried to mention someone I've never seen before. If you really "
                        "want to mention them, forward one of their messages to me, and I'll be able "
                        "to tag them!")
                elif FILE_MATCHER.match(note.value):
                    message.reply_text(
                        "This note was an incorrectly imported file from another bot - I can't use "
                        "it. If you really need it, you'll have to save it again. In "
                        "the meantime, I'll remove it from your notes list.")
                    sql.rm_note(chat_id, notename)
                else:
                    message.reply_text(
                        "This note could not be sent, as it is incorrectly formatted. Ask"
                        "@admins if you can't figure out why!")
                    LOGGER.exception("Could not parse message #%s in chat %s",
                                     notename, str(chat_id))
                    LOGGER.warning("Message was: %s", str(note.value))
        return
    elif show_none:
        message.reply_text("This note doesn't exist")
Ejemplo n.º 5
0
def temp_ban(bot: Bot, update: Update, args: List[str]) -> str:
    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(
            tld(chat.id, "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(tld(chat.id, "I can't seem to find this user"))
            return ""
        else:
            raise

    if is_user_ban_protected(chat, user_id, member):
        message.reply_text(
            tld(
                chat.id,
                "This user is ban protected, meaning that you cannot ban this user!"
            ))
        return ""

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

    if not reason:
        message.reply_text(
            tld(chat.id, "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.kick_member(user_id, until_date=bantime)
        #bot.send_sticker(chat.id, BAN_STICKER)  # banhammer marie sticker
        message.reply_text(
            "Banned! User will be banned for {}.".format(time_val))
        return log

    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            #bot.send_sticker(chat.id, BAN_STICKER)  # banhammer marie sticker
            message.reply_text(
                tld(chat.id,
                    "Banned! User will be banned for {}.").format(time_val),
                quote=False)
            return log
        else:
            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(
                tld(chat.id, "Well damn, I can't ban that user."))

    return ""
Ejemplo n.º 6
0
def send(update, message, keyboard, backup_message):
    chat = update.effective_chat
    cleanserv = sql.clean_service(chat.id)
    reply = update.message.message_id
    # Clean service welcome
    if cleanserv:
        try:
            dispatcher.bot.delete_message(chat.id, update.message.message_id)
        except BadRequest:
            pass
        reply = False
    try:
        msg = update.effective_message.reply_text(
            message,
            parse_mode=ParseMode.HTML,
            reply_markup=keyboard,
            disable_web_page_preview=True)
    except IndexError:
        msg = update.effective_message.reply_text(
            markdown_parser(backup_message + "\nNote: the current message was "
                            "invalid due to markdown issues. Could be "
                            "due to the user's name."),
            parse_mode=ParseMode.MARKDOWN)
    except KeyError:
        msg = update.effective_message.reply_text(
            markdown_parser(backup_message + "\nNote: the current message is "
                            "invalid due to an issue with some misplaced "
                            "curly brackets. Please update"),
            parse_mode=ParseMode.MARKDOWN)
    except BadRequest as excp:
        if excp.message == "Button_url_invalid":
            msg = update.effective_message.reply_text(
                markdown_parser(
                    backup_message +
                    "\nNote: the current message has an invalid url "
                    "in one of its buttons. Please update."),
                parse_mode=ParseMode.MARKDOWN)
        elif excp.message == "Unsupported url protocol":
            msg = update.effective_message.reply_text(
                markdown_parser(
                    backup_message +
                    "\nNote: the current message has buttons which "
                    "use url protocols that are unsupported by "
                    "telegram. Please update."),
                parse_mode=ParseMode.MARKDOWN)
        elif excp.message == "Wrong url host":
            msg = update.effective_message.reply_text(
                markdown_parser(
                    backup_message +
                    "\nNote: the current message has some bad urls. "
                    "Please update."),
                parse_mode=ParseMode.MARKDOWN)
            LOGGER.warning(message)
            LOGGER.warning(keyboard)
            LOGGER.exception("Could not parse! got invalid url host errors")
        else:
            try:
                msg = update.effective_message.reply_text(
                    markdown_parser(
                        backup_message +
                        "\nNote: An error occured when sending the "
                        "custom message. Please update."),
                    reply_to_message_id=reply,
                    parse_mode=ParseMode.MARKDOWN)
            except BadRequest:
                return ""
    return msg
Ejemplo n.º 7
0
def reply_filter(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user
    message = update.effective_message  # type: Optional[Message]
    to_match = extract_text(message)
    if not to_match:
        return
    
    if user.id == 777000:
        return

    chat_filters = sql.get_chat_triggers(chat.id)
    for keyword in chat_filters:
        pattern = r"( |^|[^\w])" + re.escape(keyword) + r"( |$|[^\w])"
        if re.search(pattern, to_match, flags=re.IGNORECASE):
            filt = sql.get_filter(chat.id, keyword)
            if filt.is_sticker:
                message.reply_sticker(filt.reply)
            elif filt.is_document:
                try:
                    message.reply_document(filt.reply)
                except:
                    print("L")
            elif filt.is_image:
                message.reply_photo(filt.reply)
            elif filt.is_audio:
                message.reply_audio(filt.reply)
            elif filt.is_voice:
                message.reply_voice(filt.reply)
            elif filt.is_video:
                try:
                    message.reply_video(filt.reply)
                except:
                    print("Nut")
            elif filt.has_markdown:
                buttons = sql.get_buttons(chat.id, filt.keyword)
                keyb = build_keyboard(buttons)
                keyboard = InlineKeyboardMarkup(keyb)

                try:
                    message.reply_text(filt.reply, parse_mode=ParseMode.MARKDOWN,
                                       disable_web_page_preview=True,
                                       reply_markup=keyboard)
                except BadRequest as excp:
                    if excp.message == "Unsupported url protocol":
                        message.reply_text("You seem to be trying to use an unsupported url protocol. Telegram "
                                           "doesn't support buttons for some protocols, such as tg://. Please try "
                                           "again, or ask in @HarukaAyaGroup for help.")
                    elif excp.message == "Reply message not found":
                        bot.send_message(chat.id, filt.reply, parse_mode=ParseMode.MARKDOWN,
                                         disable_web_page_preview=True,
                                         reply_markup=keyboard)
                    else:
                        try:
                            message.reply_text("This note could not be sent, as it is incorrectly formatted. Ask in @HarukaAyaGroup if you can't figure out why!")
                            LOGGER.warning("Message %s could not be parsed", str(filt.reply))
                            LOGGER.exception("Could not parse filter %s in chat %s", str(filt.keyword), str(chat.id))
                        except:
                            print("Nut")

            else:
                # LEGACY - all new filters will have has_markdown set to True.
                message.reply_text(filt.reply)
            break
Ejemplo n.º 8
0
def settings_button(update: Update, context: CallbackContext):
    query = update.callback_query
    user = update.effective_user
    bot = context.bot
    mod_match = re.match(r"stngs_module\((.+?),(.+?)\)", query.data)
    prev_match = re.match(r"stngs_prev\((.+?),(.+?)\)", query.data)
    next_match = re.match(r"stngs_next\((.+?),(.+?)\)", query.data)
    back_match = re.match(r"stngs_back\((.+?)\)", query.data)
    try:
        if mod_match:
            chat_id = mod_match.group(1)
            module = mod_match.group(2)
            chat = bot.get_chat(chat_id)
            text = "*{}* has the following settings for the *{}* module:\n\n".format(
                escape_markdown(chat.title), CHAT_SETTINGS[module].__mod_name__
            ) + CHAT_SETTINGS[module].__chat_settings__(chat_id, user.id)
            query.message.reply_text(
                text=text,
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=InlineKeyboardMarkup(
                    [
                        [
                            InlineKeyboardButton(
                                text="Back",
                                callback_data="stngs_back({})".format(chat_id),
                            )
                        ]
                    ]
                ),
            )

        elif prev_match:
            chat_id = prev_match.group(1)
            curr_page = int(prev_match.group(2))
            chat = bot.get_chat(chat_id)
            query.message.reply_text(
                "Hi there! There are quite a few settings for {} - go ahead and pick what "
                "you're interested in.".format(chat.title),
                reply_markup=InlineKeyboardMarkup(
                    paginate_modules(
                        curr_page - 1, CHAT_SETTINGS, "stngs", chat=chat_id
                    )
                ),
            )

        elif next_match:
            chat_id = next_match.group(1)
            next_page = int(next_match.group(2))
            chat = bot.get_chat(chat_id)
            query.message.reply_text(
                "Hi there! There are quite a few settings for {} - go ahead and pick what "
                "you're interested in.".format(chat.title),
                reply_markup=InlineKeyboardMarkup(
                    paginate_modules(
                        next_page + 1, CHAT_SETTINGS, "stngs", chat=chat_id
                    )
                ),
            )

        elif back_match:
            chat_id = back_match.group(1)
            chat = bot.get_chat(chat_id)
            query.message.reply_text(
                text="Hi there! There are quite a few settings for {} - go ahead and pick what "
                "you're interested in.".format(escape_markdown(chat.title)),
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=InlineKeyboardMarkup(
                    paginate_modules(0, CHAT_SETTINGS, "stngs", chat=chat_id)
                ),
            )

        # ensure no spinny white circle
        bot.answer_callback_query(query.id)
        query.message.delete()
    except BadRequest as excp:
        if excp.message not in [
            "Message is not modified",
            "Query_id_invalid",
            "Message can't be deleted",
        ]:
            LOGGER.exception("Exception in settings buttons. %s", str(query.data))
Ejemplo n.º 9
0
def import_data(bot: Bot, update):
    msg = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    # TODO: allow uploading doc with command, not just as reply
    # only work with a doc

    conn = connected(bot, update, chat, user.id, need_admin=True)
    if conn:
        chat = dispatcher.bot.getChat(conn)
        chat_id = conn
        chat_name = dispatcher.bot.getChat(conn).title
    else:
        if update.effective_message.chat.type == "private":
            update.effective_message.reply_text(
                tld(chat.id, "common_cmd_group_only"))
            return ""

        chat = update.effective_chat
        chat_id = update.effective_chat.id
        chat_name = update.effective_message.chat.title

    if msg.reply_to_message and msg.reply_to_message.document:
        try:
            file_info = bot.get_file(msg.reply_to_message.document.file_id)
        except BadRequest:
            msg.reply_text(tld(chat.id, "backups_file_corrupted"))
            return

        with BytesIO() as file:
            file_info.download(out=file)
            file.seek(0)
            data = json.load(file)

        # only import one group
        if len(data) > 1 and str(chat.id) not in data:
            msg.reply_text(tld(chat.id, "backups_contains_multiple_chats"))
            return

        # Check if backup is this chat
        try:
            if data.get(str(chat.id)) == None:
                if conn:
                    text = tld(
                        chat.id,
                        "backups_from_another_chat").format(f"*{chat_name}*")
                else:
                    text = tld(chat.id,
                               "backups_from_another_chat").format("this chat")
                return msg.reply_text(text, parse_mode="markdown")
        except:
            return msg.reply_text(tld(chat.id, "backups_err_unknown"))
        # Check if backup is from self
        try:
            if str(bot.id) != str(data[str(chat.id)]['bot']):
                return msg.reply_text(tld(chat.id, "backups_from_another_bot"))
        except:
            pass
        # Select data source
        if str(chat.id) in data:
            data = data[str(chat.id)]['hashes']
        else:
            data = data[list(data.keys())[0]]['hashes']

        try:
            for mod in DATA_IMPORT:
                mod.__import_data__(str(chat.id), data)
        except Exception:
            msg.reply_text(tld(chat.id, "backups_restore_err"))

            LOGGER.exception("Imprt for the chat %s with the name %s failed.",
                             str(chat.id), str(chat.title))
            return

        # TODO: some of that link logic
        # NOTE: consider default permissions stuff?
        if conn:
            text = tld(chat.id,
                       "backups_fully_restored").format(f" to *{chat_name}*")
        else:
            text = tld(chat.id, "backups_fully_restored").format("")
        msg.reply_text(text, parse_mode="markdown")
Ejemplo n.º 10
0
def import_data(bot: Bot, update):
	msg = update.effective_message  # type: Optional[Message]
	chat = update.effective_chat  # type: Optional[Chat]
	user = update.effective_user  # type: Optional[User]
	# TODO: allow uploading doc with command, not just as reply
	# only work with a doc
	spam = spamfilters(update.effective_message.text, update.effective_message.from_user.id, update.effective_chat.id, update.effective_message)
	if spam == True:
		return

	conn = connected(bot, update, chat, user.id, need_admin=True)
	if conn:
		chat = dispatcher.bot.getChat(conn)
		chat_id = conn
		chat_name = dispatcher.bot.getChat(conn).title
	else:
		if update.effective_message.chat.type == "private":
			send_message(update.effective_message, tld(update.effective_message, "You can use this command in group and not in PM"))
			return ""
		chat = update.effective_chat
		chat_id = update.effective_chat.id
		chat_name = update.effective_message.chat.title

	if msg.reply_to_message and msg.reply_to_message.document:
		filetype = msg.reply_to_message.document.file_name
		if filetype.split('.')[-1] not in ("backup", "json", "txt"):
			send_message(update.effective_message, tld(update.effective_message, "Invalid backup file!"))
			return
		try:
			file_info = bot.get_file(msg.reply_to_message.document.file_id)
		except BadRequest:
			send_message(update.effective_message, tld(update.effective_message, "Try downloading and re-uploading the file as yourself before importing - this one seems broken!"))
			return

		with BytesIO() as file:
			file_info.download(out=file)
			file.seek(0)
			data = json.load(file)

		try:
			# If backup is from Emilia
			if data.get('bot_base') == "Kanna":
				imp_antiflood = False
				imp_blacklist = False
				imp_blacklist_count = 0
				
				
				imp_disabled_count = 0
				imp_filters_count = 0
				
				imp_locks = False
				imp_notes = 0
				imp_report = False
				imp_rules = False
				
				
				NOT_IMPORTED = "This cannot be imported because from other bot."
				NOT_IMPORTED_INT = 0
				# If backup is from this bot, import all files
				if data.get('bot_id') == bot.id:
					is_self = True
				else:
					is_self = False
				# Import antiflood
				if data.get('antiflood'):
					imp_antiflood = True
					flood_limit = data['antiflood'].get('flood_limit')
					flood_mode = data['antiflood'].get('flood_mode')
					flood_duration = data['antiflood'].get('flood_duration')

					# Add to db
					antifloodsql.set_flood(chat_id, int(flood_limit))
					antifloodsql.set_flood_strength(chat_id, flood_mode, flood_duration)

				# Import blacklist
				if data.get('blacklists'):
					imp_blacklist = True
					blacklist_mode = data['blacklists'].get('blacklist_mode')
					blacklist_duration = data['blacklists'].get('blacklist_duration')
					blacklisted = data['blacklists'].get('blacklists')

					# Add to db
					blacklistsql.set_blacklist_strength(chat_id, blacklist_mode, blacklist_duration)
					if blacklisted:
						for x in blacklisted:
							blacklistsql.add_to_blacklist(chat_id, x.lower())
							imp_blacklist_count += 1

				# Import blacklist sticker
				
				# Import disabled
				if data.get('disabled'):
					candisable = disabledsql.get_disableable()
					if data['disabled'].get('disabled'):
						for listdisabled in data['disabled'].get('disabled'):
							if listdisabled in candisable:
								disabledsql.disable_command(chat_id, listdisabled)
								imp_disabled_count += 1

				# Import filters
				if data.get('filters'):
					NOT_IMPORTED += "\n\nFilters:\n"
					for x in data['filters'].get('filters'):
						# If from self, import all
						if is_self:
							is_sticker = False
							is_document = False
							is_image = False
							is_audio = False
							is_voice = False
							is_video = False
							has_markdown = False
							universal = False
							if x['type'] == 1:
								is_sticker = True
							elif x['type'] == 2:
								is_document = True
							elif x['type'] == 3:
								is_image = True
							elif x['type'] == 4:
								is_audio = True
							elif x['type'] == 5:
								is_voice = True
							elif x['type'] == 6:
								is_video = True
							elif x['type'] == 0:
								has_markdown = True
							note_data, buttons = button_markdown_parser(x['reply'], entities=0)
							filtersql.add_filter(chat_id, x['name'], note_data, is_sticker, is_document, is_image, is_audio, is_voice, is_video, buttons)
							imp_filters_count += 1	
						else:
							if x['has_markdown']:
								note_data, buttons = button_markdown_parser(x['reply'], entities=0)
								filtersql.add_filter(chat_id, x['name'], note_data, False, False, False, False, False, False, buttons)
								imp_filters_count += 1
							else:
								NOT_IMPORTED += "- {}\n".format(x['name'])
								NOT_IMPORTED_INT += 1

				# Import greetings
				
				# Import Locks
				if data.get('locks'):
					if data['locks'].get('lock_warn'):
						locksql.set_lockconf(chat_id, True)
					else:
						locksql.set_lockconf(chat_id, False)
					if data['locks'].get('locks'):
						for x in list(data['locks'].get('locks')):
							if x in LOCK_TYPES:
								is_locked = data['locks']['locks'].get('x')
								locksql.update_lock(chat_id, x, locked=is_locked)
								imp_locks = True
							if x in RESTRICTION_TYPES:
								is_locked = data['locks']['locks'].get('x')
								locksql.update_restriction(chat_id, x, locked=is_locked)
								imp_locks = True

				# Import notes
				if data.get('notes'):
					allnotes = data['notes']
					NOT_IMPORTED += "\n\nNotes:\n"
					for x in allnotes:
						# If from self, import all
						if is_self:
							note_data, buttons = button_markdown_parser(x['note_data'], entities=0)
							note_name = x['note_tag']
							note_file = None
							note_type = x['note_type']
							if x['note_file']:
								note_file = x['note_file']
							if note_type == 0:
								note_type = Types.TEXT
							elif note_type == 1:
								note_type = Types.BUTTON_TEXT
							elif note_type == 2:
								note_type = Types.STICKER
							elif note_type == 3:
								note_type = Types.DOCUMENT
							elif note_type == 4:
								note_type = Types.PHOTO
							elif note_type == 5:
								note_type = Types.AUDIO
							elif note_type == 6:
								note_type = Types.VOICE
							elif note_type == 7:
								note_type = Types.VIDEO
							elif note_type == 8:
								note_type = Types.VIDEO_NOTE
							else:
								note_type = None
							if note_type <= 8:
								notesql.add_note_to_db(chat_id, note_name, note_data, note_type, buttons, note_file)
								imp_notes += 1
						else:
							# If this text
							if x['note_type'] == 0:
								note_data, buttons = button_markdown_parser(x['text'].replace("\\", ""), entities=0)
								note_name = x['name']
								notesql.add_note_to_db(chat_id, note_name, note_data, Types.TEXT, buttons, None)
								imp_notes += 1
							else:
								NOT_IMPORTED += "- {}\n".format(x['name'])
								NOT_IMPORTED_INT += 1

				# Import reports
				if data.get('report'):
					reporting = data['report'].get('report')
					reportsql.set_chat_setting(chat_id, bool(reporting))
					imp_report = True

				# Import rules
				if data.get('rules'):
					contrules = data['rules'].get('rules')
					if contrules:
						rulessql.set_rules(chat_id, contrules)
						imp_rules = True

				# Import warn config
				
				if conn:
					text = tld(update.effective_message, "The backup is fully restored at * {} *. Welcome back! 😀").format(chat_name)
				else:
					text = tld(update.effective_message, "The backup is fully restored. Congratulations welcome back! 😀").format(chat_name)
				text += tld(update.effective_message, "\n\nWhat I return:\n")
				if imp_antiflood:
					text += tld(update.effective_message, "- Settings Antiflood\n")
				if imp_blacklist:
					text += tld(update.effective_message, "- Settings Blacklist\n")
				if imp_blacklist_count:
					text += tld(update.effective_message, "- {} blacklists\n").format(imp_blacklist_count)
				if imp_disabled_count:
					text += tld(update.effective_message, "- {} cmd disabled\n").format(imp_disabled_count)
				if imp_filters_count:
					text += tld(update.effective_message, "- {} filters\n").format(imp_filters_count)
				
				if imp_locks:
					text += tld(update.effective_message, "- Lockup\n")
				if imp_notes:
					text += tld(update.effective_message, "- {} a note\n").format(imp_notes)
				if imp_report:
					text += tld(update.effective_message, "- Reporting arrangements\n")
				if imp_rules:
					text += tld(update.effective_message, "- Order regulations group\n")
				
				try:
					send_message(update.effective_message, text, parse_mode="markdown")
				except BadRequest:
					send_message(update.effective_message, text, parse_mode="markdown", quote=False)
				if NOT_IMPORTED_INT:
					f = open("{}-notimported.txt".format(chat_id), "w")
					f.write(str(NOT_IMPORTED))
					f.close()
					bot.sendDocument(chat_id, document=open('{}-notimported.txt'.format(chat_id), 'rb'), caption=tl(update.effective_message, "*Data yang tidak dapat di import*"), timeout=360, parse_mode=ParseMode.MARKDOWN)
					os.remove("{}-notimported.txt".format(chat_id))
				return
		except Exception as err:
			send_message(update.effective_message, tld(update.effective_message, "An error occured in importing backup.Report it in @LucySupportChat"), parse_mode="markdown")
			LOGGER.exception("An error when importing from Haruka base!")
			return

		try:
			# If backup is from rose
			# doing manual lol
			if data.get('bot_id') == 609517172:
				imp_antiflood = False
				imp_blacklist = False
				imp_blacklist_count = 0
				imp_disabled_count = 0
				imp_filters_count = 0
				
				imp_notes = 0
				imp_report = False
				imp_rules = False
				
				NOT_IMPORTED = "This cannot be imported because from other bot."
				NOT_IMPORTED_INT = 0
				if data.get('data'):
					# Import antiflood
					if data['data'].get('antiflood'):
						floodlimit = data['data']['antiflood'].get('flood_limit')
						action = data['data']['antiflood'].get('action')
						actionduration = data['data']['antiflood'].get('action_duration')
						act_dur = make_time(int(actionduration))
						antifloodsql.set_flood(chat_id, int(floodlimit))
						if action == "ban":
							antifloodsql.set_flood_strength(chat_id, 1, str(act_dur))
							imp_antiflood = True
						elif action == "kick":
							antifloodsql.set_flood_strength(chat_id, 2, str(act_dur))
							imp_antiflood = True
						elif action == "mute":
							antifloodsql.set_flood_strength(chat_id, 3, str(act_dur))
							imp_antiflood = True
					# Import blacklist
					if data['data'].get('blacklists'):
						action = data['data']['blacklists'].get('action')
						actionduration = data['data']['blacklists'].get('action_duration')
						act_dur = make_time(int(actionduration))
						strengthdone = False
						if action == "del":
							strengthdone = True
							blacklistsql.set_blacklist_strength(chat_id, 1, str(act_dur))
							imp_blacklist = True
						elif action == "warn":
							strengthdone = True
							blacklistsql.set_blacklist_strength(chat_id, 2, str(act_dur))
							imp_blacklist = True
						elif action == "mute":
							strengthdone = True
							blacklistsql.set_blacklist_strength(chat_id, 3, str(act_dur))
							imp_blacklist = True
						elif action == "kick":
							strengthdone = True
							blacklistsql.set_blacklist_strength(chat_id, 4, str(act_dur))
							imp_blacklist = True
						elif action == "ban":
							strengthdone = True
							blacklistsql.set_blacklist_strength(chat_id, 5, str(act_dur))
							imp_blacklist = True
						else:
							if not strengthdone:
								action = data['data']['blacklists'].get('should_delete')
								if action:
									blacklistsql.set_blacklist_strength(chat_id, 1, "0")
									imp_blacklist = True
						blacklisted = data['data']['blacklists'].get('filters')
						if blacklisted:
							for x in blacklisted:
								blacklistsql.add_to_blacklist(chat_id, x['name'].lower())
								imp_blacklist_count += 1
					# Import disabled
					if data['data'].get('disabled'):
						if data['data']['disabled'].get('disabled'):
							candisable = disabledsql.get_disableable()
							for listdisabled in data['data']['disabled'].get('disabled'):
								if listdisabled in candisable:
									disabledsql.disable_command(chat_id, listdisabled)
									imp_disabled_count += 1
					# Import filters
					if data['data'].get('filters'):
						NOT_IMPORTED += "\n\nFilters:\n"
						if data['data']['filters'].get('filters'):
							for x in data['data']['filters'].get('filters'):
								if x['type'] == 0:
									note_data, buttons = button_markdown_parser(x['text'].replace("\\", ""), entities=0)
									filtersql.add_filter(chat_id, x['name'], note_data, False, False, False, False, False, False, buttons)
									imp_filters_count += 1
								else:
									NOT_IMPORTED += "- {}\n".format(x['name'])
									NOT_IMPORTED_INT += 1
					# Import greetings
					
					# Import notes
					if data['data'].get('notes'):
						NOT_IMPORTED += "\n\nNotes:\n"
						allnotes = data['data']['notes']['notes']
						for x in allnotes:
							# If this text
							if x['type'] == 0:
								note_data, buttons = button_markdown_parser(x['text'].replace("\\", ""), entities=0)
								note_name = x['name']
								notesql.add_note_to_db(chat_id, note_name, note_data, Types.TEXT, buttons, None)
								imp_notes += 1
							else:
								NOT_IMPORTED += "- {}\n".format(x['name'])
								NOT_IMPORTED_INT += 1
					# Import reports
					if data['data'].get('reports'):
						if data['data']['reports'].get('disable_reports'):
							reporting = False
						else:
							reporting = True
						reportsql.set_chat_setting(chat_id, reporting)
						imp_report = True
					# Import rules
					if data['data'].get('rules'):
						contrules = data['data']['rules'].get('content')
						if contrules:
							rulessql.set_rules(chat_id, contrules.replace("\\", ""))
							imp_rules = True
					
					# Import warn
					
					if conn:
						text = tld(update.effective_message, "Backup fully restored at *{}*. Congratulations welcome back! 😀").format(chat_name)
					else:
						text = tld(update.effective_message, "Backup fully restored. Congratulations welcome back! 😀").format(chat_name)
					text += tld(update.effective_message, "\n\nI returned:\n")
					if imp_antiflood:
						text += tld(update.effective_message, "- Setting Antiflood\n")
					if imp_blacklist:
						text += tld(update.effective_message, "- Settings Blacklist\n")
					if imp_blacklist_count:
						text += tld(update.effective_message, "- {} blacklists\n").format(imp_blacklist_count)
					if imp_disabled_count:
						text += tld(update.effective_message, "- {} cmd disabled\n").format(imp_disabled_count)
					if imp_filters_count:
						text += tld(update.effective_message, "- {} filters\n").format(imp_filters_count)
					
					if imp_notes:
						text += tld(update.effective_message, "- {} a note\n").format(imp_notes)
					if imp_report:
						text += tld(update.effective_message, "- Reporting arrangements\n")
					if imp_rules:
						text += tld(update.effective_message, "- Order group rules\n")
					
					try:
						send_message(update.effective_message, text, parse_mode="markdown")
					except BadRequest:
						send_message(update.effective_message, text, parse_mode="markdown", quote=False)
					if NOT_IMPORTED_INT:
						f = open("{}-notimported.txt".format(chat_id), "w")
						f.write(str(NOT_IMPORTED))
						f.close()
						bot.sendDocument(chat_id, document=open('{}-notimported.txt'.format(chat_id), 'rb'), caption=tld(update.effective_message, "*data cannot be imported*"), timeout=360, parse_mode=ParseMode.MARKDOWN)
						os.remove("{}-notimported.txt".format(chat_id))
					return
		except Exception as err:
			send_message(update.effective_message, tld(update.effective_message, "An error occured while restoring backup report at @LucySupportChat"), parse_mode="markdown")
			LOGGER.exception("An error when importing from Rose base!")
			return

		# only import one group
		if len(data) > 1 and str(chat_id) not in data:
			send_message(update.effective_message, tld(update.effective_message, "There is more than one group in this file, and no one has the same chat id as"
						   "this group - how do you choose what to import?"))
			return

		# Check if backup is this chat
		try:
			if data.get(str(chat_id)) == None:
				if conn:
					text = tld(update.effective_message, "Backup originates from another chat, I can't return another chat to chat *{}*").format(chat_name)
				else:
					text = tld(update.effective_message, "Backup originates from another chat")
				return send_message(update.effective_message, text, parse_mode="markdown")
		except:
			return send_message(update.effective_message, tld(update.effective_message, "An error has occurred in checking the data, please report it to my author at @ LucySupportChat! 🙂"))
		# Check if backup is from self
		try:
			if str(bot.id) != str(data[str(chat_id)]['bot']):
				return send_message(update.effective_message, tld(update.effective_message, "Backup comes from another bot🙂"))
		except:
			pass
		# Select data source
		if str(chat_id) in data:
			data = data[str(chat_id)]['hashes']
		else:
			data = data[list(data.keys())[0]]['hashes']

		try:
			for mod in DATA_IMPORT:
				mod.__import_data__(str(chat_id), data)
		except Exception:
			send_message(update.effective_message, tld(update.effective_message, "An error occurred while restoring your data. The process may not be complete🙂"))
			LOGGER.exception("Impor untuk id chat %s dengan nama %s gagal.", str(chat_id), str(chat.title))
			return

		# TODO: some of that link logic
		# NOTE: consider default permissions stuff?
		if conn:
			text = tld(update.effective_message, "Backup was restored successfully *{}*. Congratulations welcome back! 😀").format(chat_name)
		else:
			text = tld(update.effective_message, "Backup was restored successfully. Congratulations welcome back! 😀").format(chat_name)
		send_message(update.effective_message, text, parse_mode="markdown")
Ejemplo n.º 11
0
def reply_filter(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]
    message = update.effective_message  # type: Optional[Message]
    user = update.effective_user  # type: Optional[User]

    if int(user.id) == int(777000):
        return

    to_match = extract_text(message)
    if not to_match:
        return

    chat_filters = sql.get_chat_triggers(chat.id)
    for keyword in chat_filters:
        pattern = r"( |^|[^\w])" + re.escape(keyword) + r"( |$|[^\w])"
        if re.search(pattern, to_match, flags=re.IGNORECASE):
            filt = sql.get_filter(chat.id, keyword)
            if filt.is_sticker:
                message.reply_sticker(filt.reply)
            elif filt.is_document:
                try:
                    message.reply_document(filt.reply)
                except:
                    print("L")
            elif filt.is_image:
                message.reply_photo(filt.reply)
            elif filt.is_audio:
                message.reply_audio(filt.reply)
            elif filt.is_voice:
                message.reply_voice(filt.reply)
            elif filt.is_video:
                try:
                    message.reply_video(filt.reply)
                except:
                    print("Nut")
            elif filt.has_markdown:
                buttons = sql.get_buttons(chat.id, filt.keyword)
                keyb = build_keyboard(buttons)
                keyboard = InlineKeyboardMarkup(keyb)

                try:
                    message.reply_text(filt.reply,
                                       parse_mode=ParseMode.MARKDOWN,
                                       disable_web_page_preview=True,
                                       reply_markup=keyboard)
                except BadRequest as excp:
                    if excp.message == "Unsupported url protocol":
                        message.reply_text(
                            tld(chat.id, "cust_filters_err_protocol"))
                    elif excp.message == "Reply message not found":
                        bot.send_message(chat.id,
                                         filt.reply,
                                         parse_mode=ParseMode.MARKDOWN,
                                         disable_web_page_preview=True,
                                         reply_markup=keyboard)
                    else:
                        try:
                            message.reply_text(
                                tld(chat.id, "cust_filters_err_badformat"))
                            LOGGER.warning("Message %s could not be parsed",
                                           str(filt.reply))
                            LOGGER.exception(
                                "Could not parse filter %s in chat %s",
                                str(filt.keyword), str(chat.id))
                        except:
                            print("Nut")

            else:
                # LEGACY - all new filters will have has_markdown set to True.
                message.reply_text(filt.reply)
            break
Ejemplo n.º 12
0
def temp_ban(bot: Bot, update: Update, args: List[str]) -> str:
    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(tld(chat.id, "common_err_no_user"))
        return ""

    try:
        member = chat.get_member(user_id)
    except BadRequest as excp:
        if excp.message == "User not found.":
            message.reply_text(tld(chat.id, "bans_err_usr_not_found"))
            return ""
        else:
            raise

    if is_user_ban_protected(chat, user_id, member):
        message.reply_text(tld(chat.id, "bans_err_usr_is_admin"))
        return ""

    if user_id == bot.id:
        message.reply_text(tld(chat.id, "bans_err_usr_is_bot"))
        return ""

    if not reason:
        message.reply_text(tld(chat.id, "bans_err_tban_no_arg"))
        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 = tld(chat.id, "bans_tban_logger").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 += tld(chat.id, "bans_logger_reason").format(reason)

    try:
        chat.kick_member(user_id, until_date=bantime)
        reply = tld(chat.id, "bans_tbanned_success").format(
            mention_html(user.id, user.first_name),
            mention_html(member.user.id, member.user.first_name),
            html.escape(chat.title), time_val)
        reply += tld(chat.id, "bans_logger_reason").format(reason)
        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(tld(chat.id, "bans_tbanned_success").format(
                mention_html(user.id, user.first_name),
                mention_html(member.user.id, member.user.first_name),
                html.escape(chat.title), time_val),
                               quote=False)
            return log
        else:
            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(
                tld(chat.id, "bans_err_unknown").format("tbanning"))

    return ""
Ejemplo n.º 13
0
def temp_ban(bot: Bot, update: Update, args: List[str]) -> str:
    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(tld(chat.id, "لا يبدو أنك تشير إلى مستخدم."))
        return ""

    try:
        member = chat.get_member(user_id)
    except BadRequest as excp:
        if excp.message == "User not found":
            message.reply_text(tld(chat.id, "لا يمكنني العثور على هذا المستخدم"))
            return ""
        else:
            raise

    if is_user_ban_protected(chat, user_id, member):
        message.reply_text(tld(chat.id, "هذا المستخدم محمي ، مما يعني أنه لا يمكنك حظر هذا المستخدم!"))
        return ""

    if user_id == bot.id:
        message.reply_text(tld(chat.id, "لن احظر نفسي ، هل أنت مجنون؟"))
        return ""

    if not reason:
        message.reply_text(tld(chat.id, "لم تحدد وقتًا لحظر هذا المستخدم!"))
        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.kick_member(user_id, until_date=bantime)
        #bot.send_sticker(chat.id, BAN_STICKER)  # banhammer marie sticker
        message.reply_text("تم الحظر! سيتم حظر المستخدم ل {}.".format(time_val))
        return log

    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            #bot.send_sticker(chat.id, BAN_STICKER)  # banhammer marie sticker
            message.reply_text(tld(chat.id, "تم الحظر! سيتم حظر المستخدم ل {}.").format(time_val), quote=False)
            return log
        else:
            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(tld(chat.id, "اللعنة ، لا يمكنني حظر هذا المستخدم."))

    return ""
Ejemplo n.º 14
0
def rban(bot: Bot, update: Update, args: List[str]):
    chat = update.effective_chat
    message = update.effective_message

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

    user_id, chat_id = extract_user_and_text(message, args)

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

    try:
        chat = bot.get_chat(chat_id.split()[0])
    except BadRequest as excp:
        if excp.message == "Chat not found":
            message.reply_text(
                "Chat not found! Make sure you entered a valid chat ID and I'm part of that chat."
            )
            return
        else:
            raise

    if chat.type == 'private':
        message.reply_text("I'm sorry, but that's a private chat!")
        return

    if not is_bot_admin(chat, bot.id) or not chat.get_member(
            bot.id).can_restrict_members:
        message.reply_text(
            "I can't restrict people there! Make sure I'm admin and can ban users."
        )
        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_ban_protected(chat, user_id, member):
        message.reply_text("I really wish I could ban admins...")
        return

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

    try:
        chat.kick_member(user_id)
        message.reply_text("Banned from chat!")
    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            message.reply_text('Banned!', quote=False)
        elif excp.message in RBAN_ERRORS:
            message.reply_text(excp.message)
        else:
            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.")
Ejemplo n.º 15
0
def extract_user_and_text(message: Message, args: List[str]) -> (Optional[int], Optional[str]):
    prev_message = message.reply_to_message
    split_text = message.text.split(None, 1)

    if len(split_text) < 2:
        return id_from_reply(message)  # only option possible

    text_to_parse = split_text[1]

    text = ""

    entities = list(message.parse_entities([MessageEntity.TEXT_MENTION]))
    if len(entities) > 0:
        ent = entities[0]
    else:
        ent = None

    # if entity offset matches (command end/text start) then all good
    if entities and ent and ent.offset == len(message.text) - len(text_to_parse):
        ent = entities[0]
        user_id = ent.user.id
        text = message.text[ent.offset + ent.length:]

    elif len(args) >= 1 and args[0][0] == '@':
        user = args[0]
        user_id = get_user_id(user)
        if not user_id:
            message.reply_text("I don't have that user in my db. You'll be able to interact with them if "
                               "you reply to that person's message instead, or forward one of that user's messages.")
            return None, None

        else:
            user_id = user_id
            res = message.text.split(None, 2)
            if len(res) >= 3:
                text = res[2]

    elif len(args) >= 1 and args[0].isdigit():
        user_id = int(args[0])
        res = message.text.split(None, 2)
        if len(res) >= 3:
            text = res[2]

    elif prev_message:
        user_id, text = id_from_reply(message)

    else:
        return None, None

    try:
        message.bot.get_chat(user_id)
    except BadRequest as excp:
        if excp.message in ("User_id_invalid", "Chat not found"):
            message.reply_text("I don't seem to have interacted with this user before - please forward a message from "
                               "them to give me control! (like a voodoo doll, I need a piece of them to be able "
                               "to execute certain commands...)")
        else:
            LOGGER.exception("Exception %s on user %s", excp.message, user_id)

        return None, None

    return user_id, text
Ejemplo n.º 16
0
def temp_nomedia(bot: Bot, update: Update, args: List[str]) -> str:
    chat = update.effective_chat
    user = update.effective_user
    message = update.effective_message

    conn = connected(bot, update, chat, user.id)
    if conn:
        chatD = dispatcher.bot.getChat(conn)
    else:
        if chat.type == "private":
            return
        else:
            chatD = chat

    user_id, reason = extract_user_and_text(message, args)

    if not user_id:
        message.reply_text(tld(chat.id, "mute_not_refer"))
        return ""

    try:
        member = chat.get_member(user_id)
    except BadRequest as excp:
        if excp.message == "User not found":
            message.reply_text(tld(chat.id, "mute_not_existed"))
            return ""
        else:
            raise

    if is_user_admin(chat, user_id, member):
        message.reply_text(tld(chat.id, "restrict_is_admin"))
        return ""

    if user_id == bot.id:
        message.reply_text(tld(chat.id, "restrict_is_bot"))
        return ""

    if not reason:
        message.reply_text(tld(chat.id, "nomedia_need_time"))
        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 RESTRICTED" \
          "\n<b>• Admin:</b> {}" \
          "\n<b>• User:</b> {}" \
          "\n<b>• ID:</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), user_id, time_val)
    if reason:
        log += tld(chat.id, "bans_logger_reason").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,
                                     can_send_messages=True,
                                     can_send_media_messages=False,
                                     can_send_other_messages=False,
                                     can_add_web_page_previews=False)
            message.reply_text(
                tld(chat.id, "nomedia_success").format(time_val, chatD.title))
            return log
        else:
            message.reply_text(
                tld(chat.id,
                    "restrict_already_restricted").format(chatD.title))

    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            message.reply_text(tld(chat.id, "nomedia_success").format(
                time_val, chatD.title),
                               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(tld(chat.id, "restrict_cant_restricted"))

    return ""
Ejemplo n.º 17
0
def help_button(bot: Bot, update: Update):
    query = update.callback_query
    chat = update.effective_chat
    mod_match = re.match(r"help_module\((.+?)\)", query.data)
    prev_match = re.match(r"help_prev\((.+?)\)", query.data)
    next_match = re.match(r"help_next\((.+?)\)", query.data)
    back_match = re.match(r"help_back", query.data)
    try:
        if mod_match:
            module = mod_match.group(1)
            mod_name = tld(chat.id, "modname_" + module).strip()
            help_txt = tld(
                chat.id, module +
                "_help")  # tld_help(chat.id, HELPABLE[module].__mod_name__)

            if not help_txt:
                LOGGER.exception(f"Help string for {module} not found!")

            text = tld(chat.id, "here_is_help").format(mod_name, help_txt)
            query.message.reply_text(text=text,
                                     parse_mode=ParseMode.MARKDOWN,
                                     reply_markup=InlineKeyboardMarkup([[
                                         InlineKeyboardButton(
                                             text=tld(chat.id, "btn_go_back"),
                                             callback_data="help_back")
                                     ]]))

        elif prev_match:
            curr_page = int(prev_match.group(1))
            query.message.reply_text(tld(chat.id, "send-help").format(
                dispatcher.bot.first_name,
                "" if not ALLOW_EXCL else tld(chat.id, "cmd_multitrigger")),
                                     parse_mode=ParseMode.MARKDOWN,
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(
                                             chat.id, curr_page - 1, HELPABLE,
                                             "help")))

        elif next_match:
            next_page = int(next_match.group(1))
            query.message.reply_text(tld(chat.id, "send-help").format(
                dispatcher.bot.first_name,
                "" if not ALLOW_EXCL else tld(chat.id, "cmd_multitrigger")),
                                     parse_mode=ParseMode.MARKDOWN,
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(
                                             chat.id, next_page + 1, HELPABLE,
                                             "help")))

        elif back_match:
            query.message.reply_text(text=tld(chat.id, "send-help").format(
                dispatcher.bot.first_name,
                "" if not ALLOW_EXCL else tld(chat.id, "cmd_multitrigger")),
                                     parse_mode=ParseMode.MARKDOWN,
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(
                                             chat.id, 0, HELPABLE, "help")))

        # ensure no spinny white circle
        bot.answer_callback_query(query.id)
        query.message.delete()
    except BadRequest as excp:
        if excp.message == "Message is not modified":
            pass
        elif excp.message == "Query_id_invalid":
            pass
        elif excp.message == "Message can't be deleted":
            pass
        else:
            LOGGER.exception("Exception in help buttons. %s", str(query.data))
Ejemplo n.º 18
0


        # ensure no spinny white circle
        bot.answer_callback_query(query.id)
        query.message.delete()
    except BadRequest as excp:
        if excp.message == "Message is not modified":
            pass
        elif excp.message == "Query_id_invalid":
            pass
        elif excp.message == "Message can't be deleted":
            pass
        else:
            LOGGER.exception("Exception in help buttons. %s", str(query.data))


@run_async
def get_help(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]
    args = update.effective_message.text.split(None, 1)

    # ONLY send help in PM
    if chat.type != chat.PRIVATE:

        update.effective_message.reply_text("Contact me in PM to get the list of possible commands.",
                                            reply_markup=InlineKeyboardMarkup(
                                                [[InlineKeyboardButton(text="Help",
                                                                       url="t.me/{}?start=help".format(
                                                                           bot.username))]]))
        return
Ejemplo n.º 19
0
def ban(bot: Bot, update: Update, args: List[str]) -> str:
    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(tld(chat.id, "Tag orangnya."))
        return ""

    try:
        member = chat.get_member(user_id)
    except BadRequest as excp:
        if excp.message == "User not found":
            message.reply_text(
                tld(chat.id, "Saya tidak bisa menemukan orang ini"))
            return ""
        else:
            raise

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

    if is_user_ban_protected(chat, user_id, member):
        message.reply_text(tld(chat.id, "Tidak bisa ban admin."))
        return ""

    log = "<b>{}:</b>" \
          "\n#BANNED" \
          "\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(member.user.id, member.user.first_name), user_id)

    reply = "{} Telah di ban HAHA!".format(
        mention_html(member.user.id, member.user.first_name))

    if reason:
        log += "\n<b>Reason:</b> {}".format(reason)

    try:
        chat.kick_member(user_id)
        #bot.send_sticker(chat.id, BAN_STICKER)  # banhammer marie sticker
        message.reply_text(tld(chat.id, "Banned!"))
        return log

    except BadRequest as excp:
        if excp.message == "Reply tidak ditemukan":
            # Do not reply
            #bot.send_sticker(chat.id, BAN_STICKER)  # banhammer marie sticker
            message.reply_text(tld(chat.id, "Banned!"), quote=False)
            return log
        else:
            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(
                tld(chat.id, "Well damn, saya tidak bisa ban dia."))

    return ""
Ejemplo n.º 20
0
def extract_user_and_text(message: Message,
                          args: List[str]) -> (Optional[int], Optional[str]):
    chat = message.chat  # type: Optional[Chat]
    prev_message = message.reply_to_message
    split_text = message.text.split(None, 1)

    if len(split_text) < 2:
        return id_from_reply(message)  # only option possible

    text_to_parse = split_text[1]

    text = ""

    entities = list(message.parse_entities([MessageEntity.TEXT_MENTION]))
    if len(entities) > 0:
        ent = entities[0]
    else:
        ent = None

    # if entity offset matches (command end/text start) then all good
    if entities and ent and ent.offset == len(
            message.text) - len(text_to_parse):
        ent = entities[0]
        user_id = ent.user.id
        text = message.text[ent.offset + ent.length:]

    elif len(args) >= 1 and args[0][0] == '@':
        user = args[0]
        user_id = get_user_id(user)
        if not user_id:
            message.reply_text(tld(chat.id, 'helpers_user_not_in_db'))
            return None, None

        else:
            user_id = user_id
            res = message.text.split(None, 2)
            if len(res) >= 3:
                text = res[2]

    elif len(args) >= 1 and args[0].isdigit():
        user_id = int(args[0])
        res = message.text.split(None, 2)
        if len(res) >= 3:
            text = res[2]

    elif prev_message:
        user_id, text = id_from_reply(message)

    else:
        return None, None

    try:
        message.bot.get_chat(user_id)
    except BadRequest as excp:
        if excp.message in ("User_id_invalid", "Chat not found"):
            message.reply_text(tld(chat.id, 'helpers_user_not_in_db'))
        else:
            LOGGER.exception("Exception %s on user %s", excp.message, user_id)

        return None, None

    return user_id, text
Ejemplo n.º 21
0
def ban(bot: Bot, update: Update, args: List[str]) -> str:
    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(tld(chat.id, "Who"))
        return ""

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

    if user_id == bot.id:
        message.reply_text(tld(chat.id, "lol no"))
        return ""
    
    if user_id == 777000:
        message.reply_text(tld(chat.id, "Pfft"))
        return ""

    if is_user_ban_protected(chat, user_id, member):
        message.reply_text(tld(chat.id, "Nope."))
        return ""

    log = "<b>{}:</b>" \
          "\n#BANNED" \
          "\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(member.user.id, member.user.first_name), user_id)

    reply = "Bye ii {}".format(mention_html(member.user.id, member.user.first_name))

    if reason:
        log += "\n<b>Reason:</b> {}".format(reason)

    try:
        chat.kick_member(user_id)
        keyboard = []
        bot.send_sticker(chat.id, BAN_STICKER)  # banhammer marie sticker
        message.reply_text(reply, reply_markup=keyboard, parse_mode=ParseMode.HTML)
        return log

    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            #bot.send_sticker(chat.id, BAN_STICKER)  # banhammer marie sticker
            message.reply_text(tld(chat.id, "Banned!"), quote=False)
            return log
        else:
            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(tld(chat.id, "Well damn, I can't ban that user."))

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

    conn = connected(bot, update, chat, user.id)
    if not conn == False:
        chatD = dispatcher.bot.getChat(conn)
    else:
        if chat.type == "private":
            exit(1)
        else:
            chatD = chat

    user_id, reason = extract_user_and_text(message, args)

    if not user_id:
        message.reply_text(
            tld(chat.id, "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(tld(chat.id, "I can't seem to find this user"))
            return ""
        else:
            raise

    if is_user_admin(chat, user_id, member):
        message.reply_text(
            tld(chat.id,
                "DEMI ALEK LAKO BISA GUA MUTE ADMIN UDAH GUA MUTE..."))
        return ""

    if user_id == bot.id:
        message.reply_text(tld(chat.id, "GILA LU MAU MUTE GUA?"))
        return ""

    if not reason:
        message.reply_text(
            tld(chat.id,
                "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,
                                     can_send_messages=False)
            message.reply_text(
                tld(chat.id,
                    "Muted for {} in {}!").format(time_val, chatD.title))
            return log
        else:
            message.reply_text(
                tld(chat.id,
                    "This user is already muted in {}!").format(chatD.title))

    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            message.reply_text(tld(chat.id, "Muted for {} in {}!").format(
                time_val, chatD.title),
                               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(
                tld(chat.id, "Well damn, I can't mute that user."))

    return ""
Ejemplo n.º 23
0
def ban(bot: Bot, update: Update, args: List[str]) -> str:
    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(
            tld(chat.id, "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(tld(chat.id, "I can't seem to find this user"))
            return ""
        else:
            raise

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

    if is_user_ban_protected(chat, user_id, member):
        message.reply_text(
            tld(
                chat.id,
                "Why would I ban an admin? That sounds like a pretty dumb idea."
            ))
        return ""

    log = "<b>{}:</b>" \
          "\n#BANNED" \
          "\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(member.user.id, member.user.first_name), user_id)

    reply = "{} has been banned!".format(
        mention_html(member.user.id, member.user.first_name))

    if reason:
        log += "\n<b>Reason:</b> {}".format(reason)

    try:
        chat.kick_member(user_id)
        #bot.send_sticker(chat.id, BAN_STICKER)  # banhammer marie sticker
        message.reply_text(tld(chat.id, "Banned!"))
        return log

    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            #bot.send_sticker(chat.id, BAN_STICKER)  # banhammer marie sticker
            message.reply_text(tld(chat.id, "Banned!"), quote=False)
            return log
        else:
            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(
                tld(chat.id, "Well damn, I can't ban that user."))

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

    conn = connected(bot, update, chat, user.id)
    if not conn == False:
        chatD = dispatcher.bot.getChat(conn)
    else:
        if chat.type == "private":
            exit(1)
        else:
            chatD = chat

    user_id, reason = extract_user_and_text(message, args)

    if not user_id:
        message.reply_text(
            tld(chat.id, "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(tld(chat.id, "I can't seem to find this user"))
            return ""
        else:
            raise

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

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

    if not reason:
        message.reply_text(
            tld(chat.id,
                "You haven't specified a time to restrict 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 RESTRICTED" \
          "\n<b>• Admin:</b> {}" \
          "\n<b>• User:</b> {}" \
          "\n<b>• ID:</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), user_id, 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,
                                     can_send_messages=True,
                                     can_send_media_messages=False,
                                     can_send_other_messages=False,
                                     can_add_web_page_previews=False)
            message.reply_text(
                tld(chat.id,
                    "Restricted from sending media for {} in {}!").format(
                        time_val, chatD.title))
            return log
        else:
            message.reply_text(
                tld(chat.id, "This user is already restricted in {}.").format(
                    chatD.title))

    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            message.reply_text(tld(chat.id, "Restricted for {} in {}!").format(
                time_val, chatD.title),
                               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(
                tld(chat.id, "Well damn, I can't restrict that user."))

    return ""
Ejemplo n.º 25
0
def import_data(bot: Bot, update):
	msg = update.effective_message  # type: Optional[Message]
	chat = update.effective_chat  # type: Optional[Chat]
	user = update.effective_user  # type: Optional[User]
	# TODO: allow uploading doc with command, not just as reply
	# only work with a doc

	conn = connected(bot, update, chat, user.id, need_admin=True)
	if conn:
		chat = dispatcher.bot.getChat(conn)
		chat_id = conn
		chat_name = dispatcher.bot.getChat(conn).title
	else:
		if update.effective_message.chat.type == "private":
			update.effective_message.reply_text("This command can only be runned on group, not PM.")
			return ""

		chat = update.effective_chat
		chat_id = update.effective_chat.id
		chat_name = update.effective_message.chat.title

	if msg.reply_to_message and msg.reply_to_message.document:
		try:
			file_info = bot.get_file(msg.reply_to_message.document.file_id)
		except BadRequest:
			msg.reply_text("Try downloading and uploading the file yourself again, This one seem broken!")
			return

		with BytesIO() as file:
			file_info.download(out=file)
			file.seek(0)
			data = json.load(file)

		# only import one group
		if len(data) > 1 and str(chat.id) not in data:
			msg.reply_text("There are more than one group in this file and the chat.id is not same! How am i supposed to import it?")
			return

		# Check if backup is this chat
		try:
			if data.get(str(chat.id)) == None:
				if conn:
					text = "Backup comes from another chat, I can't return another chat to chat *{}*".format(chat_name)
				else:
					text = "Backup comes from another chat, I can't return another chat to this chat"
				return msg.reply_text(text, parse_mode="markdown")
		except:
			return msg.reply_text("There is problem while importing the data! Please ask in @sabrinasupport about why this happened.")
		# Check if backup is from self
		try:
			if str(bot.id) != str(data[str(chat.id)]['bot']):
				return msg.reply_text("Backup from another bot that is not suggested might cause the problem, documents, photos, videos, audios, records might not work as it should be. However, You can still request a feature regarding this in @sabrinasupport !")
		except:
			pass
		# Select data source
		if str(chat.id) in data:
			data = data[str(chat.id)]['hashes']
		else:
			data = data[list(data.keys())[0]]['hashes']

		try:
			for mod in DATA_IMPORT:
				mod.__import_data__(str(chat.id), data)
		except Exception:
			msg.reply_text("An error occurred while recovering your data. The process failed. If you experience a problem with this, please ask in @sabrinasupport . My owner and community will be happy to help. Also, bugs report makes me even better!\nThank you!")

			LOGGER.exception("Imprt for the chat %s with the name %s failed.", str(chat.id), str(chat.title))
			return

		# TODO: some of that link logic
		# NOTE: consider default permissions stuff?
		if conn:


			text = "Backup fully restored on *{}*.".format(chat_name)
		else:
			text = "Backup fully restored"
		msg.reply_text(text, parse_mode="markdown")
Ejemplo n.º 26
0
def report(bot: Bot, update: Update) -> str:
    message = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]

    if chat and message.reply_to_message and sql.chat_should_report(chat.id):
        reported_user = message.reply_to_message.from_user  # type: Optional[User]
        chat_name = chat.title or chat.first or chat.username
        admin_list = chat.get_administrators()

        #if reported_user == "483808054":
        #    continue
       # 
        #if user.id == "435606081":
        #    continue

        if chat.username and chat.type == Chat.SUPERGROUP:
            msg = "<b>{}:</b>" \
                  "\n<b>Reported user:</b> {} (<code>{}</code>)" \
                  "\n<b>Reported by:</b> {} (<code>{}</code>)".format(html.escape(chat.title),
                                                                      mention_html(
                                                                          reported_user.id,
                                                                          reported_user.first_name),
                                                                      reported_user.id,
                                                                      mention_html(user.id,
                                                                                   user.first_name),
                                                                      user.id)
            link = "\n<b>Link:</b> " \
                   "<a href=\"http://telegram.me/{}/{}\">click here</a>".format(chat.username, message.message_id)

            should_forward = True
            keyboard = [
                [InlineKeyboardButton(u"➡ Message", url="https://t.me/{}/{}".format(chat.username, str(
                    message.reply_to_message.message_id)))],
                [InlineKeyboardButton(u"⚠ Kick",
                                      callback_data="report_{}=kick={}={}".format(chat.id, reported_user.id,
                                                                                  reported_user.first_name)),
                 InlineKeyboardButton(u"⛔️ Ban",
                                      callback_data="report_{}=banned={}={}".format(chat.id, reported_user.id,
                                                                                    reported_user.first_name))],
                [InlineKeyboardButton(u"❎ Delete Message",
                                      callback_data="report_{}=delete={}={}".format(chat.id, reported_user.id,
                                                                                    message.reply_to_message.message_id))]]
            reply_markup = InlineKeyboardMarkup(keyboard)

        else:
            msg = "{} is calling for admins in \"{}\"!".format(mention_html(user.id, user.first_name),
                                                               html.escape(chat_name))
            link = ""
            should_forward = True

        for admin in admin_list:
            if admin.user.is_bot:  # can't message bots
                continue

            if sql.user_should_report(admin.user.id):
                try:
                    if not chat.type == Chat.SUPERGROUP:
                        bot.send_message(admin.user.id, msg + link, parse_mode=ParseMode.HTML)

                        if should_forward:
                            message.reply_to_message.forward(admin.user.id)

                            if len(message.text.split()) > 1:  # If user is giving a reason, send his message too
                                message.forward(admin.user.id)

                    if not chat.username:
                        bot.send_message(admin.user.id, msg + link, parse_mode=ParseMode.HTML)

                        if should_forward:
                            message.reply_to_message.forward(admin.user.id)

                            if len(message.text.split()) > 1:  # If user is giving a reason, send his message too
                                message.forward(admin.user.id)

                    if chat.username and chat.type == Chat.SUPERGROUP:
                        bot.send_message(admin.user.id, msg + link, parse_mode=ParseMode.HTML, reply_markup=reply_markup)

                        if should_forward:
                            message.reply_to_message.forward(admin.user.id)

                            if len(message.text.split()) > 1:  # If user is giving a reason, send his message too
                                message.forward(admin.user.id)

                except Unauthorized:
                    pass
                except BadRequest as excp:  # TODO: cleanup exceptions
                    LOGGER.exception("Exception while reporting user")

        message.reply_to_message.reply_text("{} reported the message to the admins.".
                                            format(mention_html(user.id, user.first_name)),
                                            parse_mode=ParseMode.HTML)
        return msg

    return ""
Ejemplo n.º 27
0
def settings_button(bot: Bot, update: Update):
    query = update.callback_query
    user = update.effective_user
    chatP = update.effective_chat  # type: Optional[Chat]
    mod_match = re.match(r"stngs_module\((.+?),(.+?)\)", query.data)
    prev_match = re.match(r"stngs_prev\((.+?),(.+?)\)", query.data)
    next_match = re.match(r"stngs_next\((.+?),(.+?)\)", query.data)
    back_match = re.match(r"stngs_back\((.+?)\)", query.data)
    try:
        if mod_match:
            chat_id = mod_match.group(1)
            module = mod_match.group(2)
            chat = bot.get_chat(chat_id)
            text = "*{}* has the following settings for the *{}* module:\n\n".format(escape_markdown(chat.title),
                                                                                     CHAT_SETTINGS[
                                                                                         module].__mod_name__) + \
                   CHAT_SETTINGS[module].__chat_settings__(bot, update, chat, chatP, user)
            query.message.reply_text(
                text=text,
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=InlineKeyboardMarkup([[
                    InlineKeyboardButton(
                        text="Back",
                        callback_data="stngs_back({})".format(chat_id))
                ]]))

        elif prev_match:
            chat_id = prev_match.group(1)
            curr_page = int(prev_match.group(2))
            chat = bot.get_chat(chat_id)
            query.message.reply_text(tld(
                user.id, "send-group-settings").format(chat.title),
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(curr_page - 1,
                                                          CHAT_SETTINGS,
                                                          "stngs",
                                                          chat=chat_id)))

        elif next_match:
            chat_id = next_match.group(1)
            next_page = int(next_match.group(2))
            chat = bot.get_chat(chat_id)
            query.message.reply_text(tld(
                user.id, "send-group-settings").format(chat.title),
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(next_page + 1,
                                                          CHAT_SETTINGS,
                                                          "stngs",
                                                          chat=chat_id)))

        elif back_match:
            chat_id = back_match.group(1)
            chat = bot.get_chat(chat_id)
            query.message.reply_text(text=tld(user.id,
                                              "send-group-settings").format(
                                                  escape_markdown(chat.title)),
                                     parse_mode=ParseMode.MARKDOWN,
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(user.id,
                                                          0,
                                                          CHAT_SETTINGS,
                                                          "stngs",
                                                          chat=chat_id)))

        # ensure no spinny white circle
        bot.answer_callback_query(query.id)
        query.message.delete()
    except BadRequest as excp:
        if excp.message == "Message is not modified":
            pass
        elif excp.message == "Query_id_invalid":
            pass
        elif excp.message == "Message can't be deleted":
            pass
        else:
            LOGGER.exception("Exception in settings buttons. %s",
                             str(query.data))
Ejemplo n.º 28
0
def get(bot, update, notename, show_none=True, no_format=False):
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    conn = connected(bot, update, chat, user.id, need_admin=False)
    if conn:
        chat_id = conn
        send_id = user.id
    else:
        chat_id = update.effective_chat.id
        send_id = chat_id

    note = sql.get_note(chat_id, notename)
    message = update.effective_message  # type: Optional[Message]

    if note:
        pass
    elif notename[0] == "#":
        hashnote = sql.get_note(chat_id, notename[1:])
        if hashnote:
            note = hashnote
    elif show_none:
        message.reply_text(tld(chat.id, "note_not_existed"))
        return

    # If we're replying to a message, reply to that message (unless it's an error)
    if message.reply_to_message:
        reply_id = message.reply_to_message.message_id
    else:
        reply_id = message.message_id

    if note.is_reply:
        if MESSAGE_DUMP:
            try:
                bot.forward_message(chat_id=chat_id,
                                    from_chat_id=MESSAGE_DUMP,
                                    message_id=note.value)
            except BadRequest as excp:
                if excp.message == "Message to forward not found":
                    message.reply_text(tld(chat.id, "note_lost"))
                    sql.rm_note(chat_id, notename)
                else:
                    raise
        else:
            try:
                bot.forward_message(chat_id=chat_id,
                                    from_chat_id=chat_id,
                                    message_id=note.value)

            except BadRequest as excp:
                if excp.message == "Message to forward not found":
                    message.reply_text(tld(chat.id, "note_msg_del"))
                sql.rm_note(chat_id, notename)

            else:
                raise
    else:
        text = note.value
        keyb = []
        parseMode = ParseMode.MARKDOWN
        buttons = sql.get_buttons(chat_id, notename)
        if no_format:
            parseMode = None
            text += revert_buttons(buttons)
        else:
            keyb = build_keyboard(buttons)

        keyboard = InlineKeyboardMarkup(keyb)

        try:
            if note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT):
                try:
                    bot.send_message(send_id,
                                     text,
                                     reply_to_message_id=reply_id,
                                     parse_mode=parseMode,
                                     disable_web_page_preview=True,
                                     reply_markup=keyboard)
                except BadRequest as excp:
                    if excp.message == "Wrong http url":
                        failtext = tld(chat.id, "note_url_invalid")
                        failtext += "\n\n```\n{}```".format(
                            note.value + revert_buttons(buttons))
                        message.reply_text(failtext, parse_mode="markdown")
                    pass
            else:
                ENUM_FUNC_MAP[note.msgtype](send_id,
                                            note.file,
                                            caption=text,
                                            reply_to_message_id=reply_id,
                                            parse_mode=parseMode,
                                            disable_web_page_preview=True,
                                            reply_markup=keyboard)

        except BadRequest as excp:
            if excp.message == "Entity_mention_user_invalid":
                message.reply_text(tld(chat.id, "note_mention_invalid"))

            elif FILE_MATCHER.match(note.value):
                message.reply_text(tld(chat.id, "note_incorrect_import"))
                sql.rm_note(chat_id, notename)
            else:
                message.reply_text(tld(chat.id, "note_cannot_send"))
                LOGGER.exception("Could not parse message #%s in chat %s",
                                 notename, str(chat_id))
                LOGGER.warning("Message was: %s", str(note.value))

    return
Ejemplo n.º 29
0
def temp_nomedia(bot: Bot, update: Update, args: List[str]) -> str:
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    message = update.effective_message  # type: Optional[Message]

    conn = connected(bot, update, chat, user.id)
    if not conn == False:
        chatD = dispatcher.bot.getChat(conn)
    else:
        if chat.type == "private":
            exit(1)
        else:
            chatD = chat

    user_id, reason = extract_user_and_text(message, args)

    if not user_id:
        message.reply_text(
            tld(chat.id, "gajelas, kasi username buat gua mute, gblk."))
        return ""

    try:
        member = chat.get_member(user_id)
    except BadRequest as excp:
        if excp.message == "User not found":
            message.reply_text(tld(chat.id, "egk bisa emut dia."))
            return ""
        else:
            raise

    if is_user_admin(chat, user_id, member):
        message.reply_text(
            tld(chat.id, "pengennya gua ge ngemut dia, ttapi... dia admin"))
        return ""

    if user_id == bot.id:
        message.reply_text(tld(chat.id, "egk mau!"))
        return ""

    if not reason:
        message.reply_text(tld(chat.id, "masukin format waktu yang bener!"))
        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 RESTRICTED" \
          "\n<b>• Admin:</b> {}" \
          "\n<b>• User:</b> {}" \
          "\n<b>• ID:</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), user_id, 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,
                                     can_send_messages=True,
                                     can_send_media_messages=False,
                                     can_send_other_messages=False,
                                     can_add_web_page_previews=False)
            message.reply_text(
                tld(chat.id,
                    "Restricted from sending media for {} in {}!").format(
                        time_val, chatD.title))
            return log
        else:
            message.reply_text(
                tld(chat.id, "ok gua emut dia di {}.").format(chatD.title))

    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            message.reply_text(tld(chat.id, "gua emut {} di {}!").format(
                time_val, chatD.title),
                               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(tld(chat.id, "anjimmm gabisa."))

    return ""
Ejemplo n.º 30
0
def runban(bot: Bot, update: Update, args: List[str]):
    chat = update.effective_chat
    message = update.effective_message

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

    user_id, chat_id = extract_user_and_text(message, args)

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

    try:
        chat = bot.get_chat(chat_id.split()[0])
    except BadRequest as excp:
        if excp.message == "Chat not found":
            message.reply_text(
                "Chat not found! Make sure you entered a valid chat ID and I'm part of that chat."
            )
            return
        else:
            raise

    if chat.type == 'private':
        message.reply_text("I'm sorry, but that's a private chat!")
        return

    if not is_bot_admin(chat, bot.id) or not chat.get_member(
            bot.id).can_restrict_members:
        message.reply_text(
            "I can't unrestrict people there! Make sure I'm admin and can unban users."
        )
        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 there")
            return
        else:
            raise

    if is_user_in_chat(chat, user_id):
        message.reply_text(
            "Why are you trying to remotely unban someone that's already in that chat?"
        )
        return

    if user_id == bot.id:
        message.reply_text("I'm not gonna UNBAN myself, I'm an admin there!")
        return

    try:
        chat.unban_member(user_id)
        message.reply_text("Yep, this user can join that chat!")
    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            message.reply_text('Unbanned!', quote=False)
        elif excp.message in RUNBAN_ERRORS:
            message.reply_text(excp.message)
        else:
            LOGGER.warning(update)
            LOGGER.exception(
                "ERROR unbanning 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 unban that user.")