-
Notifications
You must be signed in to change notification settings - Fork 48
Using Streaming APIs
You can connect to the streaming API by Tokens.Streaming.
StreamingApi class has methods corresponding to following APIs
- Filter: POST statuses/filter (CoreTweet uses GET for this)
- Sample: GET statuses/sample
- Firehose: GET statuses/firehose
-
User: GET user(Obsolete) -
Site: GET site(Obsolete)
The type of each method is IEnumerable<StreamingMessage>.
StreamingMessage is the super class to represent a message received in streaming.
MessageType property shows which type of message this is and can be cast this instance to.
- DeleteStatus
- DeleteDirectMessage
- DirectMessage was deleted
- DeleteMessage
- ScrubGeo
- StatusWithheld
- UserWithheld
- Disconnect
- Stream will be disconnected for some reason
- This message means Twitter notices the reason to be disconnected. You can be disconnected without receiving this message; for example, because of connection issues.
- DisconnectMessage
- Warning
- Event
- Envelopes
- Received a message for one user (SiteStreams)
- EnvelopesMessage
- Create
- Received a status
- StatusMessage
- DirectMessage
- Friends
- Limit
- Control
- UserDelete
- User is deleted (This message is not in official documents)
- UserMessage
- RawJson
- Unknown message
- RawJsonMessage
This code outputs 10 tweets contains "tea", then disconnects.
// using System;
// using System.Linq;
// using CoreTweet;
// using CoreTweet.Streaming;
foreach(var m in t.Streaming.Filter(track: "tea")
.OfType<StatusMessage>()
.Select(x => x.Status)
.Take(10))
Console.WriteLine("Tweets about tea {0}: {1}", m.User.ScreenName, m.Text);CoreTweet supports Reactive Extensions to receive streaming messages, but in .NET Framework 3.5.
You can use Rx version methods by adding CoreTweet.Streaming.Reactive to references and adding using CoreTweet.Streaming.Reactive; to your code.
Using Rx version is the same as using IE<T> version, except the return type is IObservable<StreamingMessage>.
You can disconnect the stream by calling Dispose() of a instance of IDisposable returned by Subscribe.
This code outputs following users and their tweets for 30 seconds, then disconnects. (This code is no longer working because it is using an obsolete endpoint called User Stream.)
// using System;
// using System.Reactive.Linq;
// using System.Threading.Tasks;
// using CoreTweet;
// using CoreTweet.Streaming;
// using CoreTweet.Streaming.Reactive;
var stream = t.Streaming.UserAsObservable().Publish();
stream.OfType<FriendsMessage>()
.Subscribe(x => Console.WriteLine("Following: " + string.Join(", ", x)));
stream.OfType<StatusMessage>()
.Subscribe(x => Console.WriteLine("{0}: {1}", x.Status.User.ScreenName, x.Status.Text));
var disposable = stream.Connect();
await Task.Delay(30 * 1000);
disposable.Dispose();