示例#1
0
def save(update: Update, context: CallbackContext):
    chat_id = update.effective_chat.id
    msg = update.effective_message  # type: Optional[Message]

    note_name, text, data_type, content, buttons = get_note_type(msg)
    note_name = note_name.lower()
    if data_type is None:
        msg.reply_text("Dude, there's no note")
        return

    sql.add_note_to_db(chat_id,
                       note_name,
                       text,
                       data_type,
                       buttons=buttons,
                       file=content)

    msg.reply_text(
        f"Yas! Added `{note_name}`.\nGet it with /get `{note_name}`, or `#{note_name}`",
        parse_mode=ParseMode.MARKDOWN,
    )

    if msg.reply_to_message and msg.reply_to_message.from_user.is_bot:
        if text:
            msg.reply_text(
                "Seems like you're trying to save a message from a bot. Unfortunately, "
                "bots can't forward bot messages, so I can't save the exact message. "
                "\nI'll save all the text I can, but if you want more, you'll have to "
                "forward the message yourself, and then save it.")
        else:
            msg.reply_text(
                "Bots are kinda handicapped by telegram, making it hard for bots to "
                "interact with other bots, so I can't save this message "
                "like I usually would - do you mind forwarding it and "
                "then saving that new message? Thanks!")
        return
示例#2
0
文件: notes.py 项目: kari-36/marie
def __import_data__(chat_id, data):
    failures = []
    for notename, notedata in data.get('extra', {}).items():
        match = FILE_MATCHER.match(notedata)

        if match:
            failures.append(notename)
            notedata = notedata[match.end():].strip()
            if notedata:
                sql.add_note_to_db(chat_id, notename[1:], notedata,
                                   sql.Types.TEXT)
        else:
            sql.add_note_to_db(chat_id, notename[1:], notedata, sql.Types.TEXT)

    if failures:
        with BytesIO(str.encode("\n".join(failures))) as output:
            output.name = "failed_imports.txt"
            dispatcher.bot.send_document(
                chat_id,
                document=output,
                filename="failed_imports.txt",
                caption="These files/photos failed to import due to originating "
                "from another bot. This is a telegram API restriction, and can't "
                "be avoided. Sorry for the inconvenience!")
示例#3
0
文件: notes.py 项目: Rohk25/tgbot
def save_replied(bot, update):
    chat_id = update.effective_chat.id
    text = update.effective_message.text
    args = text.split(
        None, 3)  # use python's maxsplit to separate Cmd, note_name, and data
    if len(args) == 3 and args[1] == "from":
        notename = args[2]
    elif len(args) >= 2:
        notename = args[1]
    else:
        update.effective_message.reply_text(
            "You need to give me a notename to save this message!")
        return

    msg = update.effective_message.reply_to_message

    if MESSAGE_DUMP:
        msg = bot.forward_message(chat_id=MESSAGE_DUMP,
                                  from_chat_id=chat_id,
                                  message_id=msg.message_id)

    sql.add_note_to_db(chat_id, notename, msg.message_id, is_reply=True)
    update.effective_message.reply_text("Yas! Added replied message " +
                                        notename)
示例#4
0
def __import_data__(chat_id, data):
    failures = []
    for notename, notedata in data.get('extra', {}).items():
        match = FILE_MATCHER.match(notedata)

        if match:
            failures.append(notename)
            notedata = notedata[match.end():].strip()
            if notedata:
                sql.add_note_to_db(chat_id, notename[1:], notedata,
                                   sql.Types.TEXT)
        else:
            sql.add_note_to_db(chat_id, notename[1:], notedata, sql.Types.TEXT)

    if failures:
        with BytesIO(str.encode("\n".join(failures))) as output:
            output.name = "failed_imports.txt"
            dispatcher.bot.send_document(
                chat_id,
                document=output,
                filename="failed_imports.txt",
                caption="이러한 파일/사진은 다른 봇이 보냈기 때문에 가져오지 못했어요. "
                "이것은 Telegram API 제한사항이므로 피할 수 없어요. "
                "불편을 끼쳐드려 죄송합니다!")
