-1

Is there a way for me to get the url of a youtube video when a user type the name of the video in an input? trying to do it in my discord bot

what I have tried so far:

query = message.content.split(" ")[1:]
url = "http://www.youtube.com/results?search_query="
for word in query:
    url += word + "+"
link = webbrowser.open_new(url)
yt = YouTube(str(link))

so I used webbrowser to see the bot's perspective after adding a query to the search link (url) so it just opens a page with all the videos related to the query, now how do I make it select a certain video (most likely will always be the 1st one on the page)

President James K. Polk
  • 40,516
  • 21
  • 95
  • 125
  • 3
    [Same Question, Answeserd by User: Hurried-Helpful](https://stackoverflow.com/questions/61137974/open-first-video-by-searching-in-youtube-using-python) – DerFilip May 16 '23 at 17:53

1 Answers1

1

It looks like ur using python, so you should just use the YouTube API https://developers.google.com/youtube/v3/code_samples/code_snippets

# -*- coding: utf-8 -*-

# Sample Python code for youtube.search.list
# See instructions for running these code samples locally:
# https://developers.google.com/explorer-help/code-samples#python

import os

import google_auth_oauthlib.flow
import googleapiclient.discovery
import googleapiclient.errors

scopes = ["https://www.googleapis.com/auth/youtube.readonly"]

def main():
    # Disable OAuthlib's HTTPS verification when running locally.
    # *DO NOT* leave this option enabled in production.
    os.environ["OAUTHLIB_INSECURE_TRANSPORT"] = "1"

    api_service_name = "youtube"
    api_version = "v3"
    client_secrets_file = "YOUR_CLIENT_SECRET_FILE.json"

    # Get credentials and create an API client
    flow = google_auth_oauthlib.flow.InstalledAppFlow.from_client_secrets_file(
        client_secrets_file, scopes)
    credentials = flow.run_console()
    youtube = googleapiclient.discovery.build(
        api_service_name, api_version, credentials=credentials)

    request = youtube.search().list(
        part="snippet",
        maxResults=25,
        q="surfing"
    )
    response = request.execute()

    print(response)

if __name__ == "__main__":
    main()
Need_Info
  • 91
  • 1
  • 6