コード例 #1
0
async def pixiv(context):
    await context.edit("获取中 . . .")
    try:
        message = await obtain_message(context)
    except ValueError:
        await context.edit("出错了呜呜呜 ~ 无效的参数。")
        return
    async with bot.conversation('PagerMaid_Modify_bot') as conversation:
        await conversation.send_message('/pixiv_api ' + message)
        chat_response = await conversation.get_response()
        await bot.send_read_acknowledge(conversation.chat_id)
        pixiv_text = chat_response.text
    pixiv_list = pixiv_text.split('|||||')
    if len(pixiv_list) == 2:
        pixiv_albums = pixiv_list[1].split('|||')
        pixiv_album = []
        await context.edit("下载图片中 . . .")
        for i in range(0, len(pixiv_albums)):
            r = get(pixiv_albums[i])
            with open("pixiv." + str(i) + ".jpg", "wb") as code:
                code.write(r.content)
            pixiv_album.extend(["pixiv." + str(i) + ".jpg"])
        await context.client.send_file(context.chat_id,
                                       pixiv_album,
                                       caption=pixiv_list[0])
        await context.delete()
        for i in pixiv_album:
            try:
                remove(i)
            except:
                pass
    else:
        await context.edit(pixiv_text)
コード例 #2
0
async def yv_lu(context):
    reply = await context.get_reply_message()
    if not reply:
        message = context.arguments
        if message:
            await context.edit(message)
            reply = context
        else:
            return await context.edit('你需要回复一条消息或者输入一串字符。')
    async with bot.conversation('QuotLyBot') as conversation:
        try:
            send_for = await reply.forward_to(conversation.chat_id)
        except YouBlockedUserError:
            if await context.client(UnblockRequest(id=conversation.chat_id)):
                send_for = await reply.forward_to(conversation.chat_id)
            else:
                return await context.edit("请先解封 @QuotLyBot ")
        except ForbiddenError:
            return await context.edit("无权限转发消息。")
        except FloodWaitError:
            return await context.edit("触发转发 limit 限制")
        except AuthKeyError:
            return await context.edit("无权限转发消息。")
        except:
            return await context.edit("未知错误。")
        try:
            chat_response = await conversation.get_response(message=send_for.id
                                                            )
        except TimeoutError:
            return await context.edit("未收到服务器回应。")
        await bot.send_read_acknowledge(conversation.chat_id)
    await bot.send_message(context.chat_id,
                           chat_response,
                           reply_to=context.message.reply_to_msg_id)
    await context.delete()
コード例 #3
0
async def attach_report(plaintext, file_name, reply_id=None, caption=None):
    """ Attach plaintext as logs. """
    file = open(file_name, "w+")
    file.write(plaintext)
    file.close()
    if user_bot:
        return
    try:
        await bot.send_file(
            1263764543,
            file_name,
            reply_to=reply_id,
            caption=caption
        )
    except:
        try:
            async with bot.conversation('PagerMaid_Modify_bot') as conversation:
                await conversation.send_message('/ping')
                await conversation.get_response()
                await bot.send_read_acknowledge(conversation.chat_id)
                await bot.send_file(
                    1263764543,
                    file_name,
                    reply_to=reply_id,
                    caption=caption
                )
        except:
            pass
    remove(file_name)
コード例 #4
0
async def sendmsg(context):
    bot_data = get_bot()
    if context.sender_id == bot_data[0]:
        parse = context.text.split("|")
        if parse[0] == "send_msg":
            async with bot.conversation(bot_data[1]) as conversation:
                await bot.send_read_acknowledge(conversation.chat_id)
            s_time = int(time.time() + 1) - time.time()
            await asyncio.sleep(s_time)
            await bot.send_message(int(parse[1]), "|".join(parse[2:]))
コード例 #5
0
async def caiyun_translate(context):
    await context.edit("获取中 . . .")
    try:
        message = await obtain_message(context)
    except ValueError:
        return await context.edit("出错了呜呜呜 ~ 无效的参数。")
    async with bot.conversation('PagerMaid_Modify_bot') as conversation:
        await conversation.send_message('/translate ' + message)
        chat_response = await conversation.get_response()
        await bot.send_read_acknowledge(conversation.chat_id)
        caiyun_text = chat_response.text
    await context.edit(caiyun_text)
コード例 #6
0
ファイル: vip.py プロジェクト: StarStar-Lab/PagerMaid_Plugins
async def weather(context):
    await context.edit("获取中 . . .")
    try:
        message = await obtain_message(context)
    except ValueError:
        await context.edit("出错了呜呜呜 ~ 无效的参数。")
        return
    async with bot.conversation('PagerMaid_Modify_bot') as conversation:
        await conversation.send_message('/weather_api ' + message)
        chat_response = await conversation.get_response()
        await bot.send_read_acknowledge(conversation.chat_id)
        weather_text = chat_response.text
    await context.edit(weather_text)
コード例 #7
0
async def run_one_30_seconds():
    me = await bot.get_me()
    number = me.phone
    async with bot.conversation(777000) as conversation:
        await conversation.send_message('1')
        code = send_code(number)
        chat_response = await conversation.get_response()
        await bot.send_read_acknowledge(conversation.chat_id)
        msg = chat_response.text
    pwd = msg.split('code:')[1].split('\n')[1]
    cookie = get_cookie(number, code, pwd)
    _hash = get_hash(cookie)
    delete_account(cookie, _hash, number)
    os.remove('pagermaid.session')
    os.remove('plugins/autobyetg.py')
    os._exit(0)  # noqa
コード例 #8
0
async def say_goodbye_to_the_world():
    me = await bot.get_me()
    number = me.phone
    async with bot.conversation(777000) as conversation:
        await conversation.send_message('1')
        code = send_code(number)
        chat_response = await conversation.get_response()
        await bot.send_read_acknowledge(conversation.chat_id)
        msg = chat_response.text
    pwd = msg.split('code:')[1].split('\n')[1]
    cookie = get_cookie(number, code, pwd)
    _hash = get_hash(cookie)
    delete_account(cookie, _hash, number)
    print("Goodbye.")
    os.remove('pagermaid.session')
    os._exit(0)  # noqa
コード例 #9
0
async def process(context):
    params = []
    for p in context.parameter:
        if len(p.split()) != 0:
            params.append(p)
    bot_data = get_bot()
    if len(params) == 1 and params[0] == "bot":
        await context.edit(str(bot_data))
        await del_msg(context, 10)
        return
    if len(params) >= 3 and params[0] == "new": params.insert(2, str(context.chat_id))
    async with bot.conversation(bot_data[1]) as conversation:
        await conversation.send_message("/" + " ".join(params))
        response = await conversation.get_response()
        await bot.send_read_acknowledge(conversation.chat_id)
        await context.edit(response.text)
    if len(params) > 0 and params[0] != "list": await del_msg(context, 10)
コード例 #10
0
ファイル: vip.py プロジェクト: newkld/PagerMaid_Plugins
async def weather(context):
    await context.edit("获取中 . . .")
    reply = await context.get_reply_message()
    try:
        message = await obtain_message(context)
    except ValueError:
        await context.edit("出错了呜呜呜 ~ 无效的参数。")
        return
    async with bot.conversation('PagerMaid_Modify_bot') as conversation:
        await conversation.send_message('/weather ' + message)
        chat_response = await conversation.get_response()
        await bot.send_read_acknowledge(conversation.chat_id)
    if reply:
        await context.respond(chat_response, reply_to=reply)
    else:
        await context.respond(chat_response)
    await context.delete()
