Exemplo n.º 1
0
def get_video(message, n=2):
    search = SearchVideos(message.content, offset=1, mode="dict", max_results=2)
    search = search.result()
    for i in range(n):
        await message.author.send(str(search['search_result'][i]['link']))
Exemplo n.º 2
0
    async def stub_input(self, msg):
        if not self.troubleshooting:
            confidence = 100
            looping = False
            while confidence >= self.MATCH_CONFIDENCE_THRESHOLD:
                match = process.extract(msg, self.layer.keys())
                subcat = match[0][0]
                confidence = match[0][1]
                confidence_difference = match[0][1] - match[1][1]
                print("Not troubleshooting: {}".format(subcat))

                if confidence < self.MATCH_CONFIDENCE_THRESHOLD:
                    print("Low confidence {}".format(confidence))
                    if not looping:
                        await self.stub_output("Sorry, didnt get that.")
                    self.retry_counter += 1

                    if self.retry_counter > self.RETRY_LIMIT:
                        print("Too many tries")
                        await self.print_help(self.layer)
                    return
                print("{} Reset retries, confidence {}".format(
                    subcat, confidence))

                if confidence_difference < 5:
                    print("Confidence difference only {}, asking user".format(
                        confidence_difference))
                    await self.stub_output(
                        random.choice(sorry_messages).format(self.prevcat))
                    return

                self.retry_counter = 0
                self.layer = self.layer[subcat]

                if not isinstance(self.layer, dict):
                    self.troubleshooting = True
                    print(subcat)
                    await self.stub_output("Hmm.. lets try a few things")
                    return
                elif not looping:
                    await self.stub_output(
                        random.choice(sorry_messages).format(subcat))
                    self.prevcat = subcat
                looping = True

        else:  # provide troubleshooting help
            print("Troubleshooting")
            if msg == "yes":
                await self.stub_output("", img_name="happy.gif")
                await self.stub_output("Bye!")
                await self.reset()
                return

            self.current_advice_index += 1
            if self.current_advice_index < len(self.layer):
                await self.stub_output(self.layer[self.current_advice_index])
                await self.stub_output("Did that work?")
            else:
                await self.stub_output("", img_name="sad.gif")
                await self.stub_output(
                    "Sorry I'm not too sure how to help :( You can connect to a technician if the "
                    "videos below don't help.")
                search = SearchVideos(self.prevcat,
                                      offset=1,
                                      mode="dict",
                                      max_results=2)
                search = search.result()
                for i in range(2):
                    await self.stub_output(
                        str(search['search_result'][i]['link']))
