HunterLarco / twitter-v2

An asynchronous client library for the Twitter REST and Streaming API's
MIT License
164 stars 35 forks source link

Provide support for filtered streams #80

Open prasad-aditya opened 3 years ago

prasad-aditya commented 3 years ago

Not sure if this is already implemented, but adding support for creating filtered streams with rules will be great.

wiertz commented 3 years ago

Filtered streams are supported, see Readme https://github.com/HunterLarco/twitter-v2#streaming-api. However, twitter-v2 does not manage the filter rules – is that what you mean? Given that rules are independent of an active stream (i.e. they persist even if there is no active stream and they can be modified while the stream is running) it does not seem useful to include them as a property of the stream. However, writing your own utility function to set and update rules is rather simple, given that it only takes a simple post request:

curl -X POST 'https://api.twitter.com/2/tweets/search/stream/rules' \ -H "Content-type: application/json" \ -H "Authorization: Bearer $BEARER_TOKEN" -d \ '{ "add": [ {"value": "cat has:images", "tag": "cats with images"} ] }'

(Example taken from https://developer.twitter.com/en/docs/twitter-api/tweets/filtered-stream/quick-start)

Arnique commented 3 years ago

I was also stuck. Turns out you just use client.post() to add the filters as per official the docs.

Check out code sample here: https://github.com/HunterLarco/twitter-v2/issues/82

gustawdaniel commented 3 years ago

Try:

const Twitter = require('twitter-v2');
const client = new Twitter({ bearer_token: process.env.TWITTER_API_BEARER_TOKEN });
client.post('tweets/search/stream/rules', { add: [ {value: 'cat has:images'} ] }).then(console.log);

You should see

 {
  data: [ { value: 'cat has:images', id: '1407767983888470021' } ],
  meta: {
    sent: '2021-06-23T18:30:17.966Z',
    summary: { created: 1, not_created: 0, valid: 1, invalid: 0 }
  }
}

Then you can get your rules:

> client.get('tweets/search/stream/rules').then(console.log);
Promise { <pending> }
> {
  data: [
    {
      id: '1407650287389712386',
      value: 'from:PreciseLabPL OR from:elonmusk'
    },
    { id: '1407767983888470021', value: 'cat has:images' }
  ],
  meta: { sent: '2021-06-23T18:30:51.091Z' }
}

or remove them

> client.post('tweets/search/stream/rules', { delete: {ids: ['1407767983888470021']} }).then(console.log);
Promise { <pending> }
> {
  meta: {
    sent: '2021-06-23T18:33:00.049Z',
    summary: { deleted: 1, not_deleted: 0 }
  }
}