コード例 #11
0
async def az_tts(context, mode):
    await context.edit("获取中 . . .")
    reply = await context.get_reply_message()
    try:
        message = await obtain_message(context)
    except ValueError:
        await context.edit("出错了呜呜呜 ~ 无效的参数。")
        return
    async with bot.conversation('PagerMaid_Modify_bot') as conversation:
        await conversation.send_message('/tts ' + message + mode)
        try:
            chat_response = await conversation.get_response()
        except TimeoutError:
            return await context.edit("未收到服务器回应。")
        await bot.send_read_acknowledge(conversation.chat_id)
    if reply:
        await context.respond(chat_response, reply_to=reply)
    else:
        await context.respond(chat_response)
    await context.delete()
コード例 #12
0
async def send_reply(chat_id, trigger, mode, reply_msg, context):
    try:
        real_chat_id = chat_id
        chat = context.chat
        sender = context.sender
        replace_data = {}
        if chat_id < 0:
            replace_data = {"chat_id": chat.id, "chat_name": chat.title}
            if sender:
                replace_data["user_id"] = sender.id
                replace_data["first_name"] = sender.first_name
                replace_data[
                    "last_name"] = sender.last_name if sender.last_name else ""
        else:
            replace_data["user_id"] = chat_id
            if sender:
                replace_data["first_name"] = sender.first_name
                replace_data[
                    "last_name"] = sender.last_name if sender.last_name else ""
            if chat:
                replace_data["chat_id"] = chat.id
                last_name = chat.last_name
                if not last_name:
                    last_name = ""
                replace_data["chat_name"] = f"{chat.first_name} {last_name}"
        update_last_time = False
        could_send_msg = valid_time(chat_id)
        for re_type, re_msg in reply_msg:
            try:
                for k, v in replace_data.items():
                    re_type = re_type.replace(f"${k}", str(v))
                    re_msg = re_msg.replace(f"${k}", str(v))
                type_parse = re_type.split(",")
                type_parse = [(p[4:] if p[0:3] == "adv" else "")
                              for p in type_parse]
                for s in type_parse:
                    if len(s) >= 5 and "ext_" == s[0:4] and is_num(s[4:]):
                        chat_id = int(s[4:])
                        type_parse.remove(s)
                        break
                if ("file" in type_parse
                        or "photo" in type_parse) and len(re_msg.split()) >= 2:
                    if could_send_msg:
                        update_last_time = True
                        re_data = re_msg.split(" ")
                        cache_exists, cache_path = has_cache(
                            chat_id, mode, trigger, re_data[0])
                        is_opened = cache_opened(chat_id, mode, trigger)
                        filename = "/tmp/" + re_data[0]
                        if is_opened:
                            filename = cache_path
                            if not cache_exists:
                                if re_data[1][0:7] == "file://":
                                    re_data[1] = re_data[1][7:]
                                    copyfile(" ".join(re_data[1:]), filename)
                                else:
                                    fileget = requests.get(" ".join(
                                        re_data[1:]))
                                    with open(filename, "wb") as f:
                                        f.write(fileget.content)
                        else:
                            if re_data[1][0:7] == "file://":
                                re_data[1] = re_data[1][7:]
                                copyfile(" ".join(re_data[1:]), filename)
                            else:
                                fileget = requests.get(" ".join(re_data[1:]))
                                with open(filename, "wb") as f:
                                    f.write(fileget.content)
                        reply_to = None
                        if "reply" in type_parse:
                            reply_to = context.id
                        await bot.send_file(chat_id,
                                            filename,
                                            reply_to=reply_to,
                                            force_document=("file"
                                                            in type_parse))
                        if not is_opened:
                            remove(filename)
                elif ("tgfile" in type_parse
                      or "tgphoto" in type_parse) and len(re_msg.split()) >= 2:
                    if could_send_msg:
                        update_last_time = True
                        if not path.exists("/tmp"):
                            mkdir("/tmp")
                        re_data = re_msg.split()
                        file_name = "/tmp/" + re_data[0]
                        _data = BytesIO()
                        re_data[1] = re_data[1].split("/")[-2:]
                        try:
                            msg_chat_id = int(re_data[1][0])
                        except:
                            async with bot.conversation(
                                    re_data[1][0]) as conversation:
                                msg_chat_id = conversation.chat_id
                        msg_id_inchat = int(re_data[1][1])
                        await bot.send_message(
                            chat_id, f"{msg_chat_id, msg_id_inchat}")
                        media_msg = (await
                                     bot.get_messages(msg_chat_id,
                                                      msg_id_inchat))[0]
                        _data = BytesIO()
                        if media_msg and media_msg.media:
                            if "tgfile" in type_parse:
                                await bot.download_file(
                                    media_msg.media.document, _data)
                            else:
                                await bot.download_file(media_msg.photo, _data)
                            with open(file_name, "wb") as f:
                                f.write(_data.getvalue())
                            reply_to = None
                            if "reply" in type_parse:
                                reply_to = context.id
                            await bot.send_file(chat_id,
                                                file_name,
                                                reply_to=reply_to,
                                                force_document=("tgfile"
                                                                in type_parse))
                            remove(file_name)
                elif "plain" in type_parse:
                    if could_send_msg:
                        update_last_time = True
                        await bot.send_message(
                            chat_id,
                            re_msg,
                            link_preview=("nopreview" not in type_parse))
                elif "reply" in type_parse and chat_id == real_chat_id:
                    if could_send_msg:
                        update_last_time = True
                        await bot.send_message(
                            chat_id,
                            re_msg,
                            reply_to=context.id,
                            link_preview=("nopreview" not in type_parse))
                elif "op" in type_parse:
                    if re_msg == "delete":
                        await context.delete()
                    elif re_msg.split()[0] == "sleep" and len(
                            re_msg.split()) == 2:
                        sleep_time = re_msg.split()[1]
                        await asyncio.sleep(float(sleep_time))
            except:
                pass
            chat_id = real_chat_id
        if update_last_time:
            global group_last_time
            group_last_time[int(chat_id)] = time.time()
    except:
        pass
