| import tweepy |
| import datetime |
| import os |
|
|
| def get_tweets_from_user_list(user_list, api, tweets_per_user=10): |
| """ |
| 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") |
| for tweet in tweets: |
| tweet_time = tweet.created_at |
|
|
| if tweet_time >= yesterday: |
| all_tweets.append(tweet) |
| else: |
| |
| break |
| except tweepy.TweepyException as e: |
| print(f"Error fetching tweets for {username}: {e}") |
| |
| continue |
|
|
|
|
| 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. |
| """ |
| |
| |
| 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) |
| api.verify_credentials() |
|
|
| print("Authentication successful!") |
| return api |
| except tweepy.TweepyException as e: |
| print(f"Authentication failed: {e}") |
| return None |
|
|
|
|
|
|
| if __name__ == '__main__': |
| |
| api = authenticate() |
|
|
| if api is None: |
| print("Exiting due to authentication failure.") |
| exit() |
|
|
|
|
| |
| user_list = ["dacefupan"] |
| 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(f"Tweeted at: {tweet.created_at}\n") |
| else: |
| print("No tweets found in the last 24 hours or an error occurred.") |
|
|