Exemplo n.º 3
0
async def download_video(v_url):

    lazy = v_url
    sender = await lazy.get_sender()
    me = await lazy.client.get_me()

    if not sender.id == me.id:
        rkp = await lazy.reply("`processing...`")
    else:
        rkp = await lazy.edit("`processing...`")
    url = v_url.pattern_match.group(1)
    if not url:
        return await rkp.edit("`Error \nusage song <song name>`")
    search = SearchVideos(url, offset=1, mode="json", max_results=1)
    test = search.result()
    p = json.loads(test)
    q = p.get("search_result")
    try:
        url = q[0]["link"]
    except:
        return await rkp.edit("`failed to find`")
    type = "audio"
    await rkp.edit("`Preparing to download...`")
    if type == "audio":
        opts = {
            "format":
            "bestaudio",
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "writethumbnail":
            True,
            "prefer_ffmpeg":
            True,
            "geo_bypass":
            True,
            "nocheckcertificate":
            True,
            "postprocessors": [{
                "key": "FFmpegExtractAudio",
                "preferredcodec": "mp3",
                "preferredquality": "320",
            }],
            "outtmpl":
            "%(id)s.mp3",
            "quiet":
            True,
            "logtostderr":
            False,
        }
        video = False
        song = True
    try:
        await rkp.edit("`Fetching data, please wait..`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await rkp.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await rkp.edit("`The download content was too short.`")
        return
    except GeoRestrictedError:
        await rkp.edit(
            "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`"
        )
        return
    except MaxDownloadsReached:
        await rkp.edit("`Max-downloads limit has been reached.`")
        return
    except PostProcessingError:
        await rkp.edit("`There was an error during post processing.`")
        return
    except UnavailableVideoError:
        await rkp.edit("`Media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        await rkp.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await rkp.edit("`There was an error during info extraction.`")
        return
    except Exception as e:
        await rkp.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    if song:
        await rkp.edit(f"`Preparing to upload song:`\
        \n**{rip_data['title']}**\
        \nby *{rip_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp3",
            supports_streaming=True,
            attributes=[
                DocumentAttributeAudio(
                    duration=int(rip_data["duration"]),
                    title=str(rip_data["title"]),
                    performer=str(rip_data["uploader"]),
                )
            ],
            progress_callback=lambda d, t: asyncio.get_event_loop().
            create_task(
                progress(d, t, v_url, c_time, "Uploading..",
                         f"{rip_data['title']}.mp3")),
        )
        os.remove(f"{rip_data['id']}.mp3")
    elif video:
        await rkp.edit(f"`Preparing to upload song :`\
        \n**{rip_data['title']}**\
        \nby *{rip_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp4",
            supports_streaming=True,
            caption=url,
            progress_callback=lambda d, t: asyncio.get_event_loop().
            create_task(
                progress(d, t, v_url, c_time, "Uploading..",
                         f"{rip_data['title']}.mp4")),
        )
        os.remove(f"{rip_data['id']}.mp4")
Exemplo n.º 4
0
    async def play(self, ctx, *, search):
        """ !play "search" then pick number (ex: 1) or !play 'url' """

        if "youtube.com" in search:
            # Play from URL
            async with ctx.typing():
                result = ytdl.extract_info(search, download=False)
                
                duration = get_duration(result['duration'])
                search_list = [
                                {"link": search,
                                 "title": result['title'],
                                 "duration": duration
                                }]
            choice = 0
        else:
            # Search youtube
            search_list = []
            async with ctx.typing():
                query = SearchVideos(search, offset = 1, mode = "dict", max_results = 5)
                query_string = "```Choose a video:"
                for i in query.result()['search_result']:
                    query_string += "\n[" 
                    query_string += str(i['index'] + 1)
                    query_string += "] - " 
                    query_string += i['title']
                    query_string += " ("
                    query_string += i['duration']
                    query_string += ")"
                    info = {
                            "link": i['link'],
                            "title": i['title'],
                            "duration": i['duration']
                        }
                    search_list.append(info)

            sent_queue = await ctx.send(query_string + "```")

            # waiting for user response
            def check(m):
                return m.author.id == ctx.author.id and int(m.content) <= 5 and int(m.content) >= 1

            try:
                response = await self.bot.wait_for('message', check=check, timeout=30)
            except asyncio.TimeoutError:
                await ctx.send("**No song chosen!**")
                await sent_queue.delete()
                if response:
                    await response.delete()
                return

            choice = int(response.content) - 1
            await sent_queue.delete()
            await response.delete()
            
        # Queue and playing songs
        vc = ctx.voice_client
        if not vc.is_playing():
            async with ctx.typing():
                player = await YTDLSource.from_url(search_list[choice]['link'], loop=self.bot.loop, stream=True)
                vc.play(player, after=lambda e: print('Player error: %s' % e) if e else play_next(ctx))
            await ctx.send('**Now Playing:** {} ({})'.format(player.title, player.duration))
            self.now_playing = search_list[choice].copy()
        else:
            self.song_queue.append(search_list[choice])
            # To make sure that the original list has members in it so that both queues function normally.
            self.original_list.append(search_list[choice])
            
            await ctx.send('**Song Queued:** {} ({})'.format(search_list[choice]['title'], search_list[choice]['duration']))

        def play_next(ctx):
            # Check if queue is not empty
            if len(self.song_queue) >= 1:
                # See if there is nothing in queue
                if len(self.song_queue) <= 0:
                    asyncio.run_coroutine_threadsafe(ctx.send("**No more songs in queue.**"), self.bot.loop)
                    return

                result = asyncio.run_coroutine_threadsafe(YTDLSource.from_url(self.song_queue[0]['link'], loop=self.bot.loop, stream=True), self.bot.loop)
                player = result.result()
                try:
                    vc.play(player, after=lambda e: play_next(ctx))
                    asyncio.run_coroutine_threadsafe(ctx.send('**Now Playing:** {} ({})'.format(player.title, player.duration)), self.bot.loop)
                    self.now_playing = self.song_queue[0].copy()
                    
                    #To make sure that songs that are removed from queue are also removed from original list.
                    for i in range(len(self.original_list)):
                        if self.original_list[i]['link'] == self.now_playing['link']:
                            self.original_list.pop(i)
                            break
                    
                    del self.song_queue[0]
                except:
                    print("Something Bad Happened!")
                    pass
Exemplo n.º 5
0
async def yt_vid(client, message):
    input_str = get_text(message)
    engine = message.Engine
    type_ = "video"
    pablo = await edit_or_reply(message, engine.get_string("PROCESSING"))
    if not input_str:
        await pablo.edit(
            engine.get_string("INPUT_REQ").format("Query")
        )
        return
    _m = ('http://', 'https://')
    if "|" in input_str:
        input_str = input_str.strip()
        input_str, type_ = input_str.split("|")
    if type_ not in ['audio', 'video']:
        return await pablo.edit(engine.get_string("NEEDS_C_INPUT"))
    if input_str.startswith(_m):
        url = input_str
    else:
        await pablo.edit(engine.get_string("GETTING_RESULTS").format(input_str))
        search = SearchVideos(str(input_str), offset=1, mode="dict", max_results=1)
        if not search:
            return await pablo.edit(engine.get_string("NO_RESULTS").format(input_str))
        rt = search.result()
        result_s = rt["search_result"]
        url = result_s[0]["link"]
    try:
        yt_file, yt_data = await yt_dl(url, client, message, type_)
    except Exception as e:
        return await pablo.edit(engine.get_string("YTDL_FAILED").format(e))
    vid_title = yt_data['title']
    uploade_r = yt_data['uploader']
    yt_id = yt_data['id']
    msg = message.reply_to_message or message 
    thumb_url = f"https://img.youtube.com/vi/{yt_id}/hqdefault.jpg"
    thumb = await _dl(thumb_url)
    caption = f"**{type_.title()} Name ➠** `{vid_title}` \n**Requested For ➠** `{input_str}` \n**Channel ➠** `{uploade_r}` \n**Link ➠** `{url}`"
    c_time = time.time()
    if type_ == "video":
        await msg.reply_video(
            yt_file,
            duration=int(yt_data["duration"]),
            thumb=thumb,
            caption=caption,
            supports_streaming=True,
            progress=progress,
            progress_args=(
                pablo,
                c_time,
                f"`Uploading Downloaded Youtube File.`",
                str(yt_file),
            ),
        )
    else:
        await msg.reply_audio(
            yt_file,
            duration=int(yt_data["duration"]),
            title=str(yt_data["title"]),
            performer=uploade_r,
            thumb=thumb,
            caption=caption,
            progress=progress,
            progress_args=(
                pablo,
                c_time,
                f"`Uploading Downloaded Youtube File.`",
                str(yt_file),
            ),
        )
    await pablo.delete()
    for files in (thumb, yt_file):
        if files and os.path.exists(files):
            os.remove(files)
Exemplo n.º 6
0
async def download_video(ult):
    x = await eor(ult, "Processing..")
    url = ult.pattern_match.group(1)
    if not url:
        return await x.edit("**Error**\nUsage - `.vsong <song name>`")
    search = SearchVideos(url, offset=1, mode="json", max_results=1)
    test = search.result()
    p = json.loads(test)
    q = p.get("search_result")
    try:
        url = q[0]["link"]
    except BaseException:
        return await x.edit("`No matching songs found...`")
    type = "audio"
    await x.edit("`Preparing to download...`")
    if type == "audio":
        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:
        await x.edit("`Fetching data, please wait..`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        return await x.edit(f"`{str(DE)}`")
    except ContentTooShortError:
        return await x.edit("`The download content was too short.`")
    except GeoRestrictedError:
        return await x.edit(
            "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`"
        )
    except MaxDownloadsReached:
        return await x.edit("`Max-downloads limit has been reached.`")
    except PostProcessingError:
        return await x.edit("`There was an error during post processing.`")
    except UnavailableVideoError:
        return await x.edit("`Media is not available in the requested format.`"
                            )
    except XAttrMetadataError as XAME:
        return await x.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
    except ExtractorError:
        return await x.edit("`There was an error during info extraction.`")
    except Exception as e:
        return await x.edit(f"{str(type(e)): {str(e)}}")

    upteload = """
Uploading...
Song name - {}
By - {}
""".format(rip_data["title"], rip_data["uploader"])
    await x.edit(f"`{upteload}`")
    await ultroid_bot.send_file(
        ult.chat_id,
        f"{rip_data['id']}.mp4",
        supports_streaming=True,
        caption=
        f"⫸ Song - {rip_data['title']}\n⫸ By - {rip_data['uploader']}\n",
    )
    os.remove(f"{rip_data['id']}.mp4")
    await x.delete()
Exemplo n.º 7
0
async def play_m(client, message):
    group_call = GPC.get((message.chat.id, client.me.id))
    u_s = await edit_or_reply(message, "`Processing..`")
    input_str = get_text(message)
    if not input_str:
        if not message.reply_to_message:
            return await u_s.edit_text("`Reply To A File To PLay It.`")
        if not message.reply_to_message.audio:
            return await u_s.edit("`Reply To A File To PLay It.`")
        await u_s.edit_text("`Please Wait, Let Me Download This File!`")
        audio = message.reply_to_message.audio
        audio_original = await message.reply_to_message.download()
        vid_title = audio.title or audio.file_name
        uploade_r = message.reply_to_message.audio.performer or "Unknown Artist."
        dura_ = message.reply_to_message.audio.duration
        dur = datetime.timedelta(seconds=dura_)
        raw_file_name = (
            ''.join(random.choice(string.ascii_lowercase) for i in range(5))
            + ".raw"
        )

        url = message.reply_to_message.link
    else:
        search = SearchVideos(str(input_str), offset=1, mode="dict", max_results=1)
        rt = search.result()
        result_s = rt.get("search_result")
        if not result_s:
           return await u_s.edit(f"`No Song Found Matching With Query - {input_str}, Please Try Giving Some Other Name.`")
        url = result_s[0]["link"]
        dur = result_s[0]["duration"]
        vid_title = result_s[0]["title"]
        yt_id = result_s[0]["id"]
        uploade_r = result_s[0]["channel"]
        start = time.time()
        try:
           audio_original = await yt_dl(url, client, message, start)
        except BaseException as e:
           return await u_s.edit(f"**Failed To Download** \n**Error :** `{str(e)}`")
        raw_file_name = (
            ''.join(random.choice(string.ascii_lowercase) for i in range(5))
            + ".raw"
        )

    try:
        raw_file_name = await convert_to_raw(audio_original, raw_file_name)
    except BaseException as e:
        return await u_s.edit(f"`FFmpeg Failed To Convert Song To raw Format.` \n**Error :** `{e}`")
    if os.path.exists(audio_original):
        os.remove(audio_original)
    if not group_call:
        group_call = GroupCallFactory(client).get_file_group_call()
        group_call.song_name = vid_title
        GPC[(message.chat.id, client.me.id)] = group_call
        try:
            await group_call.start(message.chat.id)
        except BaseException as e:
            return await u_s.edit(f"**Error While Joining VC:** `{e}`")
        group_call.add_handler(playout_ended_handler, GroupCallFileAction.PLAYOUT_ENDED)
        group_call.input_filename = raw_file_name
        return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!")
    elif not group_call.is_connected:
        try:
            await group_call.start(message.chat.id)
        except BaseException as e:
            return await u_s.edit(f"**Error While Joining VC:** `{e}`")
        group_call.add_handler(playout_ended_handler, GroupCallFileAction.PLAYOUT_ENDED)
        group_call.input_filename = raw_file_name
        group_call.song_name = vid_title
        return await u_s.edit(f"Playing `{vid_title}` in `{message.chat.title}`!")
    else:
        s_d = s_dict.get((message.chat.id, client.me.id))
        f_info = {"song_name": vid_title,
                  "raw": raw_file_name,
                  "singer": uploade_r,
                  "dur": dur,
                  "url": url
                 }
        if s_d:
            s_d.append(f_info)
        else:
            s_dict[(message.chat.id, client.me.id)] = [f_info]
        s_d = s_dict.get((message.chat.id, client.me.id))
        return await u_s.edit(f"Added `{vid_title}` To Position `#{len(s_d)+1}`!")
Exemplo n.º 8
0
async def download_video(v_url):

    lazy = v_url ; sender = await lazy.get_sender() ; me = await lazy.client.get_me()

    if not sender.id == me.id:
        rkp = await lazy.reply("`memproses...`")
    else:
    	rkp = await lazy.edit("`memproses...`")   
    url = v_url.pattern_match.group(1)
    if not url:
         return await rkp.edit("`Error \n Ketik /lagu <judul laguny bro>`")
    search = SearchVideos(url, offset = 1, mode = "json", max_results = 1)
    test = search.result()
    p = json.loads(test)
    q = p.get('search_result')
    try:
       url = q[0]['link']
    except:
    	return await rkp.edit("`gagal mencari`")
    type = "audio"
    await rkp.edit("`Mencoba untuk mendownload..`")
    if type == "audio":
        opts = {
            'format':
            'bestaudio',
            'addmetadata':
            True,
            'key':
            'FFmpegMetadata',
            'writethumbnail':
            True,
            'prefer_ffmpeg':
            True,
            'geo_bypass':
            True,
            'nocheckcertificate':
            True,
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '128',
            }],
            'outtmpl':
            '%(id)s.mp3',
            'quiet':
            True,
            'logtostderr':
            False
        }
        video = False
        song = True    
    try:
        await rkp.edit("`Lagi ngambil data, tunggu bentar..`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await rkp.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await rkp.edit("`Error! Konten downloadnya kependekan.`")
        return
    except GeoRestrictedError:
        await rkp.edit(
            "`Videonya ga tersedia dinegara kita bro.`"
        )
        return
    except MaxDownloadsReached:
        await rkp.edit("`Max-downloads limit has been reached.`")
        return
    except PostProcessingError:
        await rkp.edit("`There was an error during post processing.`")
        return
    except UnavailableVideoError:
        await rkp.edit("`Media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        await rkp.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await rkp.edit("`There was an error during info extraction.`")
        return
    except Exception as e:
        await rkp.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    if song:
        await rkp.edit(f"`Mencoba mengupload lagu:`\
        \n**{rip_data['title']}**\
        \nby *{rip_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp3",
            supports_streaming=True,
            attributes=[
                DocumentAttributeAudio(duration=int(rip_data['duration']),
                                       title=str(rip_data['title']),
                                       performer=str(rip_data['uploader']))
            ],
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Lagi diupload..",
                         f"{rip_data['title']}.mp3")))
        os.remove(f"{rip_data['id']}.mp3")
    elif video:
        await rkp.edit(f"`Mencoba mengupload lagu:`\
        \n**{rip_data['title']}**\
        \nby *{rip_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp4",
            supports_streaming=True,
            caption=url,
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Lagi diupload..",
                         f"{rip_data['title']}.mp4")))
        os.remove(f"{rip_data['id']}.mp4")