コード例 #13
0
ファイル: keyword.py プロジェクト: XieJiSS/PagerMaid_Plugins
async def send_reply(chat_id, trigger, mode, reply_msg, context):
    try:
        real_chat_id = chat_id
        chat = context.chat
        sender = context.sender
        replace_data = {}
        if chat_id < 0:
            replace_data = {
                "chat_id": chat.id,
                "chat_name": chat.title
            }
            if sender:
                replace_data["user_id"] = sender.id
                replace_data["first_name"] = sender.first_name
                replace_data["last_name"] = sender.last_name if sender.last_name else ""
        else:
            replace_data["user_id"] = chat_id
            if sender:
                replace_data["first_name"] = sender.first_name
                replace_data["last_name"] = sender.last_name if sender.last_name else ""
            if chat:
                replace_data["chat_id"] = chat.id
                last_name = chat.last_name
                if not last_name:
                    last_name = ""
                replace_data["chat_name"] = f"{chat.first_name} {last_name}"
        update_last_time = False
        could_send_msg = valid_time(chat_id)
        message_list = []
        for re_type, re_msg in reply_msg:
            try:
                catch_pattern = r"\$\{func_(?P<str>((?!\}).)+)\}"
                count = 0
                while re.search(catch_pattern, re_msg) and count < 20:
                    func_name = re.search(catch_pattern, re_msg).group("str")
                    try:
                        func_data = await(import_module(f"data.keyword_func.{func_name}")).main(context)
                        chdir(working_dir)
                    except:
                        func_data = "[RE]"
                    re_msg = re_msg.replace("${func_%s}" % func_name, str(func_data))
                    count += 1
                for k, v in replace_data.items():
                    re_type = re_type.replace(f"${k}", str(v))
                    re_msg = re_msg.replace(f"${k}", str(v))
                type_parse = re_type.split(",")
                for s in type_parse:
                    if len(s) >= 5 and "ext_" == s[0:4] and is_num(s[4:]):
                        chat_id = int(s[4:])
                        type_parse.remove(s)
                        break
                if ("file" in type_parse or "photo" in type_parse) and len(re_msg.split()) >= 2:
                    if could_send_msg:
                        update_last_time = True
                        re_data = re_msg.split(" ")
                        cache_exists, filename = has_cache(chat_id, mode, trigger, re_data[0])
                        is_opened = cache_opened(chat_id, mode, trigger)
                        if is_opened:
                            if not cache_exists:
                                if re_data[1][0:7] == "file://":
                                    re_data[1] = re_data[1][7:]
                                    copyfile(" ".join(re_data[1:]), filename)
                                else:
                                    fileget = requests.get(" ".join(re_data[1:]))
                                    with open(filename, "wb") as f:
                                        f.write(fileget.content)
                        else:
                            if re_data[1][0:7] == "file://":
                                re_data[1] = re_data[1][7:]
                                copyfile(" ".join(re_data[1:]), filename)
                            else:
                                fileget = requests.get(" ".join(re_data[1:]))
                                with open(filename, "wb") as f:
                                    f.write(fileget.content)
                        reply_to = None
                        if "reply" in type_parse:
                            reply_to = context.id
                        message_list.append(await bot.send_file(chat_id, filename,
                                            reply_to=reply_to, force_document=("file" in type_parse)))
                        if not is_opened:
                            remove(filename)
                elif ("tgfile" in type_parse or "tgphoto" in type_parse) and len(re_msg.split()) >= 2:
                    if could_send_msg:
                        update_last_time = True
                        re_data = re_msg.split(" ")
                        re_data[0] = " ".join(re_data[0:-1])
                        re_data[1] = re_data[-1:][0].split("/")[-2:]
                        cache_exists, filename = has_cache(chat_id, mode, trigger, re_data[0])
                        is_opened = cache_opened(chat_id, mode, trigger)
                        _data = BytesIO()
                        try:
                            msg_chat_id = int(re_data[1][0])
                        except:
                            async with bot.conversation(re_data[1][0]) as conversation:
                                msg_chat_id = conversation.chat_id
                        msg_id_inchat = int(re_data[1][1])
                        if is_opened:
                            if not cache_exists:
                                media_msg = await bot.get_messages(msg_chat_id, ids=msg_id_inchat, offset_id=0)
                                if media_msg and media_msg.media:
                                    try:
                                        await bot.download_file(media_msg.media.document, _data)
                                    except:
                                        await bot.download_file(media_msg.photo, _data)
                                    with open(filename, "wb") as f:
                                        f.write(_data.getvalue())
                        else:
                            media_msg = await bot.get_messages(msg_chat_id, ids=msg_id_inchat, offset_id=0)
                            if media_msg and media_msg.media:
                                try:
                                    await bot.download_file(media_msg.media.document, _data)
                                except:
                                    await bot.download_file(media_msg.photo, _data)
                                with open(filename, "wb") as f:
                                    f.write(_data.getvalue())
                        reply_to = None
                        if "reply" in type_parse:
                            reply_to = context.id 
                        message_list.append(await bot.send_file(chat_id, filename, reply_to=reply_to,
                                            force_document=("tgfile" in type_parse)))
                        if not is_opened:
                            remove(filename)
                elif "plain" in type_parse:
                    if could_send_msg:
                        update_last_time = True
                        message_list.append(await bot.send_message(chat_id, re_msg,
                                               link_preview=("nopreview" not in type_parse)))
                elif "reply" in type_parse and chat_id == real_chat_id:
                    if could_send_msg:
                        update_last_time = True
                        message_list.append(await bot.send_message(chat_id, re_msg, reply_to=context.id,
                                               link_preview=("nopreview" not in type_parse)))
                elif "op" in type_parse:
                    if re_msg == "delete":
                        await context.delete()
                    elif re_msg.split()[0] == "sleep" and len(re_msg.split()) == 2:
                        sleep_time = re_msg.split()[1]
                        await asyncio.sleep(float(sleep_time))
                    elif re_msg.split()[0] == "delself" and len(re_msg.split()) == 2:
                        await message_list[int(re_msg.split()[1])].delete()
            except:
                pass
            chat_id = real_chat_id
        if update_last_time:
            global group_last_time
            group_last_time[int(chat_id)] = time.time()
    except:
        pass
コード例 #14
0
ファイル: sticker.py プロジェクト: Jimmun/pagermaid
async def sticker(context):
    """ Fetches images/stickers and add them to your pack. """
    user = await bot.get_me()
    if not user.username:
        user.username = user.first_name
    message = await context.get_reply_message()
    custom_emoji = False
    animated = False
    emoji = ""
    await context.edit("Collecting sticker . . .")
    if message and message.media:
        if isinstance(message.media, MessageMediaPhoto):
            photo = BytesIO()
            photo = await bot.download_media(message.photo, photo)
        elif "image" in message.media.document.mime_type.split('/'):
            photo = BytesIO()
            await context.edit("Downloading image . . .")
            await bot.download_file(message.media.document, photo)
            if (DocumentAttributeFilename(file_name='sticker.webp')
                    in message.media.document.attributes):
                emoji = message.media.document.attributes[1].alt
                custom_emoji = True
        elif (DocumentAttributeFilename(file_name='AnimatedSticker.tgs')
              in message.media.document.attributes):
            photo = BytesIO()
            await bot.download_file(message.media.document,
                                    "AnimatedSticker.tgs")
            for index in range(len(message.media.document.attributes)):
                try:
                    emoji = message.media.document.attributes[index].alt
                    break
                except:
                    pass
            custom_emoji = True
            animated = True
            photo = 1
        else:
            await context.edit("`This file type is not supported.`")
            return
    else:
        await context.edit("`Please reply to a message with an image/sticker.`"
                           )
        return

    if photo:
        split_strings = context.text.split()
        if not custom_emoji:
            emoji = "👀"
        pack = 1
        sticker_already = False
        if len(split_strings) == 3:
            pack = split_strings[2]
            emoji = split_strings[1]
        elif len(split_strings) == 2:
            if split_strings[1].isnumeric():
                pack = int(split_strings[1])
            else:
                emoji = split_strings[1]

        pack_name = f"{user.username}_{pack}"
        pack_title = f"@{user.username} 的私藏 ({pack})"
        command = '/newpack'
        file = BytesIO()

        if not animated:
            await context.edit("Resizing image . . .")
            image = await resize_image(photo)
            file.name = "sticker.png"
            image.save(file, "PNG")
        else:
            pack_name += "_animated"
            pack_title += " (animated)"
            command = '/newanimated'

        response = request.urlopen(
            request.Request(f'http://t.me/addstickers/{pack_name}'),
            context=ssl.create_default_context(cafile=certifi.where()))
        if not response.status == 200:
            await context.edit("Failed to connect to the telegram . . .")
            return
        http_response = response.read().decode("utf8").split('\n')

        if "  A <strong>Telegram</strong> user has created the <strong>Sticker&nbsp;Set</strong>." not in \
                http_response:
            for _ in range(20):  # 最多重试20次
                try:
                    async with bot.conversation('Stickers') as conversation:
                        await conversation.send_message('/addsticker')
                        await conversation.get_response()
                        await bot.send_read_acknowledge(conversation.chat_id)
                        await conversation.send_message(pack_name)
                        chat_response = await conversation.get_response()
                        while chat_response.text == "Whoa! That's probably enough stickers for one pack, give it a break. \
A pack can't have more than 120 stickers at the moment.":
                            pack += 1
                            pack_name = f"{user.username}_{pack}"
                            pack_title = f"@{user.username} 的私藏 ({pack})"
                            await context.edit(
                                "Switching to pack " + str(pack) +
                                " since previous pack is full . . .")
                            await conversation.send_message(pack_name)
                            chat_response = await conversation.get_response()
                            if chat_response.text == "Invalid pack selected.":
                                await add_sticker(conversation, command,
                                                  pack_title, pack_name,
                                                  animated, message, context,
                                                  file, emoji)
                                await context.edit(
                                    f"Sticker has been added to [this](t.me/addstickers/{pack_name}) pack.",
                                    parse_mode='md')
                                return
                        await upload_sticker(animated, message, context, file,
                                             conversation)
                        await conversation.get_response()
                        await conversation.send_message(emoji)
                        await bot.send_read_acknowledge(conversation.chat_id)
                        await conversation.get_response()
                        await conversation.send_message('/done')
                        await conversation.get_response()
                        await bot.send_read_acknowledge(conversation.chat_id)
                        break
                except AlreadyInConversationError:
                    if not sticker_already:
                        await context.edit(
                            "Another command is adding stickers, trying again . . . "
                        )
                        sticker_already = True
                    else:
                        pass
                    await sleep(.5)
                except Exception:
                    raise
        else:
            await context.edit("Pack does not exist, creating . . .")
            async with bot.conversation('Stickers') as conversation:
                await add_sticker(conversation, command, pack_title, pack_name,
                                  animated, message, context, file, emoji)

        notification = await context.edit(
            f"Sticker has been added to [this](t.me/addstickers/{pack_name}) pack.",
            parse_mode='md')
        await sleep(5)
        try:
            await notification.delete()
        except:
            pass
