示例#1
0
    def send_log(context: CallbackContext, log_chat_id: str, orig_chat_id: str,
                 result: str):
        bot = context.bot
        try:
            bot.send_message(
                log_chat_id,
                result,
                parse_mode=ParseMode.HTML,
                disable_web_page_preview=True,
            )
        except BadRequest as excp:
            if excp.message == "Chat not found":
                bot.send_message(
                    orig_chat_id,
                    "This log channel has been deleted - unsetting.")
                sql.stop_chat_logging(orig_chat_id)
            else:
                log.warning(excp.message)
                log.warning(result)
                log.exception("Could not parse")

                bot.send_message(
                    log_chat_id,
                    result +
                    "\n\nFormatting has been disabled due to an unexpected error.",
                )
def check_and_ban(update, user_id, should_message=True):
    chat = update.effective_chat  # type: Optional[Chat]
    try:
        sw_ban = sw.get_ban(int(user_id))
    except AttributeError:
        sw_ban = None
    except (SpamWatchError, Error, UnauthorizedError, NotFoundError, Forbidden,
            TooManyRequests) as e:
        log.warning(f" SpamWatch Error: {e}")
        sw_ban = None

    if sw_ban:
        chat.ban_member(user_id)
        if should_message:
            update.effective_message.reply_text(
                f"This person has been detected as a spammer by @SpamWatch and has been removed!\nReason: <code>{sw_ban.reason}</code>",
                parse_mode=ParseMode.HTML,
            )
        return

    if sql.is_user_gbanned(user_id):
        update.effective_chat.ban_member(user_id)
        if should_message:
            text = (f"<b>Alert</b>: this user is globally banned.\n"
                    f"<code>*bans them from here*</code>.\n"
                    f"<b>Appeal chat</b>: @YorkTownEagleUnion\n"
                    f"<b>User ID</b>: <code>{user_id}</code>")
            user = sql.get_gbanned_user(user_id)
            if user.reason:
                text += f"\n<b>Ban Reason:</b> <code>{html.escape(user.reason)}</code>"
            update.effective_message.reply_text(text,
                                                parse_mode=ParseMode.HTML)
示例#3
0
def check_and_ban(update, user_id, should_message=True):

    chat = update.effective_chat  # type: Optional[Chat]
    if SPB_MODE:
        try:
            status = client.raw_output(int(user_id))
            try:
                bl_check = status["results"]["attributes"]["is_blacklisted"]
            except:
                bl_check = False

            if bl_check is True:
                bl_res = status["results"]["attributes"]["blacklist_reason"]
                update.effective_chat.kick_member(user_id)
                if should_message:
                    update.effective_message.reply_text(
                        f"This person was blacklisted on @SpamProtectionBot and has been removed!\nReason: <code>{bl_res}</code>",
                        parse_mode=ParseMode.HTML,
                    )
        except HostDownError:
            log.warning("Spam Protection API is unreachable.")

    try:
        sw_ban = sw.get_ban(int(user_id))
    except AttributeError:
        sw_ban = None
    except (
            SpamWatchError,
            Error,
            UnauthorizedError,
            NotFoundError,
            Forbidden,
            TooManyRequests,
    ) as e:
        log.warning(f" SpamWatch Error: {e}")
        sw_ban = None

    if sw_ban:
        update.effective_chat.kick_member(user_id)
        if should_message:
            update.effective_message.reply_text(
                f"This person has been detected as a spammer by @SpamWatch and has been removed!\nReason: <code>{sw_ban.reason}</code>",
                parse_mode=ParseMode.HTML,
            )
        return

    if sql.is_user_gbanned(user_id):
        update.effective_chat.kick_member(user_id)
        if should_message:
            text = (f"<b>Alert</b>: this user is globally banned.\n"
                    f"<code>*bans them from here*</code>.\n"
                    f"<b>Appeal chat</b>: @YorkTownEagleUnion\n"
                    f"<b>User ID</b>: <code>{user_id}</code>")
            user = sql.get_gbanned_user(user_id)
            if user.reason:
                text += f"\n<b>Ban Reason:</b> <code>{html.escape(user.reason)}</code>"
            update.effective_message.reply_text(text,
                                                parse_mode=ParseMode.HTML)
