Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import requests
- import os
- from google.oauth2.credentials import Credentials
- from google_auth_oauthlib.flow import InstalledAppFlow
- from google.auth.transport.requests import Request
- import googleapiclient.discovery
- # Replace with your API key for YouTube Data API
- API_KEY = 'HERE_IS_MY_API_KEY' # <--- YouTube API Key
- # Define the scopes
- SCOPES = ['https://www.googleapis.com/auth/spreadsheets', 'https://www.googleapis.com/auth/youtube.readonly']
- # Your Google Sheets spreadsheet ID and range
- SPREADSHEET_ID = 'HERE_IS_MY_SPREADSHEET_ID'
- RANGE_NAME = 'Sheet1!B2:J5' # Adjust this to where you want to start writing
- # Subscriber range
- MIN_SUBSCRIBERS = 100000 # Minimum subscriber count
- MAX_SUBSCRIBERS = 1000000 # Maximum subscriber count
- def authenticate():
- """Authenticate and return the credentials."""
- creds = None
- if os.path.exists('token.json'):
- creds = Credentials.from_authorized_user_file('token.json', SCOPES)
- if not creds or not creds.valid:
- if creds and creds.expired and creds.refresh_token:
- creds.refresh(Request())
- else:
- flow = InstalledAppFlow.from_client_secrets_file(
- 'client_secret.json', SCOPES)
- creds = flow.run_local_server(port=0)
- with open('token.json', 'w') as token:
- token.write(creds.to_json())
- return creds
- def search_youtube(query, max_results=200):
- """Search YouTube for channels matching the query."""
- url = 'https://www.googleapis.com/youtube/v3/search'
- params = {
- 'part': 'snippet',
- 'q': query,
- 'type': 'channel',
- 'maxResults': max_results,
- 'key': API_KEY # YouTube API key
- }
- response = requests.get(url, params=params)
- return response.json()
- def get_channel_details(channel_id):
- """Get details for a specific YouTube channel by ID."""
- url = 'https://www.googleapis.com/youtube/v3/channels'
- params = {
- 'part': 'snippet,statistics',
- 'id': channel_id,
- 'key': API_KEY # YouTube API key
- }
- response = requests.get(url, params=params)
- return response.json()
- def write_to_google_sheet(data, creds):
- """Write the YouTube channel data to Google Sheets."""
- sheets_service = googleapiclient.discovery.build('sheets', 'v4', credentials=creds)
- body = {
- 'values': [data] # Data to write
- }
- sheets_service.spreadsheets().values().append(
- spreadsheetId=SPREADSHEET_ID,
- range=RANGE_NAME,
- valueInputOption='USER_ENTERED',
- body=body
- ).execute()
- print("Data written to Google Sheets successfully.")
- def main():
- """Main function to perform the search and display results."""
- query = 'Minecraft'
- search_results = search_youtube(query)
- # Authenticate and get the credentials
- creds = authenticate()
- qualified_channels = []
- processed_count = 0
- for item in search_results.get('items', []):
- channel_id = item['id']['channelId']
- channel_details = get_channel_details(channel_id)
- channel_info = channel_details['items'][0]
- subscriber_count = int(channel_info['statistics']['subscriberCount'])
- # Check if the channel meets the subscriber criteria
- if MIN_SUBSCRIBERS <= subscriber_count <= MAX_SUBSCRIBERS:
- title = channel_info['snippet']['title']
- channel_link = f"https://www.youtube.com/channel/{channel_id}"
- description = channel_info['snippet'].get('description', 'No description available')
- country = 'No country information available' # Placeholder
- # Prepare data for Google Sheets
- data = [title, subscriber_count, channel_link, description]
- write_to_google_sheet(data, creds)
- qualified_channels.append(data)
- processed_count += 1
- # Stop if we have 3 qualified channels or have processed 200 results
- if len(qualified_channels) >= 3 or processed_count >= 200:
- break
- print(f"Found {len(qualified_channels)} qualified channels.")
- if __name__ == '__main__':
- main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement