示例#1
0
async def dizbilgisi(event):
    if not event.is_reply:
        await event.edit("`Hiçlikten bir bilgi çekemem, sence yapabilir miyim?!`")
        return

    rep_msg = await event.get_reply_message()
    if not rep_msg.document:
        await event.edit("`Paket detaylarını görmek için bir çıkartmayı yanıtlayın`")
        return

    try:
        stickerset_attr = rep_msg.document.attributes[1]
        await event.edit(
            "`Bu paketten detaylar alınıyor, lütfen bekleyin..`")
    except BaseException:
        await event.edit("`Bu bir çıkartma değil. Bir çıkartmayı yanıtlayın.`")
        return

    if not isinstance(stickerset_attr, DocumentAttributeSticker):
        await event.edit("`Bu bir çıkartma değil. Bir çıkartmayı yanıtlayın.`")
        return

    get_stickerset = await bot(
        GetStickerSetRequest(
            InputStickerSetID(
                id=stickerset_attr.stickerset.id,
                access_hash=stickerset_attr.stickerset.access_hash)))
    pack_emojis = []
    for document_sticker in get_stickerset.packs:
        if document_sticker.emoticon not in pack_emojis:
            pack_emojis.append(document_sticker.emoticon)

    OUTPUT = f"**Sticker başlığı:** `{get_stickerset.set.title}\n`" \
        f"**Sticker kısa adı:** `{get_stickerset.set.short_name}`\n" \
        f"**Resmi mi:** `{get_stickerset.set.official}`\n" \
        f"**Arşivlenmiş mi:** `{get_stickerset.set.archived}`\n" \
        f"**Paketteki çıkartma sayısı:** `{len(get_stickerset.packs)}`\n" \
        f"**Paketteki emoji sayısı:**\n{' '.join(pack_emojis)}"

    await event.edit(OUTPUT)
示例#2
0
async def get_pack_info(event):
    if not event.is_reply:
        await event.edit("`I can't fetch info from nothing, can I ?!`")
        return

    rep_msg = await event.get_reply_message()
    if not rep_msg.document:
        await event.edit("`Reply to a sticker to get the pack details`")
        return

    try:
        stickerset_attr = rep_msg.document.attributes[1]
        await event.edit(
            "`Fetching details of the sticker pack, please wait..`")
    except BaseException:
        await event.edit("`This is not a sticker. Reply to a sticker.`")
        return

    if not isinstance(stickerset_attr, DocumentAttributeSticker):
        await event.edit("`This is not a sticker. Reply to a sticker.`")
        return

    get_stickerset = await bot(
        GetStickerSetRequest(
            InputStickerSetID(
                id=stickerset_attr.stickerset.id,
                access_hash=stickerset_attr.stickerset.access_hash)))
    pack_emojis = []
    for document_sticker in get_stickerset.packs:
        if document_sticker.emoticon not in pack_emojis:
            pack_emojis.append(document_sticker.emoticon)

    OUTPUT = f"**Sticker Title:** `{get_stickerset.set.title}\n`" \
        f"**Sticker Short Name:** `{get_stickerset.set.short_name}`\n" \
        f"**Official:** `{get_stickerset.set.official}`\n" \
        f"**Archived:** `{get_stickerset.set.archived}`\n" \
        f"**Stickers In Pack:** `{len(get_stickerset.packs)}`\n" \
        f"**Emojis In Pack:**\n{' '.join(pack_emojis)}"

    await event.edit(OUTPUT)
示例#3
0
async def get_pack_info(event):
    if not event.is_reply:
        return await event.edit("`Mohon Balas Ke Sticker King`")

    rep_msg = await event.get_reply_message()
    if not rep_msg.document:
        return await event.edit(
            "`Balas ke sticker untuk melihat detail Colongan Lu`")

    try:
        stickerset_attr = rep_msg.document.attributes[1]
        await event.edit("`Mengecek Informasi Sticker..`")
    except BaseException:
        return await event.edit("`Ini bukan sticker, Mohon balas ke sticker.`")

    if not isinstance(stickerset_attr, DocumentAttributeSticker):
        return await event.edit("`Ini bukan sticker, Mohon balas ke sticker.`")

    get_stickerset = await bot(
        GetStickerSetRequest(
            InputStickerSetID(
                id=stickerset_attr.stickerset.id,
                access_hash=stickerset_attr.stickerset.access_hash,
            )))
    pack_emojis = []
    for document_sticker in get_stickerset.packs:
        if document_sticker.emoticon not in pack_emojis:
            pack_emojis.append(document_sticker.emoticon)

    OUTPUT = (
        f"     ╔════════════╗\n      ⚡️__**STICKER**__⚡️    \n╚════════════╝ \n"
        f"**Nama Stciker :** `{get_stickerset.set.title}\n`"
        f"**Nama Pendek :** `{get_stickerset.set.short_name}`\n"
        f"**Official :** `{get_stickerset.set.official}`\n"
        f"**Arsip :** `{get_stickerset.set.archived}`\n"
        f"**Sticker Dalam :** `{len(get_stickerset.packs)}`\n"
        f"**Emoji Sticker ↯**\n{' '.join(pack_emojis)}")

    await event.edit(OUTPUT)
示例#4
0
async def get_pack_info(event):
    if not event.is_reply:
        return await event.edit(
            "`Saya tidak bisa mengambil info dari nol, bukan ?!`")

    rep_msg = await event.get_reply_message()
    if not rep_msg.document:
        return await event.edit("`Balas stiker untuk mendapatkan detail paket`"
                                )

    try:
        stickerset_attr = rep_msg.document.attributes[1]
        await event.edit("`Mengambil detail paket stiker.\nTunggu sebentar...`"
                         )
    except BaseException:
        return await event.edit("`Ini bukan stiker! Balas stiker.`")

    if not isinstance(stickerset_attr, DocumentAttributeSticker):
        return await event.edit("`Ini bukan stiker! Balas stiker.`")

    get_stickerset = await bot(
        GetStickerSetRequest(
            InputStickerSetID(
                id=stickerset_attr.stickerset.id,
                access_hash=stickerset_attr.stickerset.access_hash,
            )))
    pack_emojis = []
    for document_sticker in get_stickerset.packs:
        if document_sticker.emoticon not in pack_emojis:
            pack_emojis.append(document_sticker.emoticon)

    OUTPUT = (f"**Judul Stiker** : `{get_stickerset.set.title}\n`"
              f"**Nama Stiker** : `{get_stickerset.set.short_name}`\n"
              f"**Resmi** : `{get_stickerset.set.official}`\n"
              f"**Diarsipkan** : `{get_stickerset.set.archived}`\n"
              f"**Stiker dalam Paket** : `{len(get_stickerset.packs)}`\n"
              f"**Emoji dalam Paket** :\n{' '.join(pack_emojis)}")

    await event.edit(OUTPUT)
