async def _(event): if event.fwd_from: return event.pattern_match.group(1) if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY): os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY) if event.reply_to_msg_id: reply_message = await event.get_reply_message() # https://gist.github.com/udf/e4e3dbb2e831c8b580d8fddd312714f7 if not reply_message.sticker: return sticker = reply_message.sticker sticker_attrib = find_instance(sticker.attributes, DocumentAttributeSticker) if not sticker_attrib.stickerset: await event.reply("This sticker is not part of a pack") return is_a_s = is_it_animated_sticker(reply_message) file_ext_ns_ion = "webp" file_caption = "https://t.me/RoseSupport/33801" if is_a_s: file_ext_ns_ion = "tgs" file_caption = "Forward the ZIP file to @AnimatedStickersRoBot to get lottIE JSON containing the vector information." sticker_set = await borg(GetStickerSetRequest(sticker_attrib.stickerset)) pack_file = os.path.join( Config.TMP_DOWNLOAD_DIRECTORY, sticker_set.set.short_name, "pack.txt" ) if os.path.isfile(pack_file): os.remove(pack_file) # Sticker emojis are retrieved as a mapping of # <emoji>: <list of document ids that have this emoji> # So we need to build a mapping of <document id>: <list of emoji> # Thanks, Durov 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 borg.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]}}},") pending_tasks = [ asyncio.ensure_future( download( document, emojis, Config.TMP_DOWNLOAD_DIRECTORY + sticker_set.set.short_name, f"{i:03d}.{file_ext_ns_ion}", ) ) for i, document in enumerate(sticker_set.documents) ] await moods.edit( f"Downloading {sticker_set.set.count} sticker(s) to .{Config.TMP_DOWNLOAD_DIRECTORY}{sticker_set.set.short_name}..." ) num_tasks = len(pending_tasks) while 1: done, pending_tasks = await asyncio.wait( pending_tasks, timeout=2.5, return_when=asyncio.FIRST_COMPLETED ) try: await moods.edit( f"Downloaded {num_tasks - len(pending_tasks)}/{sticker_set.set.count}" ) except MessageNotModifiedError: pass if not pending_tasks: break await moods.edit("Downloading to my local completed") # https://gist.github.com/udf/e4e3dbb2e831c8b580d8fddd312714f7 directory_name = Config.TMP_DOWNLOAD_DIRECTORY + sticker_set.set.short_name zipf = zipfile.ZipFile(directory_name + ".zip", "w", zipfile.ZIP_DEFLATED) zipdir(directory_name, zipf) zipf.close() await borg.send_file( event.chat_id, directory_name + ".zip", caption=file_caption, force_document=True, allow_cache=False, reply_to=event.message.id, progress_callback=progress, ) try: os.remove(directory_name + ".zip") os.remove(directory_name) except: pass await moods.edit("task Completed") await asyncio.sleep(3) await event.delete() else: await moods.edit("TODO: Not Implemented")
async def _(event): try: approved_userss = approved_users.find({}) for ch in approved_userss: iid = ch["id"] userss = ch["user"] if event.is_group: if await is_register_admin(event.input_chat, event.message.sender_id): pass elif event.chat_id == iid and event.sender_id == userss: pass else: return 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): pass else: 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 not "I have deleted" 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)
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 Exception: 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 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 enumerate(blablapacks): result += f" • [pack {blablapacknames[i]}](t.me/addstickers/{blablapacks[i]})" await catevent.edit(result)
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])
async def kang(event): """ <b>param:</b> <code>emoji</code> <b>return:</b> <i>Sticker Pack link including the kanged sticker</i> """ if not event.is_reply: await event.edit("There's no image given for me to kang!") return rep_msg = await event.get_reply_message() file = rep_msg.photo or rep_msg.document if has_image(file): st_emoji = event.args.emoji or "🤔" if st_emoji not in (list(emoji.EMOJI_UNICODE.values())): await event.edit("Not a valid emoji!") return user = await event.get_sender() packname = user.username or user.first_name + "'s sticker pack!" packshort = "tg_companion_" + str(user.id) await event.edit("Processing sticker! Please wait...") async with event.client.conversation('Stickers') as conv: until_time = (datetime.datetime.now() + datetime.timedelta(minutes=1)).timestamp() await event.client( UpdateNotifySettingsRequest(peer="Stickers", settings=InputPeerNotifySettings( show_previews=False, mute_until=until_time))) try: await conv.send_message("/cancel") except YouBlockedUserError: await event.reply( "You blocked the sticker bot. Please unblock it and try again" ) return file = await event.client.download_file(file) with BytesIO(file) as mem_file, BytesIO() as sticker: resize_image(mem_file, (512, 512), sticker) sticker.seek(0) uploaded_sticker = await event.client.upload_file( sticker, file_name="sticker.png") try: await event.client( GetStickerSetRequest(InputStickerSetShortName(packname))) new_pack = False except StickersetInvalidError: new_pack = True if new_pack is False: await conv.send_message("/newpack") response = await conv.get_response() if not response.text.startswith("Yay!"): await event.edit(response.text) return await conv.send_message(packname) response = await conv.get_response() if not response.text.startswith("Alright!"): await event.edit(response.text) return await conv.send_file(InputMediaUploadedDocument( file=uploaded_sticker, mime_type='image/png', attributes=[DocumentAttributeFilename("sticker.png")]), force_document=True) await conv.send_message(st_emoji) await conv.send_message("/publish") await conv.send_message("/skip") await conv.send_message(packshort) response = conv.get_response() else: await conv.send_message("/addsticker") await conv.send_message(packshort) await conv.send_file(InputMediaUploadedDocument( file=uploaded_sticker, mime_type='image/png', attributes=[DocumentAttributeFilename("sticker.png")]), force_document=True) await conv.send_message(st_emoji) await conv.send_message("/done") await event.edit( "Sticker added! Your pack can be found [here](https://t.me/addstickers/{})" .format(packshort)) else: await event.edit("Not a valid media entity!")
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)
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)
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()