Exemplo n.º 9
0
def get_video_details(id):
    search = SearchVideos(str(id), offset=1, mode="json", max_results=1)
    ytresults = search.result()
    result_dict = json.loads(ytresults)
    return result_dict
Exemplo n.º 10
0
        posts_len = 0
        os.remove(save_news)
        f = open(save_news, "w")
        f.close()
    try:
        if tesla_youtue:
            live_news = getreq(urls)
            news_titles = live_news.select('.list_news li a[title]')
            for i in reversed(news_titles):
                links.append(i.attrs['href'])
        else:
            search = SearchVideos(keywords,
                                  offset=1,
                                  mode="dict",
                                  max_results=20)
            result = search.result()
            for key in result['search_result']:
                links.append(key['link'])
                title.append(key['title'])
                img.append(key['thumbnails'][1])

        read_save_news = open(save_news, "r")  # 저장된 갤번호 읽어오기
        read_data = []
        for data in read_save_news:
            read_data.append(data.rstrip())
        read_save_news.close()

        same_gall = all(elem in read_data for elem in links)
        if same_gall:
            print("전체복사")
            if keywords == "테슬라":
Exemplo n.º 11
0
def search(arg):
    res = SearchVideos(arg, offset=1, mode="list", max_results=5)
    return res.result()
Exemplo n.º 12
0
 def get(self, name):
     try:
         search = SearchVideos(name, offset=1, mode="json", max_results=20)
         return json.loads(search.result())
     except:
         return "Fail"
Exemplo n.º 13
0
async def song(event):
    a = event.text
    if a[5] == "s":
        return
    x = await event.edit(LANG['SEARCHING'])
    url = event.pattern_match.group(1)
    if not url:
        return await x.edit(LANG['USAGE'])
    search = SearchVideos(url, offset=1, mode="json", max_results=1)
    test = search.result()
    p = json.loads(test)
    q = p.get("search_result")
    try:
        url = q[0]["link"]
    except BaseException:
        return await x.edit(LANG['NOT_FOUND'])
    type = "audio"
    await x.edit(f"`{url} Yüklənməyə hazırlanır...`")
    if type == "audio":
        opts = {
            "format":
            "bestaudio",
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "writethumbnail":
            True,
            "prefer_ffmpeg":
            True,
            "nocheckcertificate":
            True,
            "postprocessors": [{
                "key": "FFmpegExtractAudio",
                "preferredcodec": "mp3",
                "preferredquality": "320",
            }],
            "outtmpl":
            "%(id)s.mp3",
            "quiet":
            True,
            "logtostderr":
            False,
        }
    try:
        await x.edit(LANG['UPLOADİNG'])
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await x.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await x.edit("`Yüklənəcək media çox qısadır`")
        return
    except GeoRestrictedError:
        await x.edit("`Coğrafi səbəblərdən yüklənə bilmədi`")
        return
    except MaxDownloadsReached:
        await x.edit("`Max yükləmə limitini aşdınız`")
        return
    except PostProcessingError:
        await x.edit("`Bir xəta baş verdi`")
        return
    except UnavailableVideoError:
        await x.edit("`Dəstəklənməyən media tipi`")
        return
    except XAttrMetadataError as XAME:
        return await x.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
    except ExtractorError:
        return await x.edit("`Məlumatlar gətirilən zaman bir xəta baş verdu6`")
    except Exception as e:
        return await x.edit(f"{str(type(e)): {str(e)}}")
    dir = os.listdir()
    if f"{rip_data['id']}.mp3.jpg" in dir:
        thumb = f"{rip_data['id']}.mp3.jpg"
    elif f"{rip_data['id']}.mp3.webp" in dir:
        thumb = f"{rip_data['id']}.mp3.webp"
    else:
        thumb = None
    upteload = """
» {}
» {}
""".format(rip_data["title"], rip_data["uploader"])
    await x.edit(f"`{upteload}`")
    CAPT = f"» **{rip_data['title']}**\n" + LANG['UPLOADED_WITH']
    await bot.send_file(
        event.chat_id,
        f"{rip_data['id']}.mp3",
        thumb=thumb,
        supports_streaming=True,
        caption=CAPT,
        attributes=[
            DocumentAttributeAudio(
                duration=int(rip_data["duration"]),
                title=str(rip_data["title"]),
                performer=str(rip_data["uploader"]),
            )
        ],
    )
    await x.delete()
    os.remove(f"{rip_data['id']}.mp3")
    try:
        os.remove(thumb)
    except BaseException:
        pass
