Exemplo n.º 1
0
async def upload_to_tg(message: Message):
    """ upload to telegram """
    path_ = message.filtered_input_str
    if not path_:
        await message.err("Input not foud!")
        return
    is_path_url = is_url(path_)
    del_path = False
    if is_path_url:
        del_path = True
        try:
            path_, _ = await url_download(message, path_)
        except ProcessCanceled:
            await message.canceled()
            return
        except Exception as e_e:  # pylint: disable=broad-except
            await message.err(str(e_e))
            return
    if "|" in path_:
        path_, file_name = path_.split("|")
        path_ = path_.strip()
        if os.path.isfile(path_):
            new_path = os.path.join(Config.DOWN_PATH, file_name.strip())
            os.rename(path_, new_path)
            path_ = new_path
    try:
        string = Path(path_)
    except IndexError:
        await message.err("wrong syntax")
    else:
        await message.delete()
        with message.cancel_callback():
            await upload_path(message, string, del_path)
Exemplo n.º 2
0
 async def upload(self) -> None:
     """ Upload from file/folder/link/tg file to GDrive """
     replied = self._message.reply_to_message
     is_input_url = is_url(self._message.input_str)
     dl_loc = ""
     if replied and replied.media:
         try:
             dl_loc, _ = await tg_download(self._message, replied)
         except ProcessCanceled:
             await self._message.canceled()
             return
         except Exception as e_e:
             await self._message.err(str(e_e))
             return
     elif is_input_url:
         try:
             dl_loc, _ = await url_download(self._message,
                                            self._message.input_str)
         except ProcessCanceled:
             await self._message.canceled()
             return
         except Exception as e_e:
             await self._message.err(str(e_e))
             return
     file_path = dl_loc if dl_loc else self._message.input_str
     if not os.path.exists(file_path):
         await self._message.err("invalid file path provided?")
         return
     if "|" in file_path:
         file_path, file_name = file_path.split("|")
         new_path = os.path.join(os.path.dirname(file_path.strip()),
                                 file_name.strip())
         os.rename(file_path.strip(), new_path)
         file_path = new_path
     await self._message.try_to_edit("`Loading GDrive Upload...`")
     pool.submit_thread(self._upload, file_path)
     start_t = datetime.now()
     with self._message.cancel_callback(self._cancel):
         while not self._is_finished:
             if self._progress is not None:
                 await self._message.edit(self._progress)
             await asyncio.sleep(config.Dynamic.EDIT_SLEEP_TIMEOUT)
     if dl_loc and os.path.exists(dl_loc):
         os.remove(dl_loc)
     end_t = datetime.now()
     m_s = (end_t - start_t).seconds
     if isinstance(self._output, HttpError):
         out = f"**ERROR** : `{self._output._get_reason()}`"  # pylint: disable=protected-access
     elif self._output is not None and not self._is_canceled:
         out = f"**Uploaded Successfully** __in {m_s} seconds__\n\n{self._output}"
     elif self._output is not None and self._is_canceled:
         out = self._output
     else:
         out = "`failed to upload.. check logs?`"
     await self._message.edit(out,
                              disable_web_page_preview=True,
                              log=__name__)
Exemplo n.º 3
0
async def get_media_path_and_name(message: Message,
                                  input_str=""
                                  ) -> Union[Tuple[str, str], bool]:
    if not input_str:
        input_str = message.filtered_input_str
    dl_loc, file_name = "", ""
    replied = message.reply_to_message
    if hasattr(replied, 'media'):
        dl_loc, _ = await tg_download(message, replied)
        if hasattr(replied.audio, 'file_name'):
            file_name = replied.audio.file_name
        elif hasattr(replied.video, 'file_name'):
            file_name = replied.video.file_name
        elif hasattr(replied.document, 'file_name'):
            file_name = replied.document.file_name
        else:
            file_name = Path(dl_loc).name
    elif input_str:
        if is_url(input_str):
            try:
                dl_loc, _ = await url_download(message, input_str)
                file_name = Path(dl_loc).name
            except Exception as err:
                await message.err(str(err))
                return False
    else:
        await message.err("nothing provided to process")
        return False
    if dl_loc:
        file_path = dl_loc
    else:
        file_path = input_str.strip()
        file_name = Path(file_path).name
    if not Path(file_path).exists():
        await message.err("Seems that an invalid file path provided?")
        return False
    return file_path, file_name
