Exemple #1
0
    async def play(self, ctx, url: str):

        ################################################################################################################################

        guild_id = ctx.guild.id
        guild_n = str(ctx.guild)
        channel_id = ctx.message.author.voice.channel.id
        channel_n = str(ctx.message.author.voice.channel)

        try:
            SQL.execute(
                f'select Song_Name from Music where Guild_ID = "{guild_id}" and Guild_Name = "{guild_n}" and Channel_ID = "{channel_id}" and Channel_Name = "{channel_n}"'
            )
            n_song = SQL.fetchone()
            SQL.execute(
                f'select Guild_Name from Music where Guild_ID = "{guild_id}" and Guild_Name = "{guild_n}"'
            )
            n_guild = SQL.fetchone()
        except:
            return

        ################################################################################################################################

        def check_queue(self):

            ############################################################################################################################

            DIR = os.path.dirname(__file__)
            db = sqlite3.connect(os.path.join(DIR, 'MultiBOT_DB.db'))
            SQL = db.cursor()
            SQL.execute(
                f'select Queue_Name from Music where Guild_ID = "{guild_id}" and Guild_Name = "{guild_n}"'
            )
            name_q = SQL.fetchone()
            SQL.execute(
                f'select Guild_Name from Music where Guild_ID = "{guild_id}" and Guild_Name = "{guild_n}"'
            )
            n_guild = SQL.fetchone()

            ############################################################################################################################

            q_infile = os.path.isdir('./Queues')

            if q_infile is True:
                DIR = os.path.abspath(os.path.realpath('Queues'))
                q_main = os.path.join(DIR, name_q[0])
                # length = len(os.listdir(q_main))
                # still_q = length - 1
                q_main_infile = os.path.isdir(q_main)

                if q_main_infile is True:
                    length = len(os.listdir(q_main))
                    still_q = length - 1
                    try:
                        first_file = os.listdir(q_main)[0]
                        song_num = first_file.split('-')[0]
                    except:
                        print('[Log] Музыка: нет треков в очереди')
                        db.commit()
                        return

                    main_location = os.path.dirname(os.path.realpath(__file__))
                    song_path = os.path.abspath(
                        os.path.realpath(q_main) + '\\' + first_file)

                    if length != 0:
                        print(
                            '[Log] Музыка: трек закончился, играет следующий')
                        print(f'[Log] Музыка: треков в очереди: {still_q}')
                        track_exist = os.path.isfile(
                            f'{n_song[0]}({n_guild[0]}).mp3')

                        if track_exist:
                            os.remove(f'{n_song[0]}({n_guild[0]}).mp3')

                        shutil.move(song_path, main_location)

                        for file in os.listdir('./'):

                            if file == f'{song_num}-{n_song[0]}({n_guild[0]}).mp3':
                                os.rename(file,
                                          f'{n_song[0]}({n_guild[0]}).mp3')

                        voice.play(discord.FFmpegPCMAudio(
                            f'{n_song[0]}({n_guild[0]}).mp3'),
                                   after=lambda e: check_queue(self))
                        voice.source = discord.PCMVolumeTransformer(
                            voice.source)
                        voice.source.volume = 0.05

                    else:
                        SQL.execute(
                            'update Music set Queue_Next = 1 where Guild_ID = ? and Guild_Name = ?',
                            (guild_id, guild_n))
                        db.commit()
                        return

                else:
                    SQL.execute(
                        'update Music set Queue_Next = 1 where Guild_ID = ? and Guild_Name = ?',
                        (guild_id, guild_n))
                    db.commit()
                    print(
                        '[Log] Музыка: в очереди не появлялось никаких треков')
            else:
                SQL.execute(
                    'update Music set Queue_Next = 1 where Guild_ID = ? and Guild_Name = ?',
                    (guild_id, guild_n))
                db.commit()
                print('[Log] Музыка: в очереди не появлялось никаких треков')

        track_exist = os.path.isfile(f'{n_song[0]}({n_guild[0]}).mp3')

        try:
            if track_exist:
                os.remove(f'{n_song[0]}({n_guild[0]}).mp3')
                SQL.execute(
                    'update Music set Queue_Next = 1 where Guild_ID = ? and Guild_Name = ?',
                    (guild_id, guild_n))
                db.commit()
                print('[Log] Старый файл удалён')
        except PermissionError:
            print('[Log] Нельзя удалить трек, который проигрывается')
            await ctx.send(embed=discord.Embed(
                description='Музыка: ошибка: трек проигрывается',
                color=0x0c0c0c))
            return

        SQL.execute(
            f'select Queue_Name from Music where Guild_ID = "{guild_id}" and Guild_Name = "{guild_n}"'
        )
        name_q = SQL.fetchone()
        q_infile = os.path.isdir('./Queues')

        if q_infile is True:
            DIR = os.path.abspath(os.path.realpath('Queues'))
            q_main = os.path.join(DIR, name_q[0])
            q_main_infile = os.path.isdir(q_main)

            if q_main_infile is True:
                print('[Log] Музыка: старая папка удалена')
                shutil.rmtree(q_main)

        await ctx.send(embed=discord.Embed(description='Музыка: ожидайте...',
                                           color=0x0c0c0c))

        voice = get(self.client.voice_clients, guild=ctx.guild)
        song_path = f'./{n_song[0]}({n_guild[0]}).mp3'

        ydl_opts = {
            'format':
            'bestaudio/best',
            'quiet':
            True,
            'outtmpl':
            song_path,
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '192',
            }],
        }

        try:
            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                print('[Log] Загружаем аудио')
                ydl.download([url])
            await ctx.send(embed=discord.Embed(description='Музыка: играет',
                                               color=0x0c0c0c))
            print('[Log] Музыка: играет')
        except:
            await ctx.send(embed=discord.Embed(
                description='Музыка: бот не поддерживает такие ссылки',
                color=0x0c0c0c))

        voice.play(discord.FFmpegPCMAudio(f'{n_song[0]}({n_guild[0]}).mp3'),
                   after=lambda e: check_queue(self))
        voice.source = discord.PCMVolumeTransformer(voice.source)
        voice.source.volume = 0.05
Exemple #2
0
def download_video(client,
                   video,
                   commentLimit=None,
                   displayDownloadLink=False,
                   creator=None):
    showVideo(
        client,
        video,
        commentLimit=5,
        # displayDownloadLink=displayDownloadLink,
        showRelatedVideos=True,
        showComments=True)

    dl_dir = dl_config[cfg_path] if cfg_path in dl_config else 'download'
    dl_dir_perms = int(dl_config[cfg_dir_perm],
                       base=8) if cfg_dir_perm in dl_config else 0o755
    dl_file_perms = int(dl_config[cfg_file_perm],
                        base=8) if cfg_file_perm in dl_config else 0o644

    if creator is None:
        creator = client.getCreatorInfo(video.creator.id)[0]

    val_subfolder = dl_config[cfg_subfolder].strip().lower()
    if val_subfolder == 'true' or val_subfolder == '1':
        creator_short = creator.urlname
        dl_dir = '{}/{}'.format(dl_dir, creator_short)

    if not os.path.isdir(dl_dir):
        os.makedirs(dl_dir, mode=dl_dir_perms, exist_ok=True)

    ending_video = 'mp4'
    ending_thumb = 'png'
    ending_info = 'info.json'
    basename = '{}-{}-{}'.format(video.guid, creator.title, video.title)

    basename = filter_basename(basename)

    output_template = '{}/{}.{}'.format(dl_dir, basename, ending_video)
    thumbnail_template = '{}/{}.{}'.format(dl_dir, basename, ending_thumb)

    if os.path.exists(output_template):
        print('This video is already downloaded ... skipping')

        for ending in [ending_video, ending_info, ending_thumb]:
            f_name = '{}/{}.{}'.format(dl_dir, basename, ending)
            if os.path.isfile(f_name):
                os.chmod(f_name, dl_file_perms)

        return

    if os.path.exists('{}.part'.format(output_template)):
        print('Download seems to be interrupted ... continuing')

    try:
        download_url = client.getDirectVideoURL(video.guid)
        print('Downloading Video from: {} to {}'.format(download_url, dl_dir))

        download_thumbnail(client,
                           video,
                           thumbnail_template,
                           perm=dl_file_perms)

        ydl_opts = {
            'format': 'bestaudio/best',
            'call_home': False,
            'outtmpl': output_template,
            'continue_dl': True,
            # 'writeinfojson': True,
            # 'postprocessors': [{
            # 'key': 'FFmpegExtractAudio',
            # 'preferredcodec': 'mp3',
            # 'preferredquality': '192',
            # }],
            'logger': MyLogger(),
            'progress_hooks': [download_progress_hook],
        }

        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            ydl.download([download_url])

            for ending in [ending_video, ending_info]:
                f_name = '{}/{}.{}'.format(dl_dir, basename, ending)
                if os.path.isfile(f_name):
                    os.chmod(f_name, dl_file_perms)
    except Exception as err:
        print('Download Failed!: {}', err)
        sentry_sdk.capture_exception(err)
Exemple #3
0
    os.mkdir("downloads")