def check_and_ban(update, user_id, should_message=True):
    from tg_bot import SPB_MODE
    chat = update.effective_chat  # type: Optional[Chat]
    if SPB_MODE:
        try:
            apst = requests.get(
                f'https://api.intellivoid.net/spamprotection/v1/lookup?query={update.effective_user.id}')
            api_status = apst.status_code
            if api_status == 200:
                try:
                    status = client.raw_output(int(user_id))
                    try:
                        bl_check = (status["results"]["attributes"]["is_blacklisted"])
                    except:
                        bl_check = False

                    if bl_check:
                        bl_res = (status["results"]["attributes"]["blacklist_reason"])
                        update.effective_chat.kick_member(user_id)
                        if should_message:
                            update.effective_message.reply_text(
                                f"This person was blacklisted on @SpamProtectionBot and has been removed!\nReason: <code>{bl_res}</code>",
                                parse_mode=ParseMode.HTML,
                            )
                except HostDownError:
                    log.warning("Spam Protection API is unreachable.")
        except BaseException as e:
            log.info(f'SpamProtection was disabled due to {e}')
    try:
        sw_ban = sw.get_ban(int(user_id))
    except AttributeError:
        sw_ban = None
    except (SpamWatchError, Error, UnauthorizedError, NotFoundError, Forbidden, TooManyRequests) as e:
        log.warning(f" SpamWatch Error: {e}")
        sw_ban = None

    if sw_ban:
        update.effective_chat.kick_member(user_id)
        if should_message:
            update.effective_message.reply_text(
                f"This person has been detected as a spammer by @SpamWatch and has been removed!\nReason: <code>{sw_ban.reason}</code>",
                parse_mode=ParseMode.HTML,
            )
        return

    if sql.is_user_gbanned(user_id):
        update.effective_chat.kick_member(user_id)
        if should_message:
            text = (
                f"<b>Alert</b>: this user is globally banned.\n"
                f"<code>*bans them from here*</code>.\n"
                f"<b>Appeal chat</b>: @zerounions\n"
                f"<b>User ID</b>: <code>{user_id}</code>"
            )
            user = sql.get_gbanned_user(user_id)
            if user.reason:
                text += f"\n<b>Ban Reason:</b> <code>{html.escape(user.reason)}</code>"
            update.effective_message.reply_text(text, parse_mode=ParseMode.HTML)
示例#5
0
def get_exception(excp, filt, chat):
    if excp.message == "Unsupported url protocol":
        return "You seem to be trying to use the URL protocol which is not supported. Telegram does not support key for multiple protocols, such as tg: //. Please try again!"
    if excp.message == "Reply message not found":
        return "noreply"
    log.warning("Message %s could not be parsed", str(filt.reply))
    log.exception("Could not parse filter %s in chat %s", str(filt.keyword),
                  str(chat.id))
    return "This data could not be sent because it is incorrectly formatted."