Exemplo n.º 4
0
async def stt_(message: Message):
    """ Speech to text using Wit.ai """
    send_text = bool('t' in message.flags)
    replied = message.reply_to_message
    message_id = replied.message_id if replied else message.message_id
    regex = re.compile(r'([\S]*)(?: |)([\s\S]*)')
    match = regex.search(message.filtered_input_str)
    if not match:
        await message.edit("`Please read .help stt`")
        return
    lang = match.group(1).lower()
    api = WitAiAPI(lang)
    if not api.has_api_key():
        await message.edit(
            f'`Please set WIT_AI_API_{lang.upper()} variable first!`')
        return
    dl_loc = ""
    file_name = ""
    if replied and replied.media:
        try:
            dl_loc, _ = await tg_download(message, replied)
            # Try to get file name from the media file.
            try:
                if hasattr(replied.audio, 'file_name'):
                    file_name = replied.audio.file_name
                elif hasattr(replied.video, 'file_name'):
                    file_name = replied.video.file_name
                elif hasattr(replied.document, 'file_name'):
                    file_name = replied.document.file_name
                else:
                    file_name = os.path.basename(dl_loc)
            except AttributeError:
                pass
        except ProcessCanceled:
            await message.edit("`Process Canceled!`", del_in=5)
            return
        except Exception as e_e:
            await message.err(e_e)
            return
    else:
        input_str = match.group(2) if match.group(2) else ""
        is_input_url = is_url(input_str)
        if is_input_url:
            try:
                dl_loc, _ = await url_download(message,
                                               message.filtered_input_str)
                file_name = os.path.basename(dl_loc)
            except ProcessCanceled:
                await message.edit("`Process Canceled!`", del_in=5)
                return
            except Exception as e_e:
                await message.err(e_e)
                return
    if dl_loc:
        file_path = dl_loc
    else:
        file_path = message.filtered_input_str
        file_name = os.path.basename(dl_loc)
    if not os.path.exists(file_path):
        await message.err("`Seems that an invalid file path provided?`")
        return
    await message.edit("`Starting transcribing...`")
    processed = 0
    async for _, error in api.transcribe(file_path):
        if error:
            await message.edit(error)
            return
        processed += 1
        await message.edit(f"`Processed chunk {processed} of {api.chunks}`")
    if send_text:
        text_chunks = [
            api.text[i:i + Config.MAX_MESSAGE_LENGTH]
            for i in range(0, len(api.text), Config.MAX_MESSAGE_LENGTH)
        ]
        if len(text_chunks) == 1:
            await message.edit(text_chunks[0])
        else:
            await message.edit(text_chunks[0])
            for chunk in text_chunks[1:]:
                await message.reply(chunk)
                await sleep(2)
    # send transcription text file
    await message.client.send_as_file(
        chat_id=message.chat.id,
        reply_to_message_id=message_id,
        text=api.text,
        filename=f"{file_name}_{lang}_transcription.txt")
