skip to Main Content

I am designing a twitter integration for discord and am running into rate limit issues by calling search recent tweets. I’m looking into streaming but can’t figure out how to stream multiple users (added at a command). I am currently using this code, which works great for one user, but given the rules persist for each stream, I don’t see a way to run separate instances of this easily:

const { ETwitterStreamEvent, TweetStream, TwitterApi, ETwitterApiError } = require('twitter-api-v2');

const client = new TwitterApi(process.env["BEARER_TOKEN"]);

async function startStream(userName){
  const stream = await client.v2.searchStream();
  await client.v2.updateStreamRules({
  add: [
    { value: `from:${userName}`, tag: userName },
  ],
});
  
  stream.on(
    ETwitterStreamEvent.ConnectionError,
    err => console.log('Connection error!', err),
  );
  
  stream.on(
    ETwitterStreamEvent.ConnectionClosed,
    () => console.log('Connection has been closed.'),
  );
  
  stream.on(
    ETwitterStreamEvent.Data,
    eventData => console.log(eventData),
  );
  
  stream.autoReconnect = true;
}

Is there a way to run multiple streams for different users simultaneously?

2

Answers


  1. add: [
    { value: from:${userName}, tag: userName },
    { value: from:${userName2}, tag: userName2 }
    ]});

    Login or Signup to reply.
  2. For the next ones here is a small example, functional on my side.
    In a "TwitterClient.js" file:

        const { TwitterApi } = require('twitter-api-v2');
        const client = new TwitterApi({
          appKey: process.env.TWITTER_KEY,
          appSecret: process.env.TWITTER_SECRET,
          accessToken: process.env.TWITTER_TOKEN_KEY,
          accessSecret: process.env.TWITTER_TOKEN_SECRET,
        });
        const bearer = new TwitterApi(process.env.TWITTER_BEARER_TOKEN);
        const twitterClient = client.readWrite;
        const twitterBearer = bearer.readOnly;
        
        module.exports = { twitterClient, twitterBearer };
    

    And when starting the bot, for example in index.js or ready.js :

    const { ETwitterStreamEvent } = require('twitter-api-v2');
    const userName = "<username>"; 
    const userName2 = "<username2>";
    await client.twitterBearer.v2.updateStreamRules({
       add: [
         { value: `from:${userName}`, tag: userName },
         { value: `from:${userName2}`, tag: userName2 },
       ], 
    });
    const stream = await client.twitterBearer.v2.searchStream();
    stream.on(
        ETwitterStreamEvent.Data,
        eventData => console.log(eventData),
    );
    
    stream.autoReconnect = true;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search