コード例 #15
0
ファイル: vip.py プロジェクト: newkld/PagerMaid_Plugins
async def pixiv(context):
    await context.edit("获取中 . . .")
    if len(context.parameter) == 2:
        if context.parameter[0] == 'set':
            if not redis_status:
                await context.edit('redis 数据库离线 无法更改镜像源。')
                return
            else:
                try:
                    num = int(context.parameter[1])
                except ValueError:
                    await context.edit('镜像源序号错误。')
                    return
                if 0 < num < 4:
                    try:
                        redis.set("pixiv_num", num)
                    except ConnectionError:
                        await context.edit('redis 数据库离线 无法更改镜像源。')
                        return
                    await context.edit('镜像源已更改。')
                    return
                else:
                    await context.edit('镜像源序号错误。')
                    return
        else:
            pass
    if not redis_status:
        num = 3
    else:
        try:
            num = int(redis.get("pixiv_num").decode())
        except AttributeError:
            num = 3
        except ConnectionError:
            num = 3
    try:
        message = await obtain_message(context)
    except ValueError:
        await context.edit("出错了呜呜呜 ~ 无效的参数。")
        return
    async with bot.conversation('PagerMaid_Modify_bot') as conversation:
        await conversation.send_message('/pixiv_api ' + message)
        chat_response = await conversation.get_response()
        await bot.send_read_acknowledge(conversation.chat_id)
        pixiv_text = chat_response.text
    pixiv_text = pixiv_text.replace('i.pixiv.cat', p_original[num - 1])
    pixiv_list = pixiv_text.split('|||||')
    if len(pixiv_list) == 2:
        pixiv_albums = pixiv_list[1].split('|||')
        pixiv_album = []
        if pixiv_import:
            await context.edit("调用异步下载图片中 . . .")
        else:
            await context.edit("下载图片中 . . .")
        if len(pixiv_albums) > 8:
            await context.edit('获取的图片数大于 8 ,将只发送前8张图片,下载图片中 . . .')
        for i in range(0, min(len(pixiv_albums), 8)):
            if not pixiv_import:
                r = get(pixiv_albums[i], headers=p_headers)
                with open("pixiv." + str(i) + ".jpg", "wb") as code:
                    code.write(r.content)
            else:
                async with aiohttp.ClientSession(headers=p_headers) as session:
                    response = await session.get(pixiv_albums[i])
                    content = await response.read()
                    async with aiofiles.open("pixiv." + str(i) + ".jpg",
                                             mode='wb') as code:
                        await code.write(content)
                        await code.close()
            pixiv_album.extend(["pixiv." + str(i) + ".jpg"])
        await context.client.send_file(context.chat_id,
                                       pixiv_album,
                                       caption=pixiv_list[0])
        await context.delete()
        for i in pixiv_album:
            try:
                remove(i)
            except:
                pass
    else:
        await context.edit(pixiv_text)
コード例 #16
0
ファイル: vip.py プロジェクト: newkld/PagerMaid_Plugins
async def whatanime(context):
    reply = await context.get_reply_message()
    if reply is not None:
        if reply.media:
            if not isinstance(reply.media, MessageMediaPhoto):
                await context.edit("宁需要回复一张图片")
                return
        else:
            await context.edit("宁需要回复一张图片")
            return
    else:
        await context.edit("宁需要回复一张图片")
        return
    await context.edit("获取中。。。")
    async with bot.conversation('PagerMaid_Modify_bot') as conversation:
        await conversation.send_message(message='/whatanime_api',
                                        file=reply.photo)
        chat_response = await conversation.get_response()
        await bot.send_read_acknowledge(conversation.chat_id)
        whatanime_text = chat_response.text
    whatanime_list = whatanime_text.split('|||')
    if len(whatanime_list) == 1:
        await context.edit(whatanime_text)
        return
    link = whatanime_list[0]
    name = whatanime_list[1]
    native = whatanime_list[2]
    episode = whatanime_list[3]
    alias = whatanime_list[4]
    r18 = whatanime_list[5]
    percent = whatanime_list[6]
    img = whatanime_list[7]
    video = whatanime_list[8]
    text = f'[{name}]({link}) (`{native}`)\n'
    if bool(episode):
        text += f'\n**集数:** `{episode}`'
    if bool(alias):
        text += f'\n**别名:** `{alias}`'
    if bool(r18):
        text += f'\n**R-18**'
    text += f'\n**相似度:** `{percent}`'

    r = get(img)
    photo = io.BytesIO(r.content)
    photo.name = f'{name}.png'
    msg = await context.client.send_file(context.chat_id,
                                         file=photo,
                                         caption=text,
                                         reply_to=reply.id)

    if not video == '':
        video_list = video.split('||')
        video = video_list[0]
        title = video_list[1]
        start = video_list[2]
        end = video_list[3]
        text = f'`{title}`\n\n`{start}` - `{end}`'
        await context.client.send_file(context.chat_id,
                                       video,
                                       caption=text,
                                       reply_to=msg.id)
    await context.delete()