示例#6
0
def detect_spam(update, context):
    url = "https://api.intellivoid.net/coffeehouse/v1/nlp/spam_prediction/chatroom"
    user = update.effective_user
    chat = update.effective_chat
    msg = update.effective_message
    bot = context.bot
    if user.id == bot.id:
        return

    from tg_bot import SPB_MODE, CF_API_KEY
    chat_state = sql.does_chat_nlp(chat.id)
    if SPB_MODE and CF_API_KEY and chat_state == True:
        try:
            payload = {'access_key': CF_API_KEY, 'input': msg}
            data = requests.post(url, data=payload)
            res_json = data.json()
            if res_json['success']:
                spam_check = res_json['results']['spam_prediction']['is_spam']
                if spam_check == True:
                    pred = res_json['results']['spam_prediction']['prediction']
                    try:
                        bot.restrict_chat_member(
                            chat.id, user.id,
                            telegram.ChatPermissions(can_send_messages=False))
                        msg.reply_text(
                            f"*⚠ SPAM DETECTED!*\nSpam Prediction: `{pred}`\nUser: `{telegram.utils.helpers.mention_markdown(user.id)}` was muted.",
                            parse_mode=telegram.ParseMode.MARKDOWN,
                        )
                    except telegram.BadRequest:
                        msg.reply_text(
                            f"*⚠ SPAM DETECTED!*\nSpam Prediction: `{pred}`\nUser: `{telegram.utils.helpers.mention_markdown(user.id)}`\nUser could not be restricted due to insufficient admin perms.",
                            parse_mode=telegram.ParseMode.MARKDOWN,
                        )

            elif res_json['error']['error_code'] == 21:
                reduced_msg = msg[0:170]
                payload = {'access_key': CF_API_KEY, 'input': reduced_msg}
                data = requests.post(url, data=payload)
                res_json = data.json()
                spam_check = res_json['results']['spam_prediction']['is_spam']
                if spam_check is True:
                    pred = res_json['results']['spam_prediction']['prediction']
                    try:
                        bot.restrict_chat_member(
                            chat.id, user.id,
                            telegram.ChatPermissions(can_send_messages=False))
                        msg.reply_text(
                            f"*⚠ SPAM DETECTED!*\nSpam Prediction: `{pred}`\nUser: `{telegram.utils.helpers.mention_markdown(user.id)}` was muted.",
                            parse_mode=telegram.ParseMode.MARKDOWN)
                    except telegram.BadRequest:
                        msg.reply_text(
                            f"*⚠ SPAM DETECTED!*\nSpam Prediction: `{pred}`\nUser: `{telegram.utils.helpers.mention_markdown(user.id)}`\nUser could not be restricted due to insufficient admin perms.",
                            parse_mode=telegram.ParseMode.MARKDOWN)
        except BaseException as e:
            log.warning(f"Can't reach SpamProtection API due to {e}")
            return
示例#7
0
async def detect_spam(client, message):
    url = "https://api.intellivoid.net/coffeehouse/v1/nlp/spam_prediction/chatroom"
    user = message.from_user
    chat = message.chat
    msg = message.text
    if user.id == KigyoINIT.bot_id:
        return

    chat_state = sql.does_chat_nlp(chat.id)
    if SPB_MODE and CF_API_KEY and chat_state == True:
        try:
            payload = {'access_key': CF_API_KEY, 'input': msg}
            data = await session.post(url, data=payload)
            res_json = await data.json()
            if res_json['success']:
                spam_check = res_json['results']['spam_prediction']['is_spam']
                if spam_check == True:
                    pred = res_json['results']['spam_prediction']['prediction']
                    try:
                        await kp.restrict_chat_member(
                            chat.id, user.id,
                            ChatPermissions(can_send_messages=False))
                        await message.reply_text(
                            f"**⚠ SPAM DETECTED!**\nSpam Prediction: `{pred}`\nUser: `{user.id}` was muted.",
                            parse_mode="md",
                        )
                    except BadRequest:
                        await message.reply_text(
                            f"**⚠ SPAM DETECTED!**\nSpam Prediction: `{pred}`\nUser: `{user.id}`\nUser could not be restricted due to insufficient admin perms.",
                            parse_mode="md",
                        )

            elif res_json['error']['error_code'] == 21:
                reduced_msg = msg[0:170]
                payload = {'access_key': CF_API_KEY, 'input': reduced_msg}
                data = await session.post(url, data=payload)
                res_json = await data.json()
                spam_check = res_json['results']['spam_prediction']['is_spam']
                if spam_check is True:
                    pred = res_json['results']['spam_prediction']['prediction']
                    try:
                        await kp.restrict_chat_member(
                            chat.id, user.id,
                            ChatPermissions(can_send_messages=False))
                        await message.reply_text(
                            f"**⚠ SPAM DETECTED!**\nSpam Prediction: `{pred}`\nUser: `{user.id}` was muted.",
                            parse_mode="markdown")
                    except BadRequest:
                        await message.reply_text(
                            f"**⚠ SPAM DETECTED!**\nSpam Prediction: `{pred}`\nUser: `{user.id}`\nUser could not be restricted due to insufficient admin perms.",
                            parse_mode="markdown")
        except (aiohttp.ClientConnectionError, asyncio.TimeoutError,
                aiohttp.ContentTypeError) as e:
            log.warning(f"Can't reach SpamProtection API due to {e}")
            await asyncio.sleep(0.5)
