[][src]Crate twitchchat

A simple "connection-less" twitch chat crate

This crate produces types for twitch messages and gives you methods for sending messages.

'Theory' of operation

First, by creating a Client from a ReadAdapter and a WriteAdapter. This can be simple be done by using twitchchat::sync_adapters on an std::io::TcpStream.

Then, calling Client::register with a filled-out UserConfig will connect you to Twitch.

Once connected, you can Client::wait_for_ready and the client will read (blocking) until Twitch sends a GlobalUserState message, which it'll fill out a LocalUser with various information.

Once connected, you can

Thread-safe writing:

Use Client::writer to get a clonable, thread-safe Writer that is used to writer messages to the Client.

Message filters, and why blocking in them is a bad idea

The client provides a very simplistic callback registration system

To use it, you simply just register a closure with the client via its Client::on method. It uses the type of the closures argument, one of these to create a filter

It also gives you a clone of the Writer so you don't need to move one into the closure.

When Client::read_message is called, it'll check these filters and send a clone of the requested message to the callback. Because it does this on same thread as the Client::read_message call, you can lock up the system by simplying diverging.

The client is thread safe, and clonable so one could call Client::read_message with ones own sychronization scheme to allow for a simplistic thread pool, but its best just to send the message off to a channel elsewhere

A simple example

use std::net::TcpStream;
use twitchchat::{commands::PrivMsg, Capability};
use twitchchat::{Client, Writer, SyncReadAdapter, SyncWriteAdapter};
use twitchchat::{TWITCH_IRC_ADDRESS, UserConfig};
// create a simple TcpStream
let read = TcpStream::connect(TWITCH_IRC_ADDRESS).expect("connect");
let write = read
    .try_clone()
    .expect("must be able to clone the tcpstream");

// your password and your nickname
// the twitch oauth token must be prefixed with `oauth:your_token_here`
let (pass, nick) = (std::env::var("MY_TWITCH_OAUTH_TOKEN").unwrap(), "my_name");
let config = UserConfig::with_caps() // if you need or only want specific capabilities, use .builder(), or toggle them after this call
                .token(pass)
                .nick(nick)
                .build()
                .unwrap();

// shorthand for SyncReadAdapter::new(read) and SyncWriteAdapter::new(write)
// which impl the Adapters for std::io::Read and std::io::Write
let (read, write) = twitchchat::sync_adapters(read, write);

// client takes a ReadAdapter and an std::io::Write
let mut client = Client::new(read, write);

// register with the user configuration
client.register(config).unwrap();

// wait for everything to be ready (blocks)
let user = client.wait_for_ready().unwrap();
println!(
    "connected with {} (id: {}). our color is: {}",
    user.display_name.unwrap(),
    user.user_id,
    user.color.unwrap_or_default()
);

// when we receive a commands::PrivMsg print out who sent it, and the message
// this can be done at any time, but its best to do it early
client.on(|msg: PrivMsg, _: Writer| {
    // this prints out name: msg
    let name = msg.display_name().unwrap_or_else(|| msg.user());
    println!("{}: {}", name, msg.message())
});

let w = client.writer();
// join a channel
w.join("museun").unwrap();

// sends a message to the channel
w.send("museun", "VoHiYo").unwrap();

// blocks the thread, but any callbacks set in the .on handlers will get their messages
client.run();

TestStream

TestStream is a simple TcpStream-like mock.

It lets you inject/read its internal buffers, allowing you to easily write unit tests for the Client

UserConfig

UserConfig is required to Client::register (e.g. complete the connection) with Twitch

use twitchchat::UserConfig;
let my_token = std::env::var("MY_TWITCH_OAUTH_TOKEN").unwrap();
let my_name = "my_name_123";
let config = UserConfig::builder()
    .nick(my_name)   // sets you nick
    .token(my_token) // sets you password (e.g. oauth token. must start with `oauth:`)
    // capabilities these are disabled by default. so using these "toggles" the flag (e.g. flips a boolean)
    .membership()    // this enables the membership CAP
    .commands()      // this enables the commands CAP
    .tags()          // this enables the tags CAP
    .build()         // create the config
    .unwrap();       // returns an Option, None if nick/token aren't semi-valid

The irc module

The irc module contains a very simplistic representation of the IRC protocol.

Modules

commands

An assortment of Twitch commands

conversion

Message conversion types

extension

Extensions for the various types

helpers

Helpers for writing tests

irc

IRC-related stuff

Structs

Badge

Badges attached to a message

Channel

Simple channel wrapper.

Client

Client for interacting with Twitch's chat.

Color

Color represents a Twitch color

Emotes

Emotes are little pictograms used inline in twitch messages

LocalUser

Information gathered during the GLOBALUSERSTATE event

RGB

A 24-bit triplet for hex colors. Defaults to White (0xFF,0xFF,0xFF)

SyncReadAdapter

Default synchronous Reader that uses an std::io::Read implementation

SyncWriteAdapter

Default synchronous Writer that uses an std::io::Write implementation

Tags

Tags are IRCv3 message tags. Twitch uses them extensively

Token

Token allows you to keep track of things

UserConfig

Configuration used to complete the 'registration' with the irc server

UserConfigBuilder

A builder type to create a UserConfig without dumb errors (like swapping nick/token)

Writer

A thread-safe, clonable writer for the Twitch client

Enums

BadgeKind

BadgeKind are the kind of badges that are associated with messages.

Capability

Capabilities allow you to get more data from twitch

Error

An error that the Client can return

Message

Messages created by the Client.

TwitchColor

These are the default Twitch colors

Constants

TWITCH_IRC_ADDRESS

The Twitch IRC address for non-TLS connections

TWITCH_IRC_ADDRESS_TLS

The Twitch IRC address for TLS connections

Traits

Handler

Handler allows you to implement message filtering with a struct

ReadAdapter

ReadAdapter allows you to provide your own "reader" for the client

ToMessage

Convert an IRC-like message type into something that the Twitch commands can be parsed from

WriteAdapter

WriteAdapter allows you to provide your own "writer" for the client

WriterExt

Writer extensions

Functions

colors

A helper method that returns a const array of TwitchColor colors to RGB

sync_adapters

Create a sync adapater from std::io::{Read, Write}

Type Definitions

BadgeInfo

Metadata related to the chat badges.