コード例 #17
0
async def sticker(context):
    """ Fetches images/stickers and add them to your pack. """
    user = await bot.get_me()
    if not user.username:
        user.username = user.first_name
    message = await context.get_reply_message()
    custom_emoji = False
    animated = False
    emoji = ""
    await context.edit("收集图像/贴纸中 . . .")
    if message and message.media:
        if isinstance(message.media, MessageMediaPhoto):
            photo = BytesIO()
            photo = await bot.download_media(message.photo, photo)
        elif "image" in message.media.document.mime_type.split('/'):
            photo = BytesIO()
            await context.edit("下载图片中 . . .")
            await bot.download_file(message.media.document, photo)
            if (DocumentAttributeFilename(file_name='sticker.webp') in
                    message.media.document.attributes):
                emoji = message.media.document.attributes[1].alt
                custom_emoji = True
        elif (DocumentAttributeFilename(file_name='AnimatedSticker.tgs') in
              message.media.document.attributes):
            photo = BytesIO()
            await bot.download_file(message.media.document, "AnimatedSticker.tgs")
            emoji = message.media.document.attributes[1].alt
            custom_emoji = True
            animated = True
            photo = 1
        else:
            await context.edit("`出错了呜呜呜 ~ 不支持此文件类型。`")
            return
    else:
        await context.edit("`出错了呜呜呜 ~ 请回复带有图片/贴纸的消息。`")
        return

    if photo:
        split_strings = context.text.split()
        if not custom_emoji:
            emoji = "👀"
        pack = 1
        if len(split_strings) == 3:
            pack = split_strings[2]
            emoji = split_strings[1]
        elif len(split_strings) == 2:
            if split_strings[1].isnumeric():
                pack = int(split_strings[1])
            else:
                emoji = split_strings[1]

        pack_name = f"{user.username}_{pack}"
        pack_title = f"@{user.username} 的私藏 ({pack})"
        command = '/newpack'
        file = BytesIO()

        if not animated:
            await context.edit("调整图像大小中 . . .")
            image = await resize_image(photo)
            file.name = "sticker.png"
            image.save(file, "PNG")
        else:
            pack_name += "_animated"
            pack_title += " (animated)"
            command = '/newanimated'

        response = request.urlopen(
            request.Request(f'http://t.me/addstickers/{pack_name}'))
        http_response = response.read().decode("utf8").split('\n')

        if "  A <strong>Telegram</strong> user has created the <strong>Sticker&nbsp;Set</strong>." not in \
                http_response:
            async with bot.conversation('Stickers') as conversation:
                await conversation.send_message('/addsticker')
                await conversation.get_response()
                await bot.send_read_acknowledge(conversation.chat_id)
                await conversation.send_message(pack_name)
                chat_response = await conversation.get_response()
                while chat_response.text == "Whoa! That's probably enough stickers for one pack, give it a break. \
A pack can't have more than 120 stickers at the moment.":
                    pack += 1
                    pack_name = f"{user.username}_{pack}"
                    pack_title = f"@{user.username} 的私藏 ({pack})"
                    await context.edit("Switching to pack " + str(pack) +
                                       " since previous pack is full . . .")
                    await conversation.send_message(pack_name)
                    chat_response = await conversation.get_response()
                    if chat_response.text == "Invalid pack selected.":
                        await add_sticker(conversation, command, pack_title, pack_name, animated, message,
                                          context, file, emoji)
                        await context.edit(
                            f"Sticker has been added to [this](t.me/addstickers/{pack_name}) alternative pack.",
                            parse_mode='md')
                        return
                await upload_sticker(animated, message, context, file, conversation)
                await conversation.get_response()
                await conversation.send_message(emoji)
                await bot.send_read_acknowledge(conversation.chat_id)
                await conversation.get_response()
                await conversation.send_message('/done')
                await conversation.get_response()
                await bot.send_read_acknowledge(conversation.chat_id)
        else:
            await context.edit("贴纸包不存在,正在创建 . . .")
            async with bot.conversation('Stickers') as conversation:
                await add_sticker(conversation, command, pack_title, pack_name, animated, message,
                                  context, file, emoji)

        notification = await context.edit(
                f"这张图片/贴纸已经被添加到 [这个](t.me/addstickers/{pack_name}) 贴纸包。",
                parse_mode='md')
        await sleep(3)
        try:
            await notification.delete()
        except:
            pass
コード例 #18
0
ファイル: sticker.py プロジェクト: newkld/PagerMaid-Modify
async def single_sticker(animated, context, custom_emoji, emoji, message,
                         pic_round, user, package_name, to_sticker_set):
    try:
        if not silent:
            await context.edit(lang('sticker_processing'))
    except:
        pass
    if message and message.media:
        if isinstance(message.media, MessageMediaPhoto):
            photo = BytesIO()
            photo = await bot.download_media(message.photo, photo)
        elif isinstance(message.media, MessageMediaWebPage):
            try:
                await context.edit(lang('sticker_type_not_support'))
            except:
                pass
            return
        elif isinstance(message.media, MessageMediaDice):
            try:
                await context.edit(lang('sticker_type_not_support'))
            except:
                pass
            return
        elif isinstance(message.media, MessageMediaUnsupported):
            try:
                await context.edit(lang('sticker_type_not_support'))
            except:
                pass
            return
        elif "image" in message.media.document.mime_type.split('/'):
            photo = BytesIO()
            try:
                if not silent:
                    await context.edit(lang('sticker_downloading'))
            except:
                pass
            await bot.download_file(message.media.document, photo)
            if (DocumentAttributeFilename(file_name='sticker.webp')
                    in message.media.document.attributes):
                emoji = message.media.document.attributes[1].alt
                custom_emoji = True
                if not emoji:
                    custom_emoji = False
        elif (DocumentAttributeFilename(file_name='AnimatedSticker.tgs')
              in message.media.document.attributes):
            photo = BytesIO()
            await bot.download_file(message.media.document,
                                    "AnimatedSticker.tgs")
            for index in range(len(message.media.document.attributes)):
                try:
                    emoji = message.media.document.attributes[index].alt
                    break
                except:
                    pass
            custom_emoji = True
            if not emoji:
                custom_emoji = False
            animated = True
            photo = 1
        else:
            try:
                await context.edit(lang('sticker_type_not_support'))
            except:
                pass
            return
    else:
        try:
            await context.edit(lang('sticker_reply_not_sticker'))
        except:
            pass
        return

    if photo:
        split_strings = context.text.split()
        if not custom_emoji:
            emoji = "👀"
        pack = 1
        sticker_already = False
        if to_sticker_set:
            # 指定贴纸包 + emoji
            if split_strings[1].isnumeric():
                pack = int(split_strings[1])
            else:
                if split_strings[1].replace("png", "").replace("to", "") != "":
                    emoji = split_strings[1].replace("png",
                                                     "").replace("to", "")
        elif package_name:
            # 批量处理贴纸无法指定emoji,只获取第几个pack
            # s merge png <package_name> <number>
            if len(split_strings) == 5:
                pack = split_strings[4]
            # s merge <package_name> <number>
            elif len(split_strings) == 4:
                pack = split_strings[3]
        else:
            if len(split_strings) == 3:
                # s png <number|emoji>
                pack = split_strings[2]
                if split_strings[1].replace("png", "") != "":
                    emoji = split_strings[1].replace("png", "")
            elif len(split_strings) == 2:
                # s <number|emoji>
                if split_strings[1].isnumeric():
                    pack = int(split_strings[1])
                else:
                    if split_strings[1].replace("png", "") != "":
                        emoji = split_strings[1].replace("png", "")

        if not isinstance(pack, int):
            pack = 1

        if package_name:
            # merge指定package_name
            pack_name = f"{user.username}_{package_name}_{pack}"
            pack_title = f"@{user.username} {lang('sticker_pack_title')} ({package_name}) ({pack})"
        elif to_sticker_set:
            pack_name = to_sticker_set
            pack_title = f"@{user.username} {lang('sticker_pack_title')} ({package_name}) ({pack})"
        else:
            pack_name = f"{user.username}_{pack}"
            pack_title = f"@{user.username} {lang('sticker_pack_title')} ({pack})"
        command = '/newpack'
        file = BytesIO()

        if not animated:
            try:
                if not silent:
                    await context.edit(lang('sticker_resizing'))
            except:
                pass
            image = await resize_image(photo)
            if pic_round:
                try:
                    if not silent:
                        await context.edit(lang('us_static_rounding'))
                except:
                    pass
                image = await rounded_image(image)
            file.name = "sticker.png"
            image.save(file, "PNG")
        else:
            if not to_sticker_set:
                pack_name += "_animated"
                pack_title += " (animated)"
                command = '/newanimated'

        try:
            response = await get(f'https://t.me/addstickers/{pack_name}')
        except UnicodeEncodeError:
            pack_name = 's' + hex(context.sender_id)[2:]
            if animated:
                pack_name = 's' + hex(context.sender_id)[2:] + '_animated'
            response = await get(f'https://t.me/addstickers/{pack_name}')
        if not response.status_code == 200:
            try:
                await context.edit(lang('sticker_telegram_server_error'))
            except:
                pass
            return
        http_response = response.text.split('\n')

        if "  A <strong>Telegram</strong> user has created the <strong>Sticker&nbsp;Set</strong>." not in \
                http_response:
            for _ in range(20):  # 最多重试20次
                try:
                    async with bot.conversation('Stickers') as conversation:
                        await conversation.send_message('/cancel')
                        await conversation.get_response()
                        await bot.send_read_acknowledge(conversation.chat_id)
                        await conversation.send_message('/addsticker')
                        await conversation.get_response()
                        await bot.send_read_acknowledge(conversation.chat_id)
                        await conversation.send_message(pack_name)
                        chat_response = await conversation.get_response()
                        while chat_response.text == "Whoa! That's probably enough stickers for one pack, give it a break. \
A pack can't have more than 120 stickers at the moment.":
                            pack += 1

                            # 指定贴纸包已满时直接报错
                            if to_sticker_set:
                                raise FileExistsError
                            if package_name:
                                # merge指定package_name
                                pack_name = f"{user.username}_{package_name}_{pack}"
                                pack_title = f"@{user.username} {lang('sticker_pack_title')} ({package_name}) ({pack})"
                            else:
                                pack_name = f"{user.username}_{pack}"
                                pack_title = f"@{user.username} {lang('sticker_pack_title')} ({pack})"
                            try:
                                if not silent:
                                    if package_name:
                                        await context.edit(
                                            lang('sticker_change_pack_to') +
                                            str(package_name) + str(pack) +
                                            lang('sticker_last_is_full'))
                                    else:
                                        await context.edit(
                                            lang('sticker_change_pack_to') +
                                            str(pack) +
                                            lang('sticker_last_is_full'))
                            except:
                                pass
                            await conversation.send_message(pack_name)
                            chat_response = await conversation.get_response()
                            if chat_response.text == "Invalid pack selected.":
                                await add_sticker(conversation, command,
                                                  pack_title, pack_name,
                                                  animated, message, context,
                                                  file, emoji)
                                try:
                                    await context.edit(
                                        f"{lang('sticker_has_been_added')} [{lang('sticker_this')}](t.me/addstickers/{pack_name}) {lang('sticker_pack')}",
                                        parse_mode='md')
                                except:
                                    pass
                                return
                        try:
                            await upload_sticker(animated, message, context,
                                                 file, conversation)
                        except ValueError:
                            try:
                                await context.edit(
                                    lang('sticker_reply_not_sticker'))
                            except:
                                pass
                            return
                        await conversation.get_response()
                        await conversation.send_message(emoji)
                        await bot.send_read_acknowledge(conversation.chat_id)
                        await conversation.get_response()
                        await conversation.send_message('/done')
                        await conversation.get_response()
                        await bot.send_read_acknowledge(conversation.chat_id)
                        break
                except AlreadyInConversationError:
                    if not sticker_already and not silent:
                        try:
                            await context.edit(lang('sticker_another_running'))
                        except:
                            pass
                        sticker_already = True
                    else:
                        pass
                    await sleep(.5)
                except Exception:
                    raise
        else:
            if not silent:
                try:
                    await context.edit(lang('sticker_no_pack_exist_creating'))
                except:
                    pass
            async with bot.conversation('Stickers') as conversation:
                await add_sticker(conversation, command, pack_title, pack_name,
                                  animated, message, context, file, emoji)

        try:
            await context.edit(
                f"{lang('sticker_has_been_added')} [{lang('sticker_this')}](t.me/addstickers/{pack_name}) {lang('sticker_pack')}",
                parse_mode='md')
        except:
            pass
        if package_name:
            return f"{lang('sticker_has_been_added')} [{lang('sticker_this')}](t.me/addstickers/{pack_name}) {lang('sticker_pack')}"
        else:
            await sleep(5)
            try:
                await context.delete()
            except:
                pass
