2.0.2 • Published 5 years ago

fair-twitch v2.0.2

Weekly downloads
2
License
GPL-3.0
Repository
github
Last release
5 years ago

fair-twitch is a Twitch API and Chat bot library written in JavaScript for Node.

Note: This was made for personal use, so it probably won't be supported that much. That being said, you can always submit issues and pull requests and I will look at them.

Table of contents

Installation

Install via npm:

npm install fair-twitch

Basic setup

The module is divided up into a chat and API part. The API part handes api requests, while the chat handles Twitch IRC.

var fairTwitch = require('fair-twitch');

var api = new fairTwitch.api(<options>);
// Do api stuff

var chat = new fairTwitch.chat(<option>);
// Do chat stuff...

API usage

To use the API you need to have or register a Twitch developer application to get a client ID.

You can do that on the Twitch Developer Apps Dashboard.

Once you have a clientID, you can start a simple API client:

var fairTwitch = require('fair-twitch');
var api = new fairTwitch.api('<Your Twitch client ID>');

Some API calls require OAuth token, client secret, redirect URL. These can be added to the constructor options:

var fairTwitch = require('fair-twitch');
var api = new fairTwitch.api({
  clientID: '<Your Twitch client ID',
  clientSecret: 'Your Twitch client secret',
  redirectURL: 'Your Twitch OAuth redirect URL',
  refreshToken: 'Account OAuth refresh token',
  accessToken: 'Account OAuth access token'
});

The access token will be automatically refreshed before a request if one of these conditions is met:

  • The refresh token is not null while the access token is null.
  • Retry latest request after token refresh if it emitted a 401 authentication failed response.
  • accessTokenExpireTS option is close to or less than Date.now().

You can disable auto token refresh using the autoRefreshAccessToken constructor option.

The api will automatically validate access token on construction, unless validateToken constructor option is false. You can find more info on constructor options further down.

The API will try to figure out if the call is for Twitch new API or API v5 and change authorization header accordingly. Find calls in Twitch New API reference or API v5 reference.

api.get('<API call>', function(err, data) {
  // Handle error and data
});

api.post('<API call>', function(err, data) {
  // Handle error and data
});

api.delete('<API call>', function(err, data) {
  // Handle error and data
});

api.put('<API call>', function(err, data) {
  // Handle error and data
});

The API will add client ID and authorization headers automatically. If you don't want to add a header, you can pass in an options parameter instead:

api.get({
  url: 'helix/streams',
  clientID: null, // Null to ignore client ID header
  accessToken: null // Null to ignore access token header
}, function(err, data) {
  // Handle error and data
});

The api also contains functions like api.getAuthenticationURL(...scopes) and api.getRefreshToken(code, callback) to help with the Twitch authentication process. An example of OAuth Authorization Code Flow using express can be seen here.

API constructor options

OptionDefaultDescription
clientIDnullYour Twitch client ID
clientSecretnullYour Twitch client secret
redirectURLnullYour Twitch OAuth redirect URL
refreshTokennullAccount OAuth refresh token
accessTokennullAccount OAuth access token
accessTokenExpiresTSnullThe timestamp of when the access token expires. Null means never prompt a refresh using the timestamp.
autoRefreshTokentrueIf api should auto refresh token on authorization failed error and try again
validateTokentrueIf the api should validate token on construction
apiURL'https://api.twitch.tv/'The Twitch API base URL
authURL'https://id.twitch.tv/'The Twitch auth base URL

API events

EventArgsDescription
erroranyWhen an error happens in the other events
tokenvalidatedataWhen the accesstoken was validated. Can be manually done with api.validateAccessToken()
tokenrefreshdataWhen the access token was refreshed. Can be manually done with api.refreshAccessToken()
debug...anyDebug messages

Chat usage

Chat can either log in anonymously (unable to send chat messages) or by using a valid access token with chat scopes and a login.

Login to chat anonymously:

var fairTwitch = require('fair-twitch');
var chat = new fairTwitch.chat();
chat.on('ready', function() {
  // I have now successfully connected and authenticated!
});

Login to chat with token:

var fairTwitch = require('fair-twitch');
var chat = new fairTwitch.chat({
  login: '<Your Twitch login>',
  token: '<Your OAuth access token>'
});
chat.on('ready', function() {
  // I have now successfully connected and authenticated!
});

An OAuth token can be generated here or you can do it with your own application by following Twitch's authentication process.

Join and leave channel chat rooms:

chat.join('<channel>', [callback]);
chat.part('<channel>', [callback]);

Send chat messages:

chat.say('<channel>', '<message>');

The chat automatically parses irc messages and emits events for specific messages. See further down for all events emitted.

Some other basic events:

chat.on('error', function(error) {
  // Handle errors
});

chat.on('msg', function(channel, login, message, tags) {
  // Handle a message.
  // Tags contains a bunch of information like bits.
});

