This lib supports streaming for v1 and v2 API.
- Using streaming
- Note: Use streaming without auto-connection feature
- Specific API v1.1 implementations
- Specific API v2 implementations
- Make a custom request
TweetStreamreference
For both V1 and V2 APIs, streaming methods returns a TweetStream object.
Each event of TweetStream is stored into a TypeScript enum.
import { ETwitterStreamEvent, TweetStream, TwitterApi, ETwitterApiError } from 'twitter-api-v2';
const client = new TwitterApi(); // (create a client)
const stream = await client.v1.sampleStream();
// Awaits for a tweet
stream.on(
// Emitted when Node.js {response} emits a 'error' event (contains its payload).
ETwitterStreamEvent.ConnectionError,
err => console.log('Connection error!', err),
);
stream.on(
// Emitted when Node.js {response} is closed by remote or using .close().
ETwitterStreamEvent.ConnectionClosed,
() => console.log('Connection has been closed.'),
);
stream.on(
// Emitted when a Twitter payload (a tweet or not, given the endpoint).
ETwitterStreamEvent.Data,
eventData => console.log('Twitter has sent something:', eventData),
);
stream.on(
// Emitted when a Twitter sent a signal to maintain connection active
ETwitterStreamEvent.DataKeepAlive,
() => console.log('Twitter has a keep-alive packet.'),
);
// Enable reconnect feature
stream.autoReconnect = true;
// Be sure to close the stream where you don't want to consume data anymore from it
stream.close();
// -- Alternative usage --
// You can also use async iterator to iterate over tweets!
for await (const { data } of stream) {
console.log('This is my tweet:', data);
}You can create streams that doesn't connect immediately.
This leads to the advantage of that endpoint wrappers will directly returns a TweetStream object, not wrapped in a Promise.
Give autoConnect: false in object parameters to disable auto-connect.
Call .connect() to start stream.
// Not needed to await this!
const stream = client.v2.sampleStream({ autoConnect: false });
// Assign yor event handlers
// Emitted on Tweet
stream.on(ETwitterStreamEvent.Data, console.log);
// Emitted only on initial connection success
stream.on(ETwitterStreamEvent.Connected, () => console.log('Stream is started.'));
// Start stream!
await stream.connect({ autoReconnect: true, autoReconnectRetries: Infinity });API v1.1 streaming-related endpoints works only with classic OAuth 1.0a authentication.
Method: v1.filterStream.
Endpoint: statuses/filter.json.
Level: Read-only.
const client = ...; // (create a OAuth 1.0a client)
const streamFilter = await client.v1.filterStream({
// See FilterStreamParams interface.
track: 'JavaScript',
follow: [1842984n, '1850485928354'],
});
// Event data will be tweets of v1 API.Method: v1.sampleStream.
Endpoint: statuses/sample.json.
Level: Read-only.
const client = ...; // (create a OAuth 1.0a client)
const stream = await client.v1.sampleStream();
// Event data will be tweets of v1 API.API v2 streaming-related endpoints works only with Bearer OAuth2 authentication.
Method: v2.searchStream.
Endpoint: tweets/search/stream.
Level: Read-only.
const client = ...; // (create a Bearer OAuth2 client)
const stream = await client.v2.searchStream();
// Event data will be tweets of v2 API.Method: v2.streamRules.
Endpoint: tweets/search/stream/rules (GET).
Level: Read-only.
Returns: StreamingV2GetRulesResult.
const client = ...; // (create a Bearer OAuth2 client)
const rules = await client.v2.streamRules();
// Log every rule ID
console.log(rules.data.map(rule => rule.id));Method: v2.updateStreamRules.
Endpoint: tweets/search/stream/rules (POST).
Level: Read-write.
Takes: StreamingV2UpdateRulesParams.
Returns: StreamingV2UpdateRulesResult.
const client = ...; // (create a Bearer OAuth2 client)
// Add rules
const addedRules = await client.v2.updateStreamRules({
add: [
{ value: 'JavaScript', tag: 'js' },
{ value: 'TypeScript', tag: 'ts' },
],
});
// Delete rules
const deleteRules = await client.v2.updateStreamRules({
delete: {
ids: ['281646', '1534843'],
},
});Method: v2.sampleStream.
Endpoint: tweets/sample/stream.
Level: Read-only.
const client = ...; // (create a Bearer OAuth2 client)
const stream = await client.v2.sampleStream();
// Event data will be tweets of v2 API.If you know endpoint and parameters (or you don't want them to be parsed), you can make raw requests using shortcuts by HTTP methods:
getStream()postStream()or using raw request handler:sendStream()
NOTE: Be careful to select the good API prefix for version 1.1. 1.1 does not use the same URL for classic endpoints and streaming endpoints.
You can access quicky to an instance with the streaming prefix using v1.stream.
// For v1
const streamFilter = await client.v1.stream.getStream('statuses/filter.json', { track: 'JavaScript,TypeScript' });
// For v2
const sampleFilterv2 = await client.v2.getStream('tweets/sample/stream');.autoReconnect: boolean/ defaultsfalse/ Set this totrueto enable reconnect feature..autoReconnectRetries: number/ default5/ IfautoReconnectistrue, maximum tries made until give up. Each try is spaced by return of.nextRetryTimeout()call milliseconds..keepAliveTimeoutMs: number/ default120000(2 minutes) / Defined whenever connection should be automatically closed if nothing is received from Twitter during this time (it should not happend in any situation, because Twitter sends keep-alive packets). Can be set toInfinityto disable this feature..nextRetryTimeout: TStreamConnectRetryFn/ Override this function that takes atryOccurence(starting from 1) and returns the number of milliseconds to wait before trying to reconnect to Twitter..close(): EmitsConnectionClosedevent and terminates connection..destroy(): Same asclose(), but unbind all registred event listeners before..clone(): Promise<TweetStream>: Returns a newTweetStreamwith the same request parameters, with the same event listeners bound..reconnect(): Promise<void>: Tries to make a new request to Twitter with the same original parameters. If successful, continue streaming with new response..connect(params?: IConnectTweetStreamParams): Promise<TweetStream>: Connect the stream. Only ifautoConnecthas been set tofalsewhen stream is created.
All events are part of enum ETwitterStreamEvent exported by the package.
.ConnectionError: Emitted with theerrparameter given byrequest.on('error')orresponse.on('error')handlers..ConnectionClosed: Emitted when.close()is called or when the connection is manually closed by distant server..ConnectionLost: When nothing is received from Twitter during.keepAliveTimeoutMsmilliseconds, emit this event and start either close or reconnection process..ReconnectAttempt: Emitted before a reconnect attempt is made (payload: attemptnumber)..Connected: Emitted when the initial connection attempt succeeds. (only using manual.connect()after creating a stream withautoConnect: false).ConnectError: Emitted when the initial connection has failed. Event data is0, to match logic of.ReconnectError..Reconnected: Emitted when a reconnection attempt succeeds..ReconnectError: Emitted when a auto-reconnect try attempt has failed. Event data is anumberrepresenting the number of times the request has been re-made (starts from0)..ReconnectLimitExceeded: Emitted when.autoReconnectRetrieslimit exceeds..DataKeepAlive: Emitted when Twitter sends a\r\nto maintain connection open..Data: Emitted with stream data, when Twitter sends something..DataError: Emitted when Twitter sends a JSON error payload..TweetParseError: When the thing sent by Twitter cannot be JSON-parsed. Contains the parse error..Error: Emitted either when a.ConnectionErroror a.TweetParseErroroccurs. Contains{ type: .ConnectionError | .TweetParseError, error: any }.