async def convert_sticker_to_gif(sticker): gif_id = sticker_to_gif.get(str(sticker.id), None) if gif_id: access_hash = access_hashes[str(gif_id)] return types.InputDocument(gif_id, access_hash, b'') file = BytesIO() await borg.download_media(sticker, file=file) file.seek(0) # remove alpha im = Image.open(file) alpha = im.convert('RGBA').getchannel('A') size = max(im.width, im.height) new_im = Image.new('RGBA', (size, size), (40, 40, 40, 255)) xy = (round((size - im.width) / 2), round((size - im.height) / 2)) new_im.paste(im, box=xy, mask=alpha) file = BytesIO() new_im.save(file, format='gif') file.seek(0) # upload file file = await event.upload_file(file, part_size_kb=512) file = types.InputMediaUploadedDocument(file, 'video/mp4', []) media = await event(UploadMediaRequest('me', file)) media = utils.get_input_document(media) # save (that's right, this is relational json) sticker_to_gif[str(sticker.id)] = media.id gif_to_sticker[str(media.id)] = sticker.id access_hashes[str(sticker.id)] = sticker.access_hash access_hashes[str(media.id)] = media.access_hash storage.sticker_to_gif = sticker_to_gif storage.access_hashes = access_hashes return media
async def pic_gifcmd(event): # sourcery no-metrics "To convert replied image or sticker to spining round video." args = event.pattern_match.group(1) reply = await event.get_reply_message() if not reply: return await edit_delete(event, "`Reply to supported Media...`") media_type(reply) catevent = await edit_or_reply(event, "__Making round spin video wait a sec.....__") output = await _cattools.media_to_pic(event, reply, noedits=True) if output[1] is None: return await edit_delete( output[0], "__Unable to extract image from the replied message.__" ) meme_file = convert_toimage(output[1]) image = Image.open(meme_file) w, h = image.size outframes = [] try: outframes = await spin_frames(image, w, h, outframes) except Exception as e: return await edit_delete(output[0], f"**Error**\n__{str(e)}__") output = io.BytesIO() output.name = "Output.gif" outframes[0].save(output, save_all=True, append_images=outframes[1:], duration=1) output.seek(0) with open("Output.gif", "wb") as outfile: outfile.write(output.getbuffer()) final = os.path.join(Config.TEMP_DIR, "output.gif") output = await vid_to_gif("Output.gif", final) if output is None: return await edit_delete(catevent, "__Unable to make spin gif.__") media_info = MediaInfo.parse(final) aspect_ratio = 1 for track in media_info.tracks: if track.track_type == "Video": aspect_ratio = track.display_aspect_ratio height = track.height width = track.width PATH = os.path.join(Config.TEMP_DIR, "round.gif") if aspect_ratio != 1: crop_by = width if (height > width) else height await _catutils.runcmd( f'ffmpeg -i {final} -vf "crop={crop_by}:{crop_by}" {PATH}' ) else: copyfile(final, PATH) time.time() ul = io.open(PATH, "rb") uploaded = await event.client.fast_upload_file( file=ul, ) ul.close() media = types.InputMediaUploadedDocument( file=uploaded, mime_type="video/mp4", attributes=[ types.DocumentAttributeVideo( duration=0, w=1, h=1, round_message=True, supports_streaming=True, ) ], force_file=False, thumb=await event.client.upload_file(meme_file), ) sandy = await event.client.send_file( event.chat_id, media, reply_to=reply, video_note=True, supports_streaming=True, ) if not args: await _catutils.unsavegif(event, sandy) await catevent.delete() for i in [final, "Output.gif", meme_file, PATH, final]: if os.path.exists(i): os.remove(i)
async def video_catfile(event): # sourcery no-metrics "To make circular video note." reply = await event.get_reply_message() args = event.pattern_match.group(1) catid = await reply_id(event) if not reply or not reply.media: return await edit_delete(event, "`Reply to supported media`") mediatype = media_type(reply) if mediatype == "Round Video": return await edit_delete( event, "__Do you think I am a dumb person๐? The replied media is already in round format,recheck._", ) if mediatype not in ["Photo", "Audio", "Voice", "Gif", "Sticker", "Video"]: return await edit_delete(event, "```Supported Media not found...```") flag = True catevent = await edit_or_reply(event, "`Converting to round format..........`") catfile = await reply.download_media(file="./temp/") if mediatype in ["Gif", "Video", "Sticker"]: if not catfile.endswith((".webp")): if catfile.endswith((".tgs")): hmm = await make_gif(catevent, catfile) os.rename(hmm, "./temp/circle.mp4") catfile = "./temp/circle.mp4" media_info = MediaInfo.parse(catfile) aspect_ratio = 1 for track in media_info.tracks: if track.track_type == "Video": aspect_ratio = track.display_aspect_ratio height = track.height width = track.width if aspect_ratio != 1: crop_by = width if (height > width) else height await _catutils.runcmd( f'ffmpeg -i {catfile} -vf "crop={crop_by}:{crop_by}" {PATH}' ) else: copyfile(catfile, PATH) if str(catfile) != str(PATH): os.remove(catfile) try: catthumb = await reply.download_media(thumb=-1) except Exception as e: LOGS.error(f"circle - {str(e)}") elif mediatype in ["Voice", "Audio"]: catthumb = None try: catthumb = await reply.download_media(thumb=-1) except Exception: catthumb = os.path.join("./temp", "thumb.jpg") await thumb_from_audio(catfile, catthumb) if catthumb is not None and not os.path.exists(catthumb): catthumb = os.path.join("./temp", "thumb.jpg") copyfile(thumb_loc, catthumb) if ( catthumb is not None and not os.path.exists(catthumb) and os.path.exists(thumb_loc) ): flag = False catthumb = os.path.join("./temp", "thumb.jpg") copyfile(thumb_loc, catthumb) if catthumb is not None and os.path.exists(catthumb): await _catutils.runcmd( f"""ffmpeg -loop 1 -i {catthumb} -i {catfile} -c:v libx264 -tune stillimage -c:a aac -b:a 192k -vf \"scale=\'iw-mod (iw,2)\':\'ih-mod(ih,2)\',format=yuv420p\" -shortest -movflags +faststart {PATH}""" ) os.remove(catfile) else: os.remove(catfile) return await edit_delete( catevent, "`No thumb found to make it video note`", 5 ) if ( mediatype in [ "Voice", "Audio", "Gif", "Video", "Sticker", ] and not catfile.endswith((".webp")) ): if os.path.exists(PATH): c_time = time.time() attributes, mime_type = get_attributes(PATH) ul = io.open(PATH, "rb") uploaded = await event.client.fast_upload_file( file=ul, progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress(d, t, catevent, c_time, "Uploading....") ), ) ul.close() media = types.InputMediaUploadedDocument( file=uploaded, mime_type="video/mp4", attributes=[ types.DocumentAttributeVideo( duration=0, w=1, h=1, round_message=True, supports_streaming=True, ) ], force_file=False, thumb=await event.client.upload_file(catthumb) if catthumb else None, ) sandy = await event.client.send_file( event.chat_id, media, reply_to=catid, video_note=True, supports_streaming=True, ) if not args: await _catutils.unsavegif(event, sandy) os.remove(PATH) if flag: os.remove(catthumb) await catevent.delete() return data = reply.photo or reply.media.document img = io.BytesIO() await event.client.download_file(data, img) im = Image.open(img) w, h = im.size img = Image.new("RGBA", (w, h), (0, 0, 0, 0)) img.paste(im, (0, 0)) m = min(w, h) img = img.crop(((w - m) // 2, (h - m) // 2, (w + m) // 2, (h + m) // 2)) w, h = img.size mask = Image.new("L", (w, h), 0) draw = ImageDraw.Draw(mask) draw.ellipse((10, 10, w - 10, h - 10), fill=255) mask = mask.filter(ImageFilter.GaussianBlur(2)) img = ImageOps.fit(img, (w, h)) img.putalpha(mask) im = io.BytesIO() im.name = "cat.webp" img.save(im) im.seek(0) await event.client.send_file(event.chat_id, im, reply_to=catid) await catevent.delete()
async def ytdl_download_callback(c_q: CallbackQuery): # sourcery no-metrics yt_code = (str(c_q.pattern_match.group(1).decode("UTF-8")) if c_q.pattern_match.group(1) is not None else None) choice_id = (str(c_q.pattern_match.group(2).decode("UTF-8")) if c_q.pattern_match.group(2) is not None else None) downtype = (str(c_q.pattern_match.group(3).decode("UTF-8")) if c_q.pattern_match.group(3) is not None else None) if str(choice_id).isdigit(): choice_id = int(choice_id) if choice_id == 0: await c_q.answer("๐ Processing...", alert=False) await c_q.edit(buttons=(await download_button(yt_code))) return startTime = time() choice_str, disp_str = get_choice_by_id(choice_id, downtype) media_type = "Video" if downtype == "v" else "Audio" callback_continue = f"Downloading {media_type} Please Wait..." callback_continue += f"\n\nFormat Code : {disp_str}" await c_q.answer(callback_continue, alert=True) upload_msg = await c_q.client.send_message(BOTLOG_CHATID, "Uploading...") yt_url = BASE_YT_URL + yt_code await c_q.edit( f"<b>โฌ๏ธ Downloading {media_type} ....</b>\n\n๐ <a href={yt_url}> <b>Link</b></a>\n๐ <b>Format Code</b> : {disp_str}", parse_mode="html", ) if downtype == "v": retcode = await _tubeDl(url=yt_url, starttime=startTime, uid=choice_str) else: retcode = await _mp3Dl(url=yt_url, starttime=startTime, uid=choice_str) if retcode != 0: return await upload_msg.edit(str(retcode)) _fpath = "" thumb_pic = None for _path in glob.glob(os.path.join(Config.TEMP_DIR, str(startTime), "*")): if _path.lower().endswith((".jpg", ".png", ".webp")): thumb_pic = _path else: _fpath = _path if not _fpath: await edit_delete(upload_msg, "nothing found !") return if not thumb_pic and downtype == "v": thumb_pic = str(await pool.run_in_thread(download) (await get_ytthumb(yt_code))) attributes, mime_type = get_attributes(str(_fpath)) ul = io.open(Path(_fpath), "rb") uploaded = await c_q.client.fast_upload_file( file=ul, progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress( d, t, c_q, startTime, "trying to upload", file_name=os.path.basename(Path(_fpath)), )), ) ul.close() media = types.InputMediaUploadedDocument( file=uploaded, mime_type=mime_type, attributes=attributes, force_file=False, thumb=await c_q.client.upload_file(thumb_pic) if thumb_pic else None, ) uploaded_media = await c_q.client.send_file( BOTLOG_CHATID, file=media, caption= f"<b>File Name : </b><code>{os.path.basename(Path(_fpath))}</code>", parse_mode="html", ) await upload_msg.delete() await c_q.edit( text=f"๐น <a href={yt_url}><b>{os.path.basename(Path(_fpath))}</b></a>", file=uploaded_media.media, parse_mode="html", )
def upload(self, file, file_name=None): entity = types.InputPeerSelf() # begin _file_to_media media = None file_handle = None # begin _upload_file file_id = helpers.generate_random_long() if not file_name and getattr(file, 'name', None): file_name = file.name if file_name is None: file_name = str(file_id) file = file.read() file_size = len(file) part_size = int(utils.get_appropriated_part_size(file_size) * 1024) is_large = file_size > 10 * 1024 * 1024 hash_md5 = hashlib.md5() if not is_large: hash_md5.update(file) part_count = (file_size + part_size - 1) // part_size with BytesIO(file) as stream: for part_index in range(part_count): part = stream.read(part_size) if is_large: request = functions.upload.SaveBigFilePartRequest( file_id, part_index, part_count, part) else: request = functions.upload.SaveFilePartRequest( file_id, part_index, part) result = self.client(request) yield float(round(100.0 * (part_index / part_count), 2)) if not result: raise RuntimeError( 'Failed to upload file part {}.'.format(part_index)) if is_large: file_handle = types.InputFileBig(file_id, part_count, file_name) else: file_handle = custom.InputSizedFile(file_id, part_count, file_name, md5=hash_md5, size=file_size) # end _upload_file attributes, mime_type = utils.get_attributes(file, force_document=True, voice_note=False, video_note=False) attributes[0].file_name = file_name media = types.InputMediaUploadedDocument(file=file_handle, mime_type=mime_type, attributes=attributes) # end _file_to_media request = functions.messages.SendMediaRequest(entity, media, reply_to_msg_id=None, message='', entities=[], reply_markup=None, silent=None) t = self.client(request) if type(t) != types.Updates: t = self.client.loop.run_until_complete(t) msg = self.client._get_response_message(request, t, entity) yield msg