Exemplo n.º 14
0
async def download_video(v_url):
    approved_userss = approved_users.find({})
    for ch in approved_userss:
        iid = ch["id"]
        userss = ch["user"]
    if v_url.is_group:
        if await is_register_admin(v_url.input_chat, v_url.message.sender_id):
            pass
        elif v_url.chat_id == iid and v_url.sender_id == userss:
            pass
        else:
            return
    url = v_url.pattern_match.group(1)
    rkp = await v_url.reply("`Processing ...`")
    if not url:
        await rkp.edit("`Error \nusage video <song name>`")
    search = SearchVideos(url, offset=1, mode="json", max_results=1)
    test = search.result()
    p = json.loads(test)
    q = p.get("search_result")
    try:
        url = q[0]["link"]
    except BaseException:
        return await rkp.edit("`Failed to find that video song`")
    type = "video"
    await rkp.edit("`Preparing to download ...`")
    if type == "video":
        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,
        }
        song = False
        video = True
    try:
        await rkp.edit("`Fetching data, please wait ...`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await rkp.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await rkp.edit("`The download content was too short.`")
        return
    except GeoRestrictedError:
        await rkp.edit(
            "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`"
        )
        return
    except MaxDownloadsReached:
        await rkp.edit("`Max-downloads limit has been reached.`")
        return
    except PostProcessingError:
        await rkp.edit("`There was an error during post processing.`")
        return
    except UnavailableVideoError:
        await rkp.edit("`Media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        await rkp.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await rkp.edit("`There was an error during info extraction.`")
        return
    except Exception as e:
        await rkp.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    if video:
        await rkp.edit(f"`Sending the video song ...`")

        y = await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp4",
            supports_streaming=True,
            caption=rip_data["title"],
        )

        await y.forward_to(JULIAVSONG)
        os.system("rm -rf *.mp4")
        os.system("rm -rf *.webp")
Exemplo n.º 15
0
async def vid(client, message):
    input_str = get_text(message)
    pablo = await edit_or_reply(message, f"`Processing...`")
    if not input_str:
        await pablo.edit(
            "`Please Give Me A Valid Input. You Can Check Help Menu To Know More!`"
        )
        return
    await pablo.edit(
        f"`Getting {input_str} From Youtube Servers. Please Wait.`")
    search = SearchVideos(str(input_str), offset=1, mode="dict", max_results=1)
    rt = search.result()
    result_s = rt["search_result"]
    url = result_s[0]["link"]
    vid_title = result_s[0]["title"]
    yt_id = result_s[0]["id"]
    uploade_r = result_s[0]["channel"]
    thumb_url = f"https://img.youtube.com/vi/{yt_id}/hqdefault.jpg"
    await asyncio.sleep(0.6)
    downloaded_thumb = wget.download(thumb_url)
    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:
        with YoutubeDL(opts) as ytdl:
            ytdl_data = ytdl.extract_info(url, download=True)
    except Exception as e:
        await pablo.edit(event,
                         f"**Failed To Download** \n**Error :** `{str(e)}`")
        return
    c_time = time.time()
    file_stark = f"{ytdl_data['id']}.mp4"
    capy = f"**Video Name ➠** `{vid_title}` \n**Requested For ➠** `{input_str}` \n**Channel ➠** `{uploade_r}` \n**Link ➠** `{url}`"
    await client.send_video(
        message.chat.id,
        video=open(file_stark, "rb"),
        duration=int(ytdl_data["duration"]),
        file_name=str(ytdl_data["title"]),
        thumb=downloaded_thumb,
        caption=capy,
        supports_streaming=True,
        progress=progress,
        progress_args=(
            pablo,
            c_time,
            f"`Uploading {input_str} Song From YouTube Music!`",
            file_stark,
        ),
    )
    await pablo.delete()
    for files in (downloaded_thumb, file_stark):
        if files and os.path.exists(files):
            os.remove(files)
Exemplo n.º 16
0
    author = track.user["username"]
    title = track.title
    i = tracks.index(track) + 1
    name = ""
    #making full name
    if author in title:
        name = f"{title}"
    else:
        name = f"{author} - {title}"
    search_name = name.replace(" ", "_").replace("&", "and")
    #check if it's already downloaded
    print("_" * 100)
    if f"{search_name}.mp3" not in downloaded:
        #search on youtube to get a link
        search = SearchVideos(name, offset=1, mode="json", max_results=20)
        results = json.loads(search.result())

        if len(results["search_result"]) > 0:
            link = results["search_result"][0]["link"]
            print(f"{i}. {name} - {link}")
            urls.append(link)

            try:
                #get worse video quality xd
                print(
                    "  Finding the worst video quality (for quick download)..."
                )
                quality_data = os.popen(f"you-get -i {link}").read()
                num_of_types = round((len(quality_data.splitlines()) - 12) / 6)
                best = None
                for i in range(num_of_types):
Exemplo n.º 17
0
async def ytmusic(client, message: Message):
    global is_downloading
    if is_downloading:
        await message.reply_text(
            "Download yang lain sedang berlangsung, coba lagi nanti")
        return

    urlissed = get_text(message)

    pablo = await client.send_message(
        message.chat.id,
        f"`Mendapatkan {urlissed} dari YouTube. Mohon tunggu.`")
    if not urlissed:
        await pablo.edit(
            "Cmd perintah tidak valid, silahkan tekan /help kalo masih ga ngerti !"
        )
        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 > 10:
                await pablo.edit(
                    f"❌ Durasi vidio lagu yg lu minta {duration} menit , lu cuma bisa play vidio lagu paling lama {DURATION_LIMIT} menit... ngotak lah ajg 😁"
                )
                is_downloading = False
                return
            ytdl_data = ytdl.extract_info(url, download=True)

    except Exception as e:
        #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"**Nama Video ➠** `{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} lagu dari YouTube !`',
                       file_stark))
    await pablo.delete()
    is_downloading = False
    for files in (sedlyf, file_stark):
        if files and os.path.exists(files):
            os.remove(files)
Exemplo n.º 18
0
async def download_song(v_url):
    try:
        approved_userss = approved_users.find({})
        for ch in approved_userss:
            iid = ch["id"]
            userss = ch["user"]
        if v_url.is_group:
            if await is_register_admin(v_url.input_chat, v_url.message.sender_id):
                pass
            elif v_url.chat_id == iid and v_url.sender_id == userss:
                pass
            else:
                return
        url = v_url.pattern_match.group(1)
        rkp = await v_url.reply("`Processing ...`")
        if not url:
            await rkp.edit("`Error \nusage song <song name>`")
        search = SearchVideos(url, offset=1, mode="json", max_results=1)
        test = search.result()
        p = json.loads(test)
        q = p.get("search_result")
        try:
            url = q[0]["link"]
        except BaseException:
            return await rkp.edit("`Failed to find that song`")
        type = "audio"
        await rkp.edit("`Preparing to download ...`")
        if type == "audio":
            opts = {
                "format": "bestaudio",
                "addmetadata": True,
                "key": "FFmpegMetadata",
                "writethumbnail": True,
                "prefer_ffmpeg": True,
                "geo_bypass": True,
                "nocheckcertificate": True,
                "postprocessors": [
                    {
                        "key": "FFmpegExtractAudio",
                        "preferredcodec": "mp3",
                        "preferredquality": "320",
                    }
                ],
                "outtmpl": "%(id)s.mp3",
                "quiet": True,
                "logtostderr": False,
            }
            video = False
            song = True
        try:
            await rkp.edit("`Fetching data, please wait ...`")
            with YoutubeDL(opts) as rip:
                rip_data = rip.extract_info(url)
        except DownloadError as DE:
            await rkp.edit(f"`{str(DE)}`")
            return
        except ContentTooShortError:
            await rkp.edit("`The download content was too short.`")
            return
        except GeoRestrictedError:
            await rkp.edit(
                "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`"
            )
            return
        except MaxDownloadsReached:
            await rkp.edit("`Max-downloads limit has been reached.`")
            return
        except PostProcessingError:
            await rkp.edit("`There was an error during post processing.`")
            return
        except UnavailableVideoError:
            await rkp.edit("`Media is not available in the requested format.`")
            return
        except XAttrMetadataError as XAME:
            await rkp.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
            return
        except ExtractorError:
            await rkp.edit("`There was an error during info extraction.`")
            return
        except Exception as e:
            await rkp.edit(f"{str(type(e)): {str(e)}}")
            return
        c_time = time.time()
        if song:
            await rkp.edit(f"`Sending the song ...`")
            y = await v_url.client.send_file(
                v_url.chat_id,
                f"{rip_data['id']}.mp3",
                supports_streaming=False,
                force_document=False,
                allow_cache=False,
                attributes=[
                    DocumentAttributeAudio(
                        duration=int(rip_data["duration"]),
                        title=str(rip_data["title"]),
                        performer=str(rip_data["uploader"]),
                    )
                ],
            )
            songname = str(rip_data["title"])
            if JULIASONG:
                pass
            else:
                os.system("rm -rf *.mp3")
                os.system("rm -rf *.webp")
                os.system("rm -rf *.jpg")
                return
            suck = await ubot.get_messages(JULIASONG, limit=None)
            for c in suck:
                if not isinstance(c.message, types.MessageService):
                    if c.media != None:
                        name = c.media.document.attributes[0].title
                        if str(name) == songname:
                            os.system("rm -rf *.mp3")
                            os.system("rm -rf *.webp")
                            return
            await y.forward_to(JULIASONG)
            os.system("rm -rf *.mp3")
            os.system("rm -rf *.webp")
            os.system("rm -rf *.jpg")
    except Exception as e:
        print(e)
Exemplo n.º 19
0
async def download_video(ult):
    x = await eor(ult, "Searching...")
    url = ult.pattern_match.group(1)
    if not url:
        return await x.edit("**Error**\nUsage - `.song <song name>`")
    search = SearchVideos(url, offset=1, mode="json", max_results=1)
    test = search.result()
    p = json.loads(test)
    q = p.get("search_result")
    try:
        url = q[0]["link"]
    except BaseException:
        return await x.edit("`No matching song found...`")
    type = "audio"
    await x.edit(f"`Preparing to download {url}...`")
    if type == "audio":
        opts = {
            "format":
            "bestaudio",
            "addmetadata":
            True,
            "key":
            "FFmpegMetadata",
            "writethumbnail":
            True,
            "prefer_ffmpeg":
            True,
            "nocheckcertificate":
            True,
            "postprocessors": [{
                "key": "FFmpegExtractAudio",
                "preferredcodec": "mp3",
                "preferredquality": "320",
            }],
            "outtmpl":
            "%(id)s.mp3",
            "quiet":
            True,
            "logtostderr":
            False,
        }
    try:
        await x.edit("`Getting info...`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await x.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await x.edit("`The download content was too short.`")
        return
    except GeoRestrictedError:
        await x.edit(
            "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`"
        )
        return
    except MaxDownloadsReached:
        await x.edit("`Max-downloads limit has been reached.`")
        return
    except PostProcessingError:
        await x.edit("`There was an error during post processing.`")
        return
    except UnavailableVideoError:
        await x.edit("`Media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        return await x.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
    except ExtractorError:
        return await x.edit("`There was an error during info extraction.`")
    except Exception as e:
        return await x.edit(f"{str(type(e)): {str(e)}}")
    dir = os.listdir()
    if f"{rip_data['id']}.mp3.jpg" in dir:
        thumb = f"{rip_data['id']}.mp3.jpg"
    elif f"{rip_data['id']}.mp3.webp" in dir:
        thumb = f"{rip_data['id']}.mp3.webp"
    else:
        thumb = None
    upteload = """
Uploading...
Song name - {}
By - {}
""".format(rip_data["title"], rip_data["uploader"])
    await x.edit(f"`{upteload}`")
    await ultroid_bot.send_file(
        ult.chat_id,
        f"{rip_data['id']}.mp3",
        thumb=thumb,
        supports_streaming=True,
        caption=
        f"⫸ Song - {rip_data['title']}\n⫸ By - {rip_data['uploader']}\n",
        attributes=[
            DocumentAttributeAudio(
                duration=int(rip_data["duration"]),
                title=str(rip_data["title"]),
                performer=str(rip_data["uploader"]),
            )
        ],
    )
    await x.delete()
    os.remove(f"{rip_data['id']}.mp3")
    try:
        os.remove(thumb)
    except:
        pass
Exemplo n.º 20
0
def main(spotify_bearer, pid, out_dir, offset, use_min_dist):
    out_dir = out_dir.rstrip('/')
    if not os.path.exists(out_dir):
        os.makedirs(out_dir)
    with open(f'{out_dir}/songs', 'a+') as f:
        f.seek(0, 0)
        m = set({})
        for line in f.readlines():
            m.add(line.rstrip())
        headers1 = {'Authorization': f'Bearer {spotify_bearer}', 'Content-type': 'application/json'}
        cont = True
        offset1 = 0
        if offset:
            offset1 = offset
        while cont:
            s = http.client.HTTPSConnection("api.spotify.com")
            path = f'/v1/playlists/{pid}/tracks?market=ES&offset={offset1}'
            s.request("GET", path , headers=headers1)
            r1 = s.getresponse()
            code = r1.getcode()
            if code != 200:
                print(f'Got {code}. Probably a 401. Get a new bearer token and try again...madafaaaaka')
                return
            x1 = json.loads(r1.read().decode())
            if len(x1["items"]) < 100:
                cont = False
            for i in x1["items"]:
                try:
                    artists = " ".join([a["name"] for a in i["track"]["artists"]])
                    search = f'{artists} {i["track"]["name"]}'#.replace(" ", "%20")
                    if search in m:
                        print(f'Already downloaded {search}. Skipping')
                        continue
                    print(f'Searching for {search}')
                    r = SearchVideos(search, offset = 1, mode = "json", max_results = 20)
                    x = json.loads(r.result())
                    if len(x["search_result"]) == 0:
                        print(f'no search results for {search}')
                        continue
                    res_i = 0
                    if use_min_dist:
                        num_res = 10
                        min_dist = sys.maxsize
                        title = x["search_result"][0]["title"]
                        for i, res in enumerate(x["search_result"][:num_res]):
                            dist = editdistance.eval(search, res["title"])
                            if dist < min_dist:
                                min_dist = dist
                                res_i = i
                                title = res["title"]
                        print(f'min dist title of first {num_res} results: {title} idx {min_i}')
                    id1 = x["search_result"][res_i]["id"]
                    res = os.system(f'youtube-dlc -o \"{out_dir}/%(title)s.%(ext)s\" https://www.youtube.com/watch?v={id1} -x --audio-format \"mp3\"')
                    if res == 0 :
                        m.add(search)
                        f.write(f'{search}\n')
                except Exception as e:
                   print(f'caught exception: {e}')
            offset1 += 100
    p = subprocess.Popen(['m3ugen'], cwd=out_dir)
    p.wait()
Exemplo n.º 21
0
async def download_song(v_url):
    if v_url.is_group:
        if (await is_register_admin(v_url.input_chat,
                                    v_url.message.sender_id)):
            pass
        elif v_url.chat_id == iid and v_url.sender_id == userss:
            pass
        else:
            return
    url = v_url.pattern_match.group(1)
    rkp = await v_url.reply("`Processing ...`")
    if not url:
        await rkp.edit("`Error \nusage song <song name>`")
    search = SearchVideos(url, offset=1, mode="json", max_results=1)
    test = search.result()
    p = json.loads(test)
    q = p.get('search_result')
    try:
        url = q[0]['link']
    except BaseException:
        return await rkp.edit("`Failed to find that song`")
    type = "audio"
    await rkp.edit("`Preparing to download ...`")
    if type == "audio":
        opts = {
            'format':
            'bestaudio',
            'addmetadata':
            True,
            'key':
            'FFmpegMetadata',
            'writethumbnail':
            True,
            'prefer_ffmpeg':
            True,
            'geo_bypass':
            True,
            'nocheckcertificate':
            True,
            'postprocessors': [{
                'key': 'FFmpegExtractAudio',
                'preferredcodec': 'mp3',
                'preferredquality': '320',
            }],
            'outtmpl':
            '%(id)s.mp3',
            'quiet':
            True,
            'logtostderr':
            False
        }
        video = False
        song = True
    try:
        await rkp.edit("`Fetching data, please wait ...`")
        with YoutubeDL(opts) as rip:
            rip_data = rip.extract_info(url)
    except DownloadError as DE:
        await rkp.edit(f"`{str(DE)}`")
        return
    except ContentTooShortError:
        await rkp.edit("`The download content was too short.`")
        return
    except GeoRestrictedError:
        await rkp.edit(
            "`Video is not available from your geographic location due to geographic restrictions imposed by a website.`"
        )
        return
    except MaxDownloadsReached:
        await rkp.edit("`Max-downloads limit has been reached.`")
        return
    except PostProcessingError:
        await rkp.edit("`There was an error during post processing.`")
        return
    except UnavailableVideoError:
        await rkp.edit("`Media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        await rkp.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await rkp.edit("`There was an error during info extraction.`")
        return
    except Exception as e:
        await rkp.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    if song:
        await rkp.edit(f"`Sending the song ...`")

        y = await v_url.client.send_file(
            v_url.chat_id,
            f"{rip_data['id']}.mp3",
            supports_streaming=False,
            force_document=False,
            allow_cache=False,
            attributes=[
                DocumentAttributeAudio(duration=int(rip_data['duration']),
                                       title=str(rip_data['title']),
                                       performer=str(rip_data['uploader']))
            ])
        await y.forward_to(JULIASONG)
        os.system("rm -rf *.mp3")
        os.system("rm -rf *.webp")
from youtubesearchpython import SearchVideos, SearchPlaylists

videos = SearchVideos("NoCopyrightSounds",
                      offset=1,
                      mode="json",
                      max_results=20)
videosResult = videos.result()
print(videosResult)

playlists = SearchPlaylists("NoCopyrightSounds",
                            offset=1,
                            mode="json",
                            max_results=20)
playlistsResult = playlists.result()
print(playlistsResult)
Exemplo n.º 23
0
async def youtube(msg):
    if msg.get('text'):

        if msg['text'].startswith('/yt '):
            pesquisar = msg['text'][4:]
            search = SearchVideos(pesquisar,
                                  offset=1,
                                  mode="dict",
                                  max_results=10)
            resultado = search.result()
            #titulo = []
            #link = []
            dic_youtube = []
            for resultado in resultado['search_result']:
                titulo_captado = resultado['title']
                link_captado = resultado['link']
                #titulo.append(titulo_captado)
                #link.append(link_captado)
                dic = {'titulo': titulo_captado, 'url': link_captado}
                dic_youtube.append(dic)
            vids = [
                '[{}] {} {}'.format(num + 1, i['titulo'], i['url'])
                for num, i in enumerate(dic_youtube)
            ]
            await bot.sendMessage(
                msg['chat']['id'],
                '\n'.join(vids) if vids else "Nenhum resultado foi encontrado",
                'HTML',
                reply_to_message_id=msg['message_id'],
                disable_web_page_preview=True)
            #return True

        if msg['text'].startswith('youtube '):
            pesquisar = msg['text'][8:]
            search = SearchVideos(pesquisar,
                                  offset=1,
                                  mode="dict",
                                  max_results=10)
            resultado = search.result()
            # titulo = []
            # link = []
            dic_youtube = []
            for resultado in resultado['search_result']:
                titulo_captado = resultado['title']
                link_captado = resultado['link']
                # titulo.append(titulo_captado)
                # link.append(link_captado)
                dic = {'titulo': titulo_captado, 'url': link_captado}
                dic_youtube.append(dic)
            vids = [
                '[{}] {} {}'.format(num + 1, i['titulo'], i['url'])
                for num, i in enumerate(dic_youtube)
            ]
            await bot.sendMessage(
                msg['chat']['id'],
                '\n'.join(vids) if vids else "Nenhum resultado foi encontrado",
                'HTML',
                reply_to_message_id=msg['message_id'],
                disable_web_page_preview=True)

#----------------------------------------------------------------------------------------------------------------------------------------------

        elif msg['text'].split(
        )[0] == '/ytdl':  #aqui era /ytdl tirei pra nao pesar o server

            text = msg['text'][6:]

            if text:
                sent_id = (await bot.sendMessage(
                    msg['chat']['id'],
                    'Obtendo informações do vídeo...',
                    'Markdown',
                    reply_to_message_id=msg['message_id']))['message_id']
                try:
                    if re.match(
                            r'^(https?://)?(youtu\.be/|(m\.|www\.)?youtube\.com/watch\?v=).+',
                            text):
                        yt = ydl.extract_info(text, download=False)
                    else:
                        yt = ydl.extract_info('ytsearch:' + text,
                                              download=False)['entries'][0]
                    for f in yt['formats']:
                        if f['format_id'] == '140':
                            fsize = f['filesize'] or 0
                    name = yt['title']
                except Exception as e:
                    return await bot.editMessageText(
                        (msg['chat']['id'], sent_id),
                        'Ocorreu um erro.\n\n' + str(e))
                if not fsize > 52428800:
                    if ' - ' in name:
                        performer, title = name.rsplit(' - ', 1)
                    else:
                        performer = yt.get('creator') or yt.get('uploader')
                        title = name
                    await bot.editMessageText(
                        (msg['chat']['id'], sent_id),
                        'Baixando <code>{}</code> do YouTube...\n({})'.format(
                            name, pretty_size(fsize)), 'HTML')
                    ydl.download(
                        ['https://www.youtube.com/watch?v=' + yt['id']])
                    await bot.editMessageText((msg['chat']['id'], sent_id),
                                              'Enviando áudio...')
                    await bot.sendChatAction(msg['chat']['id'],
                                             'upload_document')
                    await bot.sendAudio(msg['chat']['id'],
                                        open(ydl.prepare_filename(yt), 'rb'),
                                        performer=performer,
                                        title=title,
                                        duration=yt['duration'],
                                        reply_to_message_id=msg['message_id'])
                    os.remove(ydl.prepare_filename(yt))
                    await bot.deleteMessage((msg['chat']['id'], sent_id))
                else:
                    await bot.editMessageText((
                        msg['chat']['id'], sent_id
                    ), f'Ow, o arquivo resultante ({pretty_size(fsize)}) ultrapassa o meu limite de 50 MB'
                                              )

            else:
                await bot.sendMessage(msg['chat']['id'],
                                      '*Uso:* /ytdl URL do vídeo ou nome',
                                      'Markdown',
                                      reply_to_message_id=msg['message_id'])

            return True

        elif msg['text'].split()[0] == '':  #aqui era ytldl gorpo tirei tb
            text = msg['text'][17:]

            if text:
                sent_id = (await bot.sendMessage(
                    msg['chat']['id'],
                    'Obtendo informações do vídeo...',
                    'Markdown',
                    reply_to_message_id=msg['message_id']))['message_id']
                try:
                    if re.match(
                            r'^(https?://)?(youtu\.be/|(m\.|www\.)?youtube\.com/watch\?v=).+',
                            text):
                        yt = ydl.extract_info(text, download=False)
                    else:
                        yt = ydl.extract_info('ytsearch:' + text,
                                              download=False)['entries'][0]
                    for f in yt['formats']:
                        if f['format_id'] == '140':
                            fsize = f['filesize'] or 0
                    name = yt['title']
                except Exception as e:
                    return await bot.editMessageText(
                        (msg['chat']['id'], sent_id),
                        'Ocorreu um erro.\n\n' + str(e))
                if not fsize > 52428800:
                    if ' - ' in name:
                        performer, title = name.rsplit(' - ', 1)
                    else:
                        performer = yt.get('creator') or yt.get('uploader')
                        title = name
                    await bot.editMessageText(
                        (msg['chat']['id'], sent_id),
                        'Baixando <code>{}</code> do YouTube...\n({})'.format(
                            name, pretty_size(fsize)), 'HTML')
                    ydl.download(
                        ['https://www.youtube.com/watch?v=' + yt['id']])
                    await bot.editMessageText((msg['chat']['id'], sent_id),
                                              'Enviando áudio...')
                    await bot.sendChatAction(msg['chat']['id'],
                                             'upload_document')
                    await bot.sendAudio(msg['chat']['id'],
                                        open(ydl.prepare_filename(yt), 'rb'),
                                        performer=performer,
                                        title=title,
                                        duration=yt['duration'],
                                        reply_to_message_id=msg['message_id'])
                    os.remove(ydl.prepare_filename(yt))
                    await bot.deleteMessage((msg['chat']['id'], sent_id))
                else:
                    await bot.editMessageText((
                        msg['chat']['id'], sent_id
                    ), f'Ow, o arquivo resultante ({pretty_size(fsize)}) ultrapassa o meu limite de 50 MB'
                                              )

            else:
                await bot.sendMessage(msg['chat']['id'],
                                      '*Uso:* /ytdl URL do vídeo ou nome',
                                      'Markdown',
                                      reply_to_message_id=msg['message_id'])

            return True

        elif msg['text'].startswith('download youtube'):
            text = msg['text'][17:]

            if text:
                sent_id = (await bot.sendMessage(
                    msg['chat']['id'],
                    'Obtendo informações do vídeo...',
                    'Markdown',
                    reply_to_message_id=msg['message_id']))['message_id']
                try:
                    if re.match(
                            r'^(https?://)?(youtu\.be/|(m\.|www\.)?youtube\.com/watch\?v=).+',
                            text):
                        yt = ydl.extract_info(text, download=False)
                    else:
                        yt = ydl.extract_info('ytsearch:' + text,
                                              download=False)['entries'][0]
                    for f in yt['formats']:
                        if f['format_id'] == '140':
                            fsize = f['filesize'] or 0
                    name = yt['title']
                except Exception as e:
                    return await bot.editMessageText(
                        (msg['chat']['id'], sent_id),
                        'Ocorreu um erro.\n\n' + str(e))
                if not fsize > 52428800:
                    if ' - ' in name:
                        performer, title = name.rsplit(' - ', 1)
                    else:
                        performer = yt.get('creator') or yt.get('uploader')
                        title = name
                    await bot.editMessageText(
                        (msg['chat']['id'], sent_id),
                        'Baixando <code>{}</code> do YouTube...\n({})'.format(
                            name, pretty_size(fsize)), 'HTML')
                    ydl.download(
                        ['https://www.youtube.com/watch?v=' + yt['id']])
                    await bot.editMessageText((msg['chat']['id'], sent_id),
                                              'Enviando áudio...')
                    await bot.sendChatAction(msg['chat']['id'],
                                             'upload_document')
                    await bot.sendAudio(msg['chat']['id'],
                                        open(ydl.prepare_filename(yt), 'rb'),
                                        performer=performer,
                                        title=title,
                                        duration=yt['duration'],
                                        reply_to_message_id=msg['message_id'])
                    os.remove(ydl.prepare_filename(yt))
                    await bot.deleteMessage((msg['chat']['id'], sent_id))
                else:
                    await bot.editMessageText((
                        msg['chat']['id'], sent_id
                    ), f'Ow, o arquivo resultante ({pretty_size(fsize)}) ultrapassa o meu limite de 50 MB'
                                              )

            else:
                await bot.sendMessage(msg['chat']['id'],
                                      '*Uso:* /ytdl URL do vídeo ou nome',
                                      'Markdown',
                                      reply_to_message_id=msg['message_id'])

            return True
Exemplo n.º 24
0
async def owo(client, inline_query):
    string_given = inline_query.query.lower()
    if string_given.startswith("not4u"):
        if not ";" in string_given:
            return
        ok = string_given.split(" ", maxsplit=1)[1]
        user, msg = ok.split(";")
        fu = int(user) if user.isdigit() else user
        try:
            ui = await Friday.get_users(fu)
        except BaseException as e:
            logging.error(traceback.format_exc)
            return
        chars = string.hexdigits
        randomc = "".join(choice(chars) for _ in range(4))
        stark_data = {"secret_code": randomc, "id": ui.id, "msg": msg}
        db_s.insert(stark_data)
        texts = f"Everyone except {user.mention(style='md')} can read this message. \nClick below to check the message! \n**Note :** `Only He/She Can't open it!`"
        ok_s = [(results.append(
            title="OwO! Not For You",
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton(text="Show Message !",
                                     callback_data=f"nu_{randomc}")
            ]]),
            input_message_content=InputTextMessageContent(texts),
        ))]
        await client.answer_inline_query(inline_query.id,
                                         cache_time=0,
                                         results=ok_s)
    elif string_given.startswith("yt"):
        results = []
        try:
            input = string_given.split(" ", maxsplit=1)[1]
        except:
            return
        search = SearchVideos(str(input),
                              offset=1,
                              mode="dict",
                              max_results=50)
        rt = search.result()
        result_s = rt["search_result"]
        for i in result_s:
            url = i["link"]
            vid_title = i["title"]
            yt_id = i["id"]
            uploade_r = i["channel"]
            views = i["views"]
            thumb = f"https://img.youtube.com/vi/{yt_id}/hqdefault.jpg"
            capt = f"""
**Video Title :** `{vid_title}`
**Link :** `{url}`
**Uploader :** `{uploade_r}`
**Views :** `{views}`
            """
            results.append(
                InlineQueryResultPhoto(
                    photo_url=thumb,
                    title=vid_title,
                    caption=capt,
                    reply_markup=InlineKeyboardMarkup([[
                        InlineKeyboardButton(
                            text="Download - Audio",
                            callback_data=f"ytdl_{url}_audio"),
                        InlineKeyboardButton(text="Download - Video",
                                             callback_data=f"ytdl_{url}_video")
                    ]]),
                ))
        await client.answer_inline_query(inline_query.id,
                                         cache_time=0,
                                         results=results)
    elif string_given.startswith("git"):
        try:
            input_ = string_given.split(" ", maxsplit=1)[1]
        except:
            return
        results = []
        r = requests.get("https://api.github.com/search/repositories",
                         params={"q": input_})
        lool = r.json()
        if lool.get("total_count") == 0:
            return
        lol = lool.get("items")
        for X in lol:
            qw = X
            txt = f"""
<b>Name :</b> <i>{qw.get("name")}</i>
<b>Full Name :</b> <i>{qw.get("full_name")}</i>
<b>Link :</b> {qw.get("html_url")}
<b>Fork Count :</b> <i>{qw.get("forks_count")}</i>
<b>Open Issues :</b> <i>{qw.get("open_issues")}</i>
"""
            if qw.get("description"):
                txt += f'\n<b>Description :</b> <code>{qw.get("description")}</code>'
            if qw.get("language"):
                txt += f'\n<b>Language :</b> <code>{qw.get("language")}</code>'
            if qw.get("size"):
                txt += f'\n<b>Size :</b> <code>{qw.get("size")}</code>'
            if qw.get("score"):
                txt += f'\n<b>Score :</b> <code>{qw.get("score")}</code>'
            if qw.get("created_at"):
                txt += f'\n<b>Created At :</b> <code>{qw.get("created_at")}</code>'
            if qw.get("archived") == True:
                txt += f"\n<b>This Project is Archived</b>"

            results.append(
                InlineQueryResultArticle(
                    thumb_url="https://simpleicons.org/icons/github.svg",
                    url=qw.get("html_url"),
                    description=qw.get("description", "No Description"),
                    title=qw.get("name"),
                    input_message_content=InputTextMessageContent(
                        txt, disable_web_page_preview=True)))
        await client.answer_inline_query(inline_query.id,
                                         cache_time=0,
                                         results=results)
    elif string_given.startswith("whisper"):
        if not ";" in string_given:
            return
        ok = string_given.split(" ", maxsplit=1)[1]
        user, msg = ok.split(";")
        fu = int(user) if user.isdigit() else user
        try:
            ui = await Friday.get_users(fu)
        except BaseException as e:
            logging.error(str(e))
            return
        owo = (f"@{ui.username}"
               if ui.username else f"[{ui.first_name}](tg://user?id={ui.id})")
        chars = string.hexdigits
        randomc = "".join(choice(chars) for _ in range(4))
        stark_data = {"secret_code": randomc, "id": ui.id, "msg": msg}
        db_m.insert(stark_data)
        texts = f"A Whisper Has Been Sent For {owo} . \nClick Below To Check Message! \n**Note :** `Only He/She Can Open It!`"
        ok_s = [(InlineQueryResultArticle(
            title="Ssh! This is A Secret Message",
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton(text="Show Message !",
                                     callback_data=f"sc_{randomc}")
            ]]),
            input_message_content=InputTextMessageContent(texts),
        ))]
        await client.answer_inline_query(inline_query.id,
                                         cache_time=0,
                                         results=ok_s)
    elif string_given.startswith("help"):
        total_ = len(CMD_LIST)
        if Config.LOAD_UNOFFICIAL_PLUGINS:
            total_ = len(XTRA_CMD_LIST) + len(CMD_LIST)
        nice_text = f"**FridayUserBot Commands** \n**Friday Version :** __{friday_version}__ \n**PyroGram Version :** __{__version__}__ \n**Total Plugins Loaded :** __{total_}__"
        await inline_query.answer(
            cache_time=0,
            results=[(InlineQueryResultArticle(
                title="Help Article!",
                reply_markup=InlineKeyboardMarkup(HELP_BUTTONS),
                input_message_content=InputTextMessageContent(nice_text),
            ))],
        )
