Hi I have a question, I did a twitter bot that respond mentions
This is the code and run in nodejs:
function random_from_array(arr){
return arr[Math.floor(Math.random()*arr.length)];
}
app.all("/", function (request, response) {
fs.readFile(__dirname + '/last_mention_id.txt', 'utf8', function (err, last_mention_id) {
/* First, let's load the ID of the last tweet we responded to. */
console.log('last_mention_id:', last_mention_id);
Bot.get('search/tweets', { q: 'to:' + process.env.TWITTER_HANDLE + ' -from:' + process.env.TWITTER_HANDLE, since_id: last_mention_id }, function(err, data, response) {
if (err){
console.log('Error!', err);
return false;
}
/* Next, let's search for Tweets that mention our bot, starting after the last mention we responded to. */
if (data.statuses.length) {
console.log(data.statuses);
data.statuses.forEach(function(status) {
console.log(status.id_str);
console.log(status.text);
console.log(status.user.screen_name);
/* Now we can respond to each tweet. */
Bot.post('statuses/update', {
status: '@' + status.user.screen_name + ' ' + random_from_array(sentences),
in_reply_to_status_id: status.id_str
}, function(err, data, response) {
if (err){
/* TODO: Proper error handling? */
console.log('Error!', err);
}
else{
fs.writeFile(__dirname + '/last_mention_id.txt', status.id_str, function (err) {
/* TODO: Error handling? */
if(err){
console.log('Error!', err);
}
});
}
});
});
} else {
/* No new mentions since the last time we checked. */
console.log('No new mentions...');
}
});
});
response.sendStatus(200);
});
Sorry if is not in a code format. I’m new here.