chat.on('usernotice', function(channel, login, message, tags) {
  // Handle subs, resubs, giftsubs and so on.
  // Tags contains a bunch of information.
});

I've created some wrappers to help handle notifications and joined channels. You can create them using:

var notifications = chat.createNotificationsEmitter();
// If done with it, run notifications.dispose();

var roomTracker = chat.createRoomTracker();
// If done with it, run roomTracker.dispose();

Read more about NotificationsEmitter or RoomTracker futher below.

Chat events

EventArgsDescription
erroranyWhen an error has happened
parseerrorline, errorWhen a parse error happens
readynoneWhen successfully connected and authorized
rawmessage, parsedA raw IRC event
rawSendmessageWhen a raw message is sent out
joinchannelWhen you have joined a channel
partchannelWhen you have left a channel
userjoinchannel, loginWhen a user joined a channel
userpartchannel, loginWhen a user left a channel
msgchannel, login, message, tagsWhen a message was submitted to a channel
roomstatechannel, tagsWhen a channel changes its roomstate (like submode, slowmode)
usernoticechannel, login, message, tagsWhen a usernotice has happened (like a sub, resub, giftsub)
noticechannel, message, tagsWhen a channel notice happens (example: slow mode off)
clearchatchannelHappens when a chat is cleared by a moderator
userbanchannel, login, tagsUser was permanently or temporarily banned (tags has ban-duration if not permanent)
clearmsgchannel, tagsHappens when a single message was removed
globaluserstatetagsHappens on successful login, tags contain information about user. Note: Does not happen on anonymous logins
userstatechannel, tagsHappens when you join a channel, tags contain information about user
hostchannel, target, [viewers]Happens when a channel hosts a target channel. Viewers is a number when started hosting, undefined if already hosting. If taget is '-', it means it stopped hosting

Chat constructor options

OptionDefaultDescription
loginnullThe Twitch login.
tokennullThe Twitch auth token. Required if login is given. Example: cfabdegwdoklmawdzdo98xt2fo512y
autoReconnecttrueIf it should autoconnect on connection loss
requestCAPtrueIf you want to request Twitch capabilities
autoConnectbooleanIf you want to connect automatically on construction
url'irc.chat.twitch.tv'The Twitch IRC URL
port6667The Twitch IRC Port
successMessagescustom array of stringsSome of the required messages for a successful connect. See irc docs for information. Do not change unless the default is not updated for it

Chat notifications emitter

Chat notifications emitter is a chat wrapper that helps with handling usernotice and bits messages. The object is an event emitter.

Create a notifications emitter:

var notifications = chat.createNotificationsEmitter();
notifications.on('sub', function(channel, data) {
  // Handle new subscription in channel
});

Dispose emitter when done:

// This will remove listeners from chat object
notifications.dispose();

Notifications emitter events

EventArgsDescription
subchannel, data, tagsWhen a new subscription happens
resubchannel, data, tagsWhen a resubscription happens
giftsubchannel, data, tagsWhen someone gifts another user a subscription (does not emit each from massgiftsub)
massgiftsubchannel, data, tagsWhen someone mass gift subs to a channel. Data contains information about all recepients
bitschannel, data, tagsWhen someone sends bit message to a channel
anyevent, channel, data, tagsWhen any of the above events happen

Chat room tracker

Chat room tracker is a chat wrapper that helps with handling which channels/rooms you have joined and what it's room states are. The object is an event emitter.

Create a room tracker:

var roomTracker = chat.createRoomTracker();
roomTracker.on('<event>', ...);

Dispose emitter when done:

// This will remove listeners from chat object
roomTracker.dispose();

Print out the rooms you're in:

roomTracker.rooms.forEach(function(room) {
  console.log('I am in channel #' + room.channel);
  console.log('Channel state:', room.state);
});

Notice that the room tracker will only track new join and part events.

Room tracker events

EventArgsDescription
joinchannelWhen a channel is joined
partchannelWhen a channel is left
statechannel, stateWhen a channel room state has changed
changechannelWhen any changes has been made to any room (join, left, state)

Migrating from 1.x

The module has gone under a complete rewrite from 1.x to 2.x to work with the new Twitch api and chat. It's recommended that you either keep 1.x or rebuild your app using the new docs from this readme.

2.0.2

5 years ago

2.0.1

5 years ago

2.0.0

5 years ago

1.3.2

6 years ago

1.3.1

6 years ago

1.3.0

6 years ago

1.2.2

6 years ago

1.2.1

6 years ago

1.2.0

6 years ago

1.1.4

7 years ago

1.1.3

7 years ago

1.1.2

7 years ago

1.1.1

7 years ago

1.1.0

7 years ago

1.0.4

7 years ago

1.0.3

7 years ago

1.0.2

7 years ago

1.0.0

7 years ago