Beispiel #1
0
def help_button(bot: Bot, update: Update):
    query = update.callback_query
    chat = update.effective_chat
    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)
    mod_match = re.match(r"help_module\((.+?)\)", 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)

            bot.edit_message_text(chat_id=query.message.chat_id,
                                  message_id=query.message.message_id,
                                  text=text,
                                  parse_mode=ParseMode.MARKDOWN,
                                  reply_markup=InlineKeyboardMarkup([[
                                      InlineKeyboardButton(
                                          text=tld(chat.id, "btn_go_back"),
                                          callback_data="help_back")
                                  ]]),
                                  disable_web_page_preview=True)

        elif prev_match:
            curr_page = int(prev_match.group(1))
            bot.edit_message_text(chat_id=query.message.chat_id,
                                  message_id=query.message.message_id,
                                  text=tld(chat.id, "send-help").format(
                                      dispatcher.bot.first_name,
                                      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))
            bot.edit_message_text(chat_id=query.message.chat_id,
                                  message_id=query.message.message_id,
                                  text=tld(chat.id, "send-help").format(
                                      dispatcher.bot.first_name,
                                      tld(chat.id, "cmd_multitrigger")),
                                  parse_mode=ParseMode.MARKDOWN,
                                  reply_markup=InlineKeyboardMarkup(
                                      paginate_modules(
                                          chat.id, next_page + 1, HELPABLE,
                                          "help")))

        elif back_match:
            bot.edit_message_text(chat_id=query.message.chat_id,
                                  message_id=query.message.message_id,
                                  text=tld(chat.id, "send-help").format(
                                      dispatcher.bot.first_name,
                                      tld(chat.id, "cmd_multitrigger")),
                                  parse_mode=ParseMode.MARKDOWN,
                                  reply_markup=InlineKeyboardMarkup(
                                      paginate_modules(chat.id, 0, HELPABLE,
                                                       "help")),
                                  disable_web_page_preview=True)

        # ensure no spinny white circle
        bot.answer_callback_query(query.id)
        # query.message.delete()

    except BadRequest:
        pass
Beispiel #2
0
def reply_filter(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]
    message = update.effective_message  # type: Optional[Message]
    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(
                            "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."
                        )
                    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 filter could not be sent, as it is incorrectly formatted."
                            )
                            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
Beispiel #3
0
def extract_unt_fedban(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 and not str(user_id).isdigit():
            message.reply_text("I don't have that user in my db. You will be able to interact with them if "
                               "You reply to the person's message, or forward one of the 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") and not str(user_id).isdigit():
            message.reply_text("I don't seem to have interacted with this user before - please forward messages from "
                               "them to give me control! (Like a voodoo doll, I need a piece to be able to"
                               "to execute certain commands...)")
            return None, None
        elif excp.message != "Chat not found":
            LOGGER.exception("Exception %s on user %s", excp.message, user_id)
            return None, None
        elif not str(user_id).isdigit():
            return None, None

    return user_id, text
Beispiel #4
0
def extract_user_and_text(message: Message,
                          args: List[str]) -> (Optional[int], Optional[str]):
    chat = message.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
Beispiel #5
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,
            reply_to_message_id=reply,
            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,
            reply_to_message_id=reply)
    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,
            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 == "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)
            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