示例#5
0
def save(bot: Bot, update: Update):
    chat_id = update.effective_chat.id
    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("메모가 존재하지 않아요!")
        return

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

    sql.add_note_to_db(chat_id,
                       note_name,
                       text,
                       data_type,
                       buttons=buttons,
                       file=content)

    msg.reply_text(
        "{note_name} 을(를) 추가했어요.\n/get {note_name} 또는 #{note_name} 을(를) 이용하여 노트를 가져옵니다."
        .format(note_name=note_name))

    if msg.reply_to_message and msg.reply_to_message.from_user.is_bot:
        if text:
            msg.reply_text("저에게 메시지를 저장하려고 하는 것 같아요. 불행하게도, "
                           "봇은 봇의 메시지를 전달할 수 없어요, 그래서 전 정확한 메시지를 저장할 수 없어요. "
                           "\n가능한 한 모든 메시지들을 저장하겠지만, "
                           "더 많은 내용을 원한다면 직접 메시지를 전달하고 저장해야 해요.")
        else:
            msg.reply_text("봇들은 Telegram 으로 인한 장애가 있어서, 봇이 다른 봇과 상호작용하기 "
                           "힘들기 때문에 이 메시지를 평소와 같이 "
                           "저장하실 수 없어요 - 그 메시지를 전달하고 나서 그 새로운 메시지를 저장해도 "
                           "괜찮을까요? 고마워요!")
        return
示例#6
0
def __import_data__(chat_id, data):
    failures = []
    for notename, notedata in data.get('extra', {}).items():
        match = FILE_MATCHER.match(notedata)

        if match:
            failures.append(notename)
            notedata = notedata[match.end():].strip()
            if notedata:
                sql.add_note_to_db(chat_id, notename[1:], notedata,
                                   sql.Types.TEXT)
        else:
            sql.add_note_to_db(chat_id, notename[1:], notedata, sql.Types.TEXT)

    if failures:
        with BytesIO(str.encode("\n".join(failures))) as output:
            output.name = "failed_imports.txt"
            dispatcher.bot.send_document(
                chat_id,
                document=output,
                filename="failed_imports.txt",
                caption="این فایل یا عکس ها رو نمیتونم پردازش کنم "
                "چون از طرف یه ربات دیگه هستن و تلگرام اجازه بهم نمیده "
                "ببخشید ولی در این مورد کاری ازم ساخته نیس!!")
示例#7
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 not conn == False:
        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

    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)
示例#8
0
def import_data(bot: Bot, update):
    msg = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    # TODO: allow uploading doc with command, not just as reply
    # only work with a doc
    conn = connected(bot, update, chat, user.id, need_admin=True)
    if conn:
        chat = dispatcher.bot.getChat(conn)
        chat_id = conn
        chat_name = dispatcher.bot.getChat(conn).title
    else:
        if update.effective_message.chat.type == "private":
            update.effective_message.reply_text(
                "This command can only be runned on group, not PM.")
            return ""
        chat = update.effective_chat
        chat_id = update.effective_chat.id
        chat_name = update.effective_message.chat.title

    if msg.reply_to_message and msg.reply_to_message.document:
        filetype = msg.reply_to_message.document.file_name
        if filetype.split('.')[-1] not in ("backup", "json", "txt"):
            msg.reply_text("File is not valid!")
            return
        try:
            file_info = bot.get_file(msg.reply_to_message.document.file_id)
        except BadRequest:
            msg.reply_text(
                "Try downloading and uploading the file yourself again, This one seem broken!"
            )
            return

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

        try:
            # If backup is from Monica
            if data.get('bot_base') == "Monica":
                imp_notes = 0
                NOT_IMPORTED = "This cannot be imported because from other bot."
                NOT_IMPORTED_INT = 0
                # If backup is from this bot, import all files
                if data.get('bot_id') == bot.id:
                    is_self = True
                else:
                    is_self = False

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

                if conn:
                    text = (update.effective_message,
                            "Full backup returned on *{}*. Welcome backup! "
                            ).format(chat_name)
                else:
                    text = (
                        update.effective_message,
                        "Backup fully restored.\nDone with welcome backup! "
                    ).format(chat_name)
                try:
                    msg.reply_text(text, parse_mode="markdown")
                except BadRequest:
                    msg.reply_text(text, parse_mode="markdown", quote=False)
                if NOT_IMPORTED_INT:
                    f = open("{}-notimported.txt".format(chat_id), "w")
                    f.write(str(NOT_IMPORTED))
                    f.close()
                    bot.sendDocument(
                        chat_id,
                        document=open('{}-notimported.txt'.format(chat_id),
                                      'rb'),
                        caption=tl(update.effective_message,
                                   "*Data that can't be imported*"),
                        timeout=360,
                        parse_mode=ParseMode.MARKDOWN)
                    os.remove("{}-notimported.txt".format(chat_id))
                return
        except Exception as err:
            msg.reply_text(tl(
                update.effective_message,
                "An error has occurred getting Ctrl backup!\nGo, ping [Support Chat](https://t.me/ctrlsupport) and ask if any solution of it!\n\nMaybe they can resolve your issue!"
            ),
                           parse_mode="markdown")
            LOGGER.exception("An error when importing from Julie base!")
            return

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

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

        try:
            for mod in DATA_IMPORT:
                mod.__import_data__(str(chat.id), data)
        except Exception:
            msg.reply_text(
                "An error occurred while recovering your data. The process failed. If you experience a problem with this, please ask in @ctrlsupport!\nThank you!"
            )

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

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

            text = "Backup fully restored on *{}*.".format(chat_name)
        else:
            text = "Backup fully restored"
        msg.reply_text(text, parse_mode="markdown")
