- I'm new to API and Twitter
- I managed to retrieve the 'normal' 20 Tweets (Status)
- Is there a way to retrieve a whole week at once?
- Or do I have to write a code that permanently calls 20 Tweets and append each after the other?
1 Answers
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
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)
#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
Both API needs access token assignment
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);
});
node get-tweet.js > result.json
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
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
Detail parameter is in here
Token from Developer Dashboard
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

- 5,257
- 2
- 10
- 14
-
Thank you very much for your answer Bench Vue. Questions: - Do I get all the tweets with use_timeline or only the ones posted by myself? - If I don't use Postman but an IDE the code would be: week_timeline = api.user_timeline() print(week_timeline) Many thanks and happy weekend! – Picnic Feb 11 '23 at 10:54
-
@Picnic, There are many way to get tilmeline, your point is Tweepy V1 method. I added my answer by V2 user id API. It can get all of any user's tweet for some period. You are also happy weekend! – Bench Vue Feb 11 '23 at 22:46
-
Hi everybody. Thank you very much for your help. I don't want to extract tweets from specific users. I need MY timeline for a certain time period. I guess for this I need api.search_30_day(). Do you agree? PS: I don't use Postman, please show me your result in Python code. – Picnic Feb 22 '23 at 13:26
-
No problem, don't forget vote me. You can vote by click up arrow in my answer. – Bench Vue Feb 22 '23 at 13:26
-
It was actually another question of mine :-) Can you answer it? – Picnic Feb 24 '23 at 13:27
-
What is another question? – Bench Vue Feb 24 '23 at 13:39
-
I don't want to extract tweets from specific users. I need MY timeline for a certain time period. I guess for this I need api.search_30_day(). Do you agree? PS: I don't use Postman, please show me your result in Python code. – Picnic Feb 25 '23 at 13:48
-
@Picnic, I added Python Timeline Demo by `tweepy` for getting 30 days timeline. The user name is general , you can use your tweet name or other name. – Bench Vue Feb 26 '23 at 01:22
-
Thank you very much, that's very useful for me. That's very kind of you! – Picnic Mar 05 '23 at 21:12
-
No problem, don't forget vote to me. You can click up arrow in my answer. It will be help to keep answer to every one. Thanks! – Bench Vue Mar 05 '23 at 21:50
-
Did that, pushed the up arrow! – Picnic Mar 05 '23 at 22:08
-
You clicked twice it. It means no point to me. You click again the answer will turn to green colored check box and give me 15 points. Can try it again? – Bench Vue Mar 05 '23 at 22:10
-
Hope it worked now. Can you tell? – Picnic Mar 05 '23 at 22:50
-
I tried to follow and understand your code. Could you help me with '[userTweets, count] = get_all_tweets(user_name)'? You call the function with get_all_tweets(user_name). But what is [userTweets, count]? A list? – Picnic Mar 06 '23 at 20:08
-
Those are return two values from `def get_all_tweets(user_name):` function. The end of line of function is `return userTweets, count`. First item is user's tweets data. It is appended by `userTweets.append`. Second item is number of tweet. So [userTweets, count] multiple return values from function and assign new variable. So it means assign both value , userTweets <- userTweets and count <- count This [tutorial](https://pythonbasics.org/multiple-return/) help to understand. – Bench Vue Mar 06 '23 at 20:17
-
I posted a new question in order to vote you again: https://stackoverflow.com/questions/75678392/twitter-api-call-several-user-names-with-python Could you please have a look? – Picnic Mar 12 '23 at 15:54
-
I answer your new question for multiple users. – Bench Vue Mar 12 '23 at 23:24
-
1Thank you very much, Bench Vue. I saw it, it works, i pushed the arrow up :-) – Picnic Mar 15 '23 at 19:33
-
@Picnic, Thanks you so much. Now you got more than 15 points, Can you up vote again. It will raise 10 more points to me. – Bench Vue Mar 15 '23 at 20:07
-
@Picnic, Thanks, I got 10 more points. One more this answer also possible 10 more up points. Thanks! – Bench Vue Mar 15 '23 at 20:30
-
I posted a new question regarding keyword search in Twitter API. Maybe you can help again... – Picnic Mar 15 '23 at 21:51
-
I will look at your new question. – Bench Vue Mar 15 '23 at 22:35