Exemplo n.º 5
0
async def play_music(msg: Message, forceplay: bool):
    """ play music """
    input_str = msg.filtered_input_str or getattr(msg.reply_to_message, 'text',
                                                  '') or ''
    path = Path(input_str)
    if input_str:
        if is_yt_url(input_str):
            name, duration = await get_song_info(input_str)
            if duration == -1:
                return await reply_text(
                    msg, "**ERROR:** `Max song duration limit reached!`")
            if Dynamic.PLAYING and not forceplay:
                msg = await reply_text(msg,
                                       get_scheduled_text(name, input_str))
            resource = UrlResource.parse(msg, name, input_str, duration)
            if forceplay:
                QUEUE.insert(0, resource)
            else:
                QUEUE.append(resource)
        elif is_url(input_str):
            try:
                height, width, has_audio, has_video = await get_file_info(
                    input_str)
                if not has_audio and not has_video:
                    raise Exception
                duration = await get_duration(shlex.quote(input_str))
                res = await pool.run_in_thread(requests.get
                                               )(input_str,
                                                 allow_redirects=True,
                                                 stream=True)
                headers = dict(res.headers)
                try:
                    filename = headers["Content-Disposition"].split(
                        '=', 1)[1].strip('"') or ''
                except KeyError:
                    filename = "Video" if has_video else "Music"
            except Exception:
                return await reply_text(
                    msg, "`invalid direct link provided to stream!`")
            resource = UrlResource.parse(msg, filename.replace('_', ' '),
                                         input_str, duration,
                                         (height, width, has_audio, has_video))
            Vars.CLIENT = msg.client
            if forceplay:
                QUEUE.insert(0, resource)
            else:
                if Dynamic.PLAYING:
                    await reply_text(
                        msg, get_scheduled_text(resource, resource.url))
                QUEUE.append(resource)
        elif (path.exists() and path.is_file()):
            if not path.name.endswith((".mkv", ".mp4", ".webm", ".m4v", ".mp3",
                                       ".flac", ".wav", ".m4a")):
                return await reply_text(
                    msg, "`invalid file path provided to stream!`")
            filename = path.name
            duration = await get_duration(path)
            resource = TgResource.parse(msg, filename.replace('_', ' '),
                                        str(path.absolute()), duration)
            Vars.CLIENT = msg.client
            if forceplay:
                QUEUE.insert(0, resource)
            else:
                if Dynamic.PLAYING:
                    await reply_text(msg, get_scheduled_text(resource))
                QUEUE.append(resource)
        else:
            mesg = await reply_text(msg, f"Searching `{input_str}` on YouTube")
            title, link = await get_song(input_str)
            if link:
                _, duration = await get_song_info(link)
                if duration == -1:
                    return await mesg.edit(
                        "Invalid YouTube link found during search!")
                if Dynamic.PLAYING and not forceplay:
                    msg = await reply_text(msg,
                                           get_scheduled_text(title, link))
                await mesg.delete()
                resource = UrlResource.parse(msg, title, link, duration)
                if forceplay:
                    QUEUE.insert(0, resource)
                else:
                    QUEUE.append(resource)
            else:
                await mesg.edit("No results found.")
    elif msg.reply_to_message:
        replied = msg.reply_to_message
        replied_file = replied.audio or replied.video or replied.document
        if not (replied.audio or replied.video or
                (replied.document and "video" in replied.document.mime_type)):
            return await reply_text(msg, "Input not found")
        if replied.audio:
            resource = TgResource(
                replied, replied_file.title or replied_file.file_name
                or "Song", replied.audio.duration)
        else:
            resource = TgResource(replied,
                                  replied_file.file_name,
                                  0,
                                  quality=int(msg.flags.get('-q', "80")),
                                  is_video='-v' in msg.flags)

        if msg.sender_chat:
            setattr(resource.message, 'sender_chat', msg.sender_chat)
        elif msg.from_user:
            setattr(resource.message, 'from_user', msg.from_user)
        Vars.CLIENT = msg.client
        if forceplay:
            QUEUE.insert(0, resource)
        else:
            if Dynamic.PLAYING:
                await reply_text(msg,
                                 get_scheduled_text(resource, replied.link))
            QUEUE.append(resource)
    else:
        return await reply_text(msg, "Input not found")

    if not Dynamic.PLAYING or forceplay:
        await skip_song()
