async def upload_sticker(sticker: Sticker): sticker.file.seek(0) file = await client.upload_file(sticker.file, part_size_kb=512) file = types.InputMediaUploadedDocument(file, 'image/png', []) media = await client(UploadMediaRequest('me', file)) return types.InputStickerSetItem(document=utils.get_input_document(media), emoji=sticker.emoji)
async def upload(event: NewMessage.Event) -> None: """ Upload media to Telegram. **{prefix}upload (path)** or **{prefix}ul (path)** """ match = event.matches[0].group(3) target_files = [] if not match: await event.answer("`Uploaded the void.`") return match = match.strip().replace("\\", "/") if match else "" fmatch = pathlib.Path(match) dmatch = pathlib.Path(downloads / match) if "*" not in match: if fmatch.exists(): target_files.append(fmatch) elif dmatch.exists(): target_files.append(dmatch) if not target_files: for f in downloads.glob("*.*"): if f.match(match) and f.is_file(): target_files.append(f) # Un-comment this for recursive file fetching from the bot's root dir """for f in pathlib.Path('.').glob('**/*.*'): if f in target_files: continue if not f.match('*/__pycache__/*') and f.match(match) and f.is_file(): target_files.append(f)""" if not target_files: await event.answer("`Couldn't find what you were looking for.`") return files = "\n".join([f"`{await _get_file_name(f)}`" for f in target_files]) if len(target_files) > 1: await event.answer(f"**Found multiple files for {match}:**\n{files}") return for f in target_files: f = f.absolute() prog = ProgressCallback(event, filen=await _get_file_name(f, False)) attributes, mime_type = get_attributes(str(f)) ul = io.open(f, "rb") uploaded = await client.fast_upload_file( file=ul, progress_callback=prog.up_progress) ul.close() media = types.InputMediaUploadedDocument(file=uploaded, mime_type=mime_type, attributes=attributes, thumb=None) await client.send_file(event.chat_id, file=media, force_document=True, reply_to=event) await event.answer(f"`Successfully uploaded {files}.`")
async def download_audio(event): """To download audio from YouTube and many other sites.""" url = event.pattern_match.group(1) rmsg = await event.get_reply_message() if not url and rmsg: myString = rmsg.text url = re.search("(?P<url>https?://[^\s]+)", myString).group("url") if not url: return await edit_or_reply(event, "`What I am Supposed to find? Give link`") catevent = await edit_or_reply(event, "`Preparing to download...`") reply_to_id = await reply_id(event) ytdl_data = await ytdl_down(catevent, audio_opts, url) if ytdl_data is None: return await catevent.edit(f"`Preparing to upload song:`\ \n**{ytdl_data['title']}**\ \nby *{ytdl_data['uploader']}*") f = pathlib.Path(f"{ytdl_data['title']}.mp3".replace("|", "_")) catthumb = pathlib.Path(f"{ytdl_data['title']}.mp3.jpg".replace("|", "_")) if not os.path.exists(catthumb): catthumb = pathlib.Path(f"{ytdl_data['title']}.mp3.webp".replace( "|", "_")) if not os.path.exists(catthumb): catthumb = None c_time = time.time() ul = io.open(f, "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, "upload", file_name=f)), ) ul.close() attributes, mime_type = await fix_attributes(f, ytdl_data, supports_streaming=True) media = types.InputMediaUploadedDocument( file=uploaded, mime_type=mime_type, attributes=attributes, thumb=await event.client.upload_file(catthumb) if catthumb else None, ) await event.client.send_file( event.chat_id, file=media, reply_to=reply_to_id, caption=ytdl_data["title"], supports_streaming=True, force_document=False, ) os.remove(f) if catthumb: os.remove(catthumb) await catevent.delete()
async def download_video(event): """Para descargar videos de YouTube y muchos otros sitios.""" url = event.pattern_match.group(1) rmsg = await event.get_reply_message() if not url and rmsg: myString = rmsg.text url = re.search("(?P<url>https?://[^\s]+)", myString).group("url") if not url: return await edit_or_reply( event, "¿Qué se supone que debo encontrar? Coloca un enlace") catevent = await edit_or_reply(event, "`Preparando para descargar`") reply_to_id = await reply_id(event) ytdl_data = await ytdl_down(catevent, video_opts, url) if ytdl_down is None: return f = pathlib.Path(f"{ytdl_data['title']}.mp4".replace("|", "_")) catthumb = pathlib.Path(f"{ytdl_data['title']}.jpg".replace("|", "_")) if not os.path.exists(catthumb): catthumb = pathlib.Path(f"{ytdl_data['title']}.webp".replace("|", "_")) if not os.path.exists(catthumb): catthumb = None await catevent.edit(f"`Preparando todo para subir el video:`\ \n**{ytdl_data['title']}**\ \nSubido por *{ytdl_data['uploader']}*") ul = io.open(f, "rb") c_time = time() attributes, mime_type = await fix_attributes(f, ytdl_data, supports_streaming=True) 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, "upload", file_name=f)), ) ul.close() media = types.InputMediaUploadedDocument( file=uploaded, mime_type=mime_type, attributes=attributes, thumb=await event.client.upload_file(catthumb) if catthumb else None, ) await event.client.send_file( event.chat_id, file=media, reply_to=reply_to_id, caption=ytdl_data["title"], ) os.remove(f) if catthumb: os.remove(catthumb) await event.delete()
async def upload(event: NewMessage.Event) -> None: """Upload media to Telegram.""" match = event.matches[0].group(3) target_files = [] if not match: await event.answer("__Uploaded the void?__") return match = match.strip().replace('\\', '/') if match else '' fmatch = pathlib.Path(match) if '*' in match and '/' not in match: for f in downloads.glob('*.*'): if f.match(match): target_files.append(f) elif '*' not in match and '/' in match: if fmatch.exists(): target_files.append(fmatch) elif (downloads / match).exists(): target_files.append(downloads / match) for f in pathlib.Path('.').glob('**/*.*'): if f in target_files: continue if not f.match('*/__pycache__/*') and f.match(match): target_files.append(f) if not target_files: await event.answer("__Couldn't find what you were looking for.__") return files = ', '.join([f.stem for f in target_files]) for f in target_files: f = f.resolve() prog = ProgressCallback(event, filen=f.stem) attributes, mime_type = get_attributes(str(f)) ul = io.open(f, 'rb') uploaded = await client.fast_upload_file( file=ul, progress_callback=prog.up_progress) ul.close() media = types.InputMediaUploadedDocument(file=uploaded, mime_type=mime_type, attributes=attributes, thumb=None) await client.send_file(event.chat_id, file=media, caption=str(f.parent / f.name), force_document=True, reply_to=event) await event.answer(f"__Successfully uploaded {files}.__")
async def _(event): if event.fwd_from: return mone = await event.edit("Processing ...") input_str = event.pattern_match.group(1) thumb = thumb_image_path if os.path.exists(thumb_image_path) else None if os.path.exists(input_str): start = datetime.now() c_time = time.time() with open(input_str, "rb") as out: res = await upload_file( event.client, out, progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task(progress(d, t, mone, c_time, "uploading"))) attributes, mime_type = utils.get_attributes(input_str, ) media = types.InputMediaUploadedDocument( file=res, mime_type=mime_type, attributes=attributes, thumb=thumb, ) await event.reply(file=media) # await bot.send_file( # event.chat_id, # input_str, # force_document=True, # supports_streaming=False, # allow_cache=False, # reply_to=event.message.id, # thumb=thumb, # progress_callback=lambda d, t: asyncio.get_event_loop().create_task( # progress(d, t, mone, c_time, "trying to upload") # ) # ) end = datetime.now() os.remove(input_str) ms = (end - start).seconds j = await event.reply(f"Uploaded in {ms} seconds.") await asyncio.sleep(2) await j.delete() else: k = await event.reply("404: File Not Found") await asyncio.sleep(2) await k.delete()
async def upload(path, event, udir_event, catflag=None): # sourcery no-metrics catflag = catflag or False reply_to_id = await reply_id(event) if os.path.isdir(path): await event.client.send_message( event.chat_id, f"**Folder : **`{str(path)}`", ) Files = os.listdir(path) Files = sortthings(Files, path) for file in Files: catpath = os.path.join(path, file) await upload(Path(catpath), event, udir_event) elif os.path.isfile(path): fname = os.path.basename(path) c_time = time.time() thumb = None if os.path.exists(thumb_image_path): thumb = thumb_image_path f = path.absolute() attributes, mime_type = get_attributes(str(f)) ul = io.open(f, "rb") uploaded = await event.client.fast_upload_file( file=ul, progress_callback=lambda d, t: asyncio.get_event_loop(). create_task( progress( d, t, event, c_time, "trying to upload", file_name=fname)), ) ul.close() media = types.InputMediaUploadedDocument( file=uploaded, mime_type=mime_type, attributes=attributes, force_file=catflag, thumb=await event.client.upload_file(thumb) if thumb else None, ) await event.client.send_file( event.chat_id, file=media, caption=f"**File Name : **`{fname}`", reply_to=reply_to_id, ) UPLOAD_.uploaded += 1
async def yt_dl(event): """ Download videos from YouTube with their url in multiple formats. **{prefix}ytdl link1 link2 link3 [kwargs]** Stream and progress are set to True, while update is at 10% by default. **Arguments:** `format` (The format to convert/download the video in), `delete` (Whether to delete the local files or not), `upload` (Whether to upload the downloaded files or not), `update` (The percentage to update the progress at), `stream` (Whether to upload the files as streamable or not), `progress` (Whether to update the progress by edits or not) """ match = event.matches[0].group(1) force_document = True if not match: await event.answer( "`.ytdl <url>` or `.ytdl <url1> .. <urln> format=<fmt>`") return args, kwargs = await client.parse_arguments(match) fmt = kwargs.get('format', kwargs.get('fmt', False)) auto_delete = kwargs.get('delete', False) upload = kwargs.get('upload', True) round_message = kwargs.get('round_message', kwargs.get('round', False)) update = kwargs.get('update', 10) supports_streaming = kwargs.get('supports_streaming', kwargs.get('stream', True)) progress = kwargs.get('progress', True) if not upload and auto_delete: await event.answer( "`The void doesn't make sense! Either don't upload or delete.`") return ffmpeg = await is_ffmpeg_there() params = copy.deepcopy(ydl_opts) warnings = [] if fmt: fmt = fmt.strip().lower() if fmt == 'listformats': fmts = [] for url in args: info = await extract_info( client.loop, concurrent.futures.ThreadPoolExecutor(), params, url) if isinstance(info, dict): fmts.append(await list_formats(info)) elif isinstance(info, str): warnings.append(info) else: warnings.append( f'```{await client.get_traceback(info)}```') if fmts: text = "**Formats:**\n" text += "\n\n".join(fmts) await event.answer(text) if warnings: text = "**Warnings:**\n" text += "\n\n".join(f"```{w}```" for w in warnings) reply = True if fmts else False await event.answer(text, reply=reply) return elif fmt in audioFormats and ffmpeg: params.update(format='bestaudio') params['postprocessors'].append({ 'key': 'FFmpegExtractAudio', 'preferredcodec': fmt, 'preferredquality': '320', }) elif fmt in videoFormats and ffmpeg: params['postprocessors'].append({ 'key': 'FFmpegVideoConvertor', 'preferedformat': fmt }) else: params.update(format=fmt) if ffmpeg: params.update(key='FFmpegMetadata') if fmt in ['mp3', 'mp4', 'm4a']: params.update(writethumbnail=True) params['postprocessors'].append({'key': 'EmbedThumbnail'}) if progress: event.media = None progress = ProgressHook(event, update) params['progress_hooks'].append(progress.hook) progress_cb = ProgressCallback(event, update=update) for url in args: await event.answer(f"`Processing {url}...`") output = await extract_info( loop=client.loop, ydl_opts=params, url=url, download=True, executor=concurrent.futures.ThreadPoolExecutor()) if isinstance(output, str): result = warning + output if not ffmpeg else output warnings.append(result) elif isinstance(output, BaseException): warnings.append(f'```{await client.get_traceback(output)}```') elif output is None: await event.answer('`Oh oh, sum ting went wong`') return else: if upload: path, thumb, info = output title = info.get('title', info.get('id', 'Unknown title')) url = info.get('webpage_url', None) href = f"[{title}]({url})" text = success.format(href) result = warning + text if not ffmpeg else text dl = io.open(path, 'rb') if progress: progress_cb.filen = title uploaded = await client.fast_upload_file( dl, progress_cb.up_progress if progress else None) dl.close() attributes, mime_type = await fix_attributes( path, info, round_message, supports_streaming) media = types.InputMediaUploadedDocument( file=uploaded, mime_type=mime_type, attributes=attributes, thumb=await client.upload_file(thumb) if thumb else None) if supports_streaming and path.suffix == '.mp4': force_document = False if round_message: force_document = False await client.send_file(event.chat_id, media, caption=href, force_document=force_document) if thumb: os.remove(thumb) if auto_delete: os.remove(path) else: if thumb: os.remove(thumb) if warnings: text = "**Warnings:**\n" text += ",\n\n".join(warnings) await event.answer(text) else: await event.delete()
async def yt_dl(event): """ Download videos from YouTube with their url in multiple formats. **{prefix}ytdl link1 link2 link3 [kwargs]** Stream and progress are set to True, while update is at 10% by default. **Arguments:** `format` (The format to convert/download the video in), `delete` (Whether to delete the local files or not), `upload` (Whether to upload the downloaded files or not), `update` (The percentage to update the progress at), `stream` (Whether to upload the files as streamable or not), `progress` (Whether to update the progress by edits or not) """ match = event.matches[0].group(1) force_document = True if not match: await event.answer( "`.ytdl <url>` or `.ytdl <url1> .. <urln> format=<fmt>`") return args, kwargs = await client.parse_arguments(match) fmt = kwargs.get("format", kwargs.get("fmt", False)) auto_delete = kwargs.get("delete", False) upload = kwargs.get("upload", True) progress = kwargs.get("progress", True) round_message = kwargs.get("round_message", kwargs.get("round", False)) update = kwargs.get("update", 10) supports_streaming = kwargs.get("supports_streaming", kwargs.get("stream", True)) if not upload and auto_delete: await event.answer("`The void doesn't make sense!\ \nEither don't upload or delete.`") return ffmpeg = await is_ffmpeg_there() params = copy.deepcopy(ydl_opts) params["postprocessor_args"] = ( ["-preset", "ultrafast", "-tune", "fastdecode"] if ffmpeg else []) warnings = [] if fmt: fmt = fmt.strip().lower() if fmt in audioFormats and ffmpeg: params.update(format="bestaudio") params["postprocessors"].append({ "key": "FFmpegExtractAudio", "preferredcodec": fmt, "preferredquality": "320", }) if fmt in ["mp3", "m4a"]: params["postprocessors"].append({"key": "EmbedThumbnail"}) if fmt in ["mp3"]: params["postprocessor_args"] += [ "-write_id3v1", "1", "-id3v2_version", "3", ] elif fmt in videoFormats and ffmpeg: params["postprocessors"].append({ "key": "FFmpegVideoConvertor", "preferedformat": fmt }) if fmt in ["mp4"]: params["postprocessors"].append({"key": "EmbedThumbnail"}) else: params.update(format=fmt) if ffmpeg: params.update(key="FFmpegMetadata") else: fmts = [] for url in args: info = await extract_info(client.loop, concurrent.futures.ThreadPoolExecutor(), params, url) if isinstance(info, dict): fmts.append(await list_formats(info)) elif isinstance(info, str): warnings.append(info) else: warnings.append(f"```{await client.get_traceback(info)}```") if fmts: text = "**Formats:**\n" text += ",\n\n".join(f"```{f}```" for f in fmts) await event.answer(text) if warnings: text = "**Warnings:**\n" text += ",\n\n".join(f"```{w}```" for w in warnings) reply = bool(fmts) await event.answer(text, reply=reply) return if progress: event.media = None progress = ProgressHook(event, update) params["progress_hooks"].append(progress.hook) progress_cb = ProgressCallback(event, update=update) for url in args: await event.answer(f"`Processing {url}...`") output = await extract_info( loop=client.loop, ydl_opts=params, url=url, download=True, executor=concurrent.futures.ThreadPoolExecutor(), ) if isinstance(output, str): result = warning + output if not ffmpeg else output warnings.append(result) elif isinstance(output, BaseException): warnings.append(f"```{await client.get_traceback(output)}```") elif output is None: await event.answer("`Oh oh, some thing went wrong!`") return else: path, thumb, info = output if upload: title = info.get("title", info.get("id", "Unknown title")) url = info.get("webpage_url", None) href = f"[{title}]({url})" text = success.format(href) result = warning + text if not ffmpeg else text dl = io.open(path, "rb") if progress: progress_cb.filen = title uploaded = await client.fast_upload_file( dl, progress_cb.up_progress if progress else None) dl.close() attributes, mime_type = await fix_attributes( path, info, round_message, supports_streaming) media = types.InputMediaUploadedDocument( file=uploaded, mime_type=mime_type, attributes=attributes, thumb=await client.upload_file(thumb) if thumb else None, ) if supports_streaming and path.suffix == ".mp4": force_document = False if round_message: force_document = False await client.send_file( event.chat_id, media, caption=href, reply_to=event.reply_to_msg_id, force_document=force_document, ) if thumb: os.remove(thumb) if auto_delete: os.remove(path) else: if thumb: os.remove(thumb) if warnings: text = "**Warnings:**\n" text += ",\n\n".join(warnings) await event.answer(text) else: await event.delete()
async def download_audio(event): """Para descargar audio de YouTube y muchos otros sitios.""" url = event.pattern_match.group(1) rmsg = await event.get_reply_message() if not url and rmsg: myString = rmsg.text url = re.search("(?P<url>https?://[^\s]+)", myString).group("url") if not url: return await edit_or_reply( event, "`¿Qué se supone que debo hacer? Coloca un enlace`") catevent = await edit_or_reply(event, "`Preparando la descarga...`") reply_to_id = await reply_id(event) try: vid_data = YoutubeDL({ "no-playlist": True }).extract_info(url, download=False) except ExtractorError: vid_data = {"Título": url, "Subido por": "Skueletor", "Formatos": []} startTime = time() retcode = await _mp3Dl(url=url, starttime=startTime, uid="320") if retcode != 0: return await event.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: return await edit_delete(catevent, "__Incapaz de subir el archivo__") await catevent.edit(f"`Preparando todo para subir video:`\ \n**{vid_data['Título']}**\ \nSubido por *{vid_data['uploader']}*") attributes, mime_type = get_attributes(str(_fpath)) ul = io.open(pathlib.Path(_fpath), "rb") if thumb_pic is None: thumb_pic = str(await pool.run_in_thread(download) (await get_ytthumb(get_yt_video_id(url)))) uploaded = await event.client.fast_upload_file( file=ul, progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress( d, t, catevent, startTime, "Intentando subirlo", file_name=os.path.basename(pathlib.Path(_fpath)), )), ) ul.close() media = types.InputMediaUploadedDocument( file=uploaded, mime_type=mime_type, attributes=attributes, force_file=False, thumb=await event.client.upload_file(thumb_pic) if thumb_pic else None, ) await event.client.send_file( event.chat_id, file=media, caption= f"<b>Nombre del archivo : </b><code>{vid_data.get('title', os.path.basename(pathlib.Path(_fpath)))}</code>", reply_to=reply_to_id, parse_mode="html", ) for _path in [_fpath, thumb_pic]: os.remove(_path) await catevent.delete()
async def download_audio(event): """To download audio from YouTube and many other sites.""" url = event.pattern_match.group(1) rmsg = await event.get_reply_message() if not url and rmsg: myString = rmsg.text url = re.search("(?P<url>https?://[^\s]+)", myString).group("url") if not url: return await edit_or_reply(event, "`What I am Supposed to do? Give link`") catevent = await edit_or_reply(event, "`Preparing to download...`") reply_to_id = await reply_id(event) try: vid_data = YoutubeDL({ "no-playlist": True }).extract_info(url, download=False) except ExtractorError: vid_data = {"title": url, "uploader": "Catuserbot", "formats": []} startTime = time() retcode = await _mp3Dl(url=url, starttime=startTime, uid="320") if retcode != 0: return await event.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: return await edit_delete(catevent, "__Unable to upload file__") await catevent.edit(f"`Preparing to upload video:`\ \n**{vid_data['title']}**\ \nby *{vid_data['uploader']}*") attributes, mime_type = get_attributes(str(_fpath)) ul = io.open(pathlib.Path(_fpath), "rb") if thumb_pic is None: thumb_pic = str(await pool.run_in_thread(download) (await get_ytthumb(get_yt_video_id(url)))) uploaded = await event.client.fast_upload_file( file=ul, progress_callback=lambda d, t: asyncio.get_event_loop().create_task( progress( d, t, catevent, startTime, "trying to upload", file_name=os.path.basename(pathlib.Path(_fpath)), )), ) ul.close() media = types.InputMediaUploadedDocument( file=uploaded, mime_type=mime_type, attributes=attributes, force_file=False, thumb=await event.client.upload_file(thumb_pic) if thumb_pic else None, ) await event.client.send_file( event.chat_id, file=media, caption= f"<b>File Name : </b><code>{vid_data.get('title', os.path.basename(pathlib.Path(_fpath)))}</code>", reply_to=reply_to_id, parse_mode="html", ) for _path in [_fpath, thumb_pic]: os.remove(_path) await catevent.delete()
async def _(event): if event.fwd_from: return input_str = event.pattern_match.group(1) mone = await event.edit("Processing ...") if os.path.exists(input_str): start = datetime.now() # await event.edit("Processing ...") lst_of_files = sorted(get_lst_of_files(input_str, [])) logger.info(lst_of_files) u = 0 await event.edit("Found {} files. ".format(len(lst_of_files)) + "Uploading will start soon. " + "Please wait!") thumb = thumb_image_path if os.path.exists(thumb_image_path) else None for single_file in lst_of_files: if os.path.exists(single_file): # https://stackoverflow.com/a/678242/4723940 caption_rts = os.path.basename(single_file) force_document = True supports_streaming = False document_attributes = [] width = 0 height = 0 if os.path.exists(thumb_image_path): metadata = extractMetadata(createParser(thumb_image_path)) if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") if single_file.upper().endswith(Config.TL_VID_STREAM_TYPES): metadata = extractMetadata(createParser(single_file)) duration = 0 if metadata.has("duration"): duration = metadata.get('duration').seconds document_attributes = [ DocumentAttributeVideo(duration=duration, w=width, h=height, round_message=False, supports_streaming=True) ] supports_streaming = True force_document = False if single_file.upper().endswith(Config.TL_MUS_STREAM_TYPES): metadata = extractMetadata(createParser(single_file)) duration = metadata.get( 'duration').seconds if metadata.has("duration") else 0 title = metadata.get("title") if metadata.has( "title") else "" artist = metadata.get("artist") if metadata.has( "artist") else "" document_attributes = [ DocumentAttributeAudio(duration=duration, voice=False, title=title, performer=artist, waveform=None) ] supports_streaming = True force_document = False try: c_time = time.time() with open(single_file, "rb") as out: res = await upload_file( event.client, out, progress_callback=lambda d, t: asyncio. get_event_loop().create_task( progress(d, t, mone, c_time, "uploading"))) attributes, mime_type = utils.get_attributes( single_file, ) media = types.InputMediaUploadedDocument( file=res, mime_type=mime_type, attributes=document_attributes, thumb=thumb, force_file=force_document, supports_streaming=supports_streaming) await event.reply(file=media) # await bot.send_file( # event.chat_id, # single_file, # caption=caption_rts, # force_document=force_document, # supports_streaming=supports_streaming, # allow_cache=False, # reply_to=event.message.id, # thumb=thumb, # attributes=document_attributes, # # progress_callback=lambda d, t: asyncio.get_event_loop().create_task( # # progress(d, t, event, c_time, "trying to upload") # # ) # ) except Exception as e: await bot.send_message(event.chat_id, "{} caused `{}`".format( caption_rts, str(e)), reply_to=event.message.id) # some media were having some issues continue os.remove(single_file) u += 1 # await event.edit("Uploaded {} / {} files.".format(u, len(lst_of_files))) # @ControllerBot was having issues, # if both edited_updates and update events come simultaneously. await asyncio.sleep(5) end = datetime.now() ms = (end - start).seconds await event.edit("Uploaded {} files in {} seconds.".format(u, ms)) else: await event.edit("404: Directory Not Found")
async def _(event): if event.fwd_from: return mone = await event.edit("Processing ...") input_str = event.pattern_match.group(1) thumb = None file_name = input_str if os.path.exists(file_name): start = datetime.now() metadata = extractMetadata(createParser(file_name)) duration = 0 width = 0 height = 0 if metadata: if metadata.has("duration"): duration = metadata.get('duration').seconds if os.path.exists(thumb_image_path): metadata = extractMetadata(createParser(thumb_image_path)) if metadata.has("width"): width = metadata.get("width") if metadata.has("height"): height = metadata.get("height") if os.path.exists(thumb_image_path): thumb = thumb_image_path else: thumb = await take_screen_shot(file_name, Config.TMP_DOWNLOAD_DIRECTORY, duration // 2) # Telegram only works with MP4 files # this is good, since with MKV files sent as streamable Telegram responds, # Bad Request: VIDEO_CONTENT_TYPE_INVALID c_time = time.time() try: start = datetime.now() with open(file_name, "rb") as out: res = await upload_file( event.client, out, progress_callback=lambda d, t: asyncio.get_event_loop( ).create_task( progress(d, t, mone, c_time, "uploading as a stream"))) attributes, mime_type = utils.get_attributes(input_str, ) media = types.InputMediaUploadedDocument( file=res, mime_type=mime_type, attributes=[ DocumentAttributeVideo(duration=duration, w=width, h=height, round_message=False, supports_streaming=True) ], thumb=thumb, ) await event.reply(file=media) # await bot.send_file( # event.chat_id, # file_name, # thumb=thumb, # caption=input_str, # force_document=False, # allow_cache=False, # reply_to=event.message.id, # attributes=[ # DocumentAttributeVideo( # duration=duration, # w=width, # h=height, # round_message=False, # supports_streaming=True # ) # ], # progress_callback=lambda d, t: asyncio.get_event_loop().create_task( # progress(d, t, mone, c_time, "trying to upload") # ) # ) except Exception as e: await mone.edit(str(e)) else: end = datetime.now() os.remove(input_str) ms = (end - start).seconds await mone.edit(f"Uploaded in {ms} seconds.") else: await mone.edit("404: File Not Found")
async def yt_dl(event): """Download videos from YouTube with their url in multiple formats.""" url = event.matches[0].group(1) fmt = event.matches[0].group(2) if not url: await event.answer("`.ytdl <url>` or `.ytdl <url> <format>`") return ffmpeg = await is_ffmpeg_there() params = copy.deepcopy(ydl_opts) if fmt: fmt = fmt.strip() if fmt == 'listformats': info = await extract_info( client.loop, concurrent.futures.ThreadPoolExecutor(), params, url ) if isinstance(info, dict): fmts = await list_formats(info) await event.answer(fmts) else: await event.answer(info) return elif fmt in audioFormats and ffmpeg: params.update(format='bestaudio') params['postprocessors'].append( { 'key': 'FFmpegExtractAudio', 'preferredcodec': fmt, 'preferredquality': '320', } ) elif fmt in videoFormats and ffmpeg: params.update(format='bestvideo') params['postprocessors'].append( { 'key': 'FFmpegVideoConvertor', 'preferedformat': fmt } ) else: params.update(format=fmt) if ffmpeg: params.update(key='FFmpegMetadata') if fmt in ['mp3', 'mp4', 'm4a']: params.update(writethumbnail=True) params['postprocessors'].append({'key': 'EmbedThumbnail'}) progress = ProgressHook(event) await event.answer("`Processing...`") params['progress_hooks'].append(progress.hook) output = await extract_info( loop=client.loop, executor=concurrent.futures.ThreadPoolExecutor(), ydl_opts=params, url=url, download=True ) warning = ( f"`WARNING: FFMPEG is not installed!` [FFMPEG install guide]({ffurl})" " `If you requested multiple formats, they won't be merged.`\n\n" ) if isinstance(output, str): result = warning + output if not ffmpeg else output await event.answer(result, link_preview=False) else: path, thumb, info = output title = info.get('title', info.get('id', 'Unknown title')) uploader = info.get('uploader', None) duration = int(info.get('duration', 0)) width = info.get('width', None) height = info.get('height', None) url = info.get('webpage_url', None) href = f"[{title}]({url})" text = success.format(href) result = warning + text if not ffmpeg else text progress_cb = ProgressCallback(event, filen=title) dl = io.open(path, 'rb') uploaded = await client.fast_upload_file(dl, progress_cb.up_progress) dl.close() attributes, mime_type = get_attributes(path) if path.suffix[1:] in audioFormats: attributes.append( types.DocumentAttributeAudio(duration, None, title, uploader) ) elif path.suffix[1:] in videoFormats: attributes.append( types.DocumentAttributeVideo(duration, width, height) ) media = types.InputMediaUploadedDocument( file=uploaded, mime_type=mime_type, attributes=attributes, thumb=await client.upload_file(thumb) if thumb else None ) await client.send_file( event.chat_id, media, caption=href, force_document=True ) if thumb: os.remove(thumb) await event.delete()