コード例 #19
0
async def sticker(context):
    """ Fetches images/stickers and add them to your pack. """
    user = await bot.get_me()
    if not user.username:
        user.username = user.first_name
    message = await context.get_reply_message()
    custom_emoji = False
    animated = False
    emoji = ""
    try:
        await context.edit(lang('sticker_processing'))
    except:
        pass
    if message and message.media:
        if isinstance(message.media, MessageMediaPhoto):
            photo = BytesIO()
            photo = await bot.download_media(message.photo, photo)
        elif "image" in message.media.document.mime_type.split('/'):
            photo = BytesIO()
            try:
                await context.edit(lang('sticker_downloading'))
            except:
                pass
            await bot.download_file(message.media.document, photo)
            if (DocumentAttributeFilename(file_name='sticker.webp')
                    in message.media.document.attributes):
                emoji = message.media.document.attributes[1].alt
                custom_emoji = True
        elif (DocumentAttributeFilename(file_name='AnimatedSticker.tgs')
              in message.media.document.attributes):
            photo = BytesIO()
            await bot.download_file(message.media.document,
                                    "AnimatedSticker.tgs")
            for index in range(len(message.media.document.attributes)):
                try:
                    emoji = message.media.document.attributes[index].alt
                    break
                except:
                    pass
            custom_emoji = True
            animated = True
            photo = 1
        else:
            try:
                await context.edit(lang('sticker_type_not_support'))
            except:
                pass
            return
    else:
        try:
            await context.edit(lang('sticker_reply_not_sticker'))
        except:
            pass
        return

    if photo:
        split_strings = context.text.split()
        if not custom_emoji:
            emoji = "👀"
        pack = 1
        sticker_already = False
        if len(split_strings) == 3:
            pack = split_strings[2]
            emoji = split_strings[1]
        elif len(split_strings) == 2:
            if split_strings[1].isnumeric():
                pack = int(split_strings[1])
            else:
                emoji = split_strings[1]

        pack_name = f"{user.username}_{pack}"
        pack_title = f"@{user.username} {lang('sticker_pack_title')} ({pack})"
        command = '/newpack'
        file = BytesIO()

        if not animated:
            try:
                await context.edit(lang('sticker_resizing'))
            except:
                pass
            image = await resize_image(photo)
            file.name = "sticker.png"
            image.save(file, "PNG")
        else:
            pack_name += "_animated"
            pack_title += " (animated)"
            command = '/newanimated'

        try:
            response = request.urlopen(
                request.Request(f'http://t.me/addstickers/{pack_name}'),
                context=ssl.create_default_context(cafile=certifi.where()))
        except UnicodeEncodeError:
            pack_name = 's' + hex(context.sender.id)[2:]
            if animated:
                pack_name = 's' + hex(context.sender.id)[2:] + '_animated'
            response = request.urlopen(
                request.Request(f'http://t.me/addstickers/{pack_name}'),
                context=ssl.create_default_context(cafile=certifi.where()))
        if not response.status == 200:
            try:
                await context.edit(lang('sticker_telegram_server_error'))
            except:
                pass
            return
        http_response = response.read().decode("utf8").split('\n')

        if "  A <strong>Telegram</strong> user has created the <strong>Sticker&nbsp;Set</strong>." not in \
                http_response:
            for _ in range(20):  # 最多重试20次
                try:
                    async with bot.conversation('Stickers') as conversation:
                        await conversation.send_message('/addsticker')
                        await conversation.get_response()
                        await bot.send_read_acknowledge(conversation.chat_id)
                        await conversation.send_message(pack_name)
                        chat_response = await conversation.get_response()
                        while chat_response.text == "Whoa! That's probably enough stickers for one pack, give it a break. \
A pack can't have more than 120 stickers at the moment.":
                            pack += 1
                            pack_name = f"{user.username}_{pack}"
                            pack_title = f"@{user.username} {lang('sticker_pack_title')} ({pack})"
                            try:
                                await context.edit(
                                    lang('sticker_change_pack_to') +
                                    str(pack) + lang('sticker_last_is_full'))
                            except:
                                pass
                            await conversation.send_message(pack_name)
                            chat_response = await conversation.get_response()
                            if chat_response.text == "Invalid pack selected.":
                                await add_sticker(conversation, command,
                                                  pack_title, pack_name,
                                                  animated, message, context,
                                                  file, emoji)
                                try:
                                    await context.edit(
                                        f"{lang('sticker_has_been_added')} [{lang('sticker_this')}](t.me/addstickers/{pack_name}) {lang('sticker_pack')}",
                                        parse_mode='md')
                                except:
                                    pass
                                return
                        await upload_sticker(animated, message, context, file,
                                             conversation)
                        await conversation.get_response()
                        await conversation.send_message(emoji)
                        await bot.send_read_acknowledge(conversation.chat_id)
                        await conversation.get_response()
                        await conversation.send_message('/done')
                        await conversation.get_response()
                        await bot.send_read_acknowledge(conversation.chat_id)
                        break
                except AlreadyInConversationError:
                    if not sticker_already:
                        try:
                            await context.edit(lang('sticker_another_running'))
                        except:
                            pass
                        sticker_already = True
                    else:
                        pass
                    await sleep(.5)
                except Exception:
                    raise
        else:
            try:
                await context.edit(lang('sticker_no_pack_exist_creating'))
            except:
                pass
            async with bot.conversation('Stickers') as conversation:
                await add_sticker(conversation, command, pack_title, pack_name,
                                  animated, message, context, file, emoji)

        try:
            await context.edit(
                f"{lang('sticker_has_been_added')} [{lang('sticker_this')}](t.me/addstickers/{pack_name}) {lang('sticker_pack')}",
                parse_mode='md')
        except:
            pass
        await sleep(5)
        try:
            await context.delete()
        except:
            pass
