[][src]Crate twitter_stream

Twitter Stream

A library for listening on Twitter Streaming API.

Usage

Add this to your Cargo.toml:

[dependencies]
futures = "0.3"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
twitter-stream = "0.12"

Overview

Here is a basic example that prints public mentions to @Twitter in JSON format:

use futures::prelude::*;
use twitter_stream::{Token, TwitterStream};

let token = Token::from_parts("consumer_key", "consumer_secret", "access_key", "access_secret");

TwitterStream::track("@Twitter", &token)
    .try_flatten_stream()
    .try_for_each(|json| {
        println!("{}", json);
        future::ok(())
    })
    .await
    .unwrap();

See the TwitterStream type documentation for details.

Streaming messages

TwitterStream yields the raw JSON strings returned by the Streaming API. Each string value contains exactly one JSON value.

The underlying Streaming API sends a blank line every 30 seconds as a "keep-alive" signal, but TwitterStream discards it so that you can always expect to yield a valid JSON string. On the other hand, this means that you cannot use the blank line to set a timeout on Stream-level. If you want the stream to time out on network stalls, set a timeout on the underlying HTTP connector, instead of the Stream (see the timeout example in the crate's repository for details).

The JSON string usually, but not always, represents a Tweet object. When deserializing the JSON string, you should be able to handle any kind of JSON value. A possible implementation of deserialization would be like the following:

#[derive(serde::Deserialize)]
#[serde(untagged)]
enum StreamMessage {
    Tweet(Tweet),
    // Discards anything other than a Tweet.
    // You can handle other message types as well by adding correspoiding variants.
    Other(serde::de::IgnoredAny),
}

#[derive(serde::Deserialize)]
struct Tweet { /* ... */ }

The echo_bot example in the crate's repository shows an example of a StreamMessage implementation.

See the Twitter Developers Documentation for the types and formats of the JSON messages.

Re-exports

pub use oauth_credentials::Credentials;
pub use crate::builder::Builder;
pub use crate::error::Error;

Modules

builder

A Builder type for TwitterStream.

error

Error type

hyperhyper

Type aliases for use with hyper crate's HTTP client.

service

A trait alias for Service.

Structs

FutureTwitterStream

A future returned by constructor methods which resolves to a TwitterStream.

TwitterStream

A listener for Twitter Streaming API, yielding JSON strings returned from the API.

Type Definitions

Token

A set of OAuth client credentials and token credentials used for authorizing requests to the Streaming API.