KEMBAR78
Using Streaming APIs · CoreTweet/CoreTweet Wiki · GitHub
Skip to content
This repository was archived by the owner on Sep 1, 2023. It is now read-only.

Using Streaming APIs

Acid Chicken (硫酸鶏) edited this page Aug 30, 2018 · 8 revisions

Start Streaming API

You can connect to the streaming API by Tokens.Streaming. StreamingApi class has methods corresponding to following APIs

Receiving Messages

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.

Sample Code

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

Using Rx in streaming

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.

Sample Code

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();
Clone this wiki locally