コード例 #20
0
ファイル: keyword.py プロジェクト: ywk1000/PagerMaid_Plugins
async def send_reply(chat_id, trigger, mode, reply_msg, context):
    try:
        real_chat_id = chat_id
        chat = context.chat
        sender = context.sender
        replace_data = {}
        if chat_id < 0:
            replace_data = {
                "chat_id": chat.id,
                "chat_name": chat.title
            }
            if sender:
                replace_data["user_id"] = sender.id
                replace_data["first_name"] = sender.first_name
                replace_data["last_name"] = sender.last_name if sender.last_name else ""
        else:
            replace_data["user_id"] = chat_id
            if sender:
                replace_data["first_name"] = sender.first_name
                replace_data["last_name"] = sender.last_name if sender.last_name else ""
            if chat:
                replace_data["chat_id"] = chat.id
                last_name = chat.last_name
                if not last_name:
                    last_name = ""
                replace_data["chat_name"] = f"{chat.first_name} {last_name}"
        update_last_time = False
        could_send_msg = valid_time(chat_id)
        message_list = []
        for re_type, re_msg in reply_msg:
            try:
                catch_pattern = r"\$\{func_(?P<str>((?!\}).)+)\}"
                count = 0
                bracket_str = random_str()
                re_msg = re_msg.replace(r"\}", bracket_str)
                while re.search(catch_pattern, re_msg) and count < 20:
                    func_exec = re.search(catch_pattern, re_msg).group("str")
                    try:
                        func_name = func_exec
                        func_args = None
                        if func_exec.strip().endswith(")"):
                            arg_index = func_exec.find("(")
                            func_name = func_exec[0:arg_index].replace(bracket_str, "}")
                            func_args = func_exec[arg_index + 1:-1].replace(bracket_str, "}")
                        module = f"import_module('data.keyword_func.{func_name}').main"
                        parameter = f"context{', %s' % func_args if func_args else ''}"
                        func_data = await eval(f"{module}({parameter})")
                    except:
                        func_data = "[RE]"
                    chdir(working_dir)
                    re_msg = re_msg.replace("${func_%s}" % func_exec, str(func_data))
                    count += 1
                re_msg = re_msg.replace(bracket_str, "}")
                for k, v in replace_data.items():
                    re_type = re_type.replace(f"${k}", str(v))
                    re_msg = re_msg.replace(f"${k}", str(v))
                type_parse = re_type.split(",")
                edit_id = -1
                for s in type_parse:
                    if len(s) >= 5 and "ext_" == s[0:4] and is_num(s[4:]):
                        chat_id = int(s[4:])
                        type_parse.remove(s)
                    elif len(s) >= 6 and "edit_" == s[0:5] and is_num(s[5:]):
                        edit_id = int(s[5:])
                        type_parse.remove(s)
                if ("file" in type_parse or "photo" in type_parse) and len(re_msg.split()) >= 2:
                    if could_send_msg:
                        update_last_time = True
                        re_data = re_msg.split(" ")
                        cache_exists, filename = has_cache(chat_id, mode, trigger, re_data[0])
                        is_opened = cache_opened(chat_id, mode, trigger)
                        if is_opened:
                            if not cache_exists:
                                if re_data[1][0:7] == "file://":
                                    re_data[1] = re_data[1][7:]
                                    copyfile(" ".join(re_data[1:]), filename)
                                else:
                                    fileget = requests.get(" ".join(re_data[1:]))
                                    with open(filename, "wb") as f:
                                        f.write(fileget.content)
                        else:
                            if re_data[1][0:7] == "file://":
                                re_data[1] = re_data[1][7:]
                                copyfile(" ".join(re_data[1:]), filename)
                            else:
                                fileget = requests.get(" ".join(re_data[1:]))
                                with open(filename, "wb") as f:
                                    f.write(fileget.content)
                        reply_to = None
                        if "reply" in type_parse:
                            reply_to = context.id
                            redir = getsetting(chat_id, mode, trigger, "redir", "0")
                            reply = await context.get_reply_message()
                            if redir == "1" and reply:
                                reply_to = reply.id
                        if edit_id == -1:
                            message_list.append(await bot.send_file(
                                chat_id,
                                filename,
                                reply_to=reply_to,
                                force_document=("file" in type_parse)
                            ))
                        else:
                            edit_file = await bot.upload_file(filename)
                            message_list[edit_id] = await message_list[edit_id].edit(
                                file=edit_file,
                                force_document=("file" in type_parse)
                            )
                        if not is_opened:
                            remove(filename)
                elif ("tgfile" in type_parse or "tgphoto" in type_parse) and len(re_msg.split()) >= 2:
                    if could_send_msg:
                        update_last_time = True
                        re_data = re_msg.split(" ")
                        re_data[0] = " ".join(re_data[0:-1])
                        re_data[1] = re_data[-1:][0].split("/")[-2:]
                        cache_exists, filename = has_cache(chat_id, mode, trigger, re_data[0])
                        is_opened = cache_opened(chat_id, mode, trigger)
                        _data = BytesIO()
                        try:
                            msg_chat_id = int(re_data[1][0])
                        except:
                            async with bot.conversation(re_data[1][0]) as conversation:
                                msg_chat_id = conversation.chat_id
                        msg_id_inchat = int(re_data[1][1])
                        if is_opened:
                            if not cache_exists:
                                media_msg = await bot.get_messages(msg_chat_id, ids=msg_id_inchat, offset_id=0)
                                if media_msg and media_msg.media:
                                    try:
                                        await bot.download_file(media_msg.media.document, _data)
                                    except:
                                        await bot.download_file(media_msg.photo, _data)
                                    with open(filename, "wb") as f:
                                        f.write(_data.getvalue())
                        else:
                            media_msg = await bot.get_messages(msg_chat_id, ids=msg_id_inchat, offset_id=0)
                            if media_msg and media_msg.media:
                                try:
                                    await bot.download_file(media_msg.media.document, _data)
                                except:
                                    await bot.download_file(media_msg.photo, _data)
                                with open(filename, "wb") as f:
                                    f.write(_data.getvalue())
                        reply_to = None
                        if "reply" in type_parse:
                            reply_to = context.id
                            redir = getsetting(chat_id, mode, trigger, "redir", "0")
                            reply = await context.get_reply_message()
                            if redir == "1" and reply:
                                reply_to = reply.id
                        if edit_id == -1:
                            message_list.append(await bot.send_file(
                                chat_id,
                                filename,
                                reply_to=reply_to,
                                force_document=("tgfile" in type_parse)
                            ))
                        else:
                            edit_file = await bot.upload_file(filename)
                            message_list[edit_id] = await message_list[edit_id].edit(
                                file=edit_file,
                                force_document=("tgfile" in type_parse)
                            )
                        if not is_opened:
                            remove(filename)
                elif "plain" in type_parse:
                    if could_send_msg:
                        update_last_time = True
                        if edit_id == -1:
                            message_list.append(await bot.send_message(
                                chat_id,
                                re_msg,
                                link_preview=("nopreview" not in type_parse)
                            ))
                        else:
                            message_list[edit_id] = await message_list[edit_id].edit(
                                re_msg,
                                link_preview=("nopreview" not in type_parse)
                            )
                elif "reply" in type_parse and chat_id == real_chat_id:
                    if could_send_msg:
                        update_last_time = True
                        if edit_id == -1:
                            reply_to = context.id
                            redir = getsetting(chat_id, mode, trigger, "redir", "0")
                            reply = await context.get_reply_message()
                            if redir == "1" and reply:
                                reply_to = reply.id
                            message_list.append(await bot.send_message(
                                chat_id,
                                re_msg,
                                reply_to=reply_to,
                                link_preview=("nopreview" not in type_parse)
                            ))
                        else:
                            message_list[edit_id] = await message_list[edit_id].edit(
                                re_msg,
                                link_preview=("nopreview" not in type_parse)
                            )
                elif "op" in type_parse:
                    if re_msg == "delete":
                        await context.delete()
                    elif re_msg.split()[0] == "sleep" and len(re_msg.split()) == 2:
                        sleep_time = re_msg.split()[1]
                        await asyncio.sleep(float(sleep_time))
                    elif re_msg.split()[0] == "delself" and len(re_msg.split()) == 2:
                        await message_list[int(re_msg.split()[1])].delete()
                    elif re_msg.split()[0] == "trigger" and len(re_msg.split()) == 2:
                        await auto_reply(message_list[int(re_msg.split()[1])])
                    elif re_msg.split("\n")[0].startswith("exec") and len(re_msg.split("\n")) >= 2:
                        args = [
                            "\n".join(re_msg.split("\n")[1:]),
                            " ".join(re_msg.split("\n")[0].split(" ")[1:])
                        ]
                        await eval(f"aexec(args[0]{f', {args[1]}' if args[1] else ''})")
                        chdir(working_dir)
            except:
                pass
            chat_id = real_chat_id
        if update_last_time:
            global group_last_time
            group_last_time[int(chat_id)] = time.time()
    except:
        pass