Exemplo n.º 6
0
async def play_music(msg: Message, forceplay: bool):
    """ play music """
    global CLIENT  # pylint: disable=global-statement

    input_str = msg.filtered_input_str
    flags = msg.flags
    is_video = "-v" in flags
    path = Path(input_str)
    quality = flags.get('-q', 80)
    if input_str:
        if yt_regex.match(input_str):
            details = await _get_song_info(input_str)
            if not details:
                return await reply_text(
                    msg, "**ERROR:** `Max song duration limit reached!`")
            name, duration = details
            if PLAYING and not forceplay:
                msg = await reply_text(msg,
                                       _get_scheduled_text(name, input_str))
            else:
                msg = await reply_text(msg, f"[{name}]({input_str})")
            flags["duration"] = duration
            setattr(msg, '_flags', flags)
            if forceplay:
                QUEUE.insert(0, msg)
            else:
                QUEUE.append(msg)
        elif (is_url(input_str) or (path.exists() and path.is_file())):
            if path.exists():
                if not path.name.endswith((".mkv", ".mp4", ".webm", ".m4v",
                                           ".mp3", ".flac", ".wav", ".m4a")):
                    return await reply_text(
                        msg, "`invalid file path provided to stream!`")
                path_to_media = str(path.absolute())
                filename = path.name
            else:
                try:
                    res = await pool.run_in_thread(requests.get
                                                   )(input_str,
                                                     allow_redirects=True,
                                                     stream=True)
                    headers = dict(res.headers)
                    if ("video" not in headers.get("Content-Type", '') and
                            "audio" not in headers.get("Content-Type", '')):
                        height, width, has_audio, has_video = await get_file_info(
                            input_str)
                        setattr(msg, 'file_info',
                                (height, width, has_audio, has_video))
                        if not has_audio and not has_video:
                            raise Exception
                    path_to_media = input_str
                    try:
                        filename = headers["Content-Disposition"].split(
                            '=', 1)[1].strip('"') or ''
                    except KeyError:
                        filename = None
                    if not filename:
                        if hasattr(msg, 'file_info'):
                            _, _, _, has_video = msg.file_info
                            filename = "Video" if has_video else "Music"
                        else:
                            filename = 'Link'
                except Exception as e:
                    LOG.exception(e)
                    return await reply_text(
                        msg, "`invalid direct link provided to stream!`")
            setattr(msg, 'path_to_media', path_to_media)
            setattr(msg, 'file_name', filename.replace('_', ' '))
            setattr(msg, 'is_video', is_video)
            setattr(msg, 'quality', quality)
            CLIENT = msg.client
            if forceplay:
                QUEUE.insert(0, msg)
            else:
                if PLAYING:
                    await reply_text(msg, _get_scheduled_text(msg.file_name))
                QUEUE.append(msg)
        else:
            mesg = await reply_text(msg, f"Searching `{input_str}` on YouTube")
            title, link = await _get_song(input_str)
            if link:
                details = await _get_song_info(link)
                if not details:
                    return await mesg.edit(
                        "Invalid YouTube link found during search!")
                _, duration = details
                if PLAYING and not forceplay:
                    msg = await reply_text(msg,
                                           _get_scheduled_text(title, link))
                else:
                    msg = await msg.edit(f"[{title}]({link})")
                flags["duration"] = duration
                await mesg.delete()
                setattr(msg, '_flags', flags)
                if forceplay:
                    QUEUE.insert(0, msg)
                else:
                    QUEUE.append(msg)
            else:
                await mesg.edit("No results found.")
    elif msg.reply_to_message:
        replied = msg.reply_to_message
        replied_file = replied.audio or replied.video or replied.document
        if not replied_file:
            return await reply_text(msg, "Input not found")
        if replied.audio:
            setattr(replied.audio, 'file_name', replied_file.title
                    or replied_file.file_name or "Song")
            setattr(replied.audio, 'is_video', False)
            setattr(replied.audio, 'quality', 100)
        elif replied.video:
            setattr(replied.video, 'is_video', is_video)
            setattr(replied.video, 'quality', quality)
        elif replied.document and "video" in replied.document.mime_type:
            setattr(replied.document, 'is_video', is_video)
            setattr(replied.document, 'quality', quality)
        else:
            return await reply_text(msg, "Replied media is invalid.")

        CLIENT = msg.client
        if forceplay:
            QUEUE.insert(0, replied)
        else:
            if PLAYING:
                await reply_text(
                    msg,
                    _get_scheduled_text(replied_file.file_name, replied.link))
            QUEUE.append(replied)
    else:
        return await reply_text(msg, "Input not found")

    if not PLAYING or forceplay:
        await _skip()