Search code examples
node.jstwitter

Send/Reply direct message using Twitter API v2


I have a nodejs application, I need to add a feature were I can send a survey using direct messaging on twitter to the user and when the user replies, the application will send the next question and so on (preferably if I can add options for the replies expected).

What I'm stuck in currently is sending the direct message, the examples that I found seem to work with the old version and not working with Twitter API v2.

One sample code that I tried but also not working is below:

const Twit = require('twit');
const config = require('./config.js');

const T = new Twit(config);

const stream = T.stream('user');

const SendMessage = user => {
    const { screen_name, name } = user.source;

    const obj = {
        screen_name: screen_name,
        text: "Hi there!"
    };
    timeout = 5000;
    setTimeout(() => {
        T.post("direct_messages/new", obj)
            .catch(err => {
                console.error("error", err.stack);
            })
            .then(result => {
                console.log(`Message sent successfully To  ${screen_name}!`);
            });
    }, timeout);
};
user = new Object;
user.source = { screen_name: 'name', name: 'userDisplayedName' };
SendMessage(user);

Output Error:

      throw er; // Unhandled 'error' event
      ^

Error: Bad Twitter streaming request: 404
    at Object.exports.makeTwitError (/../node_modules/twit/lib/helpers.js:74:13)
    at Request.<anonymous> (/../node_modules/twit/lib/streaming-api-connection.js:96:29)
    at Request.emit (events.js:327:22)
    at IncomingMessage.<anonymous> (/../node_modules/request/request.js:1083:12)
    at Object.onceWrapper (events.js:421:28)
    at IncomingMessage.emit (events.js:327:22)
    at endReadableNT (_stream_readable.js:1327:12)
    at processTicksAndRejections (internal/process/task_queues.js:80:21)
Emitted 'error' event on StreamingAPIConnection instance at:
    at Request.<anonymous> (/../node_modules/twit/lib/streaming-api-connection.js:99:14)
    at Request.emit (events.js:327:22)
    [... lines matching original stack trace ...]
    at processTicksAndRejections (internal/process/task_queues.js:80:21) {
  code: null,
  allErrors: [],
  twitterReply: '',
  statusCode: 404
}

does anyone know how to send a direct message using Twitter API v2 with Nodejs?


Solution

  • At the time of writing this answer, the Direct Message APIs have not been migrated to v2, so you will need to continue to use Twitter API v1.1 for Direct Messages.

    The error here is not in sending, but in receiving -> Bad Twitter streaming request -> 404. This is because the code you have found is trying to use the Twitter user streams API, which was removed in 2018. These have been replaced with the Account Activity API (webhooks). You will need to build an app that receives webhook events for Direct Messages, and then post replies. This is all in v1.1 of the API.