Example #1
0
async def songs(ctx):
    l = len(song_url)
    if (l == 0):
        await ctx.send("No music to play")
    for i in range(0, l):
        videosSearch = VideosSearch(song_url[i], limit=1)
        result_song_list = videosSearch.result()
        # print(result_song_list)
        title_song = result_song_list['result'][0]['title']
        text = discord.Embed(
            description=f"{i+1}# Song Name : {title_song} ",
            color=53380,
        )
        text.set_author(
            name="Discord_music_bot",
            icon_url=
            "https://static.vecteezy.com/system/resources/thumbnails/000/371/212/small/1781.jpg"
        )
        await ctx.send(embed=text)
Example #2
0
def get_youtube_search(query: str, append_audio: bool):
    results = VideosSearch(f"{query} audio" if append_audio else query,
                           limit=5).result()

    return [{
        "title": res["title"],
        "channel": res["channel"]["name"],
        "duration": res["duration"],
        "link": res["link"],
    } for res in results["result"]]
Example #3
0
async def search(client, query):
    answers = []
    string = query.query.lower().strip().rstrip()

    if string == "":
        await client.answer_inline_query(
            query.id,
            results=answers,
            switch_pm_text=_("inline_1"),
            switch_pm_parameter="help",
            cache_time=0
        )
        return
    else:
        videosSearch = VideosSearch(string.lower(), limit=50)
        for v in videosSearch.result()["result"]:
            answers.append(
                InlineQueryResultArticle(
                    title=v["title"],
                    description=_("inline_2").format(
                        v["duration"],
                        v["viewCount"]["short"]
                    ),
                    input_message_content=InputTextMessageContent(
                        "https://www.youtube.com/watch?v={}".format(
                            v["id"]
                        )
                    ),
                    thumb_url=v["thumbnails"][0]["url"]
                )
            )
        try:
            await query.answer(
                results=answers,
                cache_time=0
            )
        except errors.QueryIdInvalid:
            await query.answer(
                results=answers,
                cache_time=0,
                switch_pm_text=_("inline_3"),
                switch_pm_parameter="",
            )
Example #4
0
            def Youtube(self):
                videosSearch = VideosSearch(motcle, limit=50)
                for keys, values in videosSearch.result().items():
                    res = values[0:11]
                    link_list = []
                    i = 0
                    while i < 10:
                        res1 = res[i]
                        for key, value in res1.items():
                            if key == 'link':
                                link_list.append(value)
                                i += 1

                    label = tk.Label(
                        self,
                        text=
                        "Les dix premiers résultats de la recherche avec le mot clé ''"
                        + motcle + "'' sont :\n\n",
                        justify=LEFT,
                        anchor=NE)
                    label.grid(column=3, sticky="NE", padx=800)
                    label.place(x=300, relx=0.8, rely=0.15, anchor=NE)

                    passortie = 0.2
                    j = 1
                    for i in link_list:
                        print(i + "\n")
                        label1 = tk.Label(self,
                                          text="Sortie " + str(j) + " : " + i +
                                          "\n",
                                          justify=LEFT,
                                          anchor=NE)
                        label1.grid(column=3, sticky="NE", padx=800)
                        label1.place(x=300,
                                     relx=0.8,
                                     rely=passortie,
                                     anchor=NE)
                        passortie += 0.05
                        # Get first result
                        if j == 1:
                            global url_firstvideo
                            url_firstvideo = i
                        j += 1
Example #5
0
async def play_music(channel, voice_client, search_str=None, key=True):
    # channel = ctx.message.channel
    if voice_client.is_playing() == True:
        if key == False:
            await channel.send(p.messages['erro'][1])
        pass
    else:
        if key == True:
            song_url = p.cucaracha[0]
            titulo = p.cucaracha[1]
        else:
            video_search = VideosSearch(search_str, limit=2)
            song_url = video_search.result()['result'][0]['link']
            titulo = video_search.result()['result'][0]['title']
        with youtube_dl.YoutubeDL(p.ydl_opts) as ydl:
            song_info = ydl.extract_info(song_url, download=False)
        voice_client.play(discord.FFmpegPCMAudio(
            song_info["formats"][0]["url"], **p.FFMPEG_OPTIONS),
                          after=lambda e: print('done'))
        await channel.send(p.messages['musica'][0].format(titulo))
