Ejemplo n.º 1
0
def cmd_get(update: Update, context: CallbackContext):
    bot, args = context.bot, context.args
    chat = update.effective_chat
    note = sql.get_note(chat.id, args[0])
    if not note:
        send_message(
            update.effective_message,
            "This note does not exist",
        )
        return
    is_private, is_delete = sql.get_private_note(chat.id)
    if len(args) >= 2 and args[1].lower() == "noformat":
        if is_private:
            buttons = InlineKeyboardMarkup([[
                InlineKeyboardButton(
                    text="Click me!",
                    url=
                    f"http://t.me/YuiiChanBot?start=notes_{chat.id}={args[0]}",
                )
            ]])
            update.effective_message.reply_text(
                f"Tap here to view '{args[0]}' in your private chat.",
                parse_mode=None,
                disable_web_page_preview=True,
                reply_markup=buttons,
            )
        else:
            get(update, context, args[0], no_format=True)
    elif len(args) >= 1:
        if is_private:
            buttons = InlineKeyboardMarkup([[
                InlineKeyboardButton(
                    text="Click me!",
                    url=
                    f"http://t.me/YuiiChanBot?start=notes_{chat.id}={args[0]}",
                )
            ]])
            update.effective_message.reply_text(
                f"Tap here to view '{args[0]}' in your private chat.",
                parse_mode=None,
                disable_web_page_preview=True,
                reply_markup=buttons,
            )
        else:
            get(update, context, args[0])
    else:
        send_message(update.effective_message, "Get what?")
