Search code examples
node.jsserverside-javascripttwitter-streaming-api

How to respond to mentions using Twitter API


I have a twitter bot that is functional. It complements someone when they reply to me, which is when @myTwitterHandle is the first thing in the tweet. The following code allows me to respond to them:

function tweetEvent(tweet) {

  // Who is this in reply to?
  var reply_to = tweet.in_reply_to_screen_name;
  // Who sent the tweet?
  var name = tweet.user.screen_name;
  // What is the text?
  var txt = tweet.text;

  // Ok, if this was in reply to me
  // Replace myTwitterHandle with your own twitter handle
  console.log(reply_to, name, txt);
  if (reply_to === 'myTwitterHandle') {

  ¦ // Get rid of the @ mention
  ¦ txt = txt.replace(/@selftwitterhandle/g, '');

  ¦ // Start a reply back to the sender
  ¦ var reply = "You mentioned me! @" + name + ' ' + 'You are super cool!';

  ¦ console.log(reply);
  ¦ // Post that tweet!
  ¦ T.post('statuses/update', { status: reply }, tweeted);
  }
}

I just want to send the exact same reply whenever anyone @mentions me somewhere in the body of their tweet. I am using Node.js and the twit api client.


Solution

  • It looks like you may be referencing the tutorial found here

    I believe this is what you may be looking for

    I just want to send the exact same reply whenever anyone @mentions me somewhere in the body of their tweet.

    This script achieves the desired result:

    var stream = T.stream('statuses/filter', { track: ['@myTwitterHandle'] });
    stream.on('tweet', tweetEvent);
    
    function tweetEvent(tweet) {
    
        // Who sent the tweet?
        var name = tweet.user.screen_name;
        // What is the text?
        // var txt = tweet.text;
        // the status update or tweet ID in which we will reply
        var nameID  = tweet.id_str;
    
         // Get rid of the @ mention
        // var txt = txt.replace(/@myTwitterHandle/g, "");
    
        // Start a reply back to the sender
        var reply = "You mentioned me! @" + name + ' ' + 'You are super cool!';
        var params             = {
                                  status: reply,
                                  in_reply_to_status_id: nameID
                                 };
    
        T.post('statuses/update', params, function(err, data, response) {
          if (err !== undefined) {
            console.log(err);
          } else {
            console.log('Tweeted: ' + params.status);
          }
        })
    };