Beispiel #6
0
def ban(update, context):
    currentchat = update.effective_chat  # type: Optional[Chat]
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    message = update.effective_message  # type: Optional[Message]
    args = context.args

    user_id, reason = extract_user_and_text(message, args)
    if user_id == "error":
        send_message(update.effective_message,
                     tl(update.effective_message, reason))
        return ""

    conn = connected(context.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,
                tl(update.effective_message,
                   "You can do this command in groups, not PM"))
            return ""
        chat = update.effective_chat
        chat_id = update.effective_chat.id
        chat_name = update.effective_message.chat.title

    check = context.bot.getChatMember(chat_id, context.bot.id)
    if check.status == 'member' or check['can_restrict_members'] is False:
        if conn:
            text = tl(
                update.effective_message,
                "I can not restrict people on {}! Make sure that I am the admin and can appoint a new admin."
            ).format(chat_name)
        else:
            text = tl(
                update.effective_message,
                "I can not restrict people here! Make sure that I am the admin and can appoint a new admin."
            )
        send_message(update.effective_message, text, parse_mode="markdown")
        return ""

    if not user_id:
        send_message(
            update.effective_message,
            tl(update.effective_message,
               "You don't seem to be referring to a user."))
        return ""

    try:
        if conn:
            member = context.bot.getChatMember(chat_id, user_id)
        else:
            member = chat.get_member(user_id)
    except BadRequest as excp:
        if excp.message == "User not found":
            if conn:
                text = tl(
                    update.effective_message,
                    "I can not find this user in *{}* 😣").format(chat_name)
            else:
                text = tl(update.effective_message,
                          "I can not find this user 😣")
            send_message(update.effective_message, text, parse_mode="markdown")
            return ""
        else:
            raise

    if user_id == context.bot.id:
        send_message(
            update.effective_message,
            tl(update.effective_message,
               "Saya tidak akan BAN diri saya sendiri, apakah kamu gila? 😠"))
        return ""

    if is_user_ban_protected(chat, user_id, member):
        send_message(
            update.effective_message,
            tl(update.effective_message,
               "Saya tidak bisa banned orang ini karena dia adalah admin 😒"))
        return ""

    if member['can_restrict_members'] is False:
        if conn:
            text = tl(
                update.effective_message,
                "Anda tidak punya hak untuk membatasi seseorang pada *{}*."
            ).format(chat_name)
        else:
            text = tl(update.effective_message,
                      "Anda tidak punya hak untuk membatasi seseorang.")
        send_message(update.effective_message, text, parse_mode="markdown")
        return ""

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

    try:
        if conn:
            context.bot.kickChatMember(chat_id, user_id)
            context.bot.send_sticker(currentchat.id,
                                     BAN_STICKER)  # banhammer marie sticker
            send_message(update.effective_message,
                         tl(update.effective_message,
                            "Banned on *{}*! 😝").format(chat_name),
                         parse_mode="markdown")
        else:
            chat.kick_member(user_id)
            if message.text.split(None, 1)[0][1:] == "sban":
                update.effective_message.delete()
            else:
                context.bot.send_sticker(
                    chat.id, BAN_STICKER)  # banhammer marie sticker
                send_message(update.effective_message,
                             tl(update.effective_message, "Banned! 😝"))
        return log

    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            send_message(update.effective_message,
                         tl(update.effective_message, "Banned! 😝"),
                         quote=False)
            return log
        elif excp.message == "Message can't be deleted":
            pass
        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)
            send_message(
                update.effective_message,
                tl(update.effective_message,
                   "Well damn, I can't ban that User. 😒"))

    return ""
Beispiel #7
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,
                                                          0,
                                                          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,
                                                          0,
                                                          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))