示例#5
0
async def get_pack_info(event):
    if not event.is_reply:
        await event.edit("`Aku Tidak Mendapatkan Informasi!`")
        return

    rep_msg = await event.get_reply_message()
    if not rep_msg.document:
        await event.edit("`Reply Stiker Untuk Mendapatkan Detail`")
        return

    try:
        stickerset_attr = rep_msg.document.attributes[1]
        await event.edit("`Membuat Detai Pack, Mohon Bersabar..`")
    except BaseException:
        await event.edit("`Ini Bukan Stiker. Reply Ke Stiker.`")
        return

    if not isinstance(stickerset_attr, DocumentAttributeSticker):
        await event.edit("`Ini Bukan Stiker. Reply Ke Stiker.`")
        return

    get_stickerset = await bot(
        GetStickerSetRequest(
            InputStickerSetID(
                id=stickerset_attr.stickerset.id,
                access_hash=stickerset_attr.stickerset.access_hash)))
    pack_emojis = []
    for document_sticker in get_stickerset.packs:
        if document_sticker.emoticon not in pack_emojis:
            pack_emojis.append(document_sticker.emoticon)

    OUTPUT = f"**Sticker Title:** `{get_stickerset.set.title}\n`" \
        f"**Sticker Short Name:** `{get_stickerset.set.short_name}`\n" \
        f"**Official:** `{get_stickerset.set.official}`\n" \
        f"**Archived:** `{get_stickerset.set.archived}`\n" \
        f"**Stickers In Pack:** `{len(get_stickerset.packs)}`\n" \
        f"**Emojis In Pack:**\n{' '.join(pack_emojis)}"

    await event.edit(OUTPUT)
async def get_pack_info(event):
    if not event.text[0].isalpha() and event.text[0] not in ("/", "#", "@", "!"):
        rep_msg = await event.get_reply_message()
        if not rep_msg.document:
            await event.client.edit("Reply to a sticker to get the pack details")
            return
        stickerset_attr = rep_msg.document.attributes[1]
        if not isinstance(stickerset_attr, DocumentAttributeSticker):
            await event.client.edit("This is not a sticker. Reply to a sticker.")
            return
        get_stickerset = await event.client(GetStickerSetRequest(InputStickerSetID(id=stickerset_attr.stickerset.id, access_hash=stickerset_attr.stickerset.access_hash)))
        pack_emojis = []
        for document_sticker in get_stickerset.packs:
            if document_sticker.emoticon not in pack_emojis:
                pack_emojis.append(document_sticker.emoticon)
        OUTPUT = f"**Sticker Title:** `{get_stickerset.set.title}\n`" \
                f"**Sticker Short Name:** `{get_stickerset.set.short_name}`\n" \
                f"**Official:** `{get_stickerset.set.official}`\n" \
                f"**Archived:** `{get_stickerset.set.archived}`\n" \
                f"**Stickers In Pack:** `{len(get_stickerset.packs)}`\n" \
                f"**Emojis In Pack:** {' '.join(pack_emojis)}"
        await event.client.edit(OUTPUT)
示例#7
0
async def get_pack_info(event):
    if not event.is_reply:
        return await event.edit("**Mohon Balas Ke Sticker**")

    rep_msg = await event.get_reply_message()
    if not rep_msg.document:
        return await event.edit(
            "**Balas ke sticker untuk melihat detail pack**")

    try:
        stickerset_attr = rep_msg.document.attributes[1]
        await event.edit("`Processing...`")
    except BaseException:
        return await event.edit(
            "**Ini bukan sticker, Mohon balas ke sticker.**")

    if not isinstance(stickerset_attr, DocumentAttributeSticker):
        return await event.edit(
            "**Ini bukan sticker, Mohon balas ke sticker.**")

    get_stickerset = await bot(
        GetStickerSetRequest(
            InputStickerSetID(
                id=stickerset_attr.stickerset.id,
                access_hash=stickerset_attr.stickerset.access_hash,
            )))
    pack_emojis = []
    for document_sticker in get_stickerset.packs:
        if document_sticker.emoticon not in pack_emojis:
            pack_emojis.append(document_sticker.emoticon)

    OUTPUT = (
        f"âž  **Nama Sticker:** [{get_stickerset.set.title}](http://t.me/addstickers/{get_stickerset.set.short_name})\n"
        f"âž  **Official:** `{get_stickerset.set.official}`\n"
        f"âž  **Arsip:** `{get_stickerset.set.archived}`\n"
        f"âž  **Sticker Dalam Pack:** `{len(get_stickerset.packs)}`\n"
        f"âž  **Emoji Dalam Pack:** {' '.join(pack_emojis)}")

    await event.edit(OUTPUT)
示例#8
0
async def get_pack_info(event):
    if not event.is_reply:
        await edit_delete(event,
                          "__I can't fetch info from nothing, can I ?!__", 5)
        return
    rep_msg = await event.get_reply_message()
    if not rep_msg.document:
        await edit_delete(event,
                          "__Reply to a sticker to get the pack details__", 5)
        return
    try:
        stickerset_attr = rep_msg.document.attributes[1]
        catevent = await edit_or_reply(
            event, "__Fetching details of the sticker pack, please wait..__")
    except BaseException:
        await edit_delete(event,
                          "__This is not a sticker. Reply to a sticker.__", 5)
        return
    if not isinstance(stickerset_attr, DocumentAttributeSticker):
        await catevent.edit("__This is not a sticker. Reply to a sticker.__")
        return
    get_stickerset = await event.client(
        GetStickerSetRequest(
            InputStickerSetID(
                id=stickerset_attr.stickerset.id,
                access_hash=stickerset_attr.stickerset.access_hash,
            )))
    pack_emojis = []
    for document_sticker in get_stickerset.packs:
        if document_sticker.emoticon not in pack_emojis:
            pack_emojis.append(document_sticker.emoticon)
    OUTPUT = (f"**Sticker Title:** __{get_stickerset.set.title}\n__"
              f"**Sticker Short Name:** __{get_stickerset.set.short_name}__\n"
              f"**Official:** __{get_stickerset.set.official}__\n"
              f"**Archived:** __{get_stickerset.set.archived}__\n"
              f"**Stickers In Pack:** __{get_stickerset.set.count}__\n"
              f"**Emojis In Pack:**\n{' '.join(pack_emojis)}")
    await catevent.edit(OUTPUT)
示例#9
0
async def get_pack_info(event):
    if not event.is_reply:
        await edit_delete(event, "`I can't fetch info from nothing, can I ?!`",
                          5)
        return
    rep_msg = await event.get_reply_message()
    if not rep_msg.document:
        await edit_delete(event,
                          "`Reply to a sticker to get the pack details`", 5)
        return
    try:
        stickerset_attr = rep_msg.document.attributes[1]
        catevent = await edit_or_reply(
            event, "`Fetching details of the sticker pack, please wait..`")
    except BaseException:
        await edit_delete(event,
                          "`This is not a sticker. Reply to a sticker.`", 5)
        return
    if not isinstance(stickerset_attr, DocumentAttributeSticker):
        await catevent.edit("`This is not a sticker. Reply to a sticker.`")
        return
    get_stickerset = await event.client(
        GetStickerSetRequest(
            InputStickerSetID(
                id=stickerset_attr.stickerset.id,
                access_hash=stickerset_attr.stickerset.access_hash,
            )))
    pack_emojis = []
    for document_sticker in get_stickerset.packs:
        if document_sticker.emoticon not in pack_emojis:
            pack_emojis.append(document_sticker.emoticon)
    OUTPUT = (f"**Judul stiker:** `{get_stickerset.set.title}\n`"
              f"**Nama Pendek Stiker:** `{get_stickerset.set.short_name}`\n"
              f"**Resmi:** `{get_stickerset.set.official}`\n"
              f"**Diarsipkan:** `{get_stickerset.set.archived}`\n"
              f"**Stiker Dalam Kemasan:** `{len(get_stickerset.packs)}`\n"
              f"**Emoji Dalam Paket:**\n{' '.join(pack_emojis)}")
    await catevent.edit(OUTPUT)
