Advertisement
Vyc_Agency

Youtube search code

Sep 21st, 2024
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.14 KB | None | 0 0
  1. import requests
  2. import os
  3. from google.oauth2.credentials import Credentials
  4. from google_auth_oauthlib.flow import InstalledAppFlow
  5. from google.auth.transport.requests import Request
  6. import googleapiclient.discovery
  7.  
  8. # Replace with your API key for YouTube Data API
  9. API_KEY = 'HERE_IS_MY_API_KEY'  # <--- YouTube API Key
  10.  
  11. # Define the scopes
  12. SCOPES = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/youtube.readonly']
  13.  
  14. # Your Google Sheets spreadsheet ID and range
  15. SPREADSHEET_ID = 'HERE_IS_MY_SPREADSHEET_ID'
  16. RANGE_NAME = 'Sheet1!B2:J5'  # Adjust this to where you want to start writing
  17.  
  18. # Subscriber range
  19. MIN_SUBSCRIBERS = 100000  # Minimum subscriber count
  20. MAX_SUBSCRIBERS = 1000000  # Maximum subscriber count
  21.  
  22.  
  23. def authenticate():
  24.     """Authenticate and return the credentials."""
  25.     creds = None
  26.     if os.path.exists('token.json'):
  27.         creds = Credentials.from_authorized_user_file('token.json', SCOPES)
  28.     if not creds or not creds.valid:
  29.         if creds and creds.expired and creds.refresh_token:
  30.             creds.refresh(Request())
  31.         else:
  32.             flow = InstalledAppFlow.from_client_secrets_file(
  33.                 'client_secret.json', SCOPES)
  34.             creds = flow.run_local_server(port=0)
  35.         with open('token.json', 'w') as token:
  36.             token.write(creds.to_json())
  37.     return creds
  38.  
  39.  
  40. def search_youtube(query, max_results=200):
  41.     """Search YouTube for channels matching the query."""
  42.     url = 'https://www.googleapis.com/youtube/v3/search'
  43.     params = {
  44.         'part': 'snippet',
  45.         'q': query,
  46.         'type': 'channel',
  47.         'maxResults': max_results,
  48.         'key': API_KEY  # YouTube API key
  49.     }
  50.     response = requests.get(url, params=params)
  51.     return response.json()
  52.  
  53.  
  54. def get_channel_details(channel_id):
  55.     """Get details for a specific YouTube channel by ID."""
  56.     url = 'https://www.googleapis.com/youtube/v3/channels'
  57.     params = {
  58.         'part': 'snippet,statistics',
  59.         'id': channel_id,
  60.         'key': API_KEY  # YouTube API key
  61.     }
  62.     response = requests.get(url, params=params)
  63.     return response.json()
  64.  
  65.  
  66. def write_to_google_sheet(data, creds):
  67.     """Write the YouTube channel data to Google Sheets."""
  68.     sheets_service = googleapiclient.discovery.build('sheets', 'v4', credentials=creds)
  69.     body = {
  70.         'values': [data]  # Data to write
  71.     }
  72.     sheets_service.spreadsheets().values().append(
  73.         spreadsheetId=SPREADSHEET_ID,
  74.         range=RANGE_NAME,
  75.         valueInputOption='USER_ENTERED',
  76.         body=body
  77.     ).execute()
  78.     print("Data written to Google Sheets successfully.")
  79.  
  80.  
  81. def main():
  82.     """Main function to perform the search and display results."""
  83.     query = 'Minecraft'
  84.     search_results = search_youtube(query)
  85.  
  86.     # Authenticate and get the credentials
  87.     creds = authenticate()
  88.  
  89.     qualified_channels = []
  90.     processed_count = 0
  91.  
  92.     for item in search_results.get('items', []):
  93.         channel_id = item['id']['channelId']
  94.         channel_details = get_channel_details(channel_id)
  95.         channel_info = channel_details['items'][0]
  96.         subscriber_count = int(channel_info['statistics']['subscriberCount'])
  97.  
  98.         # Check if the channel meets the subscriber criteria
  99.         if MIN_SUBSCRIBERS <= subscriber_count <= MAX_SUBSCRIBERS:
  100.             title = channel_info['snippet']['title']
  101.             channel_link = f"https://www.youtube.com/channel/{channel_id}"
  102.             description = channel_info['snippet'].get('description', 'No description available')
  103.             country = 'No country information available'  # Placeholder
  104.  
  105.             # Prepare data for Google Sheets
  106.             data = [title, subscriber_count, channel_link, description]
  107.             write_to_google_sheet(data, creds)
  108.             qualified_channels.append(data)
  109.  
  110.         processed_count += 1
  111.  
  112.         # Stop if we have 3 qualified channels or have processed 200 results
  113.         if len(qualified_channels) >= 3 or processed_count >= 200:
  114.             break
  115.  
  116.     print(f"Found {len(qualified_channels)} qualified channels.")
  117.  
  118.  
  119. if __name__ == '__main__':
  120.     main()
  121.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement