Ejemplo n.º 1
0
async def main(args: argparse.Namespace) -> None:
    await matrix.load_config(args.config)
    client = TelegramClient(args.session, 298751,
                            "cb676d6bae20553c9996996a8f52b4d7")
    await client.start()

    if args.list:
        stickers: AllStickers = await client(GetAllStickersRequest(hash=0))
        index = 1
        width = len(str(stickers.sets))
        print("Your saved sticker packs:")
        for saved_pack in stickers.sets:
            print(f"{index:>{width}}. {saved_pack.title} "
                  f"(t.me/addstickers/{saved_pack.short_name})")
    elif args.pack[0]:
        input_packs = []
        for pack_url in args.pack[0]:
            match = pack_url_regex.match(pack_url)
            if not match:
                print(f"'{pack_url}' doesn't look like a sticker pack URL")
                return
            input_packs.append(
                InputStickerSetShortName(short_name=match.group(1)))
        for input_pack in input_packs:
            pack: StickerSetFull = await client(
                GetStickerSetRequest(input_pack))
            await reupload_pack(client, pack, args.output_dir)
    else:
        parser.print_help()

    await client.disconnect()
Ejemplo n.º 2
0
async def stick(e):
	await e.delete()
	sticker_sets = await client(GetAllStickersRequest(0))
	sticker_set = sticker_sets.sets[0]
	stickers =await client(GetStickerSetRequest(
	    stickerset=InputStickerSetID(
	        id=sticker_set.id, access_hash=sticker_set.access_hash
	    )
	))
	await client.send_file(await client.get_input_entity(e.chat_id), stickers.documents[0])
Ejemplo n.º 3
0
    async def run(self):
        async with TelegramClient('anon',
                                  api_id=self.settings.app_id,
                                  api_hash=self.settings.app_hash
                                  ) as client:  # type: TelegramClient
            sticker_sets = await client(GetAllStickersRequest(0)
                                        )  # type: AllStickers
            stickers = []
            for sticker_set in sticker_sets.sets:  # type: StickerSet
                extracted_stickers = await client(
                    GetStickerSetRequest(stickerset=InputStickerSetID(
                        id=sticker_set.id,
                        access_hash=sticker_set.access_hash)))
                stickers += extracted_stickers.documents

            await client.send_file(self.settings.login,
                                   random.choice(stickers))
Ejemplo n.º 4
0
async def ars_getall(message: Message) -> None:
    sticker_sets = await message.client(GetAllStickersRequest(0))
    sticker_pack_list = []
    for sticker_set in sticker_sets.sets:
        if len(sticker_pack_list) < 10:
            text = "我发现了一个Sticker Pack,名为\n" + sticker_set.title + "\n" + "ID为: `" + \
                str(sticker_set.id) + "` \n" + "Hash为: `" + str(sticker_set.access_hash) + \
                "` \n" + "共有" + str(sticker_set.count) + "张"
            sticker_pack_list.extend([text])
        else:
            sticker_pack_list_old = sticker_pack_list
            send_text = '\n\n'.join(sticker_pack_list_old)
            await message.client.send_message(message.chat_id, send_text)
            sticker_pack_list = []
            await sleep(2)
    sendtext = '\n\n'.join(sticker_pack_list)
    await message.client.send_message(message.chat_id, sendtext)
    await message.delete()
Ejemplo n.º 5
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()
Ejemplo n.º 6
0
async def stats(event: NewMessage.Event, ):
    ok = await event.eor("`Collecting stats...`")
    start_time = time.time()
    private_chats = 0
    bots = 0
    groups = 0
    broadcast_channels = 0
    admin_in_groups = 0
    creator_in_groups = 0
    admin_in_broadcast_channels = 0
    creator_in_channels = 0
    unread_mentions = 0
    unread = 0
    dialog: Dialog
    async for dialog in event.client.iter_dialogs():
        entity = dialog.entity
        if isinstance(entity, Channel) and entity.broadcast:
            broadcast_channels += 1
            if entity.creator or entity.admin_rights:
                admin_in_broadcast_channels += 1
            if entity.creator:
                creator_in_channels += 1

        elif (isinstance(entity, Channel) and entity.megagroup) or isinstance(
                entity, Chat):
            groups += 1
            if entity.creator or entity.admin_rights:
                admin_in_groups += 1
            if entity.creator:
                creator_in_groups += 1

        elif isinstance(entity, User):
            private_chats += 1
            if entity.bot:
                bots += 1

        unread_mentions += dialog.unread_mentions_count
        unread += dialog.unread_count
    stop_time = time.time() - start_time
    try:
        ct = (await event.client(GetBlockedRequest(1, 0))).count
    except AttributeError:
        ct = 0
    try:
        sp = await event.client(GetAllStickersRequest(0))
        sp_count = len(sp.sets)
    except BaseException:
        sp_count = 0
    full_name = inline_mention(event.client.me)
    response = f"🔸 **Stats for {full_name}** \n\n"
    response += f"**Private Chats:** {private_chats} \n"
    response += f"**  •• **`Users: {private_chats - bots}` \n"
    response += f"**  •• **`Bots: {bots}` \n"
    response += f"**Groups:** {groups} \n"
    response += f"**Channels:** {broadcast_channels} \n"
    response += f"**Admin in Groups:** {admin_in_groups} \n"
    response += f"**  •• **`Creator: {creator_in_groups}` \n"
    response += f"**  •• **`Admin Rights: {admin_in_groups - creator_in_groups}` \n"
    response += f"**Admin in Channels:** {admin_in_broadcast_channels} \n"
    response += f"**  •• **`Creator: {creator_in_channels}` \n"
    response += f"**  •• **`Admin Rights: {admin_in_broadcast_channels - creator_in_channels}` \n"
    response += f"**Unread:** {unread} \n"
    response += f"**Unread Mentions:** {unread_mentions} \n"
    response += f"**Blocked Users:** {ct}\n"
    response += f"**Total Stickers Pack Installed :** `{sp_count}`\n\n"
    response += f"**__It Took:__** {stop_time:.02f}s \n"
    await ok.edit(response)
Ejemplo n.º 7
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()