Ejemplo n.º 2
0
def save(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    conn = connected(bot, update, chat, user.id)
    if conn:
        chat_id = conn
        chat_name = dispatcher.bot.getChat(conn).title
    else:
        chat_id = update.effective_chat.id
        if chat.type == "private":
            chat_name = "local notes"
        else:
            chat_name = chat.title

    msg = update.effective_message  # type: Optional[Message]

    note_name, text, data_type, content, buttons = get_note_type(msg)

    if data_type is None:
        msg.reply_text("Dude, there's no note!")
        return

    if len(text.strip()) == 0:
        text = note_name

    if not sql.get_note(chat_id, note_name):
        sql.add_note_to_db(chat_id,
                           note_name,
                           text,
                           data_type,
                           buttons=buttons,
                           file=content)
        msg.reply_text(
            "Ok, added `{note_name}` note in *{chat_name}*.\nGet it with `/get {note_name}`, or `#{note_name}`"
            .format(note_name=note_name, chat_name=chat_name),
            parse_mode=ParseMode.MARKDOWN)
    else:
        sql.add_note_to_db(chat_id,
                           note_name,
                           text,
                           data_type,
                           buttons=buttons,
                           file=content)
        msg.reply_text(
            "Ok, Note `{note_name}` in *{chat_name}* have been updated!.\nGet it with `/get {note_name}`, or `#{note_name}`"
            .format(note_name=note_name, chat_name=chat_name),
            parse_mode=ParseMode.MARKDOWN)
Ejemplo n.º 3
0
def clear(update: Update, context: CallbackContext):
    bot, args = context.bot, context.args
    chat_id = update.effective_chat.id
    chat = update.effective_chat
    chat_name = chat.title or chat.first or chat.username
    count = 0

    if len(args) >= 1:
        notename = args[0]
    else:
        update.effective_message.reply_text("I can't clear empty notes!")
        return

    if notename.isnumeric():
        check = sql.get_note(chat_id, notename)
        # If check == true, it means that notename and noteid conflicts each other
        if check:
            update.effective_message.reply_text(
                warning.format(notename=notename))
        # If check == false, it means that we need to search notename for given noteid
        else:
            note_list = sql.get_all_chat_notes(chat_id)
            for note in note_list:
                count = count + 1
                if str(count) == notename:
                    notename = note.name
                    break  # As it can be overwritten later

    if sql.rm_note(chat_id, notename):
        update.effective_message.reply_text(
            "Note for '`{}`' has been deleted!".format(notename),
            parse_mode=ParseMode.MARKDOWN,
        )
    else:
        update.effective_message.reply_text(
            "Unfortunately, There is no such notes saved on {chat_name}!".
            format(chat_name=chat_name))
Ejemplo n.º 4
0
def hash_get(update: Update, context: CallbackContext):
    message = update.effective_message.text
    chat = update.effective_chat
    is_private, is_delete = sql.get_private_note(chat.id)
    fst_word = message.split()[0]
    no_hash = fst_word[1:]
    note = sql.get_note(chat.id, no_hash)
    if not note:
        return
    if is_private:
        buttons = InlineKeyboardMarkup([[
            InlineKeyboardButton(
                text="Click me!",
                url=f"http://t.me/YuiiChanBot?start=notes_{chat.id}={no_hash}",
            )
        ]])
        update.effective_message.reply_text(
            f"Tap here to view '{no_hash}' in your private chat.",
            parse_mode=None,
            disable_web_page_preview=True,
            reply_markup=buttons,
        )
    else:
        get(update, context, no_hash, show_none=False)
Ejemplo n.º 5
0
def get(bot, update, notename, show_none=True, no_format=False):
    chat_id = update.effective_chat.id
    note = sql.get_note(chat_id, notename)
    message = update.effective_message  # type: Optional[Message]

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

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

            keyboard = InlineKeyboardMarkup(keyb)

            try:
                if note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT):
                    bot.send_message(chat_id, text, reply_to_message_id=reply_id,
                                     parse_mode=parseMode, disable_web_page_preview=True,
                                     reply_markup=keyboard)
                else:
                    ENUM_FUNC_MAP[note.msgtype](chat_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("Looks like you tried to mention someone I've never seen before. If you really "
                                       "want to mention them, forward one of their messages to me, and I'll be able "
                                       "to tag them!")
                elif FILE_MATCHER.match(note.value):
                    message.reply_text("This note was an incorrectly imported file from another bot - I can't use "
                                       "it. If you really need it, you'll have to save it again. In "
                                       "the meantime, I'll remove it from your notes list.")
                    sql.rm_note(chat_id, notename)
                else:
                    message.reply_text("This note could not be sent, as it is incorrectly formatted. Ask in "
                                       "@MarieSupport if you can't figure out why!")
                    LOGGER.exception("Could not parse message #%s in chat %s", notename, str(chat_id))
                    LOGGER.warning("Message was: %s", str(note.value))
        return
    elif show_none:
        message.reply_text("This note doesn't exist")
Ejemplo n.º 6
0
def get(bot, update, notename, show_none=True, no_format=False):
    chat_id = update.effective_chat.id
    note = sql.get_note(chat_id, notename)
    message = update.effective_message  # type: Optional[Message]

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

        if note.is_reply:
            if 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(
                            "Pesan ini sepertinya telah hilang - Saya akan menghapusnya "
                            "dari daftar catatan Anda.")
                        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(
                            "Sepertinya pengirim asli catatan ini telah dihapus "
                            "pesan mereka - maaf! Minta admin bot Anda untuk mulai menggunakan file "
                            "pesan dump untuk menghindari ini. Saya akan menghapus catatan ini dari "
                            "catatan Anda yang disimpan.")
                        sql.rm_note(chat_id, notename)
                    else:
                        raise
        else:
            text = note.value
            keyb = []
            parseMode = ParseMode.MARKDOWN
            buttons = sql.get_buttons(chat_id, notename)
            if no_format:
                parseMode = None
                text += revert_buttons(buttons)
            else:
                keyb = build_keyboard(buttons)

            keyboard = InlineKeyboardMarkup(keyb)

            try:
                if note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT):
                    bot.send_message(
                        chat_id,
                        text,
                        reply_to_message_id=reply_id,
                        parse_mode=parseMode,
                        disable_web_page_preview=True,
                        reply_markup=keyboard,
                    )
                else:
                    ENUM_FUNC_MAP[note.msgtype](
                        chat_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(
                        "Sepertinya Anda mencoba menyebut seseorang yang belum pernah saya lihat sebelumnya. Jika Anda benar-benar "
                        "ingin menyebutkan mereka, meneruskan salah satu pesan mereka kepada saya, dan saya akan bisa "
                        "untuk menandai mereka!")
                elif FILE_MATCHER.match(note.value):
                    message.reply_text(
                        "Catatan ini adalah file yang diimpor dengan tidak benar dari bot lain - Saya tidak dapat menggunakan "
                        "Itu. Jika Anda benar-benar membutuhkannya, Anda harus menyimpannya lagi. Di "
                        "sementara itu, saya akan menghapusnya dari daftar catatan Anda."
                    )
                    sql.rm_note(chat_id, notename)
                else:
                    message.reply_text(
                        "Catatan ini tidak dapat dikirim, karena formatnya salah."
                    )
                    LOGGER.exception("Could not parse message #%s in chat %s",
                                     notename, str(chat_id))
                    LOGGER.warning("Message was: %s", str(note.value))
        return
    elif show_none:
        message.reply_text("Catatan ini tidak ada")
Ejemplo n.º 7
0
def get(update, context, notename, show_none=True, no_format=False):
    bot = context.bot
    chat_id = update.effective_chat.id
    note = sql.get_note(chat_id, notename)
    message = update.effective_message  # type: Optional[Message]

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

        if note.is_reply:
            if JOIN_LOGGER:
                try:
                    bot.forward_message(
                        chat_id=chat_id, from_chat_id=JOIN_LOGGER, message_id=note.value
                    )
                except BadRequest as excp:
                    if excp.message == "Message to forward not found":
                        message.reply_text(
                            "This message seems to have been lost - I'll remove it "
                            "from your notes list."
                        )
                        sql.rm_note(chat_id, notename)
                    else:
                        raise
            else:
                try:
                    bot.forward_message(
                        chat_id=chat_id, from_chat_id=chat_id, message_id=note.value
                    )
                except BadRequest as excp:
                    if excp.message == "Message to forward not found":
                        message.reply_text(
                            "Looks like the original sender of this note has deleted "
                            "their message - sorry! Get your bot admin to start using a "
                            "message dump to avoid this. I'll remove this note from "
                            "your saved notes."
                        )
                        sql.rm_note(chat_id, notename)
                    else:
                        raise
        else:
            VALID_NOTE_FORMATTERS = [
                "first",
                "last",
                "fullname",
                "username",
                "id",
                "chatname",
                "mention",
            ]
            valid_format = escape_invalid_curly_brackets(
                note.value, VALID_NOTE_FORMATTERS
            )
            if valid_format:
                text = valid_format.format(
                    first=escape_markdown(message.from_user.first_name),
                    last=escape_markdown(
                        message.from_user.last_name or message.from_user.first_name
                    ),
                    fullname=escape_markdown(
                        " ".join(
                            [message.from_user.first_name, message.from_user.last_name]
                            if message.from_user.last_name
                            else [message.from_user.first_name]
                        )
                    ),
                    username="******" + message.from_user.username
                    if message.from_user.username
                    else mention_markdown(
                        message.from_user.id, message.from_user.first_name
                    ),
                    mention=mention_markdown(
                        message.from_user.id, message.from_user.first_name
                    ),
                    chatname=escape_markdown(
                        message.chat.title
                        if message.chat.type != "private"
                        else message.from_user.first_name
                    ),
                    id=message.from_user.id,
                )
            else:
                text = ""

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

            keyboard = InlineKeyboardMarkup(keyb)

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

            except BadRequest as excp:
                if excp.message == "Entity_mention_user_invalid":
                    message.reply_text(
                        "Looks like you tried to mention someone I've never seen before. If you really "
                        "want to mention them, forward one of their messages to me, and I'll be able "
                        "to tag them!"
                    )
                elif FILE_MATCHER.match(note.value):
                    message.reply_text(
                        "This note was an incorrectly imported file from another bot - I can't use "
                        "it. If you really need it, you'll have to save it again. In "
                        "the meantime, I'll remove it from your notes list."
                    )
                    sql.rm_note(chat_id, notename)
                else:
                    message.reply_text(
                        "This note could not be sent, as it is incorrectly formatted. Ask in "
                        f"@YorkTownEagleUnion if you can't figure out why!"
                    )
                    log.exception(
                        "Could not parse message #%s in chat %s", notename, str(chat_id)
                    )
                    log.warning("Message was: %s", str(note.value))
        return
    elif show_none:
        message.reply_text("This note doesn't exist")
Ejemplo n.º 8
0
def get(bot, update, notename, show_none=True):
    chat_id = update.effective_chat.id
    note = sql.get_note(chat_id, notename)
    message = update.effective_message  # type: Optional[Message]

    if note:
        # If not is replying to a message, reply to that message (unless its an error)
        if message.reply_to_message:
            reply_text = message.reply_to_message.reply_text
        else:
            reply_text = message.reply_text

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

            keyboard = InlineKeyboardMarkup(keyb)
            try:
                reply_text(note.value,
                           parse_mode=ParseMode.MARKDOWN,
                           disable_web_page_preview=True,
                           reply_markup=keyboard)
            except BadRequest as excp:
                if excp.message == "Entity_mention_user_invalid":
                    message.reply_text(
                        "Looks like you tried to mention someone I've never seen before. If you really "
                        "want to mention them, forward one of their messages to me, and I'll be able "
                        "to tag them!")
                elif FILE_MATCHER.match(note.value):
                    message.reply_text(
                        "This note was an incorrectly imported file from another bot - I can't use "
                        "it. If you really need it, you'll have to save it again. In "
                        "the meantime, I'll remove it from your notes list.")
                    sql.rm_note(chat_id, notename)
                else:
                    message.reply_text(
                        "This note is not formatted correctly. Could not send. Contact @{} if you "
                        "can't figure out why!".format(OWNER_USERNAME))
                    LOGGER.exception("Could not parse message #%s in chat %s",
                                     notename, str(chat_id))
                    LOGGER.warning("Message was: %s", str(note.value))
        return
    elif show_none:
        message.reply_text("This note doesn't exist")
Ejemplo n.º 9
0
def get(bot, update, notename, show_none=True, no_format=False):
    chat_id = update.effective_chat.id
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    conn = connected(bot, update, chat, user.id, need_admin=False)
    if not conn == False:
        chat_id = conn
        send_id = user.id
    else:
        chat_id = update.effective_chat.id
        send_id = chat_id

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

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

        if note.is_reply:
            if MESSAGE_DUMP:
                try:
                    bot.forward_message(chat_id=chat_id,
                                        from_chat_id=MESSAGE_DUMP,
                                        message_id=note.value)
                except BadRequest as excp:
                    if excp.message == "ඉදිරියට යැවීමේ පණිවිඩය හමු නොවීය":
                        message.reply_text(
                            "Tඔහුගේ පණිවිඩය නැති වී ඇති බව පෙනේ - මම එය ඉවත් කරමි"
                            "ඔබගේ සටහන් ලැයිස්තුවෙන්.")
                        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.reply_text(
                            "මෙම සටහනේ මුල් යවන්නා මකා දමා ඇති බව පෙනේ"
                            "ඔවුන්ගේ පණිවිඩය - සමාවෙන්න! භාවිතා කිරීම ආරම්භ කිරීමට ඔබේ බොට් පරිපාලක ලබා ගන්න "
                            "මෙය වළක්වා ගැනීම සඳහා පණිවිඩ ඩම්ප් කරන්න. මම මෙම සටහන ඉවත් කරමි "
                            "ඔබගේ සුරකින ලද සටහන්.")
                        sql.rm_note(chat_id, notename)
                    else:
                        raise
        else:
            text = note.value
            keyb = []
            parseMode = ParseMode.MARKDOWN
            buttons = sql.get_buttons(chat_id, notename)
            should_preview_disabled = True
            if no_format:
                parseMode = None
                text += revert_buttons(buttons)
            else:
                keyb = build_keyboard(buttons)
                if "telegra.ph" in text or "youtu.be" in text:
                    should_preview_disabled = False

            keyboard = InlineKeyboardMarkup(keyb)

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

            except BadRequest as excp:
                if excp.message == "ආයතනය_සඳහන්_කිරීම_පරිශීලකයා_අවලංගුය":
                    message.reply_text(
                        "මම මීට පෙර කවදාවත් දැක නැති කෙනෙකු ගැන සඳහන් කිරීමට ඔබ උත්සාහ කළ බවක් පෙනේ. ඔබ ඇත්තටම නම් "
                        "ඒවා සඳහන් කිරීමට අවශ්‍යයි, ඔවුන්ගේ පණිවිඩයක් මා වෙත යොමු කරන්න, එවිට මට හැකි වනු ඇත"
                        "ඒවා ටැග් කිරීමට!")
                elif FILE_MATCHER.match(note.value):
                    message.reply_text(
                        "මෙම සටහන වෙනත් බොට් එකකින් වැරදි ලෙස ආනයනය කරන ලද ගොනුවකි - මට භාවිතා කළ නොහැක "
                        "එය. ඔබට එය සැබවින්ම අවශ්‍ය නම්, ඔබට එය නැවත සුරැකීමට සිදුවේ. තුළ "
                        "මේ අතර, මම එය ඔබගේ සටහන් ලැයිස්තුවෙන් ඉවත් කරමි.")
                    sql.rm_note(chat_id, notename)
                else:
                    message.reply_text(
                        "මෙම සටහන වැරදි ලෙස සංයුති කර ඇති බැවින් එය යැවිය නොහැක. ඇතුලට අහන්න"
                        "@cyberwordk ඇයි කියලා හිතාගන්න බැරි නම්!")
                    LOGGER.exception(
                        "පණිවිඩය විග්‍රහ කිරීමට නොහැකි විය #%s කතාබස් කරමින් %s",
                        notename, str(chat_id))
                    LOGGER.warning("Message was: %s", str(note.value))
        return
    elif show_none:
        message.reply_text("මෙම සටහන නොපවතී")
Ejemplo n.º 10
0
def get(bot, update, notename, show_none=True, no_format=False):
    chat_id = update.effective_chat.id
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    conn = connected(bot, update, chat, user.id, need_admin=False)
    if not conn == False:
        chat_id = conn
        send_id = user.id
    else:
        chat_id = update.effective_chat.id
        send_id = chat_id

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

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

        if note.is_reply:
            if MESSAGE_DUMP:
                try:
                    bot.forward_message(chat_id=chat_id,
                                        from_chat_id=MESSAGE_DUMP,
                                        message_id=note.value)
                except BadRequest as excp:
                    if excp.message == "Message to forward not found":
                        message.reply_text(
                            "يبدو أن هذه الرسالة قد فقدت - سأزيله"
                            "من قائمة الملاحظات الخاصة بك.")
                        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(
                            "يبدو وكأنه المرسل الأصلي لهذه المذكرة حذف"
                            "رسالتهم - آسف! احصل على مشرف بوتك للبدء في استخدام"
                            "تفريغ الرسالة لتجنب ذلك. سأزيل هذه المذكرة من"
                            "ملاحظات المحفوظة الخاصة بك.")
                        sql.rm_note(chat_id, notename)
                    else:
                        raise
        else:
            text = note.value
            keyb = []
            parseMode = ParseMode.MARKDOWN
            buttons = sql.get_buttons(chat_id, notename)
            should_preview_disabled = True
            if no_format:
                parseMode = None
                text += revert_buttons(buttons)
            else:
                keyb = build_keyboard(buttons)
                if "telegra.ph" in text or "youtu.be" in text:
                    should_preview_disabled = False

            keyboard = InlineKeyboardMarkup(keyb)

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

            except BadRequest as excp:
                if excp.message == "Entity_mention_user_invalid":
                    message.reply_text(
                        "يبدو أنك حاولت ذكر شخص ما لم أره من قبل. ان كنت حقا"
                        "هل تريد أن تذكرها، إلى الأمام إحدى رسائلها لي، وسأكون قادرا"
                        "لعلامةهم!")
                elif FILE_MATCHER.match(note.value):
                    message.reply_text(
                        "كانت هذه الملاحظة ملف مستورد بشكل غير صحيح من بوت آخر - لا يمكنني استخدامه"
                        "ذلك. إذا كنت في حاجة فعلا، فسيتعين عليك حفظها مرة أخرى. في"
                        "في هذه الأثناء، سأزيله من قائمة الملاحظات الخاصة بك.")
                    sql.rm_note(chat_id, notename)
                else:
                    message.reply_text(
                        "لا يمكن إرسال هذه الملاحظة، حيث يتم تنسيقها بشكل غير صحيح. اسأل في"
                        "@MarieSupport إذا كنت لا تستطيع معرفة السبب!")
                    LOGGER.exception("Could not parse message #%s in chat %s",
                                     notename, str(chat_id))
                    LOGGER.warning("Message was: %s", str(note.value))
        return
    elif show_none:
        message.reply_text("هذه المذكرة غير موجودة")
Ejemplo n.º 11
0
def get(bot, update, notename, show_none=True):
    chat_id = update.effective_chat.id
    note = sql.get_note(chat_id, notename)
    message = update.effective_message  # type: Optional[Message]

    if note:
        # If not is replying to a message, reply to that message (unless its an error)
        if message.reply_to_message:
            reply_text = message.reply_to_message.reply_text
        else:
            reply_text = message.reply_text

        if note.is_reply:
            if MESSAGE_DUMP:
                try:
                    bot.forward_message(chat_id=chat_id,
                                        from_chat_id=MESSAGE_DUMP,
                                        message_id=note.value)
                except BadRequest as excp:
                    if excp.message == "Message to forward not found":
                        message.reply_text(
                            "Bu mesaj kaybolmuş gibi görünüyor - onu "
                            "not listesinden kaldıracağım.")
                        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(
                            "Bu not orijinal göndereni tarafından silindi "
                            "Kullanmaya devam etmek için "
                            "mesajı yeniden göndermesini isteyin. "
                            "Notlar kısmından kaldırdım.")
                        sql.rm_note(chat_id, notename)
                    else:
                        raise
        else:
            keyb = []
            if note.has_buttons:
                buttons = sql.get_buttons(chat_id, notename)
                keyb = build_keyboard(buttons)

            keyboard = InlineKeyboardMarkup(keyb)
            try:
                reply_text(note.value,
                           parse_mode=ParseMode.MARKDOWN,
                           disable_web_page_preview=True,
                           reply_markup=keyboard)
            except BadRequest as excp:
                if excp.message == "Entity_mention_user_invalid":
                    message.reply_text(
                        "Daha önce hiç görmediğim birini söylemeyi denediniz. Eğer gerçekten "
                        "Onları kaydetmek istiyorsan, mesajlarından birini bana ilet, ben de "
                        "onu kaydedeyim!")
                elif FILE_MATCHER.match(note.value):
                    message.reply_text(
                        "Bu not başka bir bottan yanlış içe aktarılmış bir dosyaydı. onu "
                        "kullanamıyorum. Gerçekten ihtiyacınız varsa, tekrar kaydetmeniz gerekecek. "
                        "Bu arada, not listenizden kaldırırım.")
                    sql.rm_note(chat_id, notename)
                else:
                    message.reply_text("Bu mesaj gönderilemiyor "
                                       "Yanlış formatlandırılmış olabilir!")
                    LOGGER.exception("Could not parse message #%s in chat %s",
                                     notename, str(chat_id))
                    LOGGER.warning("Message was: %s", str(note.value))
        return
    elif show_none:
        message.reply_text("Bu not mevcut değil")
Ejemplo n.º 12
0
def get(bot, update, notename, show_none=True, no_format=False):
    chat_id = update.effective_chat.id
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    conn = connected(bot, update, chat, user.id, need_admin=False)
    if not conn == False:
        chat_id = conn
        send_id = user.id
    else:
        chat_id = update.effective_chat.id
        send_id = chat_id

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

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

        if note.is_reply:
            if MESSAGE_DUMP:
                try:
                    bot.forward_message(chat_id=chat_id,
                                        from_chat_id=MESSAGE_DUMP,
                                        message_id=note.value)
                except BadRequest as excp:
                    if excp.message == "pesan untuk diteruskan tidak ditemukan!":
                        message.reply_text(
                            "pesan ini sepertinya sudah hilang - saya akan menghapusnya "
                            "dari daftar catatan anda.")
                        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 == "pesan untuk diteruskan tidak ditemukan!":
                        message.reply_text(
                            "sepertinya pengirim asli catatan ini telah menghapus "
                            "pesan mereka - maaf, minta admin bot anda untuk mulai melakukan "
                            "penghapusan pesan untuk menghindari hal ini, saya akan menghapus catatan ini dari "
                            "catatan yang anda simpan.")
                        sql.rm_note(chat_id, notename)
                    else:
                        raise
        else:
            text = note.value
            keyb = []
            parseMode = ParseMode.MARKDOWN
            buttons = sql.get_buttons(chat_id, notename)
            should_preview_disabled = True
            if no_format:
                parseMode = None
                text += revert_buttons(buttons)
            else:
                keyb = build_keyboard(buttons)
                if "telegra.ph" in text or "youtu.be" in text:
                    should_preview_disabled = False

            keyboard = InlineKeyboardMarkup(keyb)

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

            except BadRequest as excp:
                if excp.message == "Entity_mention_user_invalid":
                    message.reply_text(
                        "Sepertinya Anda mencoba menyebut seseorang yang belum pernah saya lihat sebelumnya. Jika Anda benar-benar"
                        "ingin menyebutkan mereka, meneruskan salah satu pesan mereka kepada saya, dan saya akan bisa"
                        "untuk menandai mereka!")
                elif FILE_MATCHER.match(note.value):
                    message.reply_text(
                        "Catatan ini adalah file yang diimpor dengan tidak benar dari bot lain - saya tidak dapat menggunakan"
                        "itu. Jika Anda benar-benar membutuhkannya, Anda harus menyimpannya lagi. Dalam"
                        "Sementara itu, saya akan menghapusnya dari daftar catatan Anda."
                    )
                    sql.rm_note(chat_id, notename)
                else:
                    message.reply_text(
                        "Catatan ini tidak dapat dikirim, karena formatnya salah. Tanyakan dalam"
                        "@levinachannel jika Anda tidak tahu mengapa!")
                    LOGGER.exception("Could not parse message #%s in chat %s",
                                     notename, str(chat_id))
                    LOGGER.warning("Message was: %s", str(note.value))
        return
    elif show_none:
        message.reply_text("note ini tidak tersedia")
Ejemplo n.º 13
0
def get(bot, update, notename, show_none=True, no_format=False):
    chat_id = update.effective_chat.id
    note = sql.get_note(chat_id, notename)
    message = update.effective_message  # type: Optional[Message]

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

        if note.is_reply:
            if 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("이 메시지가 손실된 것 같아요. - 기록 목록에서 "
                                           "제거할게요.")
                        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(
                            "이 노트의 원래 발신인이 메시지를 삭제한 것 같아요. "
                            "미안해요! 이를 방지하기 위해 봇 관리자에게 메시지 덤프 사용을 "
                            "시작하도록 하세요. "
                            "저장된 노트에서 이 노트를 제거할게요.")
                        sql.rm_note(chat_id, notename)
                    else:
                        raise
        else:
            text = note.value
            keyb = []
            parseMode = ParseMode.MARKDOWN
            buttons = sql.get_buttons(chat_id, notename)
            if no_format:
                parseMode = None
                text += revert_buttons(buttons)
            else:
                keyb = build_keyboard(buttons)

            keyboard = InlineKeyboardMarkup(keyb)

            try:
                if note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT):
                    bot.send_message(chat_id,
                                     text,
                                     reply_to_message_id=reply_id,
                                     parse_mode=parseMode,
                                     disable_web_page_preview=True,
                                     reply_markup=keyboard)
                else:
                    ENUM_FUNC_MAP[note.msgtype](chat_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(
                        "전에 본 적이 없는 사람을 언급하려 했던 것 같군요. "
                        "정말로 그들에 대해 언급하고 싶다면, 그들의 메시지들 중 하나를 나에게 전달해주세요, "
                        "그러면 저는 그들에게 태그를 붙일 수 있을 거예요!")
                elif FILE_MATCHER.match(note.value):
                    message.reply_text("이 노트는 다른 봇에서 잘못 가져온 파일이에요 - 전 그것을 "
                                       "사용할 수 없어요. 만약 정말 필요하다면, 다시 저장할 수 있어요. "
                                       "그동안에 그것을 메모 목록에서 삭제해 드릴게요.")
                    sql.rm_note(chat_id, notename)
                else:
                    message.reply_text("이 노트의 형식이 잘못되었기 때문에 보낼 수 없어요. "
                                       "이유를 알 수 없다면 @MarieSupport 에 문의하세요!")
                    LOGGER.exception("메시지를 구문 분석할 수 없어요 #%s  - %s ", notename,
                                     str(chat_id))
                    LOGGER.warning("메시지가 있었어요: %s", str(note.value))
        return
    elif show_none:
        message.reply_text("이 기록은 존재하지 않아요.")
Ejemplo n.º 14
0
def get(bot, update, notename, show_none=True, no_format=False):
    chat_id = update.effective_chat.id
    note = sql.get_note(chat_id, notename)
    message = update.effective_message  # type: Optional[Message]

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

        if note.is_reply:
            if 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(
                            "پیامی که نشونم داده بودی رو گم کردم😶 "
                            "از لیست پاکش میکنم.")
                        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(
                            "عه فک کنم کسی که صاحب فایل بود دیلیت زده "
                            "لطفا دوباره از اول"
                            "برام تعریف کن این قسمتو . تا اون موقع "
                            "من  این بخشو از لیست پاک میکنم")
                        sql.rm_note(chat_id, notename)
                    else:
                        raise
        else:
            text = note.value
            keyb = []
            parseMode = ParseMode.MARKDOWN
            buttons = sql.get_buttons(chat_id, notename)
            if no_format:
                parseMode = None
                text += revert_buttons(buttons)
            else:
                keyb = build_keyboard(buttons)

            keyboard = InlineKeyboardMarkup(keyb)

            try:
                if note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT):
                    bot.send_message(chat_id,
                                     text,
                                     reply_to_message_id=reply_id,
                                     parse_mode=parseMode,
                                     disable_web_page_preview=True,
                                     reply_markup=keyboard)
                else:
                    ENUM_FUNC_MAP[note.msgtype](chat_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(
                        "اومم بنظر میاد میخوای یه شخصو بهم معرفی کنی که من تا حالا ندیدمش "
                        "اگه واقعا لازمه که اون شخصو من اضافه کنم . اول یه پیام ازش فوروارد کن "
                        "تا بتونم تگش کنم!")
                elif FILE_MATCHER.match(note.value):
                    message.reply_text(
                        "اومم ما رباتا نمیتونیم از اموال هم اسکی بریم . زشته! "
                        "اگه واقعا نیازه . یا از فور پیشرفته استفاده کن یا دوباره برام  "
                        "آپلود کن که لو نریم🤪.")
                    sql.rm_note(chat_id, notename)
                else:
                    message.reply_text(
                        "فرمت این فایل برای من مجاز نیست . حق ندارم اینو نگه دارم! "
                        "با @colonel294 ارتباط برقرار کن واسه دلیلش!")
                    LOGGER.exception("Could not parse message #%s in chat %s",
                                     notename, str(chat_id))
                    LOGGER.warning("Message was: %s", str(note.value))
        return
    elif show_none:
        message.reply_text("این هشتگ دیگه وجود نداره!")
Ejemplo n.º 15
0
def get(bot, update, notename, show_none=True, no_format=False):
    chat_id = update.effective_chat.id
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    conn = connected(bot, update, chat, user.id, need_admin=False)
    if not conn == False:
        chat_id = conn
        send_id = user.id
    else:
        chat_id = update.effective_chat.id
        send_id = chat_id

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

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

        if note.is_reply:
            if MESSAGE_DUMP:
                try:
                    bot.forward_message(chat_id=chat_id,
                                        from_chat_id=MESSAGE_DUMP,
                                        message_id=note.value)
                except BadRequest as excp:
                    if excp.message == "Message to forward not found":
                        message.reply_text(
                            "Wygląda na to że ta wiadomość się zagubiła - Usunę ją "
                            "z twojej listy notek.")
                        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(
                            "Wygląda na to że oryginalny wysyłający usunął swoją "
                            "wiadomość - przepraszam! Poproś administratora bota aby zasczął "
                            "tworzyć zrzuty wiadomości żeby uniknąć takich rzeczy. "
                            "Usunę tą notkę z twoich zapisanych notek.")
                        sql.rm_note(chat_id, notename)
                    else:
                        raise
        else:
            text = note.value
            keyb = []
            parseMode = ParseMode.MARKDOWN
            buttons = sql.get_buttons(chat_id, notename)
            should_preview_disabled = True
            if no_format:
                parseMode = None
                text += revert_buttons(buttons)
            else:
                keyb = build_keyboard(buttons)
                if "telegra.ph" in text or "youtu.be" in text:
                    should_preview_disabled = False

            keyboard = InlineKeyboardMarkup(keyb)

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

            except BadRequest as excp:
                if excp.message == "Entity_mention_user_invalid":
                    message.reply_text(
                        "Wygląda na to że próbujesz wspomnieć o futrzaku którego nigdy nie widziałem wcześniej. Jeżeli serio "
                        "go wspomnieć, prześlij mi jedną wiadomość od tego futrzaka do mnie a ja będę mógł wtedy "
                        "go otagować!")
                elif FILE_MATCHER.match(note.value):
                    message.reply_text(
                        "Ta notka jest niepoprawna zimportowana od innego bota - Nie mogę "
                        "użyć jej. Jeżeli serio chcesz ją mieć, musisz ją zapisać ponownie. Przez "
                        "ten czas usunę ją z listy twoich notek.")
                    sql.rm_note(chat_id, notename)
                else:
                    message.reply_text(
                        "Nie można wysłać tej notki, ponieważ jest niepoprawnie sformatowana. Spytaj "
                        "na @MarieSupport jeśli nie możesz zrozumieć dlaczego!"
                    )
                    LOGGER.exception(
                        "Nie można sparsować notki #%s w czacie %s", notename,
                        str(chat_id))
                    LOGGER.warning("Wiadomość była: %s", str(note.value))
        return
    elif show_none:
        message.reply_text("Ta notka nie istnieje")
Ejemplo n.º 16
0
def get(bot, update, notename, show_none=True, no_format=False):
    chat_id = update.effective_chat.id
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    conn = connected(bot, update, chat, user.id, need_admin=False)
    if conn:
        chat_id = conn
        send_id = user.id
    else:
        chat_id = update.effective_chat.id
        send_id = chat_id

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

    if note:
        if MessageHandlerChecker.check_user(update.effective_user.id):
            return

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

        if note.is_reply:
            if MESSAGE_DUMP:
                try:
                    bot.forward_message(
                        chat_id=update.effective_chat.id,
                        from_chat_id=MESSAGE_DUMP,
                        message_id=note.value,
                    )
                except BadRequest as excp:
                    if excp.message == "Message to forward not found":
                        message.reply_text(
                            "This message seems to have been lost - I'll remove it "
                            "from your notes list.")
                        sql.rm_note(chat_id, notename)
                    else:
                        raise
            else:
                try:
                    bot.forward_message(
                        chat_id=update.effective_chat.id,
                        from_chat_id=chat_id,
                        message_id=note.value,
                    )
                except BadRequest as excp:
                    if excp.message == "Message to forward not found":
                        message.reply_text(
                            "Looks like the original sender of this note has deleted "
                            "their message - sorry! Get your bot admin to start using a "
                            "message dump to avoid this. I'll remove this note from "
                            "your saved notes.")
                        sql.rm_note(chat_id, notename)
                    else:
                        raise
        else:
            VALID_NOTE_FORMATTERS = [
                "first",
                "last",
                "fullname",
                "username",
                "id",
                "chatname",
                "mention",
            ]
            valid_format = escape_invalid_curly_brackets(
                note.value, VALID_NOTE_FORMATTERS)
            if valid_format:
                text = valid_format.format(
                    first=escape(message.from_user.first_name),
                    last=escape(message.from_user.last_name
                                or message.from_user.first_name),
                    fullname=" ".join([
                        escape(message.from_user.first_name),
                        escape(message.from_user.last_name),
                    ] if message.from_user.last_name else
                                      [escape(message.from_user.first_name)]),
                    username="******" + escape(message.from_user.username)
                    if message.from_user.username else mention_html(
                        message.from_user.id, message.from_user.first_name),
                    mention=mention_html(message.from_user.id,
                                         message.from_user.first_name),
                    chatname=escape(message.chat.title)
                    if message.chat.type != "private" else escape(
                        message.from_user.first_name),
                    id=message.from_user.id,
                )
            else:
                text = ""

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

            keyboard = InlineKeyboardMarkup(keyb)

            try:
                if note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT):
                    bot.send_message(
                        update.effective_chat.id,
                        text,
                        reply_to_message_id=reply_id,
                        parse_mode=parseMode,
                        disable_web_page_preview=True,
                        reply_markup=keyboard,
                    )
                else:
                    ENUM_FUNC_MAP[note.msgtype](
                        update.effective_chat.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(
                        "Looks like you tried to mention someone I've never seen before. If you really "
                        "want to mention them, forward one of their messages to me, and I'll be able "
                        "to tag them!")
                elif FILE_MATCHER.match(note.value):
                    message.reply_text(
                        "This note was an incorrectly imported file from another bot - I can't use "
                        "it. If you really need it, you'll have to save it again. In "
                        "the meantime, I'll remove it from your notes list.")
                    sql.rm_note(chat_id, notename)
                else:
                    message.reply_text(
                        "This note could not be sent, as it is incorrectly formatted."
                    )

                    LOGGER.exception("Could not parse message #%s in chat %s",
                                     notename, str(chat_id))
                    LOGGER.warning("Message was: %s", str(note.value))
        return
    if show_none:
        message.reply_text("This note doesn't exist")
Ejemplo n.º 17
0
def get(bot, update, notename, show_none=True, no_format=False):
    chat_id = update.effective_chat.id
    message = update.effective_message  # type: Optional[Message]
    timer = sql.get_clearnotes(chat_id)
    delmsg = ""
    count = 0

    if notename.isnumeric():
        check = sql.get_note(chat_id, notename)
        # If check == true, it means that notename and noteid conflicts each other
        if check:
            message.reply_text(warning.format(notename=notename))
        # If check == false, it means that we need to search notename for given noteid
        else:
            note_list = sql.get_all_chat_notes(chat_id)
            for note in note_list:
                count = count + 1
                if str(count) == notename:
                    notename = note.name
                    break  # As it can be overwritten later

    note = sql.get_note(chat_id, notename)  # Removed lower() for compatibility

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

            keyboard = InlineKeyboardMarkup(keyb)

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

            except BadRequest as excp:
                if excp.message == "Entity_mention_user_invalid":
                    message.reply_text(
                        "Looks like you tried to mention someone I've never seen before. If you really "
                        "want to mention them, forward one of their messages to me, and I'll be able "
                        "to tag them!")
                elif FILE_MATCHER.match(note.value):
                    message.reply_text(
                        "This note was an incorrectly imported file from another bot - I can't use "
                        "it. If you really need it, you'll have to save it again. In "
                        "the meantime, I'll remove it from your notes list.")
                    sql.rm_note(chat_id, notename)
                else:
                    message.reply_text(
                        "This note could not be sent, as it is incorrectly formatted. Ask in "
                        "@bot_workshop if you can't figure out why!")
                    LOGGER.exception("Could not parse message #%s in chat %s",
                                     notename, str(chat_id))
                    LOGGER.warning("Message was: %s", str(note.value))
        if timer != 0:
            sleep(int(timer))
            try:
                delmsg.delete()
                message.delete()
            except:
                pass
        return
    if show_none:
        message.reply_text("This note doesn't exist")
Ejemplo n.º 18
0
def export_data(bot: Bot, update: Update, chat_data):
    msg = update.effective_message  # type: Optional[Message]
    user = update.effective_user  # type: Optional[User]

    chat_id = update.effective_chat.id
    chat = update.effective_chat
    current_chat_id = update.effective_chat.id

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

    note_list = sql.get_all_chat_notes(chat_id)
    backup = {}
    notes = {}
    button = ""
    buttonlist = []
    namacat = ""
    isicat = ""
    rules = ""
    count = 0
    countbtn = 0
    # Backuping notes
    note_list = notesql.get_all_chat_notes(chat_id)
    notes = []
    for note in note_list:
        buttonlist = ""
        note_tag = note.name
        note_type = note.msgtype
        getnote = notesql.get_note(chat_id, note.name)
        if not note.value:
            note_data = ""
        else:
            tombol = notesql.get_buttons(chat_id, note_tag)
            keyb = []
            buttonlist = ""
            for btn in tombol:
                if btn.same_line:
                    buttonlist += "[{}](buttonurl:{}:same)\n".format(
                        btn.name, btn.url)
                else:
                    buttonlist += "[{}](buttonurl:{})\n".format(
                        btn.name, btn.url)
            note_data = "{}\n\n{}".format(note.value, buttonlist)
        note_file = note.file
        if not note_file:
            note_file = ""
        notes.append({
            "note_tag": note_tag,
            "note_data": note_data,
            "note_file": note_file,
            "note_type": note_type
        })
    # Rules
    rules = rulessql.get_rules(chat_id)
    # Blacklist
    bl = list(blacklistsql.get_chat_blacklist(chat_id))
    # Disabled command
    disabledcmd = list(disabledsql.get_all_disabled(chat_id))
    # Filters (TODO)
    """
	all_filters = list(filtersql.get_chat_triggers(chat_id))
	export_filters = {}
	for filters in all_filters:
		filt = filtersql.get_filter(chat_id, filters)
		# print(vars(filt))
		if filt.is_sticker:
			tipefilt = "sticker"
		elif filt.is_document:
			tipefilt = "doc"
		elif filt.is_image:
			tipefilt = "img"
		elif filt.is_audio:
			tipefilt = "audio"
		elif filt.is_voice:
			tipefilt = "voice"
		elif filt.is_video:
			tipefilt = "video"
		elif filt.has_buttons:
			tipefilt = "button"
			buttons = filtersql.get_buttons(chat.id, filt.keyword)
			print(vars(buttons))
		elif filt.has_markdown:
			tipefilt = "text"
		if tipefilt == "button":
			content = "{}#=#{}|btn|{}".format(tipefilt, filt.reply, buttons)
		else:
			content = "{}#=#{}".format(tipefilt, filt.reply)
		print(content)
		export_filters[filters] = content
	print(export_filters)
	"""
    # Welcome (TODO)
    # welc = welcsql.get_welc_pref(chat_id)
    # Locked
    locks = locksql.get_locks(chat_id)
    locked = []
    if locks:
        if locks.sticker:
            locked.append('sticker')
        if locks.document:
            locked.append('document')
        if locks.contact:
            locked.append('contact')
        if locks.audio:
            locked.append('audio')
        if locks.game:
            locked.append('game')
        if locks.bots:
            locked.append('bots')
        if locks.gif:
            locked.append('gif')
        if locks.photo:
            locked.append('photo')
        if locks.video:
            locked.append('video')
        if locks.voice:
            locked.append('voice')
        if locks.location:
            locked.append('location')
        if locks.forward:
            locked.append('forward')
        if locks.url:
            locked.append('url')
        restr = locksql.get_restr(chat_id)
        if restr.other:
            locked.append('other')
        if restr.messages:
            locked.append('messages')
        if restr.preview:
            locked.append('preview')
        if restr.media:
            locked.append('media')
    # Warns (TODO)
    # warns = warnssql.get_warns(chat_id)
    # Backing up
    backup[chat_id] = {
        'bot': bot.id,
        'hashes': {
            'info': {
                'rules': rules
            },
            'extra': notes,
            'blacklist': bl,
            'disabled': disabledcmd,
            'locks': locked
        }
    }
    baccinfo = json.dumps(backup, indent=4)
    f = open("Ctrl{}.backup".format(chat_id), "w")
    f.write(str(baccinfo))
    f.close()
    bot.sendChatAction(current_chat_id, "upload_document")
    tgl = time.strftime("%H:%M:%S - %d/%m/%Y", time.localtime(time.time()))
    try:
        bot.sendMessage(
            MESSAGE_DUMP,
            "*Successfully imported backup:*\nChat: `{}`\nChat ID: `{}`\nOn: `{}`"
            .format(chat.title, chat_id, tgl),
            parse_mode=ParseMode.MARKDOWN)
    except BadRequest:
        pass
    bot.sendDocument(
        current_chat_id,
        document=open('Ctrl{}.backup'.format(chat_id), 'rb'),
        caption=
        "*Successfully imported backup:*\nChat: `{}`\nChat ID: `{}`\nOn: `{}`\n\nNote: This `Ctrl's Backup` is specially made for notes."
        .format(chat.title, chat_id, tgl),
        timeout=360,
        reply_to_message_id=msg.message_id,
        parse_mode=ParseMode.MARKDOWN)
    os.remove("CTRL{}.backup".format(chat_id))  # Cleaning file
Ejemplo n.º 19
0
def export_data(bot: Bot, update: Update, chat_data):
    msg = update.effective_message  # type: Optional[Message]
    user = update.effective_user  # type: Optional[User]

    chat_id = update.effective_chat.id
    chat = update.effective_chat
    current_chat_id = update.effective_chat.id

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

    jam = time.time()
    new_jam = jam + 10800
    checkchat = get_chat(chat_id, chat_data)
    if checkchat.get('status'):
        if jam <= int(checkchat.get('value')):
            timeformatt = time.strftime("%H:%M:%S %d/%m/%Y",
                                        time.localtime(checkchat.get('value')))
            update.effective_message.reply_text(
                "You can only backup once a day!\nYou can backup again in about `{}`"
                .format(timeformatt),
                parse_mode=ParseMode.MARKDOWN)
            return
        else:
            if user.id != 802002142:
                put_chat(chat_id, new_jam, chat_data)
    else:
        if user.id != 802002142:
            put_chat(chat_id, new_jam, chat_data)

    note_list = sql.get_all_chat_notes(chat_id)
    backup = {}
    notes = {}
    button = ""
    buttonlist = []
    namacat = ""
    isicat = ""
    rules = ""
    count = 0
    countbtn = 0
    # Notes
    for note in note_list:
        count += 1
        getnote = sql.get_note(chat_id, note.name)
        namacat += '{}<###splitter###>'.format(note.name)
        if note.msgtype == 1:
            tombol = sql.get_buttons(chat_id, note.name)
            keyb = []
            for btn in tombol:
                countbtn += 1
                if btn.same_line:
                    buttonlist.append(
                        ('{}'.format(btn.name), '{}'.format(btn.url), True))
                else:
                    buttonlist.append(
                        ('{}'.format(btn.name), '{}'.format(btn.url), False))
            isicat += '###button###: {}<###button###>{}<###splitter###>'.format(
                note.value, str(buttonlist))
            buttonlist.clear()
        elif note.msgtype == 2:
            isicat += '###sticker###:{}<###splitter###>'.format(note.file)
        elif note.msgtype == 3:
            isicat += '###file###:{}<###TYPESPLIT###>{}<###splitter###>'.format(
                note.file, note.value)
        elif note.msgtype == 4:
            isicat += '###photo###:{}<###TYPESPLIT###>{}<###splitter###>'.format(
                note.file, note.value)
        elif note.msgtype == 5:
            isicat += '###audio###:{}<###TYPESPLIT###>{}<###splitter###>'.format(
                note.file, note.value)
        elif note.msgtype == 6:
            isicat += '###voice###:{}<###TYPESPLIT###>{}<###splitter###>'.format(
                note.file, note.value)
        elif note.msgtype == 7:
            isicat += '###video###:{}<###TYPESPLIT###>{}<###splitter###>'.format(
                note.file, note.value)
        elif note.msgtype == 8:
            isicat += '###video_note###:{}<###TYPESPLIT###>{}<###splitter###>'.format(
                note.file, note.value)
        else:
            isicat += '{}<###splitter###>'.format(note.value)
    for x in range(count):
        notes['#{}'.format(
            namacat.split("<###splitter###>")[x])] = '{}'.format(
                isicat.split("<###splitter###>")[x])
    # Rules
    rules = rulessql.get_rules(chat_id)
    # Blacklist
    bl = list(blacklistsql.get_chat_blacklist(chat_id))
    # Disabled command
    disabledcmd = list(disabledsql.get_all_disabled(chat_id))
    # Filters (TODO)

    locks = locksql.get_locks(chat_id)
    locked = []
    if locks:
        if locks.sticker:
            locked.append('sticker')
        if locks.document:
            locked.append('document')
        if locks.contact:
            locked.append('contact')
        if locks.audio:
            locked.append('audio')
        if locks.game:
            locked.append('game')
        if locks.bots:
            locked.append('bots')
        if locks.gif:
            locked.append('gif')
        if locks.photo:
            locked.append('photo')
        if locks.video:
            locked.append('video')
        if locks.voice:
            locked.append('voice')
        if locks.location:
            locked.append('location')
        if locks.forward:
            locked.append('forward')
        if locks.url:
            locked.append('url')
        restr = locksql.get_restr(chat_id)
        if restr.other:
            locked.append('other')
        if restr.messages:
            locked.append('messages')
        if restr.preview:
            locked.append('preview')
        if restr.media:
            locked.append('media')
    # Warns (TODO)
    # warns = warnssql.get_warns(chat_id)
    # Backing up
    backup[chat_id] = {
        'bot': bot.id,
        'hashes': {
            'info': {
                'rules': rules
            },
            'extra': notes,
            'blacklist': bl,
            'disabled': disabledcmd,
            'locks': locked
        }
    }
    baccinfo = json.dumps(backup, indent=4)
    f = open("Reaper{}.backup".format(chat_id), "w")
    f.write(str(baccinfo))
    f.close()
    bot.sendChatAction(current_chat_id, "upload_document")
    tgl = time.strftime("%H:%M:%S - %d/%m/%Y", time.localtime(time.time()))
    try:
        bot.sendMessage(
            MESSAGE_DUMP,
            "*Successfully imported backup:*\nChat: `{}`\nChat ID: `{}`\nOn: `{}`"
            .format(chat.title, chat_id, tgl),
            parse_mode=ParseMode.MARKDOWN)
    except BadRequest:
        pass
    bot.sendDocument(
        current_chat_id,
        document=open('lucifer{}.backup'.format(chat_id), 'rb'),
        caption=
        "*Successfully imported backup:*\nChat: `{}`\nChat ID: `{}`\nOn: `{}`\n\nNote: This  is specially made for notes."
        .format(chat.title, chat_id, tgl),
        timeout=360,
        reply_to_message_id=msg.message_id,
        parse_mode=ParseMode.MARKDOWN)
    os.remove("lucifer{}.backup".format(chat_id))  # Cleaning file
Ejemplo n.º 20
0
def get(bot, update, notename, show_none=True):
    chat_id = update.effective_chat.id
    note = sql.get_note(chat_id, notename)
    message = update.effective_message

    if note:
        # If not is replying to a message, reply to that message (unless its an error)
        if message.reply_to_message:
            reply_text = message.reply_to_message.reply_text
        else:
            reply_text = message.reply_text

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

            keyboard = InlineKeyboardMarkup(keyb)
            try:
                reply_text(note.value,
                           parse_mode=ParseMode.MARKDOWN,
                           disable_web_page_preview=True,
                           reply_markup=keyboard)
            except BadRequest as excp:
                if excp.message == "Entity_mention_user_invalid":
                    message.reply_text(
                        "Looks like you tried to mention someone I've never seen before. If you really "
                        "want to mention them, forward one of their messages to me, and I'll be able "
                        "to tag them!")
                else:
                    message.reply_text(
                        "This note is not formatted correctly. Could not send. Contact @{} if you "
                        "can't figure out why!".format(OWNER_USERNAME))
                    print("ERROR: could not parse:" + note.value)
                    raise
        return
    elif show_none:
        message.reply_text("This note doesn't exist")