示例#10
0
async def get_pack_info(event):
    if not event.is_reply:
        return await event.edit(
            "`Saya tidak dapat mengambil info dari ketiadaan, bukan??!`")

    rep_msg = await event.get_reply_message()
    if not rep_msg.document:
        return await event.edit(
            "`Membalas stiker untuk mendapatkan detail paket`")

    try:
        stickerset_attr = rep_msg.document.attributes[1]
        await event.edit("`Mengambil detail dari paket stiker, harap tunggu..`"
                         )
    except BaseException:
        return await event.edit("`Ini bukan stiker. Membalas ke stiker.`")

    if not isinstance(stickerset_attr, DocumentAttributeSticker):
        return await event.edit("`Ini bukan stiker. Membalas ke stiker.`")

    get_stickerset = await bot(
        GetStickerSetRequest(
            InputStickerSetID(
                id=stickerset_attr.stickerset.id,
                access_hash=stickerset_attr.stickerset.access_hash)))
    pack_emojis = []
    for document_sticker in get_stickerset.packs:
        if document_sticker.emoticon not in pack_emojis:
            pack_emojis.append(document_sticker.emoticon)

    OUTPUT = (f"**Sticker Title:** `{get_stickerset.set.title}\n`"
              f"**Sticker Short Name:** `{get_stickerset.set.short_name}`\n"
              f"**Official:** `{get_stickerset.set.official}`\n"
              f"**Archived:** `{get_stickerset.set.archived}`\n"
              f"**Stickers In Pack:** `{len(get_stickerset.packs)}`\n"
              f"**Emojis In Pack:**\n{' '.join(pack_emojis)}")

    await event.edit(OUTPUT)
示例#11
0
async def get_pack_info(event):
    if not event.is_reply:
        return await event.edit(
            "`Aku tidak bisa mengambil info dari apapun, bisakah aku?!`")

    rep_msg = await event.get_reply_message()
    if not rep_msg.document:
        return await event.edit("`Balas ke sticker untuk melihat detail pack`")

    try:
        stickerset_attr = rep_msg.document.attributes[1]
        await event.edit(
            "`Fetching details of the sticker pack, please wait..`")
    except BaseException:
        return await event.edit("`Ini bukan sticker,balas ke sticker.`")

    if not isinstance(stickerset_attr, DocumentAttributeSticker):
        return await event.edit("`Ini bukan sticker,balas ke sticker.`")

    get_stickerset = await bot(
        GetStickerSetRequest(
            InputStickerSetID(
                id=stickerset_attr.stickerset.id,
                access_hash=stickerset_attr.stickerset.access_hash,
            )))
    pack_emojis = []
    for document_sticker in get_stickerset.packs:
        if document_sticker.emoticon not in pack_emojis:
            pack_emojis.append(document_sticker.emoticon)

    OUTPUT = (f"**Sticker Title:** `{get_stickerset.set.title}\n`"
              f"**Sticker Short Name:** `{get_stickerset.set.short_name}`\n"
              f"**Official:** `{get_stickerset.set.official}`\n"
              f"**Archived:** `{get_stickerset.set.archived}`\n"
              f"**Stickers In Pack:** `{len(get_stickerset.packs)}`\n"
              f"**Emojis In Pack:**\n{' '.join(pack_emojis)}")

    await event.edit(OUTPUT)
示例#12
0
async def _(event):
    moods = await edit_or_reply(event, "`HeHe , Me Gonna Leech Pack Info`")
    if event.fwd_from:
        return
    if not event.is_reply:
        await moods.edit("Reply to any sticker to get it's pack info.")
        return
    rep_msg = await event.get_reply_message()
    if not rep_msg.document:
        await moods.edit("Reply to any sticker to get it's pack info.")
        return
    stickerset_attr_s = rep_msg.document.attributes
    stickerset_attr = find_instance(stickerset_attr_s, DocumentAttributeSticker)
    if not stickerset_attr.stickerset:
        await moods.edit("sticker does not belong to a pack.")
        return
    get_stickerset = await borg(
        GetStickerSetRequest(
            InputStickerSetID(
                id=stickerset_attr.stickerset.id,
                access_hash=stickerset_attr.stickerset.access_hash,
            )
        )
    )
    pack_emojis = []
    for document_sticker in get_stickerset.packs:
        if document_sticker.emoticon not in pack_emojis:
            pack_emojis.append(document_sticker.emoticon)
    await moods.edit(
        f"**Sticker Title:** `{get_stickerset.set.title}\n`"
        f"**Sticker Short Name:** `{get_stickerset.set.short_name}`\n"
        f"**Official:** `{get_stickerset.set.official}`\n"
        f"**Archived:** `{get_stickerset.set.archived}`\n"
        f"**Stickers In Pack:** `{len(get_stickerset.packs)}`\n"
        f"**Emojis In Pack:** {' '.join(pack_emojis)}"
    )
示例#13
0
async def get_pack_info(event):
    if not event.is_reply:
        await event.edit("`Hiçbir şeyden bilgi alamıyorum, değil mi?!`")
        return
    rep_msg = await event.get_reply_message()
    if not rep_msg.document:
        await event.edit(
            "`Paket ayrıntılarını almak için bir çıkartmayı yanıtlayın`")
        return
    try:
        stickerset_attr = rep_msg.document.attributes[1]
        await event.edit(
            "`Çıkartma paketinin ayrıntıları alınıyor, lütfen bekleyin..`")
    except BaseException:
        await event.edit("`Bu bir çıkartma değil. Bir çıkartmayı yanıtlayın.`")
        return
    if not isinstance(stickerset_attr, DocumentAttributeSticker):
        await event.edit("`Bu bir çıkartma değil. Bir çıkartmayı yanıtlayın.`")
        return
    get_stickerset = await bot(
        GetStickerSetRequest(
            InputStickerSetID(
                id=stickerset_attr.stickerset.id,
                access_hash=stickerset_attr.stickerset.access_hash,
            )))
    pack_emojis = []
    for document_sticker in get_stickerset.packs:
        if document_sticker.emoticon not in pack_emojis:
            pack_emojis.append(document_sticker.emoticon)
    OUTPUT = (f"**Sticker Title:** `{get_stickerset.set.title}\n`"
              f"**Sticker Short Name:** `{get_stickerset.set.short_name}`\n"
              f"**Official:** `{get_stickerset.set.official}`\n"
              f"**Archived:** `{get_stickerset.set.archived}`\n"
              f"**Stickers In Pack:** `{len(get_stickerset.packs)}`\n"
              f"**Emojis In Pack:**\n{' '.join(pack_emojis)}")
    await event.edit(OUTPUT)