示例#8
0
async def detect_spam(client, message):
    url = "https://api.intellivoid.net/coffeehouse/v1/nlp/spam_prediction/chatroom"
    user = message.from_user
    chat = message.chat
    msg = message.text
    chat_state = sql.does_chat_nlp(chat.id)
    if SPB_MODE and CF_API_KEY and chat_state == True:
        try:
            payload = {"access_key": CF_API_KEY, "input": msg}
            data = await session.post(url, data=payload)
            res_json = await data.json()
            if res_json["success"]:
                spam_check = res_json["results"]["spam_prediction"]["is_spam"]
                if spam_check == True:
                    pred = res_json["results"]["spam_prediction"]["prediction"]
                    await kp.restrict_chat_member(
                        chat.id, user.id,
                        ChatPermissions(can_send_messages=False))
                    try:
                        await message.reply_text(
                            f"**⚠ SPAM DETECTED!**\nSpam Prediction: `{pred}`\nUser: `{user.id}` was muted.",
                            parse_mode="md",
                        )
                    except BadRequest:
                        await message.reply_text(
                            f"**⚠ SPAM DETECTED!**\nSpam Prediction: `{pred}`\nUser: `{user.id}`\nUser could not be restricted due to insufficient admin perms.",
                            parse_mode="md",
                        )

            elif res_json["error"]["error_code"] == 21:
                reduced_msg = msg[0:170]
                payload = {"access_key": CF_API_KEY, "input": reduced_msg}
                data = await session.post(url, data=payload)
                res_json = await data.json()
                spam_check = res_json["results"]["spam_prediction"]["is_spam"]
                if spam_check is True:
                    pred = res_json["results"]["spam_prediction"]["prediction"]
                    await kp.restrict_chat_member(
                        chat.id, user.id,
                        ChatPermissions(can_send_messages=False))
                    try:
                        await message.reply_text(
                            f"**⚠ SPAM DETECTED!**\nSpam Prediction: `{pred}`\nUser: `{user.id}` was muted.",
                            parse_mode="markdown",
                        )
                    except BadRequest:
                        await message.reply_text(
                            f"**⚠ SPAM DETECTED!**\nSpam Prediction: `{pred}`\nUser: `{user.id}`\nUser could not be restricted due to insufficient admin perms.",
                            parse_mode="markdown",
                        )
        except (aiohttp.ClientConnectionError, asyncio.TimeoutError):
            log.warning("Can't reach SpamProtection API")
            await asyncio.sleep(0.5)