Beispiel #8
0
def settings_button(update, context):
    query = update.callback_query
    user = update.effective_user
    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 = context.bot.get_chat(chat_id)
            getstatusadmin = context.bot.get_chat_member(chat_id, user.id)
            isadmin = getstatusadmin.status in ('administrator', 'creator')
            if isadmin is False or user.id != OWNER_ID:
                query.message.edit_text("Your admin status has changed")
                return
            text = tl(update.effective_message, "*{}* 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)
            try:
                set_button = CHAT_SETTINGS[module].__chat_settings_btn__(
                    chat_id, user.id)
            except AttributeError:
                set_button = []
            set_button.append([
                InlineKeyboardButton(
                    text=tl(query.message, "⬅️ Back"),
                    callback_data="stngs_back({})".format(chat_id))
            ])
            query.message.edit_text(
                text=text,
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=InlineKeyboardMarkup(set_button))

        elif prev_match:
            chat_id = prev_match.group(1)
            curr_page = int(prev_match.group(2))
            chat = context.bot.get_chat(chat_id)
            query.message.reply_text(text=tl(
                update.effective_message,
                "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 = context.bot.get_chat(chat_id)
            query.message.reply_text(text=tl(
                update.effective_message,
                "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 = context.bot.get_chat(chat_id)
            query.message.reply_text(text=tl(
                update.effective_message,
                "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

        context.bot.answer_callback_query(query.id)
    except Exception 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:
            query.message.edit_text(excp.message)
            LOGGER.exception("Exception in settings buttons. %s",
                             str(query.data))
Beispiel #9
0
def del_blacklist(update, context):
    chat = update.effective_chat  # type: Optional[Chat]
    message = update.effective_message  # type: Optional[Message]
    user = update.effective_user
    bot = context.bot
    to_match = extract_text(message)
    if not to_match:
        return

    getmode, value = sql.get_blacklist_setting(chat.id)

    chat_filters = sql.get_chat_blacklist(chat.id)
    for trigger in chat_filters:
        pattern = r"( |^|[^\w])" + re.escape(trigger) + r"( |$|[^\w])"
        if re.search(pattern, to_match, flags=re.IGNORECASE):
            try:
                if getmode == 0:
                    return
                elif getmode == 1:
                    message.delete()
                elif getmode == 2:
                    message.delete()
                    warn(update.effective_user,
                         chat,
                         tl(update.effective_message,
                            "Mengatakan kata '{}' yang ada di daftar hitam").
                         format(trigger),
                         message,
                         update.effective_user,
                         conn=False)
                    return
                elif getmode == 3:
                    message.delete()
                    bot.restrict_chat_member(chat.id,
                                             update.effective_user.id,
                                             can_send_messages=False)
                    bot.sendMessage(
                        chat.id,
                        tl(
                            update.effective_message,
                            "{} di bisukan karena mengatakan kata '{}' yang ada di daftar hitam"
                        ).format(mention_markdown(user.id, user.first_name),
                                 trigger),
                        parse_mode="markdown")
                    return
                elif getmode == 4:
                    message.delete()
                    res = chat.unban_member(update.effective_user.id)
                    if res:
                        bot.sendMessage(
                            chat.id,
                            tl(
                                update.effective_message,
                                "{} di tendang karena mengatakan kata '{}' yang ada di daftar hitam"
                            ).format(
                                mention_markdown(user.id, user.first_name),
                                trigger),
                            parse_mode="markdown")
                    return
                elif getmode == 5:
                    message.delete()
                    chat.kick_member(user.id)
                    bot.sendMessage(
                        chat.id,
                        tl(
                            update.effective_message,
                            "{} di blokir karena mengatakan kata '{}' yang ada di daftar hitam"
                        ).format(mention_markdown(user.id, user.first_name),
                                 trigger),
                        parse_mode="markdown")
                    return
                elif getmode == 6:
                    message.delete()
                    bantime = extract_time(message, value)
                    chat.kick_member(user.id, until_date=bantime)
                    bot.sendMessage(
                        chat.id,
                        tl(
                            update.effective_message,
                            "{} di blokir selama {} karena mengatakan kata '{}' yang ada di daftar hitam"
                        ).format(mention_markdown(user.id, user.first_name),
                                 value, trigger),
                        parse_mode="markdown")
                    return
                elif getmode == 7:
                    message.delete()
                    mutetime = extract_time(message, value)
                    bot.restrict_chat_member(chat.id,
                                             user.id,
                                             until_date=mutetime,
                                             can_send_messages=False)
                    bot.sendMessage(
                        chat.id,
                        tl(
                            update.effective_message,
                            "{} di bisukan selama {} karena mengatakan kata '{}' yang ada di daftar hitam"
                        ).format(mention_markdown(user.id, user.first_name),
                                 value, trigger),
                        parse_mode="markdown")
                    return
            except BadRequest as excp:
                if excp.message == "Message to delete not found":
                    pass
                else:
                    LOGGER.exception("Error while deleting blacklist message.")
            break
Beispiel #10
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))
Beispiel #11
0
def get(bot, update, notename, show_none=True, no_format=False):
    chat = update.effective_chat
    user = update.effective_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:
        # 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":
                        send_message(update.effective_message, tl(update.effective_message,
                                                                  "This message seems to have been lost - I'll remove it "
                                                                  "from your list of notes."))
                        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":
                        send_message(update.effective_message, tl(update.effective_message,
                                                                  "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_WELCOME_FORMATTERS = ['first', 'last', 'fullname', 'username', 'id', 'chatname', 'mention', 'rules']
            valid_format = escape_invalid_curly_brackets(note.value, VALID_WELCOME_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,
                                           rules="http://t.me/{}?start={}".format(bot.username, chat_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_parser(bot, chat_id, buttons)

            keyboard = InlineKeyboardMarkup(keyb)

            try:
                is_private, is_delete = sql.get_private_note(chat.id)
                if note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT):
                    try:
                        if is_delete:
                            update.effective_message.delete()
                        if is_private:
                            bot.send_message(user.id, text,
                                             parse_mode=parseMode, disable_web_page_preview=True,
                                             reply_markup=keyboard)
                        else:
                            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 = tl(update.effective_message,
                                          "Error: URL on the button is invalid! Please update this note.")
                            failtext += "\n\n```\n{}```".format(note.value + revert_buttons(buttons))
                            send_message(update.effective_message, failtext, parse_mode="markdown")
                        elif excp.message == "Button_url_invalid":
                            failtext = tl(update.effective_message,
                                          "Error: URL on the button is invalid! Please update this note.")
                            failtext += "\n\n```\n{}```".format(note.value + revert_buttons(buttons))
                            send_message(update.effective_message, failtext, parse_mode="markdown")
                        elif excp.message == "Message can't be deleted":
                            pass
                        elif excp.message == "Have no rights to send a message":
                            pass
                    except Unauthorized:
                        send_message(update.effective_message,
                                     tl(update.effective_message, "Contact me at PM to get this notes."),
                                     parse_mode="markdown")
                        pass
                else:
                    try:
                        if is_delete:
                            update.effective_message.delete()
                        if is_private:
                            ENUM_FUNC_MAP[note.msgtype](user.id, note.file, caption=text, 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:
                        if excp.message == "Message can't be deleted":
                            pass
                        elif excp.message == "Have no rights to send a message":
                            pass
                    except Unauthorized:
                        send_message(update.effective_message,
                                     tl(update.effective_message, "Contact me at PM to get this note."),
                                     parse_mode="markdown")
                        pass

            except BadRequest as excp:
                if excp.message == "Entity_mention_user_invalid":
                    send_message(update.effective_message, tl(update.effective_message,
                                                              "It looks like you tried to mention someone who has never seen before. "
                                                              "If you really want to mention, forwarding one of their messages to me, "
                                                              "and I will be able to mark them!"))
                elif FILE_MATCHER.match(note.value):
                    send_message(update.effective_message, tl(update.effective_message,
                                                              "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:
                    send_message(update.effective_message, tl(update.effective_message,
                                                              "This note could not be sent, as it is incorrectly formatted."))
                    LOGGER.exception("Could not parse message #%s in the chat %s", notename, str(chat_id))
                    LOGGER.warning("The message: %s", str(note.value))
        return
    elif show_none:
        send_message(update.effective_message, tl(update.effective_message, "This note doesn't exist"))
Beispiel #12
0
def del_lockables(update, context):
    chat = update.effective_chat  # type: Optional[Chat]
    message = update.effective_message  # type: Optional[Message]

    for lockable, filter in LOCK_TYPES.items():
        if lockable == "rtl":
            if sql.is_locked(chat.id, lockable) and can_delete(
                    chat, context.bot.id):
                if message.caption:
                    check = ad.detect_alphabet(u'{}'.format(message.caption))
                    if 'ARABIC' in check:
                        try:
                            message.delete()
                        except BadRequest as excp:
                            if excp.message == "Message to delete not found":
                                pass
                            else:
                                LOGGER.exception("ERROR in lockables")
                        getconf = sql.get_lockconf(chat.id)
                        if getconf:
                            warn(
                                update.effective_user,
                                chat,
                                tl(
                                    update.effective_message,
                                    "Mengirim 'Teks RTL' yang sedang di kunci saat ini"
                                ),
                                message,
                                update.effective_user,
                                conn=False)
                        break
                if message.text:
                    check = ad.detect_alphabet(u'{}'.format(message.text))
                    if 'ARABIC' in check:
                        try:
                            message.delete()
                        except BadRequest as excp:
                            if excp.message == "Message to delete not found":
                                pass
                            else:
                                LOGGER.exception("ERROR in lockables")
                        getconf = sql.get_lockconf(chat.id)
                        if getconf:
                            warn(
                                update.effective_user,
                                chat,
                                tl(
                                    update.effective_message,
                                    "Mengirim 'Teks RTL' yang sedang di kunci saat ini"
                                ),
                                message,
                                update.effective_user,
                                conn=False)
                        break
            continue
        if lockable == "button":
            if sql.is_locked(chat.id, lockable) and can_delete(
                    chat, context.bot.id):
                if message.reply_markup and message.reply_markup.inline_keyboard:
                    try:
                        message.delete()
                    except BadRequest as excp:
                        if excp.message == "Message to delete not found":
                            pass
                        else:
                            LOGGER.exception("ERROR in lockables")
                    getconf = sql.get_lockconf(chat.id)
                    if getconf:
                        warn(
                            update.effective_user,
                            chat,
                            tl(
                                update.effective_message,
                                "Mengirim 'Pesan Tombol' yang sedang di kunci saat ini"
                            ),
                            message,
                            update.effective_user,
                            conn=False)
                    break
            continue
        if filter(update) and sql.is_locked(chat.id, lockable) and can_delete(
                chat, context.bot.id):
            if lockable == "bots":
                new_members = update.effective_message.new_chat_members
                for new_mem in new_members:
                    if new_mem.is_bot:
                        if not is_bot_admin(chat, context.bot.id):
                            send_message(
                                update.effective_message,
                                tl(
                                    update.effective_message,
                                    "Saya melihat bot, dan saya diberitahu untuk menghentikan mereka bergabung... "
                                    "tapi saya bukan admin!"))
                            return

                        chat.kick_member(new_mem.id)
                        send_message(
                            update.effective_message,
                            tl(
                                update.effective_message,
                                "Hanya admin yang diizinkan menambahkan bot ke obrolan ini! Keluar dari sini!"
                            ))
                        getconf = sql.get_lockconf(chat.id)
                        if getconf:
                            warn(
                                update.effective_user,
                                chat,
                                tl(
                                    update.effective_message,
                                    "Memasukan 'Bot' yang sedang di kunci saat ini"
                                ),
                                message,
                                update.effective_user,
                                conn=False)
                        break
            else:
                try:
                    message.delete()
                except BadRequest as excp:
                    if excp.message == "Message to delete not found":
                        pass
                    else:
                        LOGGER.exception("ERROR in lockables")
                getconf = sql.get_lockconf(chat.id)
                if getconf:
                    warn(update.effective_user,
                         chat,
                         tl(update.effective_message,
                            "Mengirim '{}' yang sedang di kunci saat ini").
                         format(lockable),
                         message,
                         update.effective_user,
                         conn=False)

                break
Beispiel #13
0
def get(bot, update, notename, show_none=True, no_format=False):
    chat = update.effective_chat
    user = update.effective_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

    if note:
        pass
    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 and 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:
        if note:
            text = note.value
        else:
            text = None

        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 and 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")

            else:
                if note:
                    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
Beispiel #14
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 ""
Beispiel #15
0
                                            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


@run_async
def cmd_get(bot: Bot, update: Update, args: List[str]):
    chat = update.effective_chat
    if len(args) >= 2 and args[1].lower() == "noformat":
        get(bot, update, args[0].lower(), show_none=True, no_format=True)
    elif len(args) >= 1:
        get(bot, update, args[0].lower(), show_none=True)
    else:
        update.effective_message.reply_text(tld(chat.id, "get_invalid"))
Beispiel #16
0
def error_callback(update, context):
    # add all the dev user_ids in this list. You can also add ids of channels or groups.
    devs = [OWNER_ID]
    # we want to notify the user of this problem. This will always work, but not notify users if the update is an
    # callback or inline query, or a poll update. In case you want this, keep in mind that sending the message
    # could fail
    if update.effective_message:
        text = "Hey. I'm sorry to inform you that an error happened while I tried to handle your update. " \
               "My developer(s) will be notified."
        update.effective_message.reply_text(text)
    # This traceback is created with accessing the traceback object from the sys.exc_info, which is returned as the
    # third value of the returned tuple. Then we use the traceback.format_tb to get the traceback as a string, which
    # for a weird reason separates the line breaks in a list, but keeps the linebreaks itself. So just joining an
    # empty string works fine.
    trace = "".join(traceback.format_tb(sys.exc_info()[2]))
    # lets try to get as much information from the telegram update as possible
    payload = ""
    # normally, we always have an user. If not, its either a channel or a poll update.
    if update.effective_user:
        payload += f' with the user {mention_html(update.effective_user.id, update.effective_user.first_name)}'
    # there are more situations when you don't get a chat
    if update.effective_chat:
        payload += f' within the chat <i>{update.effective_chat.title}</i>'
        if update.effective_chat.username:
            payload += f' (@{update.effective_chat.username})'
    # but only one where you have an empty payload by now: A poll (buuuh)
    if update.poll:
        payload += f' with the poll id {update.poll.id}.'
    # lets put this in a "well" formatted text
    text = f"Hey.\n The error <code>{context.error}</code> happened{payload}. The full traceback:\n\n<code>{trace}" \
           f"</code>"
    # and send it to the dev(s)
    for dev_id in devs:
        context.bot.send_message(dev_id, text, parse_mode=ParseMode.HTML)
    # we raise the error again, so the logger module catches it. If you don't use the logger module, use it.
    try:
        raise context.error
    except Unauthorized:
        # remove update.message.chat_id from conversation list
        LOGGER.exception('Update "%s" caused error "%s"', update,
                         context.error)
    except BadRequest:
        # handle malformed requests - read more below!
        LOGGER.exception('Update "%s" caused error "%s"', update,
                         context.error)
    except TimedOut:
        # handle slow connection problems
        LOGGER.exception('Update "%s" caused error "%s"', update,
                         context.error)
    except NetworkError:
        # handle other connection problems
        LOGGER.exception('Update "%s" caused error "%s"', update,
                         context.error)
    except ChatMigrated as e:
        # the chat_id of a group has changed, use e.new_chat_id instead
        LOGGER.exception('Update "%s" caused error "%s"', update,
                         context.error)
    except TelegramError:
        # handle all other telegram related errors
        LOGGER.exception('Update "%s" caused error "%s"', update,
                         context.error)
Beispiel #17
0
def get(bot, update, notename, show_none=True, no_format=False):
    chat = update.effective_chat
    user = update.effective_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:
        # 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":
                        send_message(
                            update.effective_message,
                            tl(
                                update.effective_message,
                                "Pesan ini tampaknya telah hilang - saya akan menghapusnya "
                                "from your list of notes."))
                        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":
                        send_message(
                            update.effective_message,
                            tl(
                                update.effective_message,
                                "Sepertinya pengirim asli dari catatan ini telah dihapus "
                                "pesan mereka - maaf! Dapatkan admin bot Anda untuk mulai menggunakan "
                                "pesan dump untuk menghindari ini. Saya akan menghapus catatan ini dari "
                                "catatan tersimpan Anda."))
                        sql.rm_note(chat_id, notename)
                    else:
                        raise
        else:

            VALID_WELCOME_FORMATTERS = [
                'first', 'last', 'fullname', 'username', 'id', 'chatname',
                'mention', 'rules'
            ]
            valid_format = escape_invalid_curly_brackets(
                note.value, VALID_WELCOME_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,
                    rules="http://t.me/{}?start={}".format(
                        bot.username, chat_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_parser(bot, chat_id, buttons)

            keyboard = InlineKeyboardMarkup(keyb)

            try:
                is_private, is_delete = sql.get_private_note(chat.id)
                if note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT):
                    try:
                        if is_delete:
                            update.effective_message.delete()
                        if is_private:
                            bot.send_message(user.id,
                                             text,
                                             parse_mode=parseMode,
                                             disable_web_page_preview=True,
                                             reply_markup=keyboard)
                        else:
                            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 = tl(
                                update.effective_message,
                                "Error: URL on the button is invalid! Please update this note."
                            )
                            failtext += "\n\n```\n{}```".format(
                                note.value + revert_buttons(buttons))
                            send_message(update.effective_message,
                                         failtext,
                                         parse_mode="markdown")
                        elif excp.message == "Button_url_invalid":
                            failtext = tl(
                                update.effective_message,
                                "Error: URL on the button is invalid! Please update this note."
                            )
                            failtext += "\n\n```\n{}```".format(
                                note.value + revert_buttons(buttons))
                            send_message(update.effective_message,
                                         failtext,
                                         parse_mode="markdown")
                        elif excp.message == "Message can't be deleted":
                            pass
                        elif excp.message == "Have no rights to send a message":
                            pass
                    except Unauthorized:
                        send_message(update.effective_message,
                                     tl(update.effective_message,
                                        "Contact me at PM to get this notes."),
                                     parse_mode="markdown")
                        pass
                else:
                    try:
                        if is_delete:
                            update.effective_message.delete()
                        if is_private:
                            ENUM_FUNC_MAP[note.msgtype](
                                user.id,
                                note.file,
                                caption=text,
                                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:
                        if excp.message == "Message can't be deleted":
                            pass
                        elif excp.message == "Have no rights to send a message":
                            pass
                    except Unauthorized:
                        send_message(update.effective_message,
                                     tl(update.effective_message,
                                        "Contact me at PM to get this note."),
                                     parse_mode="markdown")
                        pass

            except BadRequest as excp:
                if excp.message == "Entity_mention_user_invalid":
                    send_message(
                        update.effective_message,
                        tl(
                            update.effective_message,
                            "It looks like you tried to mention someone who has never seen before. "
                            "If you really want to mention, forwarding one of their messages to me, "
                            "and I will be able to mark them!"))
                elif FILE_MATCHER.match(note.value):
                    send_message(
                        update.effective_message,
                        tl(
                            update.effective_message,
                            "Catatan ini adalah file yang salah diimpor dari bot lain - saya tidak bisa menggunakan "
                            "ini. Jika Anda benar-benar membutuhkannya, Anda harus menyimpannya lagi. "
                            "Sementara itu, saya akan menghapusnya dari daftar catatan Anda."
                        ))
                    sql.rm_note(chat_id, notename)
                else:
                    send_message(
                        update.effective_message,
                        tl(
                            update.effective_message,
                            "Catatan ini tidak dapat dikirim karena formatnya salah."
                        ))
                    LOGGER.exception(
                        "Tidak dapat menguraikan pesan #%s di obrolan %s",
                        notename, str(chat_id))
                    LOGGER.warning("Pesan itu: %s", str(note.value))
        return
    elif show_none:
        send_message(update.effective_message,
                     tl(update.effective_message, "Catatan ini tidak ada"))
Beispiel #18
0
def reply_filter(bot: Bot, update: Update):
    chat = update.effective_chat
    message = update.effective_message

    if 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.is_sticker:
                message.reply_sticker(filt.reply)
            elif filt.is_document:
                try:
                    message.reply_document(filt.reply)
                except Exception:
                    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 Exception:
                    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 Exception:
                            print("Nut")

            else:
                # LEGACY - all new filters will have has_markdown set to True.
                message.reply_text(filt.reply)
            break
Beispiel #19
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):
        # type: Optional[User]
        reported_user = message.reply_to_message.from_user
        chat_name = chat.title or chat.first or chat.username
        admin_list = chat.get_administrators()

        if int(reported_user.id) == int(user.id):
            return ""

        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\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,
                                         disable_web_page_preview=True)

                        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,
                                         disable_web_page_preview=True)

                        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,
                                         disable_web_page_preview=True)

                        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(
                        f"Exception while reporting user : {excp}")

        message.reply_to_message.reply_text(tld(
            chat.id,
            "reports_success").format(mention_html(user.id, user.first_name)),
                                            parse_mode=ParseMode.HTML,
                                            disable_web_page_preview=True)
        return msg

    return ""
Beispiel #20
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 ""
Beispiel #21
0
def temp_ban(update, context):
    currentchat = update.effective_chat  # type: Optional[Chat]
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    message = update.effective_message  # type: Optional[Message]
    args = context.args

    user_id, reason = extract_user_and_text(message, args)
    if user_id == "error":
        send_message(update.effective_message,
                     tl(update.effective_message, reason))
        return ""

    conn = connected(context.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,
                tl(update.effective_message,
                   "You can do this command in groups, not PM"))
            return ""
        chat = update.effective_chat
        chat_id = update.effective_chat.id
        chat_name = update.effective_message.chat.title

    check = context.bot.getChatMember(chat_id, context.bot.id)
    if check.status == 'member':
        if conn:
            text = tl(
                update.effective_message,
                "Saya tidak bisa membatasi orang di *{}*! Pastikan saya admin dan dapat menunjuk admin baru."
            ).format(chat_name)
        else:
            text = tl(
                update.effective_message,
                "Saya tidak bisa membatasi orang di sini! Pastikan saya admin dan dapat menunjuk admin baru."
            )
        send_message(update.effective_message, text, parse_mode="markdown")
        return ""
    else:
        if check['can_restrict_members'] is False:
            if conn:
                text = tl(
                    update.effective_message,
                    "Saya tidak bisa membatasi orang di *{}*! Pastikan saya admin dan dapat menunjuk admin baru."
                ).format(chat_name)
            else:
                text = tl(
                    update.effective_message,
                    "Saya tidak bisa membatasi orang di sini! Pastikan saya admin dan dapat menunjuk admin baru."
                )
            send_message(update.effective_message, text, parse_mode="markdown")
            return ""

    if not user_id:
        send_message(
            update.effective_message,
            tl(update.effective_message,
               "You don't seem to be referring to a user."))
        return ""

    try:
        if conn:
            member = context.bot.getChatMember(chat_id, user_id)
        else:
            member = chat.get_member(user_id)
    except BadRequest as excp:
        if excp.message == "User not found":
            send_message(
                update.effective_message,
                tl(update.effective_message,
                   "Saya tidak dapat menemukan pengguna ini 😣"))
            return ""
        else:
            raise

    if user_id == context.bot.id:
        send_message(
            update.effective_message,
            tl(update.effective_message,
               "Saya tidak akan BAN diri saya sendiri, apakah kamu gila? 😠"))
        return ""

    if is_user_ban_protected(chat, user_id, member):
        send_message(
            update.effective_message,
            tl(update.effective_message,
               "Saya tidak bisa banned orang ini karena dia adalah admin 😒"))
        return ""

    if member['can_restrict_members'] is False:
        send_message(
            update.effective_message,
            tl(update.effective_message,
               "Anda tidak punya hak untuk membatasi seseorang."))
        return ""

    if not reason:
        send_message(
            update.effective_message,
            tl(update.effective_message,
               "Anda belum menetapkan waktu untuk banned pengguna ini!"))
        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#TEMPBAN" \
          "\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:
        if conn:
            context.bot.kickChatMember(chat_id, user_id, until_date=bantime)
            context.bot.send_sticker(currentchat.id,
                                     BAN_STICKER)  # banhammer marie sticker
            send_message(
                update.effective_message,
                tl(update.effective_message,
                   "Banned! Pengguna diblokir untuk *{}* pada *{}*.").format(
                       time_val, chat_name),
                parse_mode="markdown")
        else:
            chat.kick_member(user_id, until_date=bantime)
            context.bot.send_sticker(chat.id,
                                     BAN_STICKER)  # banhammer marie sticker
            send_message(
                update.effective_message,
                tl(update.effective_message,
                   "Banned! Pengguna diblokir untuk {}.").format(time_val))
        return log

    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            send_message(
                update.effective_message,
                tl(update.effective_message,
                   "Banned! Pengguna diblokir untuk {}.").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)
            send_message(
                update.effective_message,
                tl(update.effective_message,
                   "Well damn, I can't ban that user. 😒"))

    return ""