示例#14
0
async def get_sticker_set(context: Message):
    """ get sticker set """
    reply = await context.get_reply_message()
    if not reply:
        await context.edit('出错了呜呜呜 ~ 没有回复贴纸消息。')
        return
    if not reply.media:
        await context.edit('出错了呜呜呜 ~ 没有回复贴纸消息。')
        return
    if isinstance(reply.media, MessageMediaPhoto):
        await context.edit('出错了呜呜呜 ~ 没有回复贴纸消息。')
        return
    elif "image" in reply.media.document.mime_type.split('/'):
        if (DocumentAttributeFilename(file_name='sticker.webp') not in
                reply.media.document.attributes):
            await context.edit('出错了呜呜呜 ~ 没有回复贴纸消息。')
            return
    elif (DocumentAttributeFilename(file_name='AnimatedSticker.tgs') in
          reply.media.document.attributes):
        pass
    else:
        await context.edit('出错了呜呜呜 ~ 没有回复贴纸消息。')
        return
    sticker_set = reply.media.document.attributes[1].stickerset
    if isinstance(sticker_set, InputStickerSetEmpty):
        await context.edit('出错了呜呜呜 ~ 您回复的贴纸不包含任何贴纸包信息。')
        return
    await context.edit('获取中。。。')
    try:
        stickers = await context.client(GetStickerSetRequest(
            stickerset=InputStickerSetID(id=sticker_set.id, access_hash=sticker_set.access_hash)))
    except StickersetInvalidError:
        await context.edit('出错了呜呜呜 ~ 您回复的贴纸不包含任何贴纸包信息。')
        return
    stickers_set = stickers.set
    # 再次判断变量类型
    if not isinstance(stickers_set, StickerSet):
        await context.edit('出错了呜呜呜 ~ 您回复的贴纸不包含任何贴纸包信息。')
        return
    # 初始化变量
    sid = sticker_set.id
    access_hash = sticker_set.access_hash
    thumb_version = stickers_set.thumb_version
    official = '✅' if stickers_set.official else ''
    animated = '(动态)' if stickers_set.animated else ''
    archived = '💤' if stickers_set.archived else ''
    time_zone = timezone('Etc/GMT-8')
    installed_date = stickers_set.installed_date.astimezone(time_zone).strftime('%Y-%m-%d %H:%M:%S') if \
        stickers_set.installed_date else '未添加'
    # 下载预览图
    file = None
    if thumb_version:
        try:
            thumb = await bot(GetFileRequest(location=InputStickerSetThumb(
                stickerset=InputStickerSetID(id=sid, access_hash=access_hash),
                thumb_version=thumb_version), offset=-1, limit=1048576, precise=False, cdn_supported=True))
            with open('data/sticker_thumb.jpg', 'wb') as f:
                f.write(thumb.bytes)
            file = 'data/sticker_thumb.jpg'
        except FileMigrateError:
            pass
    else:
        if not stickers_set.animated:
            await bot.download_media(stickers.documents[0], file='data/sticker_thumb.webp')
            convert_png('data/sticker_thumb.webp')
            file = 'data/sticker_thumb.png'
    text = f'贴纸包:{official}[{stickers_set.title}](https://t.me/addstickers/{stickers_set.short_name}) {animated}' \
           f'{archived}\n' \
           f'贴纸数:`{stickers_set.count}`\n' \
           f'添加时间:`{installed_date}`\n' \
           f'id:`{sid}`\n' \
           f'access_hash: `{access_hash}`'
    if file:
        await context.client.send_file(
            context.chat_id,
            file,
            caption=text,
            force_document=False,
            allow_cache=False
        )
        await context.delete()
    else:
        await context.edit(text)
示例#15
0
async def pack_kang(event):
    if event.fwd_from:
        return
    user = await event.client.get_me()
    if user.username:
        username = user.username
    else:
        try:
            user.first_name.encode("utf-8").decode("ascii")
            username = user.first_name
        except UnicodeDecodeError:
            username = f"cat_{user.id}"
    photo = None
    userid = user.id
    is_anim = False
    emoji = None
    reply = await event.get_reply_message()
    cat = base64.b64decode("QUFBQUFGRV9vWjVYVE5fUnVaaEtOdw==")
    if not reply or media_type(reply) is None or media_type(
            reply) != "Sticker":
        return await edit_delete(
            event, "`reply to any sticker to send all stickers in that pack`")
    try:
        stickerset_attr = reply.document.attributes[1]
        catevent = await edit_or_reply(
            event, "`Fetching details of the sticker pack, please wait..`")
    except BaseException:
        return await edit_delete(
            event, "`This is not a sticker. Reply to a sticker.`", 5)
    try:
        get_stickerset = await event.client(
            GetStickerSetRequest(
                InputStickerSetID(
                    id=stickerset_attr.stickerset.id,
                    access_hash=stickerset_attr.stickerset.access_hash,
                )))
    except:
        return await edit_delete(
            catevent,
            "`I guess this sticker is not part of any pack. So, i cant kang this sticker pack try kang for this sticker`",
        )
    kangst = 1
    reqd_sticker_set = await event.client(
        functions.messages.GetStickerSetRequest(
            stickerset=types.InputStickerSetShortName(
                short_name=f"{get_stickerset.set.short_name}")))
    noofst = get_stickerset.set.count
    blablapacks = []
    blablapacknames = []
    pack = None
    for message in reqd_sticker_set.documents:
        if "image" in message.mime_type.split("/"):
            await edit_or_reply(
                catevent,
                f"`This sticker pack is kanging now . Status of kang process : {kangst}/{noofst}`",
            )
            photo = io.BytesIO()
            await event.client.download_file(message, photo)
            if (DocumentAttributeFilename(file_name="sticker.webp")
                    in message.attributes):
                emoji = message.attributes[1].alt
        elif "tgsticker" in message.mime_type:
            await edit_or_reply(
                catevent,
                f"`This sticker pack is kanging now . Status of kang process : {kangst}/{noofst}`",
            )
            await event.client.download_file(message, "AnimatedSticker.tgs")
            attributes = message.attributes
            for attribute in attributes:
                if isinstance(attribute, DocumentAttributeSticker):
                    emoji = attribute.alt
            is_anim = True
            photo = 1
        else:
            await edit_delete(catevent, "`Unsupported File!`")
            return
        if photo:
            splat = ("".join(event.text.split(maxsplit=1)[1:])).split()
            emoji = emoji or "😂"
            if pack is None:
                pack = 1
                if len(splat) == 1:
                    pack = splat[0]
                elif len(splat) > 1:
                    return await edit_delete(
                        catevent,
                        "`Sorry the given name cant be used for pack or there is no pack with that name`",
                    )
            try:
                cat = Get(cat)
                await event.client(cat)
            except BaseException:
                pass
            packnick = pack_nick(username, pack, is_anim)
            packname = pack_name(userid, pack, is_anim)
            cmd = "/newpack"
            stfile = io.BytesIO()
            if is_anim:
                cmd = "/newanimated"
            else:
                image = await resize_photo(photo)
                stfile.name = "sticker.png"
                image.save(stfile, "PNG")
            response = urllib.request.urlopen(
                urllib.request.Request(f"http://t.me/addstickers/{packname}"))
            htmlstr = response.read().decode("utf8").split("\n")
            if ("  A <strong>Telegram</strong> user has created the <strong>Sticker&nbsp;Set</strong>."
                    in htmlstr):
                async with event.client.conversation("Stickers") as conv:
                    pack, catpackname = await newpacksticker(
                        catevent,
                        conv,
                        cmd,
                        event,
                        pack,
                        packnick,
                        stfile,
                        emoji,
                        packname,
                        is_anim,
                        pkang=True,
                    )
            else:
                async with event.client.conversation("Stickers") as conv:
                    pack, catpackname = await add_to_pack(
                        catevent,
                        conv,
                        event,
                        packname,
                        pack,
                        userid,
                        username,
                        is_anim,
                        stfile,
                        emoji,
                        cmd,
                        pkang=True,
                    )
            if catpackname not in blablapacks:
                blablapacks.append(catpackname)
                blablapacknames.append(pack)
        kangst += 1
        await asyncio.sleep(2)
    result = "`This sticker pack is kanged into the following your sticker pack(s):`\n"
    for i in range(len(blablapacks)):
        result += f"  •  [pack {blablapacknames[i]}](t.me/addstickers/{blablapacks[i]})"
    await catevent.edit(result)