def reply_filter(update, context):
    chat = update.effective_chat  # type: Optional[Chat]
    message = update.effective_message  # type: Optional[Message]

    if not update.effective_user or update.effective_user.id == 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.reply == "there is should be a new reply":
                buttons = sql.get_buttons(chat.id, filt.keyword)
                keyb = build_keyboard_parser(context.bot, chat.id, buttons)
                keyboard = InlineKeyboardMarkup(keyb)

                VALID_WELCOME_FORMATTERS = [
                    "first",
                    "last",
                    "fullname",
                    "username",
                    "id",
                    "chatname",
                    "mention",
                ]
                if filt.reply_text:
                    valid_format = escape_invalid_curly_brackets(
                        filt.reply_text, VALID_WELCOME_FORMATTERS)
                    if valid_format:
                        filtext = valid_format.format(
                            first=escape(message.from_user.first_name),
                            last=escape(message.from_user.last_name
                                        or message.from_user.first_name),
                            fullname=" ".join(
                                [
                                    escape(message.from_user.first_name),
                                    escape(message.from_user.last_name),
                                ] if message.from_user.last_name else
                                [escape(message.from_user.first_name)]),
                            username="******" + escape(message.from_user.username)
                            if message.from_user.username else mention_html(
                                message.from_user.id,
                                message.from_user.first_name),
                            mention=mention_html(message.from_user.id,
                                                 message.from_user.first_name),
                            chatname=escape(message.chat.title)
                            if message.chat.type != "private" else escape(
                                message.from_user.first_name),
                            id=message.from_user.id,
                        )
                    else:
                        filtext = ""
                else:
                    filtext = ""

                if filt.file_type in (sql.Types.BUTTON_TEXT, sql.Types.TEXT):
                    try:
                        context.bot.send_message(
                            chat.id,
                            markdown_to_html(filtext),
                            reply_to_message_id=message.message_id,
                            parse_mode=ParseMode.HTML,
                            disable_web_page_preview=True,
                            reply_markup=keyboard,
                        )
                    except BadRequest as excp:
                        error_catch = get_exception(excp, filt, chat)
                        if error_catch == "noreply":
                            try:
                                context.bot.send_message(
                                    chat.id,
                                    markdown_to_html(filtext),
                                    parse_mode=ParseMode.HTML,
                                    disable_web_page_preview=True,
                                    reply_markup=keyboard,
                                )
                            except BadRequest as excp:
                                log.exception("Error in filters: " +
                                              excp.message)
                                send_message(
                                    update.effective_message,
                                    get_exception(excp, filt, chat),
                                )
                        else:
                            try:
                                send_message(
                                    update.effective_message,
                                    get_exception(excp, filt, chat),
                                )
                            except BadRequest as excp:
                                log.exception("Failed to send message: " +
                                              excp.message)
                                pass
                else:
                    if ENUM_FUNC_MAP[
                            filt.file_type] == dispatcher.bot.send_sticker:
                        ENUM_FUNC_MAP[filt.file_type](
                            chat.id,
                            filt.file_id,
                            reply_to_message_id=message.message_id,
                            reply_markup=keyboard,
                        )
                    else:
                        ENUM_FUNC_MAP[filt.file_type](
                            chat.id,
                            filt.file_id,
                            caption=markdown_to_html(filtext),
                            reply_to_message_id=message.message_id,
                            parse_mode=ParseMode.HTML,
                            reply_markup=keyboard,
                        )
                break
            else:
                if filt.is_sticker:
                    message.reply_sticker(filt.reply)
                elif filt.is_document:
                    message.reply_document(filt.reply)
                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:
                    message.reply_video(filt.reply)
                elif filt.has_markdown:
                    buttons = sql.get_buttons(chat.id, filt.keyword)
                    keyb = build_keyboard_parser(context.bot, chat.id, buttons)
                    keyboard = InlineKeyboardMarkup(keyb)

                    try:
                        send_message(
                            update.effective_message,
                            filt.reply,
                            parse_mode=ParseMode.MARKDOWN,
                            disable_web_page_preview=True,
                            reply_markup=keyboard,
                        )
                    except BadRequest as excp:
                        if excp.message == "Unsupported url protocol":
                            try:
                                send_message(
                                    update.effective_message,
                                    "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...",
                                )
                            except BadRequest as excp:
                                log.exception("Error in filters: " +
                                              excp.message)
                                pass
                        elif excp.message == "Reply message not found":
                            try:
                                context.bot.send_message(
                                    chat.id,
                                    filt.reply,
                                    parse_mode=ParseMode.MARKDOWN,
                                    disable_web_page_preview=True,
                                    reply_markup=keyboard,
                                )
                            except BadRequest as excp:
                                log.exception("Error in filters: " +
                                              excp.message)
                                pass
                        else:
                            try:
                                send_message(
                                    update.effective_message,
                                    "This message couldn't be sent as it's incorrectly formatted.",
                                )
                            except BadRequest as excp:
                                log.exception("Error in filters: " +
                                              excp.message)
                                pass
                            log.warning("Message %s could not be parsed",
                                        str(filt.reply))
                            log.exception(
                                "Could not parse filter %s in chat %s",
                                str(filt.keyword),
                                str(chat.id),
                            )

                else:
                    # LEGACY - all new filters will have has_markdown set to True.
                    try:
                        send_message(update.effective_message, filt.reply)
                    except BadRequest as excp:
                        log.exception("Error in filters: " + excp.message)
                        pass
                break