Example #6
0
def searchyoutube():
    a = input("Enter items to be searched :")
    b = int(input("Enter number of results you want to search :"))
    videosSearch = VideosSearch(a, limit=b)
    x = videosSearch.result()
    for r in x:
        l = x[r]
        for i in range(b):
            j = str(i)
            m = l[i]
            n = m['channel']
            p = n['name']
            o = m['title']
            print()
            print(j + ')' + 'channel name :' + p + '\n' + 'Videoname :' + o +
                  '\n' + 'link :' + m['link'])
        s = int(input("\nEnter number :"))
        t = l[s]
        u = t['link']
        return u
Example #7
0
def queryKeywordPlus(keyword, count):
    """Query video title, URL and duration
    """

    result = VideosSearch(keyword, limit=count)
    resultParsed = {}

    i = 1
    for r in result.result()['result']:
        resultParsed[str(i)] = {}
        resultParsed[str(i)]['title'] = r['title']
        resultParsed[str(i)]['link'] = r['link']
        resultParsed[str(i)]['duration'] = r['duration']

        i += 1

    if not len(resultParsed):
        return -1

    return resultParsed
Example #8
0
 async def getVideoSearchObject(self):
     '''
     retry 3x
     '''
     for i in range(3):
         try:
             videoSearch = VideosSearch(self.searchTerm, limit=3).result()
             self.videoSearch = videoSearch['result'][i]
             break
         except Exception as e:
             print(traceback.format_exc())
Example #9
0
async def search(client, query):
    answers = []
    if query.query == "ETHO_ORUTHAN_PM_VANNU":
        answers.append(
            InlineQueryResultArticle(
                title="Deploy",
                input_message_content=InputTextMessageContent(
                    f"{Config.REPLY_MESSAGE}\n\n<b>You can't use this bot in your group, for that you have to make your own bot from the [SOURCE CODE](https://github.com/subinps/VCPlayerBot) below.</b>",
                    disable_web_page_preview=True),
                reply_markup=InlineKeyboardMarkup(buttons)))
        await query.answer(results=answers, cache_time=0)
        return
    string = query.query.lower().strip().rstrip()
    if string == "":
        await client.answer_inline_query(
            query.id,
            results=answers,
            switch_pm_text=("Search a youtube video"),
            switch_pm_parameter="help",
            cache_time=0)
    else:
        videosSearch = VideosSearch(string.lower(), limit=50)
        for v in videosSearch.result()["result"]:
            answers.append(
                InlineQueryResultArticle(
                    title=v["title"],
                    description=("Duration: {} Views: {}").format(
                        v["duration"], v["viewCount"]["short"]),
                    input_message_content=InputTextMessageContent(
                        "{} https://www.youtube.com/watch?v={}".format(
                            get_cmd(v["duration"]), v["id"])),
                    thumb_url=v["thumbnails"][0]["url"]))
        try:
            await query.answer(results=answers, cache_time=0)
        except errors.QueryIdInvalid:
            await query.answer(
                results=answers,
                cache_time=0,
                switch_pm_text=("Nothing found"),
                switch_pm_parameter="",
            )