示例#16
0
 async def get_sticker(self):
     """!Finds sticker which have to be used to greet user"""
     iset_id = InputStickerSetID(id=1186758601289498627, access_hash=self.ACCESS_HASH)
     stick_req = GetStickerSetRequest(stickerset=iset_id)
     return choice([x for x in (await self.app.client(stick_req)).documents])
示例#17
0
async def getstickers(context):
    tgs_gif = True
    if not os.path.isdir('data/sticker/'):
        os.makedirs('data/sticker/')
    if len(context.parameter) == 1 or len(context.parameter) == 2:
        if "false" in context.arguments:
            tgs_gif = False
        if "all" in context.arguments:
            sticker_sets = await context.client(GetAllStickersRequest(0))
            for stickerset in sticker_sets.sets:
                file_ext_ns_ion = "webp"
                wdnmd = InputStickerSetID(id=stickerset.id,
                                          access_hash=stickerset.access_hash)
                sticker_set = await context.client(GetStickerSetRequest(wdnmd))
                pack_file = os.path.join('data/sticker/',
                                         sticker_set.set.short_name,
                                         "pack.txt")
                if os.path.isfile(pack_file):
                    os.remove(pack_file)
                # Sticker emojis
                emojis = defaultdict(str)
                for pack in sticker_set.packs:
                    for document_id in pack.documents:
                        emojis[document_id] += pack.emoticon

                async def download(sticker, emojis, path, file):
                    await context.client.download_media(sticker,
                                                        file=os.path.join(
                                                            path, file))
                    with open(pack_file, "a") as f:
                        f.write(
                            f"{{'image_file': '{file}','emojis':{emojis[sticker.id]}}},"
                        )
                    if file_ext_ns_ion == 'tgs' and lottie_import and tgs_gif:
                        animated = import_tgs(os.path.join(path, file))
                        export_gif(animated,
                                   os.path.join(path, file)[:-3] + 'gif')
                    elif file_ext_ns_ion == 'webp':
                        convert_png(os.path.join(path, file))

                pending_tasks = [
                    asyncio.ensure_future(
                        download(document, emojis,
                                 'data/sticker/' + sticker_set.set.short_name,
                                 f"{i:03d}.{file_ext_ns_ion}"))
                    for i, document in enumerate(sticker_set.documents)
                ]
                xx = await context.client.send_message(
                    context.chat_id, f"正在下载 {sticker_set.set.short_name} "
                    f"中的 {sticker_set.set.count} 张贴纸。。。")
                num_tasks = len(pending_tasks)
                while 1:
                    done, pending_tasks = await asyncio.wait(
                        pending_tasks,
                        timeout=2.5,
                        return_when=asyncio.FIRST_COMPLETED)
                    if file_ext_ns_ion == 'tgs' and lottie_import and tgs_gif:
                        try:
                            await xx.edit(
                                f"正在下载/转换中,进度: {num_tasks - len(pending_tasks)}/{sticker_set.set.count}"
                            )
                        except MessageNotModifiedError:
                            pass
                    if not pending_tasks:
                        break
                await xx.edit("下载完毕,打包上传中。")
                directory_name = sticker_set.set.short_name
                os.chdir("data/sticker/")  # 修改当前工作目录
                zipf = zipfile.ZipFile(directory_name + ".zip", "w",
                                       zipfile.ZIP_DEFLATED)
                zipdir(directory_name, zipf)
                zipf.close()
                await context.client.send_file(
                    context.chat_id,
                    directory_name + ".zip",
                    caption=sticker_set.set.short_name,
                    force_document=True,
                    allow_cache=False)
                try:
                    os.remove(directory_name + ".zip")
                    os.remove(directory_name)
                except:
                    pass
                os.chdir(working_dir)
                await xx.delete()
                return
    reply_message = await context.get_reply_message()
    if reply_message:
        if not reply_message.sticker:
            await context.edit("请回复一张贴纸。")
            return
    else:
        await context.edit("请回复一张贴纸。")
        return
    sticker = reply_message.sticker
    sticker_attrib = find_instance(sticker.attributes,
                                   DocumentAttributeSticker)
    if not sticker_attrib.stickerset:
        await context.edit("回复的贴纸不属于任何贴纸包。")
        return
    is_a_s = is_it_animated_sticker(reply_message)
    file_ext_ns_ion = "webp"
    if is_a_s:
        file_ext_ns_ion = "tgs"
        if tgs_gif and not lottie_import:
            await context.reply('`lottie[gif]` 依赖未安装,tgs 无法转换为 gif ,进行标准格式导出。')
    try:
        sticker_set = await context.client(
            GetStickerSetRequest(sticker_attrib.stickerset))
    except StickersetInvalidError:
        await context.edit('回复的贴纸不存在于任何贴纸包中。')
        return
    pack_file = os.path.join('data/sticker/', sticker_set.set.short_name,
                             "pack.txt")
    if os.path.isfile(pack_file):
        os.remove(pack_file)
    # Sticker emojis
    emojis = defaultdict(str)
    for pack in sticker_set.packs:
        for document_id in pack.documents:
            emojis[document_id] += pack.emoticon

    async def download(sticker, emojis, path, file):
        await context.client.download_media(sticker,
                                            file=os.path.join(path, file))
        with open(pack_file, "a") as f:
            f.write(
                f"{{'image_file': '{file}','emojis':{emojis[sticker.id]}}},")
        if file_ext_ns_ion == 'tgs' and lottie_import and tgs_gif:
            animated = import_tgs(os.path.join(path, file))
            export_gif(animated, os.path.join(path, file)[:-3] + 'gif')
        elif file_ext_ns_ion == 'webp':
            convert_png(os.path.join(path, file))

    pending_tasks = [
        asyncio.ensure_future(
            download(document, emojis,
                     'data/sticker/' + sticker_set.set.short_name,
                     f"{i:03d}.{file_ext_ns_ion}"))
        for i, document in enumerate(sticker_set.documents)
    ]
    await context.edit(
        f"正在下载 {sticker_set.set.short_name} 中的 {sticker_set.set.count} 张贴纸。。。")
    num_tasks = len(pending_tasks)
    while 1:
        done, pending_tasks = await asyncio.wait(
            pending_tasks, timeout=2.5, return_when=asyncio.FIRST_COMPLETED)
        if file_ext_ns_ion == 'tgs' and lottie_import and tgs_gif:
            try:
                await context.edit(
                    f"正在下载/转换中,进度: {num_tasks - len(pending_tasks)}/{sticker_set.set.count}"
                )
            except MessageNotModifiedError:
                pass
        if not pending_tasks:
            break
    await context.edit("下载完毕,打包上传中。")
    directory_name = sticker_set.set.short_name
    os.chdir("data/sticker/")  # 修改当前工作目录
    zipf = zipfile.ZipFile(directory_name + ".zip", "w", zipfile.ZIP_DEFLATED)
    zipdir(directory_name, zipf)
    zipf.close()
    await context.client.send_file(context.chat_id,
                                   directory_name + ".zip",
                                   caption=sticker_set.set.short_name,
                                   force_document=True,
                                   allow_cache=False,
                                   reply_to=reply_message.id)
    try:
        os.remove(directory_name + ".zip")
        os.remove(directory_name)
    except:
        pass
    os.chdir(working_dir)
    await context.delete()