import threading
import queue
import requests
import youtube_dl
from config import DUR_LIMIT, SUDO_USERS
from helpers import run, format_duration, generate_image

ydl_opts = {
    "format": "bestaudio/best",
    "geo-bypass": True,
    "nocheckcertificate": True,
    "outtmpl": "downloads/%(id)s.%(ext)s",
}
ydl = youtube_dl.YoutubeDL(ydl_opts)
q = queue.Queue()


def worker():
    while True:
        item = q.get()

        try:
            info = ydl.extract_info(item["video"], download=False)

            if (int(info["duration"] / 60) > DUR_LIMIT
                    and item["sender_id"] not in SUDO_USERS):
                if "on_duration_limit" in item:
                    if item["on_duration_limit"]:
                        item["on_duration_limit"]["args"][0] = item[
Exemple #4
0
class YTDLSource(discord.PCMVolumeTransformer):
    YTDL_OPTIONS = {
        'format': 'bestaudio/best',
        'extractaudio': True,
        'audioformat': 'mp3',
        'outtmpl': '%(extractor)s-%(id)s-%(title)s.%(ext)s',
        'restrictfilenames': True,
        'noplaylist': True,
        'nocheckcertificate': True,
        'ignoreerrors': False,
        'logtostderr': False,
        'quiet': True,
        'no_warnings': True,
        'default_search': 'auto',
        'source_address': '0.0.0.0',
    }

    FFMPEG_OPTIONS = {
        'before_options':
        '-reconnect 1 -reconnect_streamed 1 -reconnect_delay_max 5',
        'options': '-vn',
    }

    ytdl = youtube_dl.YoutubeDL(YTDL_OPTIONS)

    def __init__(self,
                 ctx: commands.Context,
                 source: discord.FFmpegPCMAudio,
                 *,
                 data: dict,
                 volume: float = 0.5):
        super().__init__(source, volume)

        self.requester = ctx.author
        self.channel = ctx.channel
        self.data = data

        self.uploader = data.get('uploader')
        self.uploader_url = data.get('uploader_url')
        date = data.get('upload_date')
        self.upload_date = date[6:8] + '.' + date[4:6] + '.' + date[0:4]
        self.title = data.get('title')
        self.thumbnail = data.get('thumbnail')
        self.description = data.get('description')
        self.duration = self.parse_duration(int(data.get('duration')))
        self.tags = data.get('tags')
        self.url = data.get('webpage_url')
        self.views = data.get('view_count')
        self.likes = data.get('like_count')
        self.dislikes = data.get('dislike_count')
        self.stream_url = data.get('url')

    def __str__(self):
        return '**{0.title}** by **{0.uploader}**'.format(self)

    @classmethod
    async def create_source(cls,
                            ctx: commands.Context,
                            search: str,
                            *,
                            loop: asyncio.BaseEventLoop = None):
        loop = loop or asyncio.get_event_loop()

        partial = functools.partial(cls.ytdl.extract_info,
                                    search,
                                    download=False,
                                    process=False)
        data = await loop.run_in_executor(None, partial)

        if data is None:
            raise YTDLError(
                'Couldn\'t find anything that matches `{}`'.format(search))

        if 'entries' not in data:
            process_info = data
        else:
            process_info = None
            for entry in data['entries']:
                if entry:
                    process_info = entry
                    break

            if process_info is None:
                raise YTDLError(
                    'Couldn\'t find anything that matches `{}`'.format(search))

        webpage_url = process_info['webpage_url']
        partial = functools.partial(cls.ytdl.extract_info,
                                    webpage_url,
                                    download=False)
        processed_info = await loop.run_in_executor(None, partial)

        if processed_info is None:
            raise YTDLError('Couldn\'t fetch `{}`'.format(webpage_url))

        if 'entries' not in processed_info:
            info = processed_info
        else:
            info = None
            while info is None:
                try:
                    info = processed_info['entries'].pop(0)
                except IndexError:
                    raise YTDLError(
                        'Couldn\'t retrieve any matches for `{}`'.format(
                            webpage_url))

        return cls(ctx,
                   discord.FFmpegPCMAudio(info['url'], **cls.FFMPEG_OPTIONS),
                   data=info)

    @staticmethod
    def parse_duration(duration: int):
        minutes, seconds = divmod(duration, 60)
        hours, minutes = divmod(minutes, 60)
        days, hours = divmod(hours, 24)

        duration = []
        if days > 0:
            duration.append('{} days'.format(days))
        if hours > 0:
            duration.append('{} hours'.format(hours))
        if minutes > 0:
            duration.append('{} minutes'.format(minutes))
        if seconds > 0:
            duration.append('{} seconds'.format(seconds))

        return ', '.join(duration)
Exemple #5
0
    False,
    'logtostderr':
    False,
    'quiet':
    True,
    'no_warnings':
    True,
    'default_search':
    'auto',
    'source_address':
    '0.0.0.0'  # bind to ipv4 since ipv6 addresses cause issues sometimes
}

ffmpeg_options = {'options': '-vn'}

ytdl = youtube_dl.YoutubeDL(ytdl_format_options)


def getTitle(url):
    info_dict = ytdl.extract_info(url, download=False)
    title = info_dict.get('title', None)
    return title


class YTDLSource(discord.PCMVolumeTransformer):
    def __init__(self, source, *, data, volume=0.5):
        super().__init__(source, volume)

        self.data = data

        self.title = data.get('title')
Exemple #6
0
 def downloadVideo(self, ydlOpts):
     with youtube_dl.YoutubeDL(ydlOpts) as ydl:
         ydl.download([arguments.url])
Exemple #7
0
async def play(ctx, url: str):
    def check_queue():
        Queue_infile = os.path.isdir("./Queue")
        if Queue_infile is True:
            DIR = os.path.abspath(os.path.realpath("Queue"))
            length = len(os.listdir(DIR))
            still_q = length - 1
            try:
                first_file = os.listdir(DIR)[0]
            except:
                print("No more queued song(s)\n")
                queues.clear()
                return
            main_location = os.path.dirname(os.path.realpath(__file__))
            song_path = os.path.abspath(
                os.path.realpath("Queue") + "\\" + first_file)
            if length != 0:
                print("Song done, playing next queued\n")
                print(f"Songs still in queue: {still_q}")
                song_there = os.path.isfile("song.mp3")
                if song_there:
                    os.remove("song.mp3")
                shutil.move(song_path, main_location)
                for file in os.listdir("./"):
                    if file.endswith(".mp3"):
                        os.rename(file, 'song.mp3')

                voice.play(discord.FFmpegPCMAudio("song.mp3"),
                           after=lambda e: check_queue())
                voice.source = discord.PCMVolumeTransformer(voice.source)
                voice.source.volume = 0.07

            else:
                queues.clear()
                return

        else:
            queues.clear()
            print("No songs were queued before the ending of the last song\n")

    song_there = os.path.isfile("song.mp3")
    try:
        if song_there:
            os.remove("song.mp3")
            queues.clear()
            print("Removed old song file")
    except PermissionError:
        print("Trying to delete song file, but it's being played")
        await ctx.send("ERROR: Music playing")
        return

    Queue_infile = os.path.isdir("./Queue")
    try:
        Queue_folder = "./Queue"
        if Queue_infile is True:
            print("Removed old Queue Folder")
            shutil.rmtree(Queue_folder)
    except:
        print("No old Queue folder")

    await ctx.send("Getting everything ready now")

    voice = get(bot.voice_clients, guild=ctx.guild)

    ydl_opts = {
        'format':
        'bestaudio/best',
        'quiet':
        True,
        'postprocessors': [{
            'key': 'FFmpegExtractAudio',
            'preferredcodec': 'mp3',
            'preferredquality': '192',
        }],
    }
    try:
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            print("Downloading audio now\n")
            ydl.download([url])
    except:
        print(
            "FALLBACK: youtube-dl does not support this URL, using Spotify (This is normal if Spotify URL)"
        )
        c_path = os.path.dirname(os.path.realpath(__file__))
        system("spotdl -f " + '"' + c_path + '"' + " -s " + url)

    for file in os.listdir("./"):
        if file.endswith(".mp3"):
            name = file
            print(f"Renamed File: {file}\n")
            os.rename(file, "song.mp3")

    voice.play(discord.FFmpegPCMAudio("song.mp3"),
               after=lambda e: check_queue())
    voice.source = discord.PCMVolumeTransformer(voice.source)
    voice.source.volume = 0.07

    nname = name.rsplit("-", 2)
    await ctx.send(f"Playing: {nname[0]}")
    print("playing\n")
Exemple #8
0
def downloadVideo(url):
    with ytd.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])
Exemple #9
0
'''
First install youtobe downloader
pip install youtube_dl
'''

import youtube_dl

url = ['https://www.youtube.com/xxxxxx']

with youtube_dl.YoutubeDL() as ydl:
    ydl.download(url)