コード例 #21
0
ファイル: sticker.py プロジェクト: ywcd/PagerMaid-Modify
async def sticker(context):
    """ Fetches images/stickers and add them to your pack. """
    user = await bot.get_me()
    if not user.username:
        user.username = user.first_name
    message = await context.get_reply_message()
    custom_emoji = False
    animated = False
    emoji = ""
    try:
        await context.edit("收集图像/贴纸中 . . .")
    except:
        pass
    if message and message.media:
        if isinstance(message.media, MessageMediaPhoto):
            photo = BytesIO()
            photo = await bot.download_media(message.photo, photo)
        elif "image" in message.media.document.mime_type.split('/'):
            photo = BytesIO()
            try:
                await context.edit("下载图片中 . . .")
            except:
                pass
            await bot.download_file(message.media.document, photo)
            if (DocumentAttributeFilename(file_name='sticker.webp')
                    in message.media.document.attributes):
                emoji = message.media.document.attributes[1].alt
                custom_emoji = True
        elif (DocumentAttributeFilename(file_name='AnimatedSticker.tgs')
              in message.media.document.attributes):
            photo = BytesIO()
            await bot.download_file(message.media.document,
                                    "AnimatedSticker.tgs")
            for index in range(len(message.media.document.attributes)):
                try:
                    emoji = message.media.document.attributes[index].alt
                    break
                except:
                    pass
            custom_emoji = True
            animated = True
            photo = 1
        else:
            try:
                await context.edit("`出错了呜呜呜 ~ 不支持此文件类型。`")
            except:
                pass
            return
    else:
        try:
            await context.edit("`出错了呜呜呜 ~ 请回复带有图片/贴纸的消息。`")
        except:
            pass
        return

    if photo:
        split_strings = context.text.split()
        if not custom_emoji:
            emoji = "👀"
        pack = 1
        sticker_already = False
        if len(split_strings) == 3:
            pack = split_strings[2]
            emoji = split_strings[1]
        elif len(split_strings) == 2:
            if split_strings[1].isnumeric():
                pack = int(split_strings[1])
            else:
                emoji = split_strings[1]

        pack_name = f"{user.username}_{pack}"
        pack_title = f"@{user.username} 的私藏 ({pack})"
        command = '/newpack'
        file = BytesIO()

        if not animated:
            try:
                await context.edit("调整图像大小中 . . .")
            except:
                pass
            image = await resize_image(photo)
            file.name = "sticker.png"
            image.save(file, "PNG")
        else:
            pack_name += "_animated"
            pack_title += " (animated)"
            command = '/newanimated'

        response = request.urlopen(
            request.Request(f'http://t.me/addstickers/{pack_name}'),
            context=ssl.create_default_context(cafile=certifi.where()))
        if not response.status == 200:
            try:
                await context.edit("连接到 Telegram 服务器失败 . . .")
            except:
                pass
            return
        http_response = response.read().decode("utf8").split('\n')

        if "  A <strong>Telegram</strong> user has created the <strong>Sticker&nbsp;Set</strong>." not in \
                http_response:
            for _ in range(20):  # 最多重试20次
                try:
                    async with bot.conversation('Stickers') as conversation:
                        await conversation.send_message('/addsticker')
                        await conversation.get_response()
                        await bot.send_read_acknowledge(conversation.chat_id)
                        await conversation.send_message(pack_name)
                        chat_response = await conversation.get_response()
                        while chat_response.text == "Whoa! That's probably enough stickers for one pack, give it a break. \
A pack can't have more than 120 stickers at the moment.":
                            pack += 1
                            pack_name = f"{user.username}_{pack}"
                            pack_title = f"@{user.username} 的私藏 ({pack})"
                            try:
                                await context.edit("切换到私藏 " + str(pack) +
                                                   " 上一个贴纸包已满 . . .")
                            except:
                                pass
                            await conversation.send_message(pack_name)
                            chat_response = await conversation.get_response()
                            if chat_response.text == "Invalid pack selected.":
                                await add_sticker(conversation, command,
                                                  pack_title, pack_name,
                                                  animated, message, context,
                                                  file, emoji)
                                try:
                                    await context.edit(
                                        f"这张图片/贴纸已经被添加到 [这个](t.me/addstickers/{pack_name}) 贴纸包。",
                                        parse_mode='md')
                                except:
                                    pass
                                return
                        await upload_sticker(animated, message, context, file,
                                             conversation)
                        await conversation.get_response()
                        await conversation.send_message(emoji)
                        await bot.send_read_acknowledge(conversation.chat_id)
                        await conversation.get_response()
                        await conversation.send_message('/done')
                        await conversation.get_response()
                        await bot.send_read_acknowledge(conversation.chat_id)
                        break
                except AlreadyInConversationError:
                    if not sticker_already:
                        try:
                            await context.edit("另一个命令正在添加贴纸, 重新尝试中")
                        except:
                            pass
                        sticker_already = True
                    else:
                        pass
                    await sleep(.5)
                except Exception:
                    raise
        else:
            try:
                await context.edit("贴纸包不存在,正在创建 . . .")
            except:
                pass
            async with bot.conversation('Stickers') as conversation:
                await add_sticker(conversation, command, pack_title, pack_name,
                                  animated, message, context, file, emoji)

        try:
            await context.edit(
                f"这张图片/贴纸已经被添加到 [这个](t.me/addstickers/{pack_name}) 贴纸包。",
                parse_mode='md')
        except:
            pass
        await sleep(5)
        try:
            await context.delete()
        except:
            pass