File size: 3,591 Bytes
0396b0d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import tweepy
import datetime
import os

def get_tweets_from_user_list(user_list, api, tweets_per_user=10):  # Added tweets_per_user for control
    """
    Retrieves the latest tweets from a list of Twitter users within the last 24 hours.

    Args:
        user_list (list): A list of Twitter usernames (strings).
        api (tweepy.API):  An authenticated Tweepy API object.
        tweets_per_user (int): The maximum number of tweets to retrieve per user.  Defaults to 10.  Adjust as needed.

    Returns:
        list: A list of tweet objects (tweepy.models.Status) that are within the last 24 hours.
               Returns an empty list if there are errors.
    """

    all_tweets = []
    now = datetime.datetime.now()
    yesterday = now - datetime.timedelta(days=1)

    for username in user_list:
        try:
            tweets = api.user_timeline(screen_name=username, count=tweets_per_user, tweet_mode="extended")  # Use extended mode for full text
            for tweet in tweets:
                tweet_time = tweet.created_at

                if tweet_time >= yesterday:
                    all_tweets.append(tweet)
                else:
                    # Optimization:  If we've hit a tweet older than yesterday, we can stop getting tweets for this user
                    break # Stop searching for this user
        except tweepy.TweepyException as e:
            print(f"Error fetching tweets for {username}: {e}")
            # Log the error or handle it appropriately.  Consider retrying, skipping the user, etc.
            continue # Skip to the next user if there's an error


    return all_tweets



def authenticate():
    """Authenticates with the Twitter API using API keys and access tokens.

    Returns:
        tweepy.API: An authenticated Tweepy API object, or None if authentication fails.
    """
    # Replace with your actual API keys and tokens.  It's best to store these
    # in environment variables.
    consumer_key = "kiQbhfRbHvWpf7NdEtAsQYlET"
    consumer_secret = "Yu8VkZsrFtLxSjzqJgLB3kSyY7BVTFROm23smItxiG32ETjfRM"
    access_token = "1707606144-JdZ0vEGx5wdsxbg0eFof8yTaKIFJY35mSl5Qs62"
    access_token_secret = "yoOnwWeJvrL6bZMdbF6PIvbJvPdndfAgNbiYBmrA1jTtA"


    if not all([consumer_key, consumer_secret, access_token, access_token_secret]):
        print("Error: Missing Twitter API credentials.  Please set the environment variables.")
        return None


    try:
        auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
        auth.set_access_token(access_token, access_token_secret)
        api = tweepy.API(auth, wait_on_rate_limit=True)  # Enable wait_on_rate_limit
        api.verify_credentials() # Verify authentication is working

        print("Authentication successful!")
        return api
    except tweepy.TweepyException as e:
        print(f"Authentication failed: {e}")
        return None



if __name__ == '__main__':
    # Authenticate with the Twitter API
    api = authenticate()

    if api is None:
        print("Exiting due to authentication failure.")
        exit()


    # Example Usage:
    user_list = ["dacefupan"]  # Replace with the usernames you want to track
    tweets = get_tweets_from_user_list(user_list, api, tweets_per_user=5)

    if tweets:
        print(f"Found {len(tweets)} tweets from the last 24 hours:")
        for tweet in tweets:
            print(f"@{tweet.user.screen_name}: {tweet.full_text}\n") #Print the full_text
            print(f"Tweeted at: {tweet.created_at}\n")
    else:
        print("No tweets found in the last 24 hours or an error occurred.")