Exemple #10
0
    def __init__(self, init_data, opts=dict()):

        yid = init_data['yid']  # it must be here.

        if self.rickastley:
            yid = "dQw4w9WgXcQ"  #trolololo

        if not isinstance(yid, str) or len(yid) != 11:
            raise ValueError(
                "yid expected to be valid Youtube movie identifier")  #FIXME

        self.data = tempfile.SpooledTemporaryFile()
        self.fds = set()
        self.closing = False

        self.lock = Lock()  # lock to prevent threads from colliding

        self.avail = range_t()
        self.safe_range = range_t()
        self.processing_range = range_t()

        self.filesize = 4096
        self.disk = 0
        self.extension = ".mp4"  # FIXME

        self.atime = int(time())
        try:
            # convert from iso 8601
            self.ctime = timegm(
                datetime.strptime(init_data['pub_date'],
                                  "%Y-%m-%dT%H:%M:%S.%fZ").timetuple())
        except KeyError:
            self.ctime = self.atime

        self.r_session = requests.Session()

        self.yid = yid

        _pref = deepcopy(
            self.preferences)  # new object, just to not affect other intances.
        try:
            _pref['audio'] = opts['audio']
        except KeyError:
            pass
        try:
            _pref['video'] = opts['video']
        except KeyError:
            pass
        try:
            _pref['format'] = opts['format']
        except KeyError:
            pass
        try:
            _pref['stream'] = opts['stream']
        except KeyError:
            pass
        try:
            _pref['get_info_on_init'] = opts['get_info_on_init']
        except KeyError:
            pass
        self.preferences = _pref

        self.ytdl = youtube_dl.YoutubeDL({
            "quiet": True,
            "format": "bestvideo+bestaudio"
        })
        self.ytdl.add_info_extractor(self.ytdl.get_info_extractor("Youtube"))
Exemple #11
0
 def download(link, data):
     try:
         with dl.YoutubeDL(data) as ydl:
             ydl.download([link])
     except dl.utils.DownloadError as err:
         print("[!] " + err)
Exemple #12
0
def song(client, message):

    user_id = message.from_user.id
    user_name = message.from_user.first_name
    rpk = "[" + user_name + "](tg://user?id=" + str(user_id) + ")"

    query = ""
    for i in message.command[1:]:
        query += " " + str(i)
    print(query)
    m = message.reply("🔎 Finding the song...")
    ydl_opts = {"format": "bestaudio[ext=m4a]"}
    try:
        results = YoutubeSearch(query, max_results=1).to_dict()
        link = f"https://youtube.com{results[0]['url_suffix']}"
        # print(results)
        title = results[0]["title"][:40]
        thumbnail = results[0]["thumbnails"][0]
        thumb_name = f"thumb{title}.jpg"
        thumb = requests.get(thumbnail, allow_redirects=True)
        open(thumb_name, "wb").write(thumb.content)

        duration = results[0]["duration"]
        results[0]["url_suffix"]
        results[0]["views"]

    except Exception as e:
        m.edit(
            "❌ Found Nothing.\n\nTry another keywork or maybe spell it properly."
        )
        print(str(e))
        return
    m.edit("Downloading the song ")
    try:
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            info_dict = ydl.extract_info(link, download=False)
            audio_file = ydl.prepare_filename(info_dict)
            ydl.process_info(info_dict)
        rep = "**🎵 Uploaded by @Joker_prorobot**"
        secmul, dur, dur_arr = 1, 0, duration.split(":")
        for i in range(len(dur_arr) - 1, -1, -1):
            dur += int(dur_arr[i]) * secmul
            secmul *= 60
        message.reply_audio(
            audio_file,
            caption=rep,
            thumb=thumb_name,
            parse_mode="md",
            title=title,
            duration=dur,
        )
        m.delete()
    except Exception as e:
        m.edit("❌ Error")
        print(e)

    try:
        os.remove(audio_file)
        os.remove(thumb_name)
    except Exception as e:
        print(e)
Exemple #13
0
async def ytmusic(client, message: Message):
    global is_downloading
    if is_downloading:
        await message.reply_text(
            "Another download is in progress, try again after sometime.")
        return

    urlissed = get_text(message)

    pablo = await client.send_message(
        message.chat.id,
        f"`Getting {urlissed} From Youtube Servers. Please Wait.`")
    if not urlissed:
        await pablo.edit(
            "Invalid Command Syntax, Please Check Help Menu To Know More!")
        return

    search = SearchVideos(f"{urlissed}", offset=1, mode="dict", max_results=1)
    mi = search.result()
    mio = mi["search_result"]
    mo = mio[0]["link"]
    thum = mio[0]["title"]
    fridayz = mio[0]["id"]
    thums = mio[0]["channel"]
    kekme = f"https://img.youtube.com/vi/{fridayz}/hqdefault.jpg"
    await asyncio.sleep(0.6)
    url = mo
    sedlyf = wget.download(kekme)
    opts = {
        "format":
        "best",
        "addmetadata":
        True,
        "key":
        "FFmpegMetadata",
        "prefer_ffmpeg":
        True,
        "geo_bypass":
        True,
        "nocheckcertificate":
        True,
        "postprocessors": [{
            "key": "FFmpegVideoConvertor",
            "preferedformat": "mp4"
        }],
        "outtmpl":
        "%(id)s.mp4",
        "logtostderr":
        False,
        "quiet":
        True,
    }
    try:
        is_downloading = True
        with youtube_dl.YoutubeDL(opts) as ytdl:
            infoo = ytdl.extract_info(url, False)
            duration = round(infoo["duration"] / 60)

            if duration > DURATION_LIMIT:
                await pablo.edit(
                    f"❌ Videos longer than {DURATION_LIMIT} minute(s) aren't allowed, the provided video is {duration} minute(s)"
                )
                is_downloading = False
                return
            ytdl_data = ytdl.extract_info(url, download=True)

    except Exception:
        # await pablo.edit(event, f"**Failed To Download** \n**Error :** `{str(e)}`")
        is_downloading = False
        return

    c_time = time.time()
    file_stark = f"{ytdl_data['id']}.mp4"
    capy = f"**Video Name ➠** {thum} \n**Requested For :** {urlissed} \n**Channel :** {thums} \n**Link :** {mo}"
    await client.send_video(
        message.chat.id,
        video=open(file_stark, "rb"),
        duration=int(ytdl_data["duration"]),
        file_name=str(ytdl_data["title"]),
        thumb=sedlyf,
        caption=capy,
        supports_streaming=True,
        progress=progress,
        progress_args=(
            pablo,
            c_time,
            f"`Uploading {urlissed} Song From YouTube Music!`",
            file_stark,
        ),
    )
    await pablo.delete()
    is_downloading = False
    for files in (sedlyf, file_stark):
        if files and os.path.exists(files):
            os.remove(files)
Exemple #14
0
    async def queue(self, ctx, url: str):

        ################################################################################################################################

        guild_id = ctx.guild.id
        guild_n = str(ctx.guild)
        try:
            SQL.execute(
                f'select Queue_Name from Music where Guild_ID = "{guild_id}" and Guild_Name = "{guild_n}"'
            )
            name_q = SQL.fetchone()
            SQL.execute(
                f'select Song_Name from Music where Guild_ID = "{guild_id}" and Guild_Name = "{guild_n}"'
            )
            n_song = SQL.fetchone()
            SQL.execute(
                f'select Queue_Next from Music where Guild_ID = "{guild_id}" and Guild_Name = "{guild_n}"'
            )
            q_num = SQL.fetchone()
        except:
            return

        ################################################################################################################################

        q_infile = os.path.isdir('./Queues')

        if q_infile is False:
            os.mkdir('Queues')

        DIR = os.path.abspath(os.path.realpath('Queues'))
        q_main = os.path.join(DIR, name_q[0])
        q_main_infile = os.path.isdir(q_main)

        if q_main_infile is False:
            os.mkdir(q_main)

        SQL.execute(
            f'select Guild_Name from Music where Guild_ID = "{guild_id}" and Guild_Name = "{guild_n}"'
        )
        n_guild = SQL.fetchone()
        queue_path = os.path.abspath(
            os.path.realpath(q_main) +
            f'\\{q_num[0]}-{n_song[0]}({n_guild[0]}).mp3')

        ydl_opts = {
            'format':
            'bestaudio/best',
            'quiet':
            True,
            'outtmpl':
            queue_path,
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '192',
            }],
        }

        try:
            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                print('[Log] Загружаем аудио')
                ydl.download([url])
            await ctx.send(embed=discord.Embed(
                description='Музыка: трек добавлен в очередь под номером ' +
                str(q_num[0]),
                color=0x0c0c0c))
            print('[Log] Музыка: трек добавлен в очередь')
        except:
            await ctx.send(embed=discord.Embed(
                description='Музыка: бот не поддерживает такие ссылки',
                color=0x0c0c0c))

        SQL.execute(
            'update Music set Queue_Next = Queue_Next + 1 where Guild_ID = ? and Guild_Name = ?',
            (guild_id, guild_n))
