Reputation: 31
So I've coded a twitter bot to respond to one particular person with one particular message assuming it's an original tweet
The code is as follows: (ids hidden)
import { TwitterApi } from 'twitter-api-v2';
import { TwitterV2IncludesHelper } from 'twitter-api-v2';
var xdsds = ""
const client = new TwitterApi({
appKey: 'censored',
appSecret: 'censored',
accessToken: 'censored',
accessSecret: 'censored',
});
async function loop(){
const stream = await client.v2.userTimeline('censored',{
'tweet.fields': ['referenced_tweets', 'author_id'],
expansions: ['referenced_tweets.id', 'author_id'],
});
for await (const tweet of stream) {
if(stream.data.author_id == 'censored'){
console.log('you found a yeeyeeass mayank tweet')
}
xdsds = stream.data;
console.log(xdsds)
}
}
loop();
My primary issue now, is that I cannot sort through things based on author id as it doesn't work. Any ideas? And how can I stop it from responding to the same tweet twice/replying to replies rather then original tweets
Upvotes: 0
Views: 175
Reputation: 932
To reiterate, you want to reply to any tweet posted by a particular user, which is not a reply, nor retweet. For the sake of my answer I assume that 'censored'
value in client.v2.userTimeline
call and stream.data.author_id
comparison is the same.
Your condition doesn't check the value of the author_id
for a tweet, you are accessing stream.data.author_id
, but you should be checking: tweet.author_id == 'censored'
.
However, there might be a better solution. Checking the user timeline API docs, there is exclude
parameter. If you exclude both retweets
and replies
, you don't need to check the author_id
altogether and you won't receive any replies:
const stream = await client.v2.userTimeline('censored', {
exclude: 'retweets,replies'
});
To avoid responding to the same tweet twice, use either since_id
, or start_time
parameters to receive only tweets which were posted since your last request. You can persist the value to a disk or database so it survives between script runs.
For example (untested):
let lastTweetSince = undefined;
async function loop(){
const stream = await client.v2.userTimeline('censored',{
exclude: 'retweets,replies',
since_id: lastTweetSince,
});
// Get the ID of the newest tweet in the response
lastTweetSince = stream.tweets[0].id;
// ...
}
(See paginator docs)
Upvotes: 1