Example #10
0
async def search(client, query):
    answers = []
    if query.query == "ORU_MANDAN_PM_VANNU":
        answers.append(
            InlineQueryResultArticle(
                title="Deploy",
                input_message_content=InputTextMessageContent(
                    f"{REPLY_MESSAGE}\n\n<b>You can't use this me in your group, So join the below Group & Channel request movies & enjoy the music.</b>",
                    disable_web_page_preview=True),
                reply_markup=InlineKeyboardMarkup(buttons)))
        await query.answer(results=answers, cache_time=0)
        return
    string = query.query.lower().strip().rstrip()
    if string == "":
        await client.answer_inline_query(
            query.id,
            results=answers,
            switch_pm_text=("Search a youtube video"),
            switch_pm_parameter="help",
            cache_time=0)
    else:
        videosSearch = VideosSearch(string.lower(), limit=50)
        for v in videosSearch.result()["result"]:
            answers.append(
                InlineQueryResultArticle(
                    title=v["title"],
                    description=("Duration: {} Views: {}").format(
                        v["duration"], v["viewCount"]["short"]),
                    input_message_content=InputTextMessageContent(
                        "/play https://www.youtube.com/watch?v={}".format(
                            v["id"])),
                    thumb_url=v["thumbnails"][0]["url"]))
        try:
            await query.answer(results=answers, cache_time=0)
        except errors.QueryIdInvalid:
            await query.answer(
                results=answers,
                cache_time=0,
                switch_pm_text=("Nothing found"),
                switch_pm_parameter="",
            )
Example #11
0
async def dl_playlist(chat, from_user, link):
    # untill issue get fix
    # https://github.com/alexmercerind/youtube-search-python/issues/107
    """
    vids = Playlist.getVideos(link)
    try:
        vid1 = vids["videos"][0]
        duration = vid1["duration"] or "РЎЙ"
        title = vid1["title"]
        song = await get_stream_link(vid1['link'])
        thumb = f"https://i.ytimg.com/vi/{vid1['id']}/hqdefault.jpg"
        return song[0], thumb, title, vid1["link"], duration
    finally:
        vids = vids["videos"][1:]
        for z in vids:
            duration = z["duration"] or "РЎЙ"
            title = z["title"]
            thumb = f"https://i.ytimg.com/vi/{z['id']}/hqdefault.jpg"
            add_to_queue(chat, None, title, z["link"], thumb, from_user, duration)
    """
    links = await get_videos_link(link)
    try:
        search = VideosSearch(links[0], limit=1).result()
        vid1 = search["result"][0]
        duration = vid1.get("duration") or "РЎЙ"
        title = vid1["title"]
        song = await get_stream_link(vid1["link"])
        thumb = f"https://i.ytimg.com/vi/{vid1['id']}/hqdefault.jpg"
        return song, thumb, title, vid1["link"], duration
    finally:
        for z in links[1:]:
            try:
                search = VideosSearch(z, limit=1).result()
                vid = search["result"][0]
                duration = vid.get("duration") or "РЎЙ"
                title = vid["title"]
                thumb = f"https://i.ytimg.com/vi/{vid['id']}/hqdefault.jpg"
                add_to_queue(chat, None, title, vid["link"], thumb, from_user,
                             duration)
            except Exception as er:
                LOGS.exception(er)
Example #12
0
    def streams(self, limit: Optional[int] = 1) -> Iterator[Stream]:
        """Yield the track's corresponding YouTube search results audio streams.

        Args:
            limit (Optional[int]): the desired number of search result items. Defaults to 1.

        Yields:
            Iterator[Stream]: yields each one of the search result audio streams
        """
        results = VideosSearch(str(self), limit=limit).result()["result"]

        yield from (YouTube(result["link"]).streams.get_audio_only() for result in results)
Example #13
0
 def search(self, query: str) -> List[Track]:
     search = VideosSearch(query, limit=300).result()
     if search["result"]:
         tracks: List[Track] = []
         for video in search["result"]:
             track = Track(service=self.name,
                           url=video["link"],
                           type=TrackType.Dynamic)
             tracks.append(track)
         return tracks
     else:
         raise errors.NothingFoundError("")