def download_video(title_url_list, playlist_title):

    # create directories if not existing already
    directory_text = os.getcwd() + '/output/' + playlist_title + '/text/'
    directory_audio = os.getcwd() + '/output/' + playlist_title + '/audio/'
    directory_video = os.getcwd() + '/output/' + playlist_title + '/video/'
    directory_archive = os.getcwd() + '/output/' + playlist_title + '/archive/'
    if not os.path.exists(directory_video):
        os.makedirs(directory_video)
    if not os.path.exists(directory_audio):
        os.makedirs(directory_audio)
    if not os.path.exists(directory_text):
        os.makedirs(directory_text)
    if not os.path.exists(directory_archive):
        os.makedirs(directory_archive)

    video_count = len(title_url_list)

    faulty_entries = []
    for idx, val in enumerate(title_url_list[1:]):  # start at second element
        print('\nCurrent Youtube Video = ', val)
        title = val[0]
        url = val[1]
        print('Output Directory: ', directory_audio)
        ydl_opts = {
            'format':
            'bestaudio/best',
            'outtmpl':
            directory_audio + '/' + title + '.%(ext)s',
            'download_archive':
            directory_archive + '/' + title + '.%(ext)s',
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '192',
            }],
        }
        try:
            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                ydl.download([url])
            print('{} of {} already processed'.format(idx + 1, video_count))
        except:
            faulty_entries.append(title_url_list.index(val))
            print("!!!! Error downloading with youtube-dl !!!!")

    print('Faulty Youtube Videos, (deleted, copyright issues etc.): ',
          faulty_entries)

    filename = directory_text + playlist_title + '_faulty.txt'  # create text file containing the faulty video list
    f = open(filename, 'a', encoding='utf-8')
    f.truncate(0)  # clear file

    for item in sorted(
            faulty_entries, reverse=True
    ):  # remove faulty entries from the list containing all playlist video information
        temp = title_url_list[item][0] + '        ' + title_url_list[item][1]
        f.write("%s\n" % temp)  # add faulty video to text file
        del title_url_list[item]  # delete faulty entry from list
    f.close

    filename = directory_text + playlist_title + '_cleaned.txt'  # create text file containing only succesfully downloaded playlist entries
    f = open(filename, 'a', encoding='utf-8')
    f.truncate(0)  # clear file

    for item in title_url_list:
        temp = item[0] + '        ' + item[1]
        f.write("%s\n" % temp)
    f.close
Exemple #16
0
def download_button(vid: str, body: bool = False):
    try:
        vid_data = youtube_dl.YoutubeDL({
            "no-playlist": True
        }).extract_info(BASE_YT_URL + vid, download=False)
    except ExtractorError:
        vid_data = {"formats": []}
    buttons = [[
        InlineKeyboardButton("BEST - 📹 MKV",
                             callback_data=f"ytdl_download_{vid}_mkv_v"),
        InlineKeyboardButton(
            "BEST - 📹 WebM/MP4",
            callback_data=f"ytdl_download_{vid}_mp4_v",
        ),
    ]]
    # ------------------------------------------------ #
    qual_dict = defaultdict(lambda: defaultdict(int))
    qual_list = ["144p", "240p", "360p", "480p", "720p", "1080p", "1440p"]
    audio_dict = {}
    # ------------------------------------------------ #
    for video in vid_data["formats"]:

        fr_note = video.get("format_note")
        fr_id = int(video.get("format_id"))
        fr_size = video.get("filesize")
        if video.get("ext") == "mp4":
            for frmt_ in qual_list:
                if fr_note in (frmt_, frmt_ + "60"):
                    qual_dict[frmt_][fr_id] = fr_size
        if video.get("acodec") != "none":
            bitrrate = int(video.get("abr", 0))
            if bitrrate != 0:
                audio_dict[
                    bitrrate] = f"{bitrrate}Kbps ({humanbytes(fr_size) or 'N/A'})"

    video_btns = []
    for frmt in qual_list:
        frmt_dict = qual_dict[frmt]
        if len(frmt_dict) != 0:
            frmt_id = sorted(list(frmt_dict))[-1]
            frmt_size = humanbytes(frmt_dict.get(frmt_id)) or "N/A"
            video_btns.append(
                InlineKeyboardButton(
                    f"video{frmt} ({frmt_size})",
                    callback_data=f"ytdl_download_{vid}_{frmt_id}_v",
                ))
    buttons += sublists(video_btns, width=2)
    buttons += [[
        InlineKeyboardButton("BEST - 320Kbps - MP3",
                             callback_data=f"ytdl_download_{vid}_mp3_a")
    ]]
    buttons += sublists(
        [
            InlineKeyboardButton(audio_dict.get(key_),
                                 callback_data=f"ytdl_download_{vid}_{key_}_a")
            for key_ in sorted(audio_dict.keys())
        ],
        width=2,
    )
    if body:
        vid_body = f"<b>[{vid_data.get('title')}]({vid_data.get('webpage_url')})</b>"
        return vid_body, InlineKeyboardMarkup(buttons)
    return InlineKeyboardMarkup(buttons)
Exemple #17
0
def video_download(url: str, download_dir: str) -> Path:
    """Download video from ad url"""
    class MyLogger:
        def __init__(self):
            self.ad_filepath: Optional[Path] = None

        def debug(self, msg):
            print(msg)
            new_download_match = re.search('Merging formats into \"(.*)\"$',
                                           msg)
            already_downloaded_match = re.search(
                "\[download\] (.*) has already been downloaded and merged.*",
                msg)
            if new_download_match:
                final_path = new_download_match.group(1)

                # This log msg occurs after any status messages from youtube-dl
                # This field will not be updated again for a video download.
                self.ad_filepath = Path(final_path)
                return
            elif already_downloaded_match:
                filepath = already_downloaded_match.group(1)
                self.ad_filepath = Path(filepath)
                return

        def warning(self, msg):
            print(msg)

        def error(self, msg):
            print(msg)

        def info(self, msg):
            print(msg)

    def my_hook(d):
        pass

    mylogger = MyLogger()

    ydl_opts = {
        # Pick best audio and video format and combine them OR pick the file with the best combination
        # Need to capture filename of merged ffmpeg file
        # Best doesn't return the highest video, only the highest pair.
        # So 360p video may have the highest audio
        # 'format': 'best',
        # 'format': 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/bestvideo[ext=webm]+bestaudio[ext=webm]/best',
        'format': 'bestvideo+bestaudio/best',
        'nooverwrites': True,
        # 'continuedl': True,
        'progress_hooks': [my_hook],
        'logger': mylogger,
    }

    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        # Extract info about video to determine where to download the file to
        try:
            result = ydl.extract_info(url, download=False)
        except youtube_dl.utils.DownloadError as e:
            if "video is unavailable" in e.args[0]:
                raise MissingVideoError("Missing video", url=url) from e
            elif "video is private" in e.args[0]:
                raise PrivateVideoError("Private video", url=url) from e
            elif "removed by the user" in e.args[0]:
                raise UserRemovedVideoError("User removed video",
                                            url=url) from e
            elif "account associated with this video has been terminated" in e.args[
                    0]:
                raise AccountTerminationVideoError(
                    "Missing video due to account termination", url=url) from e
            else:
                raise e
        extractor = result["extractor"]

        if extractor == "generic":
            filename = extract_base_identifier(url)
            ydl_opts["outtmpl"] = download_dir + f'/{filename}.%(ext)s'
        elif extractor == "youtube":
            ydl_opts["outtmpl"] = download_dir + f'/%(id)s.%(ext)s'
            print(extractor)

    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url])

    saved_ad_filepath = mylogger.ad_filepath
    if saved_ad_filepath == download_dir:
        raise ValueError(
            f"`No video path was saved? Was the video downloaded?`, for url={url}"
        )
    else:
        return saved_ad_filepath