示例#10
0
def get(update, context, notename, show_none=True, no_format=False):
    bot = context.bot
    chat_id = update.effective_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 JOIN_LOGGER:
                try:
                    bot.forward_message(
                        chat_id=chat_id, from_chat_id=JOIN_LOGGER, 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:
            VALID_NOTE_FORMATTERS = [
                "first",
                "last",
                "fullname",
                "username",
                "id",
                "chatname",
                "mention",
            ]
            valid_format = escape_invalid_curly_brackets(
                note.value, VALID_NOTE_FORMATTERS
            )
            if valid_format:
                text = valid_format.format(
                    first=escape_markdown(message.from_user.first_name),
                    last=escape_markdown(
                        message.from_user.last_name or message.from_user.first_name
                    ),
                    fullname=escape_markdown(
                        " ".join(
                            [message.from_user.first_name, message.from_user.last_name]
                            if message.from_user.last_name
                            else [message.from_user.first_name]
                        )
                    ),
                    username="******" + message.from_user.username
                    if message.from_user.username
                    else mention_markdown(
                        message.from_user.id, message.from_user.first_name
                    ),
                    mention=mention_markdown(
                        message.from_user.id, message.from_user.first_name
                    ),
                    chatname=escape_markdown(
                        message.chat.title
                        if message.chat.type != "private"
                        else message.from_user.first_name
                    ),
                    id=message.from_user.id,
                )
            else:
                text = ""

            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(
                        chat_id,
                        text,
                        reply_to_message_id=reply_id,
                        parse_mode=parseMode,
                        reply_markup=keyboard,
                    )
                else:
                    if ENUM_FUNC_MAP[note.msgtype] == dispatcher.bot.send_sticker:
                        ENUM_FUNC_MAP[note.msgtype](
                            chat_id,
                            note.file,
                            reply_to_message_id=reply_id,
                            reply_markup=keyboard,
                        )
                    else:
                        ENUM_FUNC_MAP[note.msgtype](
                            chat_id,
                            note.file,
                            caption=text,
                            reply_to_message_id=reply_id,
                            parse_mode=parseMode,
                            reply_markup=keyboard,
                        )

            except BadRequest as excp:
                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 in "
                        f"@YorkTownEagleUnion if you can't figure out why!"
                    )
                    log.exception(
                        "Could not parse message #%s in chat %s", notename, str(chat_id)
                    )
                    log.warning("Message was: %s", str(note.value))
        return
    elif show_none:
        message.reply_text("This note doesn't exist")