Example #14
0
    def callSearch(self):
        messagebox.showinfo("Notice",
                            " Please Wait....  Searching may take some time.")
        videoName = str(self.video_Name.get())
        print(videoName)
        if videoName is not None:
            videosSearch = VideosSearch(str(videoName), limit=5)

            for i in range(5):
                self.titleList.append(
                    str(videosSearch.result()['result'][i]['title'][0:45]))
                self.linkList.append(
                    videosSearch.result()['result'][i]['link'])
            for i in range(5):
                print(self.titleList[i], "\t\t", self.linkList[i])
                #print(videosSearch.result()['result'][i]['title'][0:45])

            time.sleep(5)
            self.WidgetResult()
        else:
            print("Null Search")
Example #15
0
def youtube_downloader(numberOfSongs, dir="library"):
    for n in range(numberOfSongs):
        try:
            title = np.random.choice(os.listdir('library/rotation/'))
            artist = title.split("-")[0]
            videosSearch = VideosSearch(artist, limit=10)
            choice = np.random.choice(videosSearch.result()['result'])
            title = choice['title']
            duration = choice['duration']
            times = duration.split(':')
            if len(times) == 2:
                if int(times[0]) < 20:
                    artist = title.split("-")[0]
                    song = "-".join(title.split("-"))
                    get_file(artist, song)
            elif len(times) == 1:
                artist = title.split("-")[0]
                song = "-".join(title.split("-"))
                get_file(artist, song)
        except:
            pass
Example #16
0
	async def search(self, ctx, *, search_term):
		if not search_term:
			raise commands.UserInputError()

		search = VideosSearch(search_term, limit=10)
		res = search.result()["result"]
		queue = self.get_queue(ctx.guild.id)

		# display search message
		send = self.formatted_search(res) + "\n Please wait until bot has finished reacting."
		msg = await ctx.send(embed=discord.Embed(title=f"Search results: {search_term}", description=send))


		#react to messages
		emoji_list = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"]
		for emoji in emoji_list:
			await msg.add_reaction(emoji)

		def check(reaction, user):
			return user == ctx.message.author and reaction.emoji in emoji_list and reaction.message == msg

		react = None;
		try:
			reaction, user = await self.bot.wait_for('reaction_add', timeout=60.0, check=check)
			react = reaction.emoji

		except asyncio.TimeoutError:
			await ctx.channel.send(embed=discord.Embed(description="**Search timed out.**"))
			await msg.clear_reactions()
		
		else:
			if not ctx.voice_client:
				channel = ctx.author.voices
				if not channel:
					await ctx.send("You need to be in a voice channel to use this command.")
				await channel.channel.connect()

			url = res[emoji_list.index(react)]['link']
			await ctx.invoke(self.bot.get_command("play"), url=url)
			await msg.clear_reactions()
Example #17
0
def ytsearch(query: str):
    try:
        search = VideosSearch(query, limit=1).result()
        data = search["result"][0]
        songname = data["title"]
        url = data["link"]
        duration = data["duration"]
        thumbnail = data["thumbnails"][0]["url"]
        videoid = data["id"]
        return [songname, url, duration, thumbnail, videoid]
    except Exception as e:
        LOGS.info(str(e))
        return 0
Example #18
0
def search():
    try:
        keywords = request.args.get('keyword')
        videos = VideosSearch(keywords, limit=5).result()
        g.videos = videos['result']
        for vid in g.videos:
            # We need to change the field name 'id' to 'song_id' so it matches the name in the database. Otherwise we need to manipulate manually every value
            vid['song_id'] = vid.pop('id')

        return videos
    except Exception as e:
        print(e)
        return '100'
Example #19
0
async def download(query):
    if query.startswith("https://") and not "youtube" in query.lower():
        thumb, duration = None, "Unknown"
        title = link = query
    else:
        search = VideosSearch(query, limit=1).result()
        data = search["result"][0]
        link = data["link"]
        title = data["title"]
        duration = data.get("duration") or "РЎЙ"
        thumb = f"https://i.ytimg.com/vi/{data['id']}/hqdefault.jpg"
    dl = await get_stream_link(link)
    return dl, thumb, title, link, duration