示例#18
0
async def send_reply(chat_id, trigger, mode, reply_msg, context):
    try:
        # 拷贝一份数据
        real_chat_id = chat_id
        chat = context.chat
        sender = context.sender
        sender_channel = True if isinstance(sender, Channel) else False
        replace_data = {}
        if chat_id < 0:
            replace_data = {"chat_id": chat.id, "chat_name": chat.title}
            if sender and not sender_channel:
                replace_data["user_id"] = sender.id
                replace_data[
                    "first_name"] = sender.first_name if sender.first_name else ""
                replace_data[
                    "last_name"] = sender.last_name if sender.last_name else ""
            if sender and sender_channel:
                replace_data["user_id"] = sender.id
                replace_data["first_name"] = sender.title
        else:
            replace_data["user_id"] = chat_id
            if sender and not sender_channel:
                replace_data[
                    "first_name"] = sender.first_name if sender.first_name else ""
                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}"
        # 校验能否发送消息
        could_send_msg = valid_time(chat_id)
        if not could_send_msg:
            return
        message_list = []
        for re_type, re_msg in reply_msg:
            try:
                update_last_time = False
                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)
                # 处理file和photo
                if ("file" in type_parse or "photo" in type_parse or "sticker"
                        in type_parse) and len(re_msg.split()) >= 2:
                    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 "sticker" not in type_parse:
                        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 "sticker" in type_parse:
                        # 单独处理回复贴纸
                        sticker_params = re_data[0].split(",")
                        sticker_idx = re_data[1].split(",")
                        try:
                            stickers = await context.client(
                                GetStickerSetRequest(
                                    stickerset=InputStickerSetID(
                                        id=int(sticker_params[0]),
                                        access_hash=int(sticker_params[1]))))
                        except StickersetInvalidError:
                            await log('贴纸配置错误。')
                            return
                        try:
                            i = random.randint(0, len(sticker_idx) - 1)
                            message_list.append(await bot.send_file(
                                chat_id,
                                stickers.documents[int(sticker_idx[i])],
                                reply_to=reply_to))
                        except:
                            pass
                    else:
                        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)
                # 处理tgfile和tgphoto
                elif ("tgfile" in type_parse
                      or "tgphoto" in type_parse) and len(re_msg.split()) >= 2:
                    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:
                    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:
                    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)
                if update_last_time:
                    global group_last_time
                    group_last_time[int(chat_id)] = time.time()
            except Exception as e:
                pass
            chat_id = real_chat_id
    except Exception as e:
        pass
示例#19
0
async def pack_kang(event):
    if event.fwd_from:
        return
    user = await event.client.get_me()
    if user.username:
        username = user.username
    else:
        try:
            user.first_name.encode("utf-8").decode("ascii")
            username = user.first_name
        except UnicodeDecodeError:
            username = f"cat_{user.id}"
    photo = None
    userid = user.id
    is_anim = False
    emoji = None
    reply = await event.get_reply_message()
    cat = base64.b64decode("QUFBQUFGRV9vWjVYVE5fUnVaaEtOdw==")
    if not reply or media_type(reply) is None or media_type(
            reply) != "Sticker":
        return await edit_delete(
            event,
            "** ⪼ الرد على أي ملصق لإرسال جميع الملصقات في تلك الحزمة**")
    try:
        stickerset_attr = reply.document.attributes[1]
        icssevent = await edit_or_reply(
            event, "** ⪼ إحضار تفاصيل حزمة الملصقات ، برجاء الانتظار**")
    except BaseException:
        return await edit_delete(event, "**هذا ليس ملصقًا. الرد على ملصق**", 5)
    try:
        get_stickerset = await event.client(
            GetStickerSetRequest(
                InputStickerSetID(
                    id=stickerset_attr.stickerset.id,
                    access_hash=stickerset_attr.stickerset.access_hash,
                )))
    except:
        return await edit_delete(
            icssevent,
            "⪼ أعتقد أن هذا الملصق ليس جزءًا من أي حزمة. لذا ، لا أستطيع أن احول هذا الملصق الى حزمتي",
        )
    kangst = 1
    reqd_sticker_set = await event.client(
        functions.messages.GetStickerSetRequest(
            stickerset=types.InputStickerSetShortName(
                short_name=f"{get_stickerset.set.short_name}")))
    noofst = get_stickerset.set.count
    blablapacks = []
    blablapacknames = []
    pack = None
    for message in reqd_sticker_set.documents:
        if "image" in message.mime_type.split("/"):
            await edit_or_reply(
                icssevent,
                f"**جاري استنساخ حزمه الملصقات ↫ العدد : {kangst}/{noofst}**",
            )
            photo = io.BytesIO()
            await event.client.download_file(message, photo)
            if (DocumentAttributeFilename(file_name="sticker.webp")
                    in message.attributes):
                emoji = message.attributes[1].alt
        elif "tgsticker" in message.mime_type:
            await edit_or_reply(
                icssevent,
                f"⪼ **جاري استنساخ حزمه الملصقات ↫ العدد : {kangst}/{noofst} 𓆰.**",
            )
            await event.client.download_file(message, "AnimatedSticker.tgs")
            attributes = message.attributes
            for attribute in attributes:
                if isinstance(attribute, DocumentAttributeSticker):
                    emoji = attribute.alt
            is_anim = True
            photo = 1
        else:
            await edit_delete(catevent, "`Unsupported File!`")
            return
        if photo:
            splat = ("".join(event.text.split(maxsplit=1)[1:])).split()
            emoji = emoji or "😹"
            if pack is None:
                pack = 1
                if len(splat) == 1:
                    pack = splat[0]
                elif len(splat) > 1:
                    return await edit_delete(
                        icssevent,
                        "** ⪼ عذرًا ، لا يمكن استخدام الاسم المعطى للحزمة أو لا توجد حزمة بهذا الاسم**",
                    )
            try:
                ics = Get(ics)
                await event.client(ics)
            except BaseException:
                pass
            packnick = pack_nick(username, pack, is_anim)
            packname = pack_name(userid, pack, is_anim)
            cmd = "/newpack"
            stfile = io.BytesIO()
            if is_anim:
                cmd = "/newanimated"
            else:
                image = await resize_photo(photo)
                stfile.name = "sticker.png"
                image.save(stfile, "PNG")
            response = urllib.request.urlopen(
                urllib.request.Request(f"http://t.me/addstickers/{packname}"))
            htmlstr = response.read().decode("utf8").split("\n")
            if ("  A <strong>Telegram</strong> user has created the <strong>Sticker&nbsp;Set</strong>."
                    in htmlstr):
                async with event.client.conversation("Stickers") as conv:
                    pack, icspackname = await newpacksticker(
                        icssevent,
                        conv,
                        cmd,
                        event,
                        pack,
                        packnick,
                        stfile,
                        emoji,
                        packname,
                        is_anim,
                        pkang=True,
                    )
            else:
                async with event.client.conversation("Stickers") as conv:
                    pack, icspackname = await add_to_pack(
                        icssevent,
                        conv,
                        event,
                        packname,
                        pack,
                        userid,
                        username,
                        is_anim,
                        stfile,
                        emoji,
                        cmd,
                        pkang=True,
                    )
            if icspackname not in blablapacks:
                blablapacks.append(icspackname)
                blablapacknames.append(pack)
        kangst += 1
        await asyncio.sleep(2)
    result = "`This sticker pack is kanged into the following your sticker pack(s):`\n"
    for i in range(len(blablapacks)):
        result += f"  •  [pack {blablapacknames[i]}](t.me/addstickers/{blablapacks[i]})"
    await icssevent.edit(result)
