Quantcast
Channel: Active questions tagged youtube-api - Stack Overflow
Viewing all articles
Browse latest Browse all 3718

Need help fixing python script for youtube channel video search with date inputting

$
0
0

SORRY IM KIND OF LAZY TO WRITE A WHOLE TEXT SO I ASKED CHATGPT TO DO IT FOR ME:

I'm working on a Python script that uses the YouTube API to search for videos based on user input. However, I'm encountering issues with setting default values for start_date and end_date when the user inputs invalid data.

Here's my current code:

import osimport loggingimport jsonfrom googleapiclient.discovery import buildfrom googleapiclient.errors import HttpErrorfrom dateutil.parser import parsefrom datetime import datetime#logging configlogging.basicConfig(level=logging.INFO,                    format='%(asctime)s - %(levelname)s - %(message)s',                    datefmt='%Y-%m-%d %H:%M:%S',                    filename='log.txt')# constantsPROCESSED_VIDEOS_FILE = 'processed_videos.json'def load_processed_videos():"""Load already processed vid IDs."""    if os.path.exists(PROCESSED_VIDEOS_FILE):        with open(PROCESSED_VIDEOS_FILE, 'r') as f:            return set(json.load(f))    return set()def save_processed_video(video_id):"""Save new processed vid ID."""    processed_videos = load_processed_videos()    processed_videos.add(video_id)    with open(PROCESSED_VIDEOS_FILE, 'w') as f:        json.dump(list(processed_videos), f)def get_user_input(prompt):    return input(prompt).strip()def validate_input(input_str, allowed_chars=None):    return all(char in allowed_chars for char in input_str) if allowed_chars else Truedef validate_date(date_str):    try:        parse(date_str, fuzzy=False)        return True    except ValueError:        return Falsedef get_current_date():    return datetime.utcnow().date()def get_channel_info_by_name(youtube, channel_name):    try:        response = youtube.search().list(            q=channel_name,            part='snippet',            type='channel',            maxResults=1        ).execute()        if 'items' in response and response['items']:            channel = response['items'][0]            return channel['id']['channelId'], channel['snippet']['publishedAt']        else:            logging.info(f"Channel not found: {channel_name}")            return None, None    except HttpError as e:        logging.error(f"Error retrieving channel info: {e}")        return None, Nonedef validate_date_range(start_date, end_date):    current_date = get_current_date()    if end_date.date() > current_date:        logging.error(f"End date in the future: {current_date}")        return False    if start_date > end_date:        logging.error("Start date later than end date.")        return False    return Truedef validate_channel_join_date(channel_join_date, start_date):    channel_join_date_parsed = parse(channel_join_date).date()    if start_date.date() < channel_join_date_parsed:        logging.error(f"Start date earlier than channel join date: {channel_join_date_parsed}")        return False    return Truedef search_youtube_videos(api_key, channel_id, search_term, start_date, end_date):    youtube = build('youtube', 'v3', developerKey=api_key)    start_date, end_date = start_date.isoformat() +'Z', end_date.isoformat() +'Z'    videos = []    next_page_token = None    while True:        try:            search_response = youtube.search().list(                channelId=channel_id,                q=search_term,                part='id,snippet',                type='video',                maxResults=50,                publishedAfter=start_date,                publishedBefore=end_date,                pageToken=next_page_token            ).execute()            videos.extend([{'title': item['snippet']['title'],'videoId': item['id']['videoId'],'publishedAt': item['snippet']['publishedAt']            } for item in search_response.get('items', [])])            # check if more pages            next_page_token = search_response.get('nextPageToken')            if not next_page_token:                break        except HttpError as e:            logging.error(f"Error searching videos: {e}")            break    return videosdef display_videos(videos, header="Videos"):    if not videos:        logging.info("No videos found.")    else:        logging.info(f"\n{header}:")        for video in videos:            video_link = f"https://www.youtube.com/watch?v={video['videoId']}"            logging.info(f"- Title: {video['title']}")            logging.info(f"  ID: {video_link}")            logging.info(f"  Published At: {video['publishedAt']}\n")if __name__ == "__main__":    api_key = 'key'    try:        youtube = build('youtube', 'v3', developerKey=api_key)        channel_input = get_user_input("Enter channel ID or name (with or without @): ")        if not validate_input(channel_input, allowed_chars='@abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'):            logging.error("Invalid channel input.")            exit()        channel_id, channel_join_date = get_channel_info_by_name(youtube, channel_input)        if not channel_id:            logging.info("Channel not found. Exiting...")            exit()        search_term = get_user_input("Enter search term: ")        start_date_str = get_user_input("Enter start date (YYYY-MM-DD): ")        while not validate_date(start_date_str):            logging.error("Invalid start date.")            start_date_str = get_user_input("Enter start date (YYYY-MM-DD): ")        start_date = parse(start_date_str)        end_date_str = get_user_input("Enter end date (YYYY-MM-DD): ")        while not validate_date(end_date_str):            logging.error("Invalid end date.")            end_date_str = get_user_input("Enter end date (YYYY-MM-DD): ")        end_date = parse(end_date_str)        if not validate_date_range(start_date, end_date):            exit()        if not validate_channel_join_date(channel_join_date, start_date):            exit()        # search for videos        videos = search_youtube_videos(api_key, channel_id, search_term, start_date, end_date)        # log videos        display_videos(videos, "Found Videos")        for video in videos:            save_processed_video(video['videoId'])    except Exception as e:        logging.error(f"Unexpected error: {e}")    finally:        logging.info("Program completed.")

Problem:I want start_date to automatically be set to the channel's join date if the user input is invalid.I want end_date to automatically be set to the current date if the user input is invalid.I’ve tried using the parse() function for date handling, but it hasn't worked as expected.Error Messages:I've encountered various error messages regarding date parsing, and the logic seems to get stuck in loops.

What I've Tried:I've used the validate_date function to check user input.I've attempted to set defaults within the date validation logic but without success.Any help on how to implement these changes would be greatly appreciated!


Viewing all articles
Browse latest Browse all 3718

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>