Exemplo n.º 25
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 > 8:
                await pablo.edit(
                    f"❌ Videos longer than 8 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 as e:
        #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)
Exemplo n.º 26
0
async def download_video(v_url):
    pro = v_url
    sender = await pro.get_sender()
    me = await pro.client.get_me()
    pro1 = v_url.text
    if not sender.id == me.id:
        dc = await pro.reply("`processing, please weit...`")
    else:
        dc = await pro.edit("`processing, please weit...😍`")
    teamcobra = pro1[8:]
    if not teamcobra:
        return await dc.edit("`Error \nusage vsong <song name>`")
    search = SearchVideos(teamcobra, offset=1, mode="json", max_results=1)
    test = search.result()
    p = json.loads(test)
    q = p.get('search_result')
    try:
        teamcobra = q[0]['link']
    except:
        return await dc.edit("`failed to find your desired song`")
    type = "audio"
    await dc.edit("`Ok downloading your song🤓...`")
    if type == "audio":
        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
        }
        song = False
        video = True
    try:
        await dc.edit("`Fetching data, please wait..😋😍😎`")
        with YoutubeDL(opts) as darkcobra:
            darkcobra_data = darkcobra.extract_info(teamcobra)
    except DownloadError as error:
        await dc.edit(f"`{str(error)}`")
        return
    except ContentTooShortError:
        await dc.edit("`Oof the download content was too short😮🤐.`")
        return
    except GeoRestrictedError:
        await dc.edit(
            "`Video is not available from your geographic location due to geographic restrictions imposed by a website🤔.`"
        )
        return
    except MaxDownloadsReached:
        await dc.edit("`Max-downloads limit has been reached😶.`")
        return
    except PostProcessingError:
        await dc.edit("`There was an error during post processing😐.`")
        return
    except UnavailableVideoError:
        await dc.edit(
            "`sorry, media is not available in the requested format.`")
        return
    except XAttrMetadataError as XAME:
        await dc.edit(f"`{XAME.code}: {XAME.msg}\n{XAME.reason}`")
        return
    except ExtractorError:
        await dc.edit("`There was an error while fetching your query...`")
        return
    except Exception as e:
        await dc.edit(f"{str(type(e)): {str(e)}}")
        return
    c_time = time.time()
    if song:
        await dc.edit(f"`Preparing to upload your video song😎 `\
        \n**{darkcobra_data['title']}**\
        \nby *{darkcobra_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{darkcobra_data['id']}.mp3",
            supports_streaming=True,
            attributes=[
                DocumentAttributeAudio(
                    duration=int(darkcobra_data['duration']),
                    title=str(darkcobra_data['title']),
                    performer=str(darkcobra_data['uploader']))
            ],
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Uploading your video song😍..",
                         f"{darkcobra_data['title']}.mp3")))
        os.remove(f"{darkcobra_data['id']}.mp3")
        await v_url.delete()
    elif video:
        await dc.edit(f"`Preparing to upload your video song🤗❤ :`\
        \n**{darkcobra_data['title']}**\
        \nby *{darkcobra_data['uploader']}*")
        await v_url.client.send_file(
            v_url.chat_id,
            f"{darkcobra_data['id']}.mp4",
            supports_streaming=True,
            caption=darkcobra_data['title'],
            progress_callback=lambda d, t: asyncio.get_event_loop(
            ).create_task(
                progress(d, t, v_url, c_time, "Uploading..",
                         f"{darkcobra_data['title']}.mp4")))
        os.remove(f"{darkcobra_data['id']}.mp4")
        await dc.delete()