示例#9
0
def __import_data__(chat_id, data):
    failures = []
    for notename, notedata in data.get("extra", {}).items():
        match = FILE_MATCHER.match(notedata)
        matchsticker = STICKER_MATCHER.match(notedata)
        matchbtn = BUTTON_MATCHER.match(notedata)
        matchfile = MYFILE_MATCHER.match(notedata)
        matchphoto = MYPHOTO_MATCHER.match(notedata)
        matchaudio = MYAUDIO_MATCHER.match(notedata)
        matchvoice = MYVOICE_MATCHER.match(notedata)
        matchvideo = MYVIDEO_MATCHER.match(notedata)
        matchvn = MYVIDEONOTE_MATCHER.match(notedata)

        if match:
            failures.append(notename)
            notedata = notedata[match.end() :].strip()
            if notedata:
                sql.add_note_to_db(chat_id, notename[1:], notedata, sql.Types.TEXT)
        elif matchsticker:
            content = notedata[matchsticker.end() :].strip()
            if content:
                sql.add_note_to_db(
                    chat_id, notename[1:], notedata, sql.Types.STICKER, file=content
                )
        elif matchbtn:
            parse = notedata[matchbtn.end() :].strip()
            notedata = parse.split("<###button###>")[0]
            buttons = parse.split("<###button###>")[1]
            buttons = ast.literal_eval(buttons)
            if buttons:
                sql.add_note_to_db(
                    chat_id,
                    notename[1:],
                    notedata,
                    sql.Types.BUTTON_TEXT,
                    buttons=buttons,
                )
        elif matchfile:
            file = notedata[matchfile.end() :].strip()
            file = file.split("<###TYPESPLIT###>")
            notedata = file[1]
            content = file[0]
            if content:
                sql.add_note_to_db(
                    chat_id, notename[1:], notedata, sql.Types.DOCUMENT, file=content
                )
        elif matchphoto:
            photo = notedata[matchphoto.end() :].strip()
            photo = photo.split("<###TYPESPLIT###>")
            notedata = photo[1]
            content = photo[0]
            if content:
                sql.add_note_to_db(
                    chat_id, notename[1:], notedata, sql.Types.PHOTO, file=content
                )
        elif matchaudio:
            audio = notedata[matchaudio.end() :].strip()
            audio = audio.split("<###TYPESPLIT###>")
            notedata = audio[1]
            content = audio[0]
            if content:
                sql.add_note_to_db(
                    chat_id, notename[1:], notedata, sql.Types.AUDIO, file=content
                )
        elif matchvoice:
            voice = notedata[matchvoice.end() :].strip()
            voice = voice.split("<###TYPESPLIT###>")
            notedata = voice[1]
            content = voice[0]
            if content:
                sql.add_note_to_db(
                    chat_id, notename[1:], notedata, sql.Types.VOICE, file=content
                )
        elif matchvideo:
            video = notedata[matchvideo.end() :].strip()
            video = video.split("<###TYPESPLIT###>")
            notedata = video[1]
            content = video[0]
            if content:
                sql.add_note_to_db(
                    chat_id, notename[1:], notedata, sql.Types.VIDEO, file=content
                )
        elif matchvn:
            video_note = notedata[matchvn.end() :].strip()
            video_note = video_note.split("<###TYPESPLIT###>")
            notedata = video_note[1]
            content = video_note[0]
            if content:
                sql.add_note_to_db(
                    chat_id, notename[1:], notedata, sql.Types.VIDEO_NOTE, file=content
                )
        else:
            sql.add_note_to_db(chat_id, notename[1:], notedata, sql.Types.TEXT)

    if failures:
        with BytesIO(str.encode("\n".join(failures))) as output:
            output.name = "failed_imports.txt"
            dispatcher.bot.send_document(
                chat_id,
                document=output,
                filename="failed_imports.txt",
                caption="These files/photos failed to import due to originating "
                "from another bot. This is a telegram API restriction, and can't "
                "be avoided. Sorry for the inconvenience!",
            )