使用node.js和twitter-api-v2运行多个流

ohtdti5x  于 2023-02-21  发布在  Node.js
关注(0)|答案(2)|浏览(221)

我正在设计一个针对discord的twitter集成,但是在调用搜索最近的tweets时遇到了速率限制问题。我正在研究流媒体,但是不知道如何流媒体多个用户(通过命令添加)。我目前使用的代码对一个用户来说效果很好,但是考虑到规则对每个流媒体都是持久的,我看不到一种方法来轻松地运行单独的示例:

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;
}

是否有办法同时为不同用户运行多个流?

bt1cpqcv

bt1cpqcv1#

下面是一个小例子,在我这边是功能性的。在一个“TwitterClient.js”文件中:

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 };

当启动机器人时,例如在index.js或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;
nnt7mjpx

nnt7mjpx2#

添加:[ {值:from:${userName},标签:用户名},{值:from:${userName2},标签:用户名2} ]});

相关问题