Exemplo n.º 27
0
     query = query.replace("wikipedia", "")
     print(query)
     results = wikipedia.summary(query, sentences=2)
     speak("According to Wikipedia")
     print(results)
     speak(results)
 elif "open youtube" in query:
     webbrowser.open("youtube.com")
 elif "open stackoverflow" in query:
     webbrowser.open("stackoverflow.com")
 elif "play" and "in youtube" in query:
     speak("Please Wait")
     query = query.replace("in youtube", "")
     print(query)
     search1 = SearchVideos(query, offset=1, mode="json", max_results=5)
     results = search1.result()
     results = json.loads(results)
     link = results["search_result"][0]["link"]
     webbrowser.open(link)
 elif "open google" in query:
     webbrowser.open("google.com")
 elif 'the time' in query:
     strTime = datetime.datetime.now().strftime("%H:%M:%S")
     speak(f"Sir, the time is {strTime}")
 elif "mail" in query:
     try:
         speak("Please tell me the receipent")
         to = takeCommand()
         speak("What should I write in mail?")
         content = takeCommand()
         sendEmail(to, content)
Exemplo n.º 28
0
async def _(event):
    if event.fwd_from:
        return
    urlissed = event.pattern_match.group(1)
    myself_stark = await edit_or_reply(
        event, f"`Getting {urlissed} From Youtube Servers. Please Wait.`")
    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)
    if not os.path.isdir("./music/"):
        os.makedirs("./music/")
    path = Config.TMP_DOWNLOAD_DIRECTORY
    url = mo
    sedlyf = wget.download(kekme, out=path)
    opts = {
        "format":
        "bestaudio",
        "addmetadata":
        True,
        "key":
        "FFmpegMetadata",
        "writethumbnail":
        True,
        "prefer_ffmpeg":
        True,
        "geo_bypass":
        True,
        "nocheckcertificate":
        True,
        "postprocessors": [{
            "key": "FFmpegExtractAudio",
            "preferredcodec": "mp3",
            "preferredquality": "480",
        }],
        "outtmpl":
        "%(title)s.mp3",
        "quiet":
        True,
        "logtostderr":
        False,
    }
    try:
        with YoutubeDL(opts) as ytdl:
            ytdl_data = ytdl.extract_info(url)
    except Exception as e:
        await event.edit(f"**Failed To Download** \n**Error :** `{str(e)}`")
        return
    await asyncio.sleep(20)
    c_time = time.time()
    file_stark = f"{ytdl_data['title']}.mp3"
    lol_m = await upload_file(
        file_name=file_stark,
        client=borg,
        file=open(file_stark, "rb"),
        progress_callback=lambda d, t: asyncio.get_event_loop().create_task(
            progress(d, t, event, c_time, "Uploading Your Song!", file_stark)),
    )
    capy = f"**Song Name ➠** `{thum}` \n**Requested For ➠** `{urlissed}` \n**Channel ➠** `{thums}` \n**Link ➠** `{mo}`"
    await event.delete()
    await borg.send_file(
        event.chat_id,
        lol_m,
        force_document=False,
        allow_cache=False,
        caption=capy,
        thumb=sedlyf,
        attributes=[
            DocumentAttributeAudio(
                duration=int(ytdl_data["duration"]),
                title=str(ytdl_data["title"]),
                performer=str(ytdl_data["uploader"]),
            )
        ],
        supports_streaming=True,
    )
    for files in (sedlyf, file_stark):
        if files and os.path.exists(files):
            os.remove(files)
