Peyton Sonnefeld
Peyton Sonnefeld

Reputation: 33

How do I fix a "This stream is currently at the maximum allowed connection limit" error on the Twitter API?

I run a Discord bot with Node.js through Heroku. I've been implementing the Twitter API to post tweets from a few accounts in some of our channels but the stream crashes sporadically after a period of time. I know I'm not hitting rate limits, and to my knowledge there aren't multiple connections running despite the error saying so. This is the error I get in my logs:

Rules: {
   meta: {
   sent: '2022-08-25T17:55:50.381Z',
   summary: { created: 0, not_created: 0, valid: 0, invalid: 0 }
  }
}
/app/node_modules/twitter-v2/build/TwitterError.js:26
return new module.exports(`${json.title}: ${json.detail}`, null, json.type);
TwitterError: ConnectionException: This stream is currently at the maximum allowed connection limit.

and this is the code I'm using for the stream:

var T = new Twit({
    bearer_token: process.env.BEARER_TOKEN,
    timeout_ms: 60*1000,
    strictSSL: true
})

async function listenForever(streamFactory, dataConsumer) {
      for await (const { data } of streamFactory()) {
        dataConsumer(data);
      }
      listenForever(streamFactory, dataConsumer);
  }
  
async function  setup () {
    const endpointParameters = {
        'tweet.fields': ['text'],
        'expansions': [ 'author_id'],
        'media.fields': [ 'url' ]
    }
    try {
      console.log('Setting up Twitter....')
      const body = {
        "add": [
          // {'value': 'from:account'},
          // {'value': 'from:account'},
          // {'value': 'from:account'},
          // {'value': 'from:account'}
        ]
        // "delete": {
            // ids: [""]
        // }
      }
      const r = await T.post("tweets/search/stream/rules", body);
      console.log("Rules:", r);
  
    } catch (err) {
      console.log(err)
    }
  
    listenForever(
      () => T.stream('tweets/search/stream', endpointParameters),
      (data) => sendMessage(data)
    );
}

Upvotes: 1

Views: 543

Answers (1)

johnedstone
johnedstone

Reputation: 31

I am having the same issue with Twitter API v2 using this code (based on tweepy):

class CustomStreamingClient(tweepy.StreamingClient):
    def on_tweet(self, tweet):
        try:
            logger_stdout.info(f'{tweet.text}')
        except Exception as e:
            logger_stderr.warning('Custom Streaming Client error - {} - {}'.format(type(e).__name__, e))

def get_stream_rules():
    stream_rules = [tweepy.StreamRule(value=f'from: {ea}', tag=f'{ea}', id=f'{ea}') for ea in ids_to_follow_list]

    return stream_rules

def main():
    try:
        streaming_client = CustomStreamingClient(bearer_token)
        streaming_client.add_rules(add=get_stream_rules())


        streaming_client.filter(expansions=['author_id'])
    except Exception as e:
        logger_stderr.error('Stream error - {} - {}'.format(type(e).__name__, e))

if __name__ == '__main__':
    try:    
        main()
    except KeyboardInterrupt:
        logger_stderr.warning("""
        Closing ...
        """)

Upvotes: 1

Related Questions