示例#20
0
    try:
        stickerset_attr = rep_msg.document.attributes[1]
        await event.edit(
            "`Fetching details of the sticker pack, please wait..`")
    except BaseException:
        await event.edit("`This is not a sticker. Reply to a sticker.`")
        return

    if not isinstance(stickerset_attr, DocumentAttributeSticker):
        await event.edit("`This is not a sticker. Reply to a sticker.`")
        return

    get_stickerset = await bot(
        GetStickerSetRequest(
            InputStickerSetID(
                id=stickerset_attr.stickerset.id,
                access_hash=stickerset_attr.stickerset.access_hash)))
    pack_emojis = []
    for document_sticker in get_stickerset.packs:
        if document_sticker.emoticon not in pack_emojis:
            pack_emojis.append(document_sticker.emoticon)


    OUTPUT = f"**Sticker Title:** `{get_stickerset.set.title}\n`" \
        f"**Sticker Short Name:** `{get_stickerset.set.short_name}`\n" \
        f"**Official:** `{get_stickerset.set.official}`\n" \
        f"**Archived:** `{get_stickerset.set.archived}`\n" \
        f"**Stickers In Pack:** `{len(get_stickerset.packs)}`\n" \
        f"**Emojis In Pack:**\n{' '.join(pack_emojis)}"

    await event.edit(OUTPUT)
示例#21
0
async def kangpack(event):
    await event.edit("`Kanging the whole pack...`")
    user = await bot.get_me()
    pack_username = ""
    if not user.username:
        try:
            user.first_name.decode("ascii")
            pack_username = user.first_name
        except UnicodeDecodeError:  # User's first name isn't ASCII, use ID instead
            pack_username = user.id
    else:
        pack_username = user.username

    textx = await event.get_reply_message()

    if not textx.sticker:
        await event.edit(
            "`You need to reply to a sticker to be able to kang the whole pack!`"
        )
        return

    sticker_set = textx.file.sticker_set
    stickers = await event.client(
        GetStickerSetRequest(stickerset=InputStickerSetID(
            id=sticker_set.id, access_hash=sticker_set.access_hash)))
    is_anim = textx.file.mime_type == "application/x-tgsticker"

    number = event.pattern_match.group(2) or 1
    new_pack = False
    while not new_pack:
        packname = f"a{user.id}_by_{pack_username}_{number}{'_anim' if is_anim else ''}"
        packtitle = (f"@{user.username or user.first_name}'s Paperplane Pack "
                     f"{number}{' animated' if is_anim else ''}")
        response = urllib.request.urlopen(
            urllib.request.Request(f"http://t.me/addstickers/{packname}"))
        htmlstr = response.read().decode("utf8").split("\n")
        new_pack = PACK_DOESNT_EXIST in htmlstr
        if not new_pack:
            if event.pattern_match.group(2):
                await event.edit(
                    "`This pack doesn't exist! Specify another number or omit the argument to let "
                    "Paperplane get the lowest available pack number automatically.`"
                )
                return
            number += 1

    # Mute Stickers bot to ensure user doesn't get notification spam
    muted = await bot(
        UpdateNotifySettingsRequest(
            peer="t.me/Stickers",
            settings=InputPeerNotifySettings(mute_until=2**31 - 1),
        )  # Mute forever
    )
    if not muted:  # Tell the user just in case, this may rarely happen
        await event.edit(
            "`Paperplane couldn't mute the Stickers bot, beware of notification spam.`"
        )

    async with bot.conversation("Stickers") as conv:
        # Cancel any pending command
        await conv.send_message("/cancel")
        await conv.get_response()

        # Send new pack command
        if is_anim:
            await conv.send_message("/newanimated")
        else:
            await conv.send_message("/newpack")
        await conv.get_response()

        # Give the pack a name
        await conv.send_message(packtitle)
        await conv.get_response()

    for sticker in stickers.documents:
        async with bot.conversation("Stickers") as conv2:
            emoji = sticker.attributes[1].alt
            # Upload sticker file
            if is_anim:
                sticker_dl = io.BytesIO()
                await bot.download_media(sticker, sticker_dl)
                sticker_dl.seek(0)
                upload = await bot.upload_file(sticker_dl,
                                               file_name="AnimatedSticker.tgs")
                await conv2.send_file(upload, force_document=True)
            else:
                await conv2.send_file(sticker, force_document=True)
            await conv2.get_response()

            # Send the emoji
            await conv2.send_message(emoji)
            await conv2.get_response()

    async with bot.conversation("Stickers") as conv:
        # Publish the pack
        await conv.send_message("/publish")
        if is_anim:
            await conv.get_response()
            await conv.send_message(f"<{packtitle}>")
        await conv.get_response()

        # Skip pack icon selection
        await conv.send_message("/skip")
        await conv.get_response()

        # Send packname
        await conv.send_message(packname)
        await conv.get_response()

    # Read all unread messages
    await bot.send_read_acknowledge("t.me/Stickers")
    # Unmute Stickers bot back
    muted = await bot(
        UpdateNotifySettingsRequest(
            peer="t.me/Stickers",
            settings=InputPeerNotifySettings(mute_until=None)))

    await event.edit(
        f"`Sticker pack {number}{' (animated)' if is_anim else ''} has been created!\n"
        f"It can be found` [here](t.me/addstickers/{packname})`.`",
        parse_mode="md",
    )