示例#11
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.MARKDOWN,
            reply_markup=keyboard,
            reply_to_message_id=reply,
        )
    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,
                reply_to_message_id=reply,
            )

        elif excp.message == 'Have no rights to send a message':
            return
        elif excp.message == 'Reply message not found':
            msg = update.effective_message.reply_text(
                message,
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=keyboard,
                quote=False,
            )

        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,
                reply_to_message_id=reply,
            )

        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,
                reply_to_message_id=reply,
            )

            log.warning(message)
            log.warning(keyboard)
            log.exception('Could not parse! got invalid url host errors')
        else:
            msg = update.effective_message.reply_text(
                markdown_parser((
                    backup_message +
                    '\nNote: An error occured when sending the custom message. Please update.'
                )),
                parse_mode=ParseMode.MARKDOWN,
                reply_to_message_id=reply,
            )

            log.exception()
    return msg
示例#12
0
def ban(update, context):
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    message = update.effective_message  # type: Optional[Message]
    args = context.args
    log_message = ""
    user_id, reason = extract_user_and_text(message, args)

    if not user_id:
        message.reply_text("I doubt that's a user.")
        return log_message

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

    if user_id == context.bot.id:
        message.reply_text("Oh yeah, ban myself, noob!")
        return log_message

    if is_user_ban_protected(chat, user_id, member) and user not in DEV_USERS:
        if user_id == OWNER_ID:
            message.reply_text("I'd never ban my owner.")
            return log_message
        elif user_id in DEV_USERS:
            message.reply_text("I can't act against our own.")
            return log_message
        elif user_id in SUDO_USERS:
            message.reply_text("My sudos are ban immune")
            return log_message
        elif user_id in SUPPORT_USERS:
            message.reply_text("My support users are ban immune")
            return log_message
        elif user_id in SARDEGNA_USERS:
            message.reply_text(
                "Bring an order from Eagle Union to fight a Sardegna.")
            return log_message
        elif user_id in WHITELIST_USERS:
            message.reply_text("Neptunians are ban immune!")
            return log_message
        else:
            message.reply_text("This user has immunity and cannot be banned.")
            return log_message

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

    try:
        chat.kick_member(user_id)
        # context.bot.send_sticker(chat.id, BAN_STICKER)  # banhammer marie sticker
        context.bot.sendMessage(
            chat.id,
            "let {} walk the plank.".format(
                mention_html(member.user.id, member.user.first_name)),
            parse_mode=ParseMode.HTML,
        )
        return log

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

    return ""