Exemple #18
0
    async def add_playlist(self, url, message, type='y'):

        if len(self.playlist) > self.playlist_cap:
            await self.client.send_message(
                message.channel, ":notes: The playlist is at capacity (" +
                self.playlist_cap + " songs). Please try again later.")
        else:
            if type == 'y':
                startpos = 1
                endpos = 2
                if '&index=' in url:
                    isPlaylist = True
                    temp = url.split('&')
                    for i in range(0, (len(temp))):
                        if 'index=' in temp[i]:
                            sstart = temp[i].replace('index=', '')
                            startpos = int(sstart)
                            endpos = startpos + self.max_playlist_length - 1
                            break
                ytdl = youtube_dl.YoutubeDL({
                    'playliststart': startpos,
                    'playlistend': endpos
                })
                try:
                    result = ytdl.extract_info(url, download=False)
                    cont = True
                except youtube_dl.utils.DownloadError as e:
                    cont = False
                    if 'Incomplete YouTube ID' in str(e):
                        msg = '{0.author.name} : Not a valid Youtube video'
                        self.client.send_message(message.channel,
                                                 msg.format(message))

                if cont:
                    user_occurance = 0

                    # Checks if the message author is an admin
                    admin = False
                    for role in message.author.roles:
                        if settings['BOTSETTINGS'][
                                'botadmin'] in role.name or "Loser" in role.name or "Admin" in role.name:
                            admin = True

                    if 'entries' in result:
                        queued = 0
                        for i in range(0, len(result['entries'])):
                            # Get video url, title and set requester
                            url = result['entries'][i]['webpage_url']
                            title = result['entries'][i]['title']
                            video_already_present = False
                            user = message.author.mention
                            name = message.author.name
                            id = message.author.id

                            for item in self.playlist:
                                if item['user'] == user:
                                    user_occurance += 1
                                if item['title'] == title:
                                    video_already_present = True

                            if user_occurance > self.max_song_requests and (
                                    admin == False):
                                await self.client.send_message(
                                    message.channel,
                                    ":notes: You currently have " +
                                    str(self.max_song_requests + 1) +
                                    " songs in the playlist. Please try again later."
                                )
                            elif video_already_present:
                                await self.client.send_message(
                                    message.channel,
                                    ":notes: A song with the title `" + title +
                                    "` is already in this playlist.")
                            else:

                                if '`' in title:
                                    title = title.replace('`', '\'')

                                self.playlist.append({
                                    'url': url,
                                    'title': title,
                                    'user': user,
                                    'name': name,
                                    'id': id
                                })
                                print(title + ' Added to queue')
                                queued = queued + 1

                        # Tell user the amount of playlist songs queued
                        msg = 'Queued: `' + str(queued) + ' song(s)`'
                        await self.client.send_message(message.channel,
                                                       msg.format(message))

                    # Else it is a single video
                    else:
                        user_occurance = 0
                        video_already_present = False
                        url = result['webpage_url']
                        title = result['title']
                        user = message.author.mention
                        name = message.author.name
                        id = message.author.id

                        for item in self.playlist:
                            if item['user'] == user:
                                user_occurance += 1
                            if item['title'] == title:
                                video_already_present = True

                        if user_occurance > self.max_song_requests and (
                                admin == False):
                            await self.client.send_message(
                                message.channel,
                                ":notes: You currently have " +
                                str(self.max_song_requests + 1) +
                                " songs in the playlist. Please try again later."
                            )
                        elif video_already_present:
                            await self.client.send_message(
                                message.channel,
                                ":notes: A song with the title `" + title +
                                "` is already in this playlist.")
                        else:
                            if '`' in title:
                                title = title.replace('`', '\'')
                            # Add info to playlist
                            self.playlist.append({
                                'url': url,
                                'title': title,
                                'user': user,
                                'name': name,
                                'id': id
                            })
                            print(title + ' Added to queue')

                            # Tell user the song has been queued
                            msg = 'Added to queue: `' + title + '`'
                            await self.client.send_message(
                                message.channel, msg.format(message))

            # Soundcloud Section
            elif type == 's':
                # Set youtube_dl to use max_playlist_length to set the end of a set
                ytdl = youtube_dl.YoutubeDL(
                    {'playlistend': self.max_playlist_length})

                # Get SC song info
                cont = True
                try:
                    result = ytdl.extract_info(url, download=False)
                    cont = True
                # Invalid Link
                except youtube_dl.utils.DownloadError as e:
                    cont = False
                    if 'Unable to download JSON metadata' in str(e):
                        print('Invalid Soundcloud link')
                        msg = '{0.author.mention} : Not a valid Soundcloud song'
                        await self.client.send_message(message.channel,
                                                       msg.format(message))

                if cont:
                    # If SC set
                    if 'entries' in result:
                        for i in range(0, len(result['entries'])):
                            # Get song url, title and set requester
                            url = result['entries'][i]['webpage_url']
                            title = result['entries'][i]['title']
                            user = message.author.mention
                            name = message.author.name
                            id = message.author.id
                            # Make sure the video title cannot break code box in message
                            if '`' in title:
                                title = title.replace('`', '\'')
                            # Add info to playlist
                            self.playlist.append({
                                'url': url,
                                'title': title,
                                'user': user,
                                'name': name,
                                'id': id
                            })
                            print(title + ' Added to queue')

                        # Tell the user how many songs have been queued
                        msg = 'Queued: `' + str(len(
                            result['entries'])) + ' songs`'
                        await self.clientlient.send_message(
                            message.channel, msg.format(message))
                        # Else it is a single song
                    else:
                        # Get song url, title and set requester
                        url = result['webpage_url']
                        title = result['title']
                        user = message.author.mention
                        name = message.author.name
                        id = message.author.id
                        # Make sure the video title cannot break code box in message
                        if '`' in title:
                            title = title.replace('`', '\'')
                        # Add info to playlist
                        self.playlist.append({
                            'url': url,
                            'title': title,
                            'user': user,
                            'name': name,
                            'id': id
                        })
                        print(title + ' Added to queue')

                        # Tell the user the song has been queued
                        msg = 'Queued: `' + title + '`'
                        await self.client.send_message(message.channel,
                                                       msg.format(message))
                        # Soundcloud Section

            elif type == 'b':
                ytdl = youtube_dl.YoutubeDL(
                    {'playlistend': self.max_playlist_length})
                try:
                    result = ytdl.extract_info(url, download=False)
                    cont = True
                except youtube_dl.utils.DownloadError as e:
                    cont = False
                    if 'Unable to download JSON metadata' in str(e):
                        print('Invalid Bandcamp link')
                        msg = '{0.author.mention} : Not a valid Bandcamp song'
                        await self.client.send_message(message.channel,
                                                       msg.format(message))
                if cont == True:
                    url = result['webpage_url']
                    title = result['title']
                    user = message.author.mention
                    name = message.author.name
                    id = message.author.id
                    if '`' in title:
                        title = title.replace('`', '\'')
                    self.playlist.append({
                        'url': url,
                        'title': title,
                        'user': user,
                        'name': name,
                        'id': id
                    })
                    print(title + ' Added to queue')
                    msg = 'Queued: `' + title + '`'
                    await self.client.send_message(message.channel,
                                                   msg.format(message))
Exemple #19
0
def main():
    url_video = 'https://www.youtube.com/watch?v=6_YG9XBX04Y'
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download([url_video])
try:
    config = json.load(open(me + "/config.json"))
except Exception as error:
    print("config.json failed to load\n\n" + str(error))

    while True:
        time.sleep(1)

api_key = config["youtube_data_api_key"]
channel_id = str(input("Please input the *channel id* here > "))

ydl = None

try:
    if config["directory"] == "default":
        ydl = youtube_dl.YoutubeDL(
            {'outtmpl': me + '/videos/' + config["video_format"]})
    else:
        ydl = youtube_dl.YoutubeDL(
            {'outtmpl': config["directory"] + config["video_format"]})
except Exception as error:
    print("There was an error loading config directory\n\n" + str(error))

    while True:
        time.sleep(1)

# Yoinked from StackOverflow
# https://stackoverflow.com/a/44871104


def get_all_video_in_channel(channel_id):
Exemple #21
0
def play(video_uri):
    ydl_opts = {}
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download([video_uri])
Exemple #22
0
 def dl(self):
     with youtube_dl.YoutubeDL(self.ydl_opts) as ydl:
         ydl.download([self.url])
s3 = boto3.resource('s3')
transcribe = boto3.client('transcribe')
current_dir = os.getcwd()


video = "https://www.dailymotion.com/video/x7oq0ea"

extension = '\\video_temp\\%(title)s.%(ext)s'


ydl_opts = {'outtmpl': current_dir + extension,
            'forcefilename': True,
          }


with youtube_dl.YoutubeDL(ydl_opts) as ydl:

    ydl.download([video])
    info = ydl.extract_info(video, download=False)


extension = os.getcwd() + '\\video_temp\\{}.{}'.format(info['title'], 'mp4')


print("Uploading")

aws_title = info['title'].replace(" ","-")

s3.meta.client.upload_file(extension, 'amp-video-storage', aws_title + ".mp4")