Example #20
0
def youtube_query(query, json_file, language='en', page=30, max_minu=30):
    json_worker = JsonWorker(json_file)
    page_finish = False
    video_list = []
    videosSearch = VideosSearch(query, language=language)
    print("---------------- {} ----------------".format(query))
    for page_i in tqdm(range(page)):
        error_flag = False
        video_meta = search_results_select(
            videosSearch.result(), max_duration=[0, max_minu, 0])
        if len(video_meta) > 1:
            video_list.extend(video_meta)
        try:
            videosSearch.next()
        except:
            error_flag = True
        if error_flag:
            break
        time.sleep(2)
        if page_i == page-1:
            page_finish = True
    if len(video_list) >= 1:
        count = 0
        for vi in video_list:
            if json_worker.check_in(vi["vid"]):
                continue
            count += 1
            vi["query"] = query_all[language][query]
            json_worker.add_one(vi, vi["vid"])
        if count >= 1:
            print("{}: {}".format(query, count))
            json_worker.save()
        else:
            print("{}: {}".format(query, 0))
    else:
        print("{}: {}".format(query, 0))

    return page_finish
Example #21
0
async def inline(client: Client, query: InlineQuery):
    answers = []
    search_query = query.query.lower().strip().rstrip()

    if search_query == "":
        await client.answer_inline_query(
            query.id,
            results=answers,
            switch_pm_text="Bir YouTube video adı yazın...",
            switch_pm_parameter="help",
            cache_time=0,
        )
    else:
        search = VideosSearch(search_query, limit=50)

        for result in search.result()["result"]:
            answers.append(
                InlineQueryResultArticle(
                    title=result["title"],
                    description="{}, {} views.".format(
                        result["duration"], result["viewCount"]["short"]
                    ),
                    input_message_content=InputTextMessageContent(
                        "https://www.youtube.com/watch?v={}".format(result["id"])
                    ),
                    thumb_url=result["thumbnails"][0]["url"],
                )
            )

        try:
            await query.answer(results=answers, cache_time=0)
        except errors.QueryIdInvalid:
            await query.answer(
                results=answers,
                cache_time=0,
                switch_pm_text="Hata: Arama zaman aşımına uğradı...",
                switch_pm_parameter="",
            )
Example #22
0
def youTubeVidSearch(user_id, text):
    markup = types.InlineKeyboardMarkup()
    videos = VideosSearch(text, limit=17).result()['result']
    for video in videos:
        markup.add(
            types.InlineKeyboardButton(
                text=video['title'],
                callback_data=f"YS V {user_id} {video['id']}"))
        #YS= YouTube Search
        #V= Video
    markup.add(
        types.InlineKeyboardButton(text='الغاء البحث❗️',
                                   callback_data=f"YS cancel {user_id}"))
    return markup
	def __init__(self, query, filter=0):
		self.query = query
		self.filter = filter
		self.results = {}
		self.count = 1
		filters = {
			1: "EgJAAQ",
			2: "CAISAhAB",
			3: "CAMSAhAB"}
		if self.filter == 0:
			self.videos = VideosSearch(self.query)
		else:
			self.videos = CustomSearch(self.query, filters[self.filter])
		self.parse_results()
Example #24
0
    def search(self, keys, max_results=MAX_SEARCH_RESULTS, sortByViews=True):
        results = VideosSearch(keys, limit=max_results).result()['result']

        songs = []
        for result in results:
            title = result['title']
            views = int(result['viewCount']['text'].split(' ')[0].replace(',', ''))
            link = result['link']
            songs.append(dict(title=title, link=link, views=views))

        if sortByViews:
            return sorted(songs, key=lambda tup: tup['views'], reverse=True)
        else:
            return songs
Example #25
0
def play_yt_song(plugin, vlc_instance):
    "Plays media through parsed plugin"

    plugin.out("What song would you like to play?")
    search_term = plugin.wait_for_in()

    url = VideosSearch(search_term, limit=1).result()["result"][0]['link']

    pafy_video = pafy.new(url)
    title = pafy_video.title
    play_url = pafy_video.getbest().url

    media = vlc_instance.media_new(play_url, ":no-video")
    plugin.play_media(media, media_name=title)