示例#13
0
def temp_ban(update: Update, context: CallbackContext) -> str:
    chat = update.effective_chat
    user = update.effective_user
    message = update.effective_message
    log_message = ""
    bot, args = context.bot, context.args
    user_id, reason = extract_user_and_text(message, args)

    if not user_id:
        message.reply_text("I doubt that's a user.")
        return log_message

    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 log_message
        else:
            raise

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

    if is_user_ban_protected(chat, user_id, member):
        message.reply_text("I don't feel like it.")
        return log_message

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

    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_message

    log = (
        f"<b>{html.escape(chat.title)}:</b>\n"
        "#TEMP BANNED\n"
        f"<b>Admin:</b> {mention_html(user.id, user.first_name)}\n"
        f"<b>User:</b> {mention_html(member.user.id, member.user.first_name)}\n"
        f"<b>Time:</b> {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
        bot.sendMessage(
            chat.id,
            f"Banned! User {mention_html(member.user.id, member.user.first_name)} "
            f"will be banned for {time_val}.",
            parse_mode=ParseMode.HTML,
        )
        return log

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

    return log_message
示例#14
0
def temp_mute(update: Update, context: CallbackContext) -> str:
    bot, args = context.bot, context.args
    chat = update.effective_chat
    user = update.effective_user
    message = update.effective_message

    user_id, reason = extract_user_and_text(message, args)
    reply = check_user(user_id, bot, chat)

    if reply:
        message.reply_text(reply)
        return ""

    member = chat.get_member(user_id)

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

    split_reason = reason.split(None, 1)

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

    mutetime = extract_time(message, time_val)

    if not mutetime:
        return ""

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

    try:
        if member.can_send_messages is None or member.can_send_messages:
            chat_permissions = ChatPermissions(can_send_messages=False)
            bot.restrict_chat_member(chat.id,
                                     user_id,
                                     chat_permissions,
                                     until_date=mutetime)
            bot.sendMessage(
                chat.id,
                f"Muted <b>{html.escape(member.user.first_name)}</b> for {time_val}!",
                parse_mode=ParseMode.HTML,
            )
            return log
        else:
            message.reply_text("This user is already muted.")

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

    return ""
示例#15
0
def send(update, message, keyboard, backup_message):
    chat = update.effective_chat
    reply = None

    try:
        msg = update.effective_chat.send_message(
            message,
            parse_mode=ParseMode.MARKDOWN,
            reply_markup=keyboard,
            reply_to_message_id=reply,
        )
    except BadRequest as excp:
        if excp.message == "Reply message not found":
            msg = update.effective_chat.send_message(
                message,
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=keyboard,
                quote=False,
            )
        elif excp.message == "Button_url_invalid":
            msg = update.effective_chat.send_message(
                markdown_parser(
                    backup_message +
                    "\nNote: the current message has an invalid url "
                    "in one of its buttons. Please update."),
                parse_mode=ParseMode.MARKDOWN,
                reply_to_message_id=reply,
            )
        elif excp.message == "Unsupported url protocol":
            msg = update.effective_chat.send_message(
                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,
                reply_to_message_id=reply,
            )
        elif excp.message == "Wrong url host":
            msg = update.effective_chat.send_message(
                markdown_parser(
                    backup_message +
                    "\nNote: the current message has some bad urls. "
                    "Please update."),
                parse_mode=ParseMode.MARKDOWN,
                reply_to_message_id=reply,
            )
            log.warning(message)
            log.warning(keyboard)
            log.exception("Could not parse! got invalid url host errors")
        elif excp.message == "Have no rights to send a message":
            return
        else:
            msg = update.effective_chat.send_message(
                markdown_parser(backup_message +
                                "\nNote: An error occured when sending the "
                                "custom message. Please update."),
                parse_mode=ParseMode.MARKDOWN,
                reply_to_message_id=reply,
            )
            log.exception()
    return msg
示例#16
0
def ban(update, context):
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    message = update.effective_message  # type: Optional[Message]
    args = context.args
    log_message = ""
    user_id, reason = extract_user_and_text(message, args)

    if not user_id:
        message.reply_text("I doubt that's a user.")
        return log_message

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

    if user_id == context.bot.id:
        message.reply_text("Why are You being mean to me!")
        return log_message

    if is_user_ban_protected(chat, user_id, member) and user not in DEV_USERS:
        if user_id == OWNER_ID:
            message.reply_text("Trying to put me against my master, huh!.")
            return log_message
        elif user_id in DEV_USERS:
            message.reply_text("I can't act against our own.")
            return log_message
        elif user_id in SUDO_USERS:
            message.reply_text("My sudos are ban immune")
            return log_message
        elif user_id in SUPPORT_USERS:
            message.reply_text("My support users are ban immune")
            return log_message
        elif user_id in TIGER_USERS:
            message.reply_text("This user has immunity and cannot be banned.")
            return log_message
        elif user_id in WHITELIST_USERS:
            message.reply_text("This user has immunity and cannot be banned.")
            return log_message
        else:
            message.reply_text("This user has immunity and cannot be banned.")
            return log_message

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

    try:
        chat.kick_member(user_id)
        # context.bot.send_sticker(chat.id, BAN_STICKER)  # banhammer marie sticker
        reply = (
            f"<code>❕</code><b>Ban Event</b>\n"
            f"<code> </code><b>•  User:</b> {mention_html(member.user.id, html.escape(member.user.first_name))}"
        )
        context.bot.sendMessage(
            chat.id,
            reply,
            parse_mode=ParseMode.HTML,
        )
        return log

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

    return ""