npm

Need private packages and team management tools?Check out npm Orgs. »

node-twitch

0.1.3 • Public • Published

node-twitch

This package aims to simplify calls to the Twitch api by making the endpoints available through simple method calls.

Early version

The aim of this package is to make all twitch endpoints available through method calls in a single class. So far, the supported endpoints are limited. Therefore, a customRequest() method has been added to the api class. It lets you call any endpoint on the Twitch api using the authentication information already provided. For more info on this see Unsupported endpoints.

Installation

To install simply do,

npm install node-twitch

Usage

Before using this package, you will have to create an application on twitch to retrieve a client_id and client_secret. Use the official documentation as a guide.

Refer to the example below for a basic usage guide.

const TwitchApi = require("node-twitch");
 
// Create a new instance of the TwitchApi class and use an app access token to authenticate requests.
const api = new TwitchApi({
    client_id: "YOUR TWITCH CLIENT ID",
    client_secret: "YOUR CLIENT SECRET",
    isApp: true // When this option is enabled, an application token will be automatically acquired from twitch.
});
 
// Wait for the api to start.
api.on("ready", () => {
    // Set the options for the request.
    const options = {
        // Channels accepts a string or an array of strings representing either a user_id or a user's login name.
        channels: ["lirik", "shroud"]
    }
 
    // Call the streams endpoint.
    // The callback contains a body and a response object.
    // The body is the result returned from twitch,
    // while the response contains the http request information.
    api.getStreams(options, (body, response) => {
        console.log(body.data[0].user_name); // Should print "LIRIK" if the stream is live.
    });
});

The example above has set the isApp option set to true, which means that the api will automatically request an application token from the twitch api using your client_id and client_secret. Using this option simplifies the setup process of the api, but it prevents you from accessing any non-public user data. If you need to access private user data, such as subscribers or a user's email, you will need to authenticate the user on the client side and send the access_token and refresh_token to the server. The process of retrieving these tokens are outside the scope of this package. Refer to the official documentation on how to authenticate a user.

To use the access_token and refresh_token, refer to the following example:

const TwitchApi = require("node-twitch");
 
// Create a new instance of the TwitchApi class.
const api = new TwitchApi({
    client_id: "YOUR TWITCH CLIENT ID",
    client_secret:  "YOUR CLIENT SECRET",
    access_token: "A USER'S ACCESS TOKEN",
    refresh_token: "A USER'S REFRESH TOKEN"
});
 
// Wait for the api to start.
api.on("ready", () => {
    api.getCurrentUser( (body, response) => {
        console.log(body.data[0].display_name); // Prints the currently authenticated user's display name.
    });
});

It's worth noting that it is not necessary to wait for the ready event when using this method of authentication. In this case the the only thing the ready event indicates is that you can access the api.user object, which makes it easier to read the current user's data.

Async/Await

In addition to the syntax above, this package also uses promises, which means that you can use a async/await syntax if you'd like. The example below does the same thing as the first example, but using an async/await syntax.

const TwitchApi = require("node-twitch");
 
// Create a new instance of the TwitchApi class and use an app access token to authenticate requests.
const api = new TwitchApi({
    client_id: "YOUR TWITCH CLIENT ID",
    client_secret: "YOUR CLIENT SECRET",
    isApp: true // When this option is enabled, an application token will be automatically acquired from twitch.
});
 
// Wait for the api to start.
api.on("ready", async () => { // Uses an async function!!
    // Set the options for the request.
    const options = {
        // Channels accepts a string or an array of strings representing either a user_id or a user's login name.
        channels: ["lirik", "shroud"]
    }
 
    // Call the streams endpoint.
    // Uses async/await instead of a callback.
    // This method does not return the full response object.
    const streams = await api.getStreams(options);
    console.log(streams.data[0].user_name); // Should print "LIRIK" if the stream is live.
    
});

The biggest difference when using async/await is that the response object won't be available. Keep this in mind when deciding which syntax you'd like to use for your project.

Unsupported endpoints

If you wish to call an endpoint that is not yet supported by this package, refer to the following example:

const TwitchApi = require("node-twitch");
 
const api = new TwitchApi({
    client_id: "YOUR TWITCH CLIENT ID",
    client_secret:  "YOUR CLIENT SECRET",
    access_token: "A USER'S ACCESS TOKEN",
    refresh_token: "A USER'S REFRESH TOKEN"
});
 
// A custom request to get videos from a user_id
api.customRequest("/videos?user_id=91919297", {method: "GET"}, body => {
    console.log(body.data); // Prints array of the specified user's videos.
});

For further information, read the documentation below.

Documentation

Classes

TwitchApi

Class to control access to the Twitch api.

Typedefs

apiCallback : function

Api response callback.

apiError : Object

TwitchApi

Class to control access to the Twitch api.

Kind: global class Emits:
TwitchApi#event:ready - Fired when the api is ready to use.,
TwitchApi#event:refresh - Fired when access token is refreshed.,
TwitchApi#event:error - Fired when something goes wrong.

Properties

Name Type Description
user Object Object containing information about the currently authenticated user.
user.broadcaster_type string User's broadcaster type: "partner", "affiliate", or "".
user.description string User's channel description.
user.display_name string User's display_name.
user.email string User's email address. Is only included if scope user:read:email was included in the authentication scopes.
user.id string User's ID.
user.login string User's login name.
user.offline_image_url string URL of the user's offline image.
user.profile_image_url string URL of the user's profile image.
user.type string User's type: "staff", "admin", "global_mod", or "".
user.view_count number Total number of views of the user's channel. Does not update overtime.