Example #26
0
async def yts_search(video_q):
    query = video_q.pattern_match.group(1)
    videosSearch = VideosSearch(query, limit=1)
    h = videosSearch.result()
    title = (h['result'][0]['title'])
    ptime = (h['result'][0]['publishedTime'])
    dur = (h['result'][0]['duration'])
    views = (h['result'][0]['viewCount']['short'])
    des = (h['result'][0]['descriptionSnippet'][0]['text'])
    chn = (h['result'][0]['channel']['name'])
    chnl = (h['result'][0]['channel']['link'])
    vlink = (h['result'][0]['link'])
    final = f"""**Extracted information from youtube**:
**Title**: `{title}`
**Published Time**: `{ptime}`
**Duration**: `{dur}`
**Views**: `{views}`
**Description**: `{des}`
**Channel Name**: `{chn}`
**Channel Link**: `{chnl}`
**Video Link**: `{vlink}`
"""
    await video_q.reply(final)
Example #27
0
async def add(ctx, *, searched_song):
    print(searched_song)

    videosSearch = VideosSearch(searched_song, limit=1)
    result_song_list = videosSearch.result()
    # print(result_song_list)
    title_song = result_song_list['result'][0]['title']
    urllink = result_song_list['result'][0]['link']

    song_url.append(urllink)
    text = discord.Embed(
        title="**Song Added**",
        description=f"{title_song} is added to the Queue\nLink : {urllink}",
        color=53380,
    )
    # text.add_image(url=f"{result_song_list['result'][0]['thumbnail']['url']}")
    text.set_author(
        name="Discord_music_bot",
        icon_url=
        "https://static.vecteezy.com/system/resources/thumbnails/000/371/212/small/1781.jpg"
    )
    text.set_footer(text="m.help to know commands")
    await ctx.send(embed=text)
Example #28
0
async def ytplay(client, chat_id, requested_by, query):
    m = await client.send_message(chat_id,
                                  f"__**Searching for {query} on YouTube.**__",
                                  disable_web_page_preview=True)
    try:
        videosSearch = VideosSearch(query[0], limit=6)
        results = videosSearch.result()['result']
        # results = await arq.youtube(query[0], 6)
        text = "**Results:**\n\n"
        songbt = []
        for num in range(0, len(results) - 1):
            title = results[num]['title']
            duration = results[num]['duration']
            views = results[num]['viewCount']['short']
            url = f"{results[num]['id']}"
            text += f"  __{num + 1}.__ **{title}** {duration} views: {views}\n"
            songbt.append(
                InlineKeyboardButton(f"{num + 1}",
                                     f'choose_{requested_by}_{url}'))
        await m.edit(text, reply_markup=InlineKeyboardMarkup([songbt]))
    except Exception as e:
        await m.edit("__**Found No Song Matching Your Query.**__")
        print(str(e))
        return
Example #29
0
def search(keywords):
    """
    search the items with youtube-search-python
    return a json with 5 entries of YouTube results
    param : the artist and the song
    """

    print_debug("search : " + keywords)
    print(
        my_colored_emoji(
            "\U0001F50E",
            "search " + keywords + '" with youtube-search-python',
            "green",
        ))
    my_limit = int(param_number())
    return VideosSearch(keywords, limit=my_limit)
def callback(ch, method, properties, body):
    print(body)
    result = []
    if str(body).startswith("b'[youtube]"):
        query = str(body)[11:-1]
        print(query)
        videosSearch = VideosSearch(query, limit=1).result()['result']
        for video_data in videosSearch:
            print(video_data['link'])
            result.append(video_data['link'])

        print(result)

        ########## PUBLICA EL RESULTADO COMO EVENTO EN RABBITMQ ##########
        for link in result:
            channel.basic_publish(exchange='nestor',
                                  routing_key="publicar_slack",
                                  body=query + ":" + link)