twittertimelinepermanent

Twitter API timeline - one entire week



Solution

  • You can get whole week of tweet by Get User's lookup Tweet V2 API

    OR

    Get timeline for user by V1.1 API

    Tweet User's lookup V2

    GET /2/users/{user id}/tweets
    

    get tweet time line by V1.1 API

    GET statuses/user_timeline
    

    I will demo both with Mr. Tweet by Postman.

    #1 Get access token in here

    This token support both V2 and V1.1 API call.

    #2 Get Tweets one week by v2

    https://api.twitter.com/2/users/44196397/tweets?max_results=20&start_time=2023-01-18T00:00:01Z&end_time=2023-01-25T00:00:01Z
    

    enter image description here

    If you want to more detail information for each tweet. Add attribute option in here by Adding query parameters(like a like count, create at and so on)

    enter image description here

    #3 Get timeline, 20 Tweets by v1.1

    Timeline API Two methods in here

    https://api.twitter.com/2/users/:id/timelines/reverse_chronological
    

    OR

    https://api.twitter.com/2/users/:id/tweets
    

    Demo for get tweet with 2nd methods

    https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=elonmusk&count=20
    

    enter image description here

    Both API needs access token assignment enter image description here

    Both API can be programming by node.js or Python languages.

    const axios = require('axios')
    
    const API_KEY = '<your API Key>'
    const API_KEY_SECRET = '<your API Secret>'
    
    const getToken = async () => {
        try {
            const resp = await axios.post(
                url = 'https://api.twitter.com/oauth2/token',
                data = '',
                config = {
                    params: {
                        'grant_type': 'client_credentials'
                    },
                    auth: {
                        username: API_KEY,
                        password: API_KEY_SECRET
                    }
                }
            );
            return Promise.resolve(resp.data.access_token);
        } catch (err) {
            console.error(err)
            return Promise.reject(err)
        }
    };
    const getUserId = async (username, token) => {
        try {
            const resp = await axios.get(
                url = `https://api.twitter.com/2/users/by/username/${username}`,
                config = {
                    headers: {
                        'Accept-Encoding': 'application/json',
                        'Authorization': `Bearer ${token}`,
                    }
                }
            );
            // { data: { id: '44196397', name: 'Elon Musk', username: 'elonmusk' } }
            return Promise.resolve(resp.data.data.id)
        } catch (err) {
            return Promise.reject(err)
        }
    };
    
    const getTweetTimeline = async (user_id, start_date, end_date, token) => {
        try {
            const tweets = [];
            let index = 1
            let next_token = 'start'
            while (next_token != null) {
                let url = `https://api.twitter.com/2/users/${user_id}/tweets?start_time=${start_date}&end_time=${end_date}&tweet.fields=created_at&max_results=20`
                if (next_token != 'start') {
                    url = `https://api.twitter.com/2/users/${user_id}/tweets?start_time=${start_date}&end_time=${end_date}&tweet.fields=created_at&max_results=20&pagination_token=${next_token}`
                }
                const resp = await axios.get(
                    url = url,
                    config = {
                        headers: {
                            'Accept-Encoding': 'application/json',
                            'Authorization': `Bearer ${token}`,
                        }
                    }
                );
                for(const item of resp.data.data) {
                    tweets.push({
                        index : index,
                        created_at: item.created_at,
                        text: item.text,
                        id : item.id
                    })
                    index = index + 1
                }
                next_token = resp.data.meta.next_token
            }
            return Promise.resolve(tweets)
        } catch (err) {
            console.error(err)
            return Promise.reject(err)
        }
    }
    
    getToken()
        .then(token => {
            console.log(token);
            getUserId('elonmusk', token)
                .then(user_id => {
                    getTweetTimeline(user_id,'2023-02-05T00:00:00Z','2023-02-11T23:59:59Z', token)
                        .then(tweets => {
                            for(const tweet of tweets) {
                                console.log(tweet)
                            }
                        })
                        .catch(error => {
                            console.log(error.message);
                        });
                })
                .catch(error => {
                    console.log(error.message);
                });
    
        })
        .catch(error => {
            console.log(error.message);
        });
    

    Result enter image description here

    node get-tweet.js > result.json
    

    enter image description here

    Update for My Time line using Python with tweepy library.

    I will use OAuth 2.0 App Only (center column), with my-user name (or other name - both supports) and get tweens during 30 days (exclude, retweets, replies) Tweet V2 timeline API

    GET /2/users/:id/tweets
    

    enter image description here

    The tweepy call that API intently in here

    Tweepy's API Client.get_users_tweets() will call Tweep V2 API's GET /2/users/:id/tweets

    enter image description here

    Detail parameter is in here

    Token from Developer Dashboard

    enter image description here

    Python Demo Code

    import tweepy
    
    def get_all_tweets(user_name):
        bearer_token ='<your App Bearer Token>' # From https://developer.twitter.com/en/portal
        client = tweepy.Client(bearer_token=bearer_token)
    
        user = client.get_user(username = user_name)
        user_id = user.data.id
        userTweets = []
        count = 0
        limit = 1000
        pagination_token = None
        start_time = '2023-01-01T00:00:00Z' # YYYY-MM-DDTHH:mm:ssZ
        end_time   = '2023-01-31T00:00:00Z' # YYYY-MM-DDTHH:mm:ssZ
        while count < limit:
            tweets = client.get_users_tweets(
                id = user_id,
                exclude = ['retweets','replies'],
                pagination_token = pagination_token,
                start_time = start_time,
                end_time = end_time,
                max_results = 100)
            if 'next_token' in tweets.meta.keys():
                if (tweets.meta['next_token']) is not None:
                    pagination_token = tweets.meta['next_token']
                else:
                    pagination_token = None
            else:
                pagination_token = None
            if tweets.data is not None:
                for tweet in tweets.data:
                    count += 1
                    userTweets.append({
                        "id": tweet.id,
                        "test": tweet.text
                    })
            if pagination_token is None:
                break
        return userTweets, count
    # user_name can assign your tweet name
    user_name = 'elonmusk'
    [tweets, count] = get_all_tweets(user_name)
    
    print(count)
    for tweet in tweets:
        tweet_url = f"https://twitter.com/{user_name}/status/{tweet['id']}"
        print(tweet)
        print(tweet_url)
    

    Run it

    python get-tweet.py
    

    Result enter image description here