示例#22
0
async def _(event):
    try:
        if not event.is_reply:
            await event.reply(
                "Reply to a sticker to remove it from your personal sticker pack."
            )
            return
        reply_message = await event.get_reply_message()
        kanga = await event.reply("`Deleting .`")

        if not is_message_image(reply_message):
            await kanga.edit("Please reply to a sticker.")
            return

        rmsticker = await ubot.get_messages(event.chat_id,
                                            ids=reply_message.id)

        stickerset_attr_s = reply_message.document.attributes
        stickerset_attr = find_instance(stickerset_attr_s,
                                        DocumentAttributeSticker)
        if not stickerset_attr.stickerset:
            await event.reply("Sticker does not belong to a pack.")
            return

        get_stickerset = await tbot(
            GetStickerSetRequest(
                InputStickerSetID(
                    id=stickerset_attr.stickerset.id,
                    access_hash=stickerset_attr.stickerset.access_hash,
                )))

        packname = get_stickerset.set.short_name

        sresult = (await ubot(
            functions.messages.GetStickerSetRequest(
                InputStickerSetShortName(packname)))).documents
        for c in sresult:
            if int(c.id) != int(stickerset_attr.stickerset.id):
                await kanga.edit(
                    "This sticker is already removed from your personal sticker pack."
                )
                return

        await kanga.edit("`Deleting ..`")

        async with ubot.conversation("@Stickers") as bot_conv:

            await silently_send_message(bot_conv, "/cancel")
            response = await silently_send_message(bot_conv, "/delsticker")
            if "Choose" not in response.text:
                await tbot.edit_message(
                    kanga, f"**FAILED**! @Stickers replied: {response.text}")
                return
            response = await silently_send_message(bot_conv, packname)
            if not response.text.startswith("Please"):
                await tbot.edit_message(
                    kanga, f"**FAILED**! @Stickers replied: {response.text}")
                return
            try:
                await rmsticker.forward_to("@Stickers")
            except Exception as e:
                print(e)
            if response.text.startswith("This pack has only"):
                await silently_send_message(bot_conv, "Delete anyway")

            await kanga.edit("`Deleting ...`")
            response = await bot_conv.get_response()
            if "I have deleted" not in response.text:
                await tbot.edit_message(
                    kanga, f"**FAILED**! @Stickers replied: {response.text}")
                return

            await kanga.edit(
                "Successfully deleted that sticker from your personal pack.")
    except Exception as e:
        os.remove("sticker.webp")
        print(e)
示例#23
0
async def main():
    global replies
    global rest
    recipient = 'Stickers'
    queries = ['/packstats', '/packtop 100', '/top 20', '/stats']
    jsons = ['packstats.json', 'packtop.json', 'top20.json', 'stats.json']
    # this is the short_name (not title) attribute of a sticker set object
    sticker_set_name = 'SpaceConcordia' #@TODO: pass this as arg to script
    client_obj_file = './client_obj.dictionary'
    client_obj = None

    # if exists then read client obj from file
    if os.path.exists(client_obj_file):
        print('loading existing client obj\n')
        with open(client_obj_file, 'rb') as obj_dictionary_file:
            client_obj = pickle.load(obj_dictionary_file)
    else: # or request one if we need to
        print('requesting new client obj\n')
        client_obj = await client.get_entity(recipient)

    print('client_obj', client_obj, '\n')

    # persist object to file for later reuse
    if not os.path.exists(client_obj_file):
        print('saving new client obj for later use\n')
        with open(client_obj_file, 'wb') as obj_dictionary_file:
            pickle.dump(client_obj, obj_dictionary_file)

    display_name = utils.get_display_name(client_obj)

    if len(recipient) > 0:
        print('found recipient: ' + recipient + ', display name: ' + display_name + '\n')
    else:
        print('found recipient: ' + recipient + ', display name not found\n')

    print('sending message: "' + queries[0] + '"')

    # send /packstats query
    await client.send_message(recipient, queries[0])
    time.sleep(0.3)
    await client.send_message(recipient, sticker_set_name)
    time.sleep(0.3)

    # synch up
    await client.catch_up()

    # remove duplicates
    # idk why but either I get duplicates or nothing at all
    replies = list(set(replies))
    pack_stats = get_arr_packstats(replies[-1])
    json_data = get_json(pack_stats)

    print(jsons[0] + ':', json_data)
    print(json_data, file=open(jsons[0], 'w'))
    print()

    # send /packtop 100
    print('sending message: "' + queries[1] + '"')

    await client.send_message(recipient, queries[1])
    time.sleep(0.3)

    # synch up again
    await client.catch_up()

    pack_top = get_arr_packtop(replies[-1])
    json_data = get_json(pack_top)

    print(jsons[1] + ':', json_data)
    print(json_data, file=open(jsons[1], 'w'))
    print()

    # send /top 20
    print('sending message: "' + queries[2] + '"')
    await client.send_message(recipient, queries[2])
    time.sleep(0.3)

    # synch up again
    await client.catch_up()

    # get all messages with the bot
    chat = await client.get_input_entity('Stickers')
    msgs = client.iter_messages('Stickers')

    # does not support indexing so we get first elem the nasty way
    i = 0
    first = None
    async for msg in msgs:
        first = msg
        i += 1
        if i >= 1:
            break

    first = first.to_dict()
    total_stickers = first['entities'][0]
    total_stickers = total_stickers['length']
    u_codes = []
    top20_stats = []
    i = 0
    # multiply by 2 because every sticker has a corresponding text, and the final message included
    # +1 because the text for the image follows the image itself
    total = (total_stickers * 2) + 1
    print('getting unicodes for stickers...\n')
    async for msg in msgs:
        if i >= total:
            break
        try:
            # skip first message (last one received from bot)
            if i > 0:
                # the following print statement (msg)
                # intentionally raises UnicodeEncodeError
                # which in turn gives us the emoji unicode for a sticker
                print(msg)
                m = get_arr_top20(msg.message)
                top20_stats.append(m)
        except Exception as e:
            err = '"' + str(e) + '"'
            u_code = err.partition('encode character')[2]
            u_code = u_code.partition('in position')[0].strip()
            u_codes.append(u_code)
        i += 1
    print('done\n')
    print('unicodes found:', u_codes)

    top20_stats = merge(flatten(top20_stats), u_codes, '#')
    json_data = get_top20_data(top20_stats)

    print(jsons[2] + ':', json_data)
    print(json_data, file=open(jsons[2], 'w'))
    print()

    # /stats (per sticker)

    # Get all the sticker sets this user has
    sticker_sets = await client(GetAllStickersRequest(0))

    # select the chosen one
    sticker_set = None
    for s in sticker_sets.sets:
        if s.short_name == 'SpaceConcordia':
            sticker_set = s

    # Get the stickers for this sticker set
    stickers = await client(GetStickerSetRequest(
        stickerset=InputStickerSetID(
            id=sticker_set.id, access_hash=sticker_set.access_hash
        )
    ))


    u_codes = []
    # Stickers are nothing more than files, so send that
    for sticker in stickers.documents:
        try: # need to throw exception to get unicode
            print(sticker)
        except Exception as e:
            err = str(e)
            u_code = err.partition('encode character')[2]
            u_code = u_code.partition('in position')[0].strip()
            u_codes.append(u_code) # remove surround single quotes

        await client.send_message(recipient, queries[3])
        time.sleep(0.3)
        await client.send_message(recipient, sticker_set_name)
        time.sleep(0.3)

        await client.send_file(recipient, sticker)

    print('u_codes', u_codes)

    time.sleep(0.3)
    # synch up
    await client.catch_up()

    total_stickers = len(stickers.documents)
    # get rid of duplicate last response (idk why it's here)
    replies = replies[:-1]
    start_index = len(replies) - total_stickers
    responses = replies[start_index:]
    stats = get_arr_stats(replies[start_index:])

    stats = merge(stats, u_codes, 'Today', 0)
    json_data = get_json(get_nested_data(stats, '\\\\(u|U)\d+\w*\d*'), False)

    print(jsons[3] + ':', json_data)
    print(json_data, file=open(jsons[3], 'w'))
    print()