objects = s3.meta.client.list_objects_v2(
Exemple #24
0
    async def inline_answer(_, inline_query: InlineQuery):
        results = []
        i_q = inline_query.query
        string = i_q.lower()  # All lower
        str_x = i_q.split(" ", 2)  # trigger @username Text
        str_y = i_q.split(" ", 1)  # trigger and Text
        string_split = string.split()  # All lower and Split each word

        if inline_query.from_user.id == Config.OWNER_ID or inline_query.from_user.id in Config.SUDO_USERS:

            if string == "syntax":
                owner = [[
                    InlineKeyboardButton(text="Contact",
                                         url="https://t.me/deleteduser420")
                ]]
                results.append(
                    InlineQueryResultPhoto(
                        photo_url=
                        "https://coverfiles.alphacoders.com/123/123388.png",
                        caption="Hey I solved **𝚂𝚢𝚗𝚝𝚊𝚡's ░ Σrr♢r**",
                        reply_markup=InlineKeyboardMarkup(owner)))

            if str_y[0] == "ytdl":
                if len(str_y) == 2:
                    link = str_y[1]
                    x = ytdl.YoutubeDL({
                        'no-playlist': True
                    }).extract_info(link, download=False)
                    formats = x.get('formats', [x])
                    ytlink_code = x.get('id', None)
                    #uploader = x.get('uploader', None)
                    #channel_url = x.get('channel_url', None)
                    vid_title = x.get('title', None)
                    #upload_date = date_formatter(str(x.get('upload_date', None)))
                    vid_thumb = get_ytthumb(ytlink_code)
                    buttons = ytdl_btn_generator(formats, ytlink_code)
                    caption_text = f"**{vid_title}**"
                    #caption_text += f"🔗 [Link]({link})  |  📅 : {upload_date}"
                    #caption_text += f"📹 : [{uploader}]({channel_url})"

                    results.append(
                        InlineQueryResultPhoto(
                            photo_url=vid_thumb,
                            title=vid_title,
                            description="⬇️ Click to Download",
                            caption=caption_text,
                            reply_markup=InlineKeyboardMarkup(buttons)))

            if string == "age_verification_alert":
                buttons = [[
                    InlineKeyboardButton(
                        text="Yes I'm 18+",
                        callback_data="age_verification_true"),
                    InlineKeyboardButton(
                        text="No I'm Not",
                        callback_data="age_verification_false")
                ]]
                results.append(
                    InlineQueryResultPhoto(
                        photo_url="https://i.imgur.com/Zg58iXc.jpg",
                        caption="**ARE YOU OLD ENOUGH FOR THIS ?**",
                        reply_markup=InlineKeyboardMarkup(buttons)))

            if str_y[0] == "reddit":
                reddit_api = "https://meme-api.herokuapp.com/gimme/"
                if len(str_y) == 2:
                    subreddit_regex = r"^([a-zA-Z]+)\.$"
                    match = re.search(subreddit_regex, str_y[1])
                    if match:
                        subreddit_name = match.group(1)
                        reddit_api += f"{subreddit_name}/30"
                    else:
                        return

                else:
                    reddit_api += "30"

                cn = requests.get(reddit_api)
                r = cn.json()
                if "code" in r:
                    bool_is_gallery = False
                    code = r['code']
                    code_message = r['message']
                    results.append(
                        InlineQueryResultArticle(
                            title=str(code),
                            input_message_content=InputTextMessageContent(
                                f"**Error Code: {code}**\n`{code_message}`"),
                            description="Enter A Valid Subreddit Name !",
                            thumb_url="https://i.imgur.com/7a7aPVa.png"))
                else:
                    bool_is_gallery = True
                    for post in r['memes']:
                        if 'url' in post:
                            postlink = post['postLink']
                            subreddit = post['subreddit']
                            title = post['title']
                            media_url = post['url']
                            author = post['author']
                            upvote = post['ups']
                            captionx = f"<b>{title}</b>\n"
                            captionx += f"`Posted by u/{author}`\n"
                            captionx += f"↕️ <code>{upvote}</code>\n"
                            thumbnail = reddit_thumb_link(post['preview'])
                            if post['spoiler']:
                                captionx += "⚠️ Post marked as SPOILER\n"
                            if post['nsfw']:
                                captionx += "🔞 Post marked Adult \n"
                            buttons = [[
                                InlineKeyboardButton(f"Source: r/{subreddit}",
                                                     url=postlink)
                            ]]
                            if media_url.endswith(".gif"):
                                results.append(
                                    InlineQueryResultAnimation(
                                        animation_url=media_url,
                                        thumb_url=thumbnail,
                                        caption=captionx,
                                        reply_markup=InlineKeyboardMarkup(
                                            buttons)))
                            else:
                                results.append(
                                    InlineQueryResultPhoto(
                                        photo_url=media_url,
                                        thumb_url=thumbnail,
                                        caption=captionx,
                                        reply_markup=InlineKeyboardMarkup(
                                            buttons)))
                await inline_query.answer(results=results,
                                          cache_time=1,
                                          is_gallery=bool_is_gallery,
                                          switch_pm_text="Available Commands",
                                          switch_pm_parameter="inline")
                return

            if string == "rick":
                rick = [[
                    InlineKeyboardButton(
                        text="🔍",
                        url="https://www.youtube.com/watch?v=dQw4w9WgXcQ")
                ]]
                results.append(
                    InlineQueryResultArticle(
                        title="Not a Rick Roll",
                        input_message_content=InputTextMessageContent(
                            "Search Results"),
                        description="Definately Not a Rick Roll",
                        thumb_url="https://i.imgur.com/hRCaKAy.png",
                        reply_markup=InlineKeyboardMarkup(rick)))

            if string == "alive":
                buttons = [[
                    InlineKeyboardButton("🔧 SETTINGS",
                                         callback_data="settings_btn"),
                    InlineKeyboardButton(text="⚡️ REPO",
                                         url=Config.UPSTREAM_REPO)
                ]]

                alive_info = f"""
    **[USERGE-X](https://telegram.dog/x_xtests) is Up and Running**

 • 🐍 Python :  `v{versions.__python_version__}`
 • 🔥 Pyrogram :  `v{versions.__pyro_version__}`
 • 🧬 𝑿 :  `v{get_version()}`

    🕔 Uptime : {userge.uptime}
"""

                if not MEDIA_URL:
                    await get_alive_()

                if MEDIA_URL:
                    if MEDIA_TYPE == 'url_gif':
                        results.append(
                            InlineQueryResultAnimation(
                                animation_url=MEDIA_URL,
                                caption=alive_info,
                                reply_markup=InlineKeyboardMarkup(buttons)))
                    elif MEDIA_TYPE == 'url_image':
                        results.append(
                            InlineQueryResultPhoto(
                                photo_url=MEDIA_URL,
                                caption=alive_info,
                                reply_markup=InlineKeyboardMarkup(buttons)))
                    elif MEDIA_TYPE == 'tg_image':
                        results.append(
                            InlineQueryResultCachedPhoto(
                                file_id=MEDIA_URL[0],
                                file_ref=MEDIA_URL[1],
                                caption=alive_info,
                                reply_markup=InlineKeyboardMarkup(buttons)))
                    else:
                        results.append(
                            InlineQueryResultCachedDocument(
                                title="USERGE-X",
                                file_id=MEDIA_URL[0],
                                file_ref=MEDIA_URL[1],
                                caption=alive_info,
                                description="ALIVE",
                                reply_markup=InlineKeyboardMarkup(buttons)))
                else:  #default
                    random_alive = random.choice(ALIVE_IMGS)
                    results.append(
                        InlineQueryResultPhoto(
                            photo_url=random_alive,
                            caption=alive_info,
                            reply_markup=InlineKeyboardMarkup(buttons)))

            if string == "geass":
                results.append(
                    InlineQueryResultAnimation(
                        animation_url="https://i.imgur.com/DeZHcRK.gif",
                        caption="To defeat evil, I must become a greater evil",
                    ))

            if string == "gapps":
                buttons = [[
                    InlineKeyboardButton("Open GApps",
                                         callback_data="open_gapps"),
                    InlineKeyboardButton("Flame GApps",
                                         callback_data="flame_gapps")
                ],
                           [
                               InlineKeyboardButton("Nik GApps",
                                                    callback_data="nik_gapps")
                           ]]
                results.append(
                    InlineQueryResultArticle(
                        title="GApps",
                        input_message_content=InputTextMessageContent(
                            "[\u200c](https://i.imgur.com/BZBMrfn.jpg) **LATEST Android 10 arm64 GApps**"
                        ),
                        description=
                        "Get Latest GApps Download Links Directly from SF",
                        thumb_url="https://i.imgur.com/Npzw8Ph.png",
                        reply_markup=InlineKeyboardMarkup(buttons)))

            if len(string_split) == 2:  #workaround for list index out of range
                if string_split[0] == "ofox":
                    codename = string_split[1]
                    t = TelegraphPoster(use_api=True)
                    t.create_api_token('Userge-X')
                    photo = "https://i.imgur.com/582uaSk.png"
                    api_host = 'https://api.orangefox.download/v2/device/'
                    try:
                        cn = requests.get(f"{api_host}{codename}")
                        r = cn.json()
                    except ValueError:
                        return
                    s = requests.get(
                        f"{api_host}{codename}/releases/stable/last").json()
                    info = f"📱 **Device**: {r['fullname']}\n"
                    info += f"👤 **Maintainer**: {r['maintainer']['name']}\n\n"
                    recovery = f"🦊 <code>{s['file_name']}</code>\n"
                    recovery += f"📅 {s['date']}\n"
                    recovery += f"ℹ️ **Version:** {s['version']}\n"
                    recovery += f"📌 **Build Type:** {s['build_type']}\n"
                    recovery += f"🔰 **Size:** {s['size_human']}\n\n"
                    recovery += "📍 **Changelog:**\n"
                    recovery += f"<code>{s['changelog']}</code>\n\n"
                    msg = info
                    msg += recovery
                    notes_ = s.get('notes')
                    if notes_:
                        notes = t.post(title='READ Notes',
                                       author="",
                                       text=notes_)
                        buttons = [[
                            InlineKeyboardButton("🗒️ NOTES", url=notes['url']),
                            InlineKeyboardButton("⬇️ DOWNLOAD", url=s['url'])
                        ]]
                    else:
                        buttons = [[
                            InlineKeyboardButton(text="⬇️ DOWNLOAD",
                                                 url=s['url'])
                        ]]

                    results.append(
                        InlineQueryResultPhoto(
                            photo_url=photo,
                            thumb_url="https://i.imgur.com/o0onLYB.jpg",
                            title="Latest OFOX RECOVERY",
                            description=f"For device : {codename}",
                            caption=msg,
                            reply_markup=InlineKeyboardMarkup(buttons)))

            if string == "repo":
                results.append(REPO_X)

            if str_x[0].lower() == "op" and len(str_x) > 1:
                txt = i_q[3:]

                opinion = os.path.join(PATH, "emoji_data.txt")
                try:
                    view_data = json.load(open(opinion))
                except:
                    view_data = False

                if view_data:
                    # Uniquely identifies an inline message
                    new_id = {int(inline_query.id): [{}]}
                    view_data.update(new_id)
                    json.dump(view_data, open(opinion, 'w'))
                else:
                    d = {int(inline_query.id): [{}]}
                    json.dump(d, open(opinion, 'w'))

                buttons = [[
                    InlineKeyboardButton(
                        "👍", callback_data=f"op_y_{inline_query.id}"),
                    InlineKeyboardButton(
                        "👎", callback_data=f"op_n_{inline_query.id}")
                ]]
                results.append(
                    InlineQueryResultArticle(
                        title="Ask For Opinion",
                        input_message_content=InputTextMessageContent(txt),
                        description=f"Q. {txt}",
                        thumb_url="https://i.imgur.com/Zlc98qS.jpg",
                        reply_markup=InlineKeyboardMarkup(buttons)))

            if string == "buttonnn":
                async for data in BUTTON_BASE.find():
                    button_data = data['msg_data']
                text, buttons = pb(button_data)
                try:
                    photo_url = data['photo_url']
                except KeyError:
                    photo_url = None
                if photo_url:
                    results.append(
                        InlineQueryResultPhoto(photo_url=photo_url,
                                               caption=text,
                                               reply_markup=buttons))
                else:
                    results.append(
                        InlineQueryResultArticle(
                            title=text,
                            input_message_content=InputTextMessageContent(
                                text),
                            reply_markup=buttons))

            if str_y[0].lower() == "stylish":
                if len(str_y) == 2:
                    results = []
                    input_text = str_y[1]
                    font_names = [
                        'serif', 'sans', 'sans_i', 'serif_i', 'medi_b', 'medi',
                        'double', 'cursive_b', 'cursive', 'bigsmall',
                        'reverse', 'circle', 'circle_b', 'mono', 'square_b',
                        'square', 'smoth', 'goth', 'wide', 'web', 'weeb',
                        'weeeb'
                    ]
                    for f_name in font_names:
                        styled_str = await font_gen(f_name, input_text)
                        results.append(
                            InlineQueryResultArticle(
                                title=f_name.upper(),
                                input_message_content=InputTextMessageContent(
                                    styled_str),
                                description=styled_str))
                    await inline_query.answer(
                        results=results,
                        cache_time=1,
                        switch_pm_text="Available Commands",
                        switch_pm_parameter="inline")
                    return

            if str_x[0].lower() == "secret":
                if len(str_x) == 3:
                    user_name = str_x[1]
                    msg = str_x[2]
                    try:
                        a = await userge.get_users(user_name)
                        user_id = a.id
                    except:
                        return
                    secret = os.path.join(PATH, "secret.txt")
                    try:
                        view_data = json.load(open(secret))
                    except:
                        view_data = False

                    if view_data:
                        # Uniquely identifies an inline message
                        new_id = {
                            str(inline_query.id): {
                                'user_id': user_id,
                                'msg': msg
                            }
                        }
                        view_data.update(new_id)
                        json.dump(view_data, open(secret, 'w'))
                    else:
                        d = {
                            str(inline_query.id): {
                                'user_id': user_id,
                                'msg': msg
                            }
                        }
                        json.dump(d, open(secret, 'w'))

                    buttons = [[
                        InlineKeyboardButton(
                            "🔐  SHOW",
                            callback_data=f"secret_{inline_query.id}")
                    ]]
                    results.append(
                        InlineQueryResultArticle(
                            title="Send A Secret Message",
                            input_message_content=InputTextMessageContent(
                                f"📩 <b>Secret Msg</b> for {user_name}. Only he/she can open it."
                            ),
                            description=f"Send Secret Message to: {user_name}",
                            thumb_url="https://i.imgur.com/c5pZebC.png",
                            reply_markup=InlineKeyboardMarkup(buttons)))
            MAIN_MENU = InlineQueryResultArticle(
                title="Main Menu",
                input_message_content=InputTextMessageContent(
                    " 𝐔𝐒𝐄𝐑𝐆𝐄-𝐗  𝗠𝗔𝗜𝗡 𝗠𝗘𝗡𝗨 "),
                url="https://github.com/code-rgb/USERGE-X",
                description="Userge-X Main Menu",
                thumb_url="https://i.imgur.com/1xsOo9o.png",
                reply_markup=InlineKeyboardMarkup(main_menu_buttons()))
            results.append(MAIN_MENU)
            if len(results) != 0:
                await inline_query.answer(results=results,
                                          cache_time=1,
                                          switch_pm_text="Available Commands",
                                          switch_pm_parameter="inline")
        else:
            results.append(REPO_X)
            owner_name = (await userge.get_me()).first_name
            await inline_query.answer(
                results=results,
                cache_time=1,
                switch_pm_text=f"This bot is only for {owner_name}",
                switch_pm_parameter="start")
Exemple #25
0

transcript_li


# In[11]:


len(transcript_list)


# In[102]:



ydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s%(ext)s'})

def metaData(element):
    if(str(element['url'])=='AaImCn4a-bI'):
        result ={}
    else:
        with ydl:
            result = ydl.extract_info(
                'https://www.youtube.com/watch?v='+str(element['url']),
                download=False # We just want to extract the info
            )
    return result


# In[4]:
import youtube_dl
import inspect

print(inspect.getdoc(youtube_dl.YoutubeDL()))
"""
YoutubeDL class.

YoutubeDL objects are the ones responsible of downloading the
actual video file and writing it to disk if the user has requested
it, among some other tasks. In most cases there should be one per
program. As, given a video URL, the downloader doesn't know how to
extract all the needed information, task that InfoExtractors do, it
has to pass the URL to one of them.

For this, YoutubeDL objects have a method that allows
InfoExtractors to be registered in a given order. When it is passed
a URL, the YoutubeDL object handles it to the first InfoExtractor it
finds that reports being able to handle it. The InfoExtractor extracts
all the information about the video or videos the URL refers to, and
YoutubeDL process the extracted information, possibly using a File
Downloader to download the video.

YoutubeDL objects accept a lot of parameters. In order not to saturate
the object constructor with arguments, it receives a dictionary of
options instead. These options are available through the params
attribute for the InfoExtractors to use. The YoutubeDL also
registers itself as the downloader in charge for the InfoExtractors
that are added to it, so this is a "mutual registration".

Available options:
Exemple #27
0
    def grabData(self):

        if self.search:
            pl_url = 'https://www.youtube.com/results?search_query=' + self.search_term.replace(
                ' ', '+')

        else:  # allow start page to be set by url rather than search term
            pl_url = self.search_term

        data = {
            'urls': [],
            'titles': [],
            'thumb_urls': [],
            'thumb_paths': [],
            'durations': [],
            'views': [],
            'ratings': [],
            'dates': [],
            'playlist_url': pl_url,
            'total_videos': 0,
            'page_title': ''
        }

        with youtube_dl.YoutubeDL(self.meta_opts) as ydl:
            meta = ydl.extract_info(pl_url, download=False)

        for e in meta['entries']:
            title = e.get('title')
            data['urls'].append('https://www.youtube.com/watch?v=' +
                                e.get('url'))
            data['titles'].append(title)

        data['total_videos'] = len(data['urls'])
        data['page_title'] = meta['title']
        data['urls'] = data['urls'][self.limit[0]:self.limit[1]]
        data['titles'] = data['titles'][self.limit[0]:self.limit[1]]

        date = time.strftime("%d-%m-%Y--%H-%M-%S")
        image_dir = '/tmp/qt/yt-thumbs/' + date + '/'
        mktmpdir(image_dir)

        self.data = data
        thread_dict = {}

        for i, u in enumerate(data['urls']):

            idx = str(i)
            worker = Worker(idx, u, image_dir=image_dir)
            thread = QThread()
            thread.setObjectName('thread_' + idx)
            worker.moveToThread(thread)

            worker.sig_data.connect(self.on_individ_data_received)

            thread.started.connect(worker.indiv_video_data)
            thread.start()
            self.__threads.append((thread, worker))
            thread_dict[idx] = thread

        for x in thread_dict:
            thread_dict[x].wait()
Exemple #28
0
def _ytDownload(url,
                location=None,
                checkFunc=None,
                resultsList=None,
                maxEntries=-1):
    """
    this is the lower level downloading func
    it shouldn't be used directly
    """
    dirAtFunStart = Easy.Cwd
    if location is None:
        location = Easy.Cwd
    nowStr = Easy.NowLocalStr()
    workDir = Easy.TmpDir(dir=location, prefix='01--working--' + nowStr)
    Easy.Cd(workDir)

    urlsExtarctedToDownload = []
    if resultsList is None:
        resultsList = []

    ret = YtResult()
    ret.attempStartTimeStr = nowStr
    ret.url = url
    ret.workDir = workDir

    try:

        ## Check for early skip
        if True:  ##'v=' in url:
            ## easiest checks are for id as parts after 'v='
            ## or just as part after last slash
            uEnd = url.split('/')[-1]
            uEnd = uEnd.split('?v=')[-1]
            uEnd = uEnd.split('&v=')[-1]
            ## if we've chopped off the end via slash or v=
            ## then if it's a simple video, it shouldn't have '?'
            ## in it
            if checkFunc is not None and not '?' in uEnd:
                if not checkFunc(uEnd):
                    #print( f'early skip: {url}' )
                    raise CheckerError('Early skip! check failed on id: ' +
                                       str(uEnd))
        tmpUrl = url
        if '&' in url:
            urlSplit = url.split('&')
            loopI = len(urlSplit) - 1
            while loopI >= 0:
                listPart = urlSplit[loopI]
                if loopI > 0 and urlSplit[loopI].startswith('list='):
                    del urlSplit[loopI]
                loopI -= 1
            tmpUrl = '&'.join(urlSplit)
        print(tmpUrl)

        ydl_opts = {
            #'merge_output_format':'mkv',
            #'extract_flat':True,
            'extractaudio': True,
            'noplaylist': True,
            #'audio_only':True,
            'restrict_filenames': True,
            #'no_overwrites':True,
            #'no_post_overwrites':True,
            'keepvideo': False,
            #'extract-audio' : True,
            'quiet': False,
            #'noplaylist':True,
            #'get_filename':True,
            #'progress_hooks': [my_hook],
            #def my_hook(d):
        }
        ydl = youtube_dl.YoutubeDL(ydl_opts)
        #pdb.set_trace()
        result = ydl.extract_info(
            tmpUrl, download=False)  ## tmpUrl to ensure not a list!
        #pdb.set_trace()
        ret.resultEx = result
        if 'entries' in result:
            raise "handling of playlists/channels is disabled currently"
            ## old playlist handling code was here, moved to end of this file for reference
        else:
            fname = ydl.prepare_filename(result)
            title = result['title']
            id = result['id']
            acodec = result['acodec']
            ext = result['acodec']
            if checkFunc is not None:
                if not checkFunc(id):
                    raise CheckerError('Check failed on id: ' + str(id))
            else:
                ret.check = True
            ## This is a hack to prevent youtube_dl from running sys.exit
            oldSysExit = sys.exit

            def fakeExit(arg):
                raise FakeExitError

            sys.exit = fakeExit
            try:
                youtube_dl.main([
                    url,
                    '--extract-audio',
                    '--no-playlis',
                ])
            except KeyboardInterrupt as err:
                oldSysExit(1)
                raise err
            except FakeExitError:
                'pass'
                #print( 'sys.exit was prevented' )
            sys.exit = oldSysExit

            ## if we were able to dl a file
            ## find name, fix name, move files
            files = Easy.Ls(Easy.Cwd)
            if not len(files):
                print(f'Error, unable to download url: {url}')
            else:
                dlFname = files[0]
                ret.dlFname = dlFname
                #print( f'dlFname: {dlFname}' )
                fixedName = Easy.Mods.re.sub(r'[^\x00-\x7f]', r'', dlFname)
                if dlFname != fixedName:
                    os.rename(dlFname, fixedName)  ## make Easy.Rename
                os.rename(fixedName, os.path.join(location, fixedName))
                ret.fname = fixedName
                ret.txtFile = os.path.join(
                    location, fixedName) + '.alreadyDownloaded.txt'
                if not os.path.exists(ret.txtFile):
                    with open(ret.txtFile, 'w') as txtFh:
                        import json
                        metadata = {}
                        metadata['date_of_dl'] = Easy.NowLocalStr()
                        metadata['title'] = title
                        json.dump(metadata, txtFh)
                        #txtFh.write( 'already downloaded' )
    ## This gets triggered if the checkFails,
    ## in which case most of the above code never runs
    ## since it would be after the CheckerError
    except CheckerError as err:
        pass
    ## Really important to handle keyboard errors! For quit with Ctrl-c
    except KeyboardInterrupt as err:
        raise err
    ## On most other errors we just continue after printing a warning
    except:
        Easy.PrintTraceback()
        print('continuing anyway...')
    finally:
        ## really important we go back to original directory!
        Easy.Cd(dirAtFunStart)
        try:
            os.rmdir(workDir)
        except:
            ## something is really wrong in this case, so we don't continue on
            print(f"Couldn't delete tmp dir: {workDir}")

        ## regardless of whether our result has much useful data in it, we add the result
        resultsList.append(ret)
        ## return the same list we were given, but modifed, with YtResult added
        return resultsList
Exemple #29
0
    async def play(self, ctx, arg_1='/', arg_2='/', arg_3='/'):
        channel = ctx.message.author.voice.channel
        music_urls = config.MUSIC_URL
        if not channel:
            await ctx.send("You are not connected to a voice channel")
            return
        voice = get(self.bot.voice_clients, guild=ctx.guild)
        if voice and voice.is_connected():
            await voice.move_to(channel)
        else:
            voice = await channel.connect()
        await self.bot.voice_clients[0].disconnect()
        if voice and voice.is_connected():
            await voice.move_to(channel)
        else:
            voice = await channel.connect()
        song = ''
        if arg_1 == '/':
            keys = random.sample(music_urls.keys(), len(music_urls))
            song = random.choice(keys)
            print(song)
        elif arg_2 == '/':
            song = arg_1
        elif arg_3 == '/':
            name = [arg_1, arg_2]
            song = '_'.join(name)
        else:
            name = [arg_1, arg_2, arg_3]
            song = '_'.join(name)

        song.title()
        for urls in music_urls:
            if song == urls:
                url = music_urls[urls]
                break
        song_there = os.path.isfile("song.wav")
        try:
            if song_there:
                os.remove("song.wav")
                print("Removed old song file")
        except PermissionError:
            print("Trying to delete song file, but it's being played")
            await ctx.send("ERROR: Music playing")
            return

        ydl_opts = {
            'format':
            'bestaudio/best',
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'wav',
                'preferredquality': '192',
            }],
        }
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            print("Downloading audio now\n")
            ydl.download([url])

        for file in os.listdir("./"):
            if file.endswith(".wav"):
                name = file
                print(f"Renamed File: {file}\n")
                os.rename(file, "song.wav")
        source = FFmpegPCMAudio('song.wav')
        player = voice.play(source)
Exemple #30
0
def download(URLs, proxy_url):
    mkdirs(os.path.expanduser('~/.DMArchive'))
    mkdirs(os.path.expanduser('~/.DMArchive/downloads'))

    ydl_opts = {
        'outtmpl':
        os.path.expanduser('~/.DMArchive/downloads/%(title)s-%(id)s.%(ext)s'),
        'download_archive':
        os.path.expanduser(
            '~/.DMArchive/.ytdlarchive'
        ),  ## I guess we will avoid doing this because it prevents failed uploads from being redone in our current system. Maybe when we turn it into an OOP library?
        'restrictfilenames':
        True,
        'verbose':
        True,  ## We only care about errors not successes, anything else is pollution
        'progress_with_newline':
        True,
        'forcetitle':
        True,
        'continuedl':
        True,
        'retries':
        9001,
        'fragment_retries':
        9001,
        'forcejson':
        True,
        'writeinfojson':
        True,
        'writedescription':
        True,
        'writethumbnail':
        True,
        'writeannotations':
        True,
        'writesubtitles':
        True,
        'allsubtitles':
        True,
        'ignoreerrors':
        True,  ## Geo-blocked, copyrighted/private/deleted will be printed to STDOUT and channel ripping will continue uninterupted, use with verbose off
        'fixup':
        'warn',  ## Slightly more verbosity for debugging problems
        'nooverwrites':
        True,  ## Don't touch what's already been downloaded, speeds things
        'consoletitle':
        True,  ## Download percentage in console title
        'prefer_ffmpeg':
        True,  ## ffmpeg is better than avconv, let's prefer it's use
        'call_home':
        True,  ## Warns on out of date youtube-dl script, helps debugging for youtube-dl devs
        'logger':
        MyLogger(),
        'progress_hooks': [my_hook]
    }

    if proxy_url is not None:  # use proxy url as argument
        ydl_opts['proxy'] = proxy_url

    # format: We don't set a default format. Youtube-dl will choose the best option for us automatically.
    # Since the end of April 2015 and version 2015.04.26 youtube-dl uses -f bestvideo+bestaudio/best as default format selection (see #5447, #5456).
    # If ffmpeg or avconv are installed this results in downloading bestvideo and bestaudio separately and muxing them together into a single file giving the best overall quality available.
    # Otherwise it falls back to best and results in downloading best available quality served as a single file.
    # best is also needed for videos that don't come from YouTube because they don't provide the audio and video in two different files.

    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        ydl.download(URLs)