Exemplo n.º 29
0
async def ytmusic(client, message: Message):
    urlissed = get_text(message)
    if not urlissed:
        await client.send_message(
            message.chat.id,
            "Invalid Command Syntax, Please Check Help Menu To Know More!",
        )
        return
    pablo = await client.send_message(
        message.chat.id,
        f"`Getting {urlissed} From Youtube Servers. Please Wait.`")
    search = SearchVideos(f"{urlissed}", offset=1, mode="dict", max_results=1)
    mi = search.result()
    mio = mi["search_result"]
    mo = mio[0]["link"]
    mio[0]["duration"]
    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)
    sedlyf = wget.download(kekme)
    opts = {
        "format":
        "bestaudio",
        "addmetadata":
        True,
        "key":
        "FFmpegMetadata",
        "writethumbnail":
        True,
        "prefer_ffmpeg":
        True,
        "geo_bypass":
        True,
        "nocheckcertificate":
        True,
        "postprocessors": [{
            "key": "FFmpegExtractAudio",
            "preferredcodec": "mp3",
            "preferredquality": "720",
        }],
        "outtmpl":
        "%(id)s.mp3",
        "quiet":
        True,
        "logtostderr":
        False,
    }
    try:
        with YoutubeDL(opts) as ytdl:
            ytdl_data = ytdl.extract_info(mo, download=True)
    except Exception as e:
        await pablo.edit(f"**Failed To Download** \n**Error :** `{str(e)}`")
        return
    c_time = time.time()
    capy = f"**🎼 Uploaded by ➠ 𝙉𝙪𝙧𝙖 𝙙𝙖𝙧𝙡𝙞𝙣𝙜 🖤**"
    file_stark = f"{ytdl_data['id']}.mp3"
    await client.send_audio(
        message.chat.id,
        audio=open(file_stark, "rb"),
        duration=int(ytdl_data["duration"]),
        title=str(ytdl_data["title"]),
        performer=str(ytdl_data["uploader"]),
        thumb=sedlyf,
        caption=capy,
        progress=progress,
        progress_args=(
            pablo,
            c_time,
            f"`Uploading {urlissed} Song From YouTube Music!`",
            file_stark,
        ),
    )
    await pablo.delete()
    for files in (sedlyf, file_stark):
        if files and os.path.exists(files):
            os.remove(files)
Exemplo n.º 30
0
async def ytmusic(client, message: Message):
    global is_downloading
    if is_downloading:
        await message.reply_text(
            "Unduhan yang lain sedang berlangsung, coba lagi nanti.")
        return

    urlissed = get_text(message)

    pablo = await client.send_message(
        message.chat.id,
        f"`Mendownload {urlissed} dari youtube, tunggu sebentar!`")
    if not urlissed:
        await pablo.edit(
            "Sintax, Perintah tidak valid. Silahkan periksa menu help untuk mengetahui lebih lanjut!"
        )
        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 > 8:
                await pablo.edit(
                    f"❌ Video berdurasi lebih dari 8 menit tidak diperbolehkan, video yang diperbolehkan berdurasi {duration} minute(s)"
                )
                is_downloading = False
                return
            ytdl_data = ytdl.extract_info(url, download=True)

    except Exception as e:
        #await pablo.edit(event, f"**Gagal mengunduh** \n**Terjadi kesalahan :** `{str(e)}`")
        is_downloading = False
        return

    c_time = time.time()
    file_stark = f"{ytdl_data['id']}.mp4"
    capy = f"**Judul video :** `{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)