new TwitchApi(config)

Initialize the api.

Param Type Description
config Object A configuration object containing your client_id and client_secret, as well as an access_token and refresh_token.
config.client_id string Your client id.
config.client_secret string Your client secret.
[config.access_token] string The access token from an authenticated user.
[config.refresh_token] string The refresh token from an authenticated user.
[config.isApp] bool A boolean value that determines whether or not the api should fetch an app access token. When using this option, you are only able to access public user information.

twitchApi.getBitsLeaderboard(options, [callback])

Get the bits leaderboard of a user or top users.

Kind: instance method of TwitchApi

Param Type Description
options Object The options for the request.
[options.count] number Number of results to be returned. Maximum: 100. Default: 10.
[options.period] string Time period over which data is aggregated (PST time zone). This parameter interacts with started_at. Valid values are given below. Default: "all". For more information visit the official api docs.
[options.started_at] string Timestamp for the period over which the returned data is aggregated. Must be in RFC 3339 format. Ignored if period is "all".
[options.user_id] string ID of the user whose results are returned; i.e., the person who paid for the Bits. If user_id is not provided, the endpoint returns the Bits leaderboard data across top users (subject to the value of count).
[callback] apiCallback The callback function.

twitchApi.getUsers(ids, [callback])

Get one or more users by their login names or twitch ids. If only one user is needed, a single string will suffice.

Kind: instance method of TwitchApi

Param Type Description
ids string | Array.<string> A list of ids and/or login names for the users to get.
[callback] apiCallback The function that will be called when execution is finished.

twitchApi.getCurrentUser([callback])

Gets the currently authenticated users profile information.

Kind: instance method of TwitchApi

Param Type Description
[callback] apiCallback The callback function.

twitchApi.getFollows(options, [callback])

Get follows to or from a channel. Must provide either from_id or to_id.

Kind: instance method of TwitchApi

Param Type Description
options Object The options to customize the request.
[options.after] string Cursor for forward pagination: tells the server where to start fetching the next set of results, in a multi-page response. The cursor value specified here is from the pagination response field of a prior query.
[options.first] number Maximum number of objects to return. Maximum: 100. Default: 20.
options.from_id string User ID. Return list of channels that the supplied user is following.
options.to_id string User ID. Return list of users who are following the supplied channel.
[callback] apiCallback The callback function.

twitchApi.getSubsById(broadcaster_id, [callback])

Get subscribers from a channel/broadcaster id.

Kind: instance method of TwitchApi

Param Type Description
broadcaster_id string | number The id of the twitch channel to get subscribers from.
[callback] apiCallback The callback function.

twitchApi.getUsersSubStatus(user_ids, [callback])

Get subscription status of users to the current broadcaster.

Kind: instance method of TwitchApi

Param Type Description
user_ids string | Array.<string> The user id/ids to check against the currently authenticated user.
[callback] apiCallback The callback function.

twitchApi.getStreams([options], [callback])

Get one or more live streams.

Kind: instance method of TwitchApi

Param Type Description
[options] Object An options object used to create the request.
[options.after] string Cursor for forward pagination: tells the server where to start fetching the next set of results, in a multi-page response. The cursor value specified here is from the pagination response field of a prior query.
[options.before] string Cursor for backward pagination: tells the server where to start fetching the next set of results, in a multi-page response. The cursor value specified here is from the pagination response field of a prior query.
[options.community_id] string Returns streams in a specified community ID. You can specify up to 100 IDs.
[options.first] number Maximum number of objects to return. Maximum: 100. Default: 20.
[options.game_id] string Returns streams broadcasting a specified game ID. You can specify up to 100 IDs.
[options.channels] string | Array.<string> A list of user ids and/or user login names, or a string of a single user id or user login name. This is not a native twitch api parameter.
[callback] apiCallback The function that will be called when execution is finished.

twitchApi.customRequest(endpoint, options, [callback])

Make a request to an endpoint that doesn't have a function.

Kind: instance method of TwitchApi

Param Type Description
endpoint string The endpoint to call including query parameters eg. "/games?id=493057"
options Object A request options object, see the request module for all available options. The url parameter will be overwritten by the first argument of the function, so there is no need to specify it.
[callback] apiCallback The callback function.

"ready"

Event fired when the api is ready to use.

Kind: event emitted by TwitchApi

"refresh"

Refresh event fired when the access token is refreshed. Listening to this event lets you access new refresh and access tokens as they refresh. The refresh and access token in the existing instance will update automatically.

Kind: event emitted by TwitchApi Properties

Name Type Description
access_token string The new access token.
refresh_token string The new refresh token. Is not always included.
expires_in number The amount of time in seconds until the access token expires.
scope string | Array.<string> The scopes associated with the access token.

"error"

Error event emitted when something fails in the api.

Kind: event emitted by TwitchApi

apiCallback : function

Api response callback.

Kind: global typedef

Param Type Description
body Object A json parsed object containing the body of the response.
response Object The entire response object from the request.

apiError : Object

Kind: global typedef Properties

Name Type Description
type string The type of error, eg. "http"
code number The status code of the http request.
statusMessage string Short message explaining the error.
message string Long message explaining the error.

install

npm i node-twitch

Downloadsweekly downloads

15

version

0.1.3

license

ISC

homepage

github.com

repository

Gitgithub

last publish

collaborators

  • avatar
Report a vulnerability