@splitmedialabs/chinterface
v3.0.19
Published
Universal Chat interface library for popular stream services
Readme
Chinterface (Chat Interface)
A unified interface for Chats around the world.
Services Supported
- Twitch (Read/Write)
- Kick (Read/Write)
- YouTube (Read/Write)
- YouTube Live (Read/Write)
- Facebook Live (Read/Write)
Notes
It is recommend to apply the following styles to emotes across all services.
.emoticon {
vertical-align: middle;
display: inline-block;
}Twitch
This interface connects to Twitch's chat socket server. New messages arrive instantly as they are sent on Twitch.
Setup and Usage
// Twitch.
import chinterface from 'chinterface';
async function twitch() {
const twitch = chinterface.service('twitch');
try {
// Set the default config values.
await twitch.setConfig({
// Main configuration
clientId: 'as545trdsFdgghNXoyit83nguf11gpOx', // REQUIRED. Your Twitch Application Client ID.
channel: 'oyed', // REQUIRED. If you do not know the channel, pass through accessToken and make a request to loadUser().
userId: 123456, // Optional; REQUIRED to fetch badges. If you do not know the user ID, pass through accessToken and make a request to loadUser().
// Settings
reconnect: false, // Default: true [auto reconnect if connection is lost]
parseEmoticon: false, // Default: true [convert emoticons to images]
formatMessages: false, // Default: true [process message and convert emoticons; body will be null if false]
// Optional; REQUIRED for sending/writing messages
username: 'oyed', // The user's Twitch username. This is ONLY used to authenticate to send messages.
accessToken: 'as545trdsFdgghNXoyit83nguf11gpOx', // The user's Twitch API access token. This is ONLY used to authenticate to send messages.
});
// If you do not know the username, channel or userId, make a request to loadUser(). It will set these values for you.
await twitch.loadUser();
// Connect to the socket server.
await twitch.connect();
// To receive and listen for new, formatted messages.
twitch.on('message', (data) => {
/**
* `data` will always return the following structure:
*
* {string} id - The chat message ID; generated by Twitch.
* {string} username
* {string} body - The processed message, with <img> tags for emotes.
* {string} raw - The unprocessed message, direct from the service.
* {number} timestamp - The time in milliseconds.
* {Object} extra - Service-specific information.
*/
console.log('New message', data);
});
// To send a message.
twitch.send('test message');
// Helix HTTP 401 or IRC "Login authentication failed" / login_unsuccessful.
twitch.on('refresh-token', (errorDetails) => {
twitch.setConfig({
accessToken: 'new',
});
twitch.connect();
});
// Disconnect from the socket server.
await twitch.disconnect();
} catch (e) {
console.log(e);
}
}Chinterface provides a set of unique events and functions that assist in the display and handling of messages for Twitch.
Fetch and Set Twitch User Information
In cases where you do not know the userId, channel or username, you can use the loadUser() function to set the config for you.
Requires clientId and accessToken. This function will NOT overwrite any previously set properties.
await twitch.loadUser();Accessing TMI Events
Chinterface provides a clean wrapper to directly access TMI Events. This is useful when you want to listen to clearchat, timeouts or bans.
See here for a list of events: https://docs.tmijs.org/v1.2.1/Events.html
twitch.clientOn('timeout', (channel, username, reason, duration) => {
// Remove all messages for the given channel and username
});
twitch.clientOn('ban', (channel, username, reason) => {
// Remove all messages for the given channel and username
]);
twitch.clientOn('clearchat', channel => {
// Remove all messages for the given channel
});Badges
It's common to output a user's associated badges when displaying Twitch messages. You may use the getBadges() function to return a list of badges and respective URLs for the connected channel.
Requires clientId and userId. If you do not know the user ID, make a request to loadUser() first.
// Get all badges for all connected Twitch channels
const badges = await twitch.getBadges();Kick
This interface reads live chat over Kick's public Pusher WebSocket (the same socket kick.com uses). Send and loadUser() use the official Kick Public API. Live read is unofficial: Kick's documented Events API is webhooks-only, which this client library cannot receive.
- Chat
- Users
- Channels
- Webhook payloads (shape reference only; not consumed)
- OAuth
Kick Public API requests are Bearer-only. Do not pass clientId (there is no Client-ID header). If a consumer still passes clientId, it is ignored.
Setup and Usage
// Kick.
import chinterface from '@splitmedialabs/chinterface';
async function kick() {
const kick = chinterface.service('kick');
try {
// Set the default config values.
await kick.setConfig({
// Main configuration
channel: 'oyed', // Kick slug. If unknown, pass accessToken and call loadUser().
userId: 123456, // Optional; REQUIRED to send. Filled by loadUser() if omitted.
chatroomId: 259821, // Optional; resolved from slug on connect if omitted.
// Settings
reconnect: false, // Default: true [auto reconnect if connection is lost]
parseEmoticon: false, // Default: true [convert emoticons to images]
formatMessages: false, // Default: true [process message and convert emoticons]
// Optional; REQUIRED for sending/writing messages and loadUser()
accessToken: '...', // Kick user token (Bearer).
sendAs: 'user', // Optional; 'user' (default) or 'bot'
});
// Only needed for authenticated user information, not anonymous chat reading.
await kick.loadUser();
// To receive and listen for new, formatted messages.
kick.on('message', (data) => {
/**
* `data` will always return the following structure:
*
* {string} id - Kick message UUID.
* {string} username
* {string} body - The processed message, with <img> tags for emotes.
* {string} raw - The unprocessed message, direct from the service.
* {number} timestamp - The time in milliseconds.
* {Object} extra - Service-specific information.
*
* extra.colour - sender.identity.color
* extra.badges - Twitch-like object, e.g. { moderator: '1', subscriber: '3' }
* extra.subscriber - boolean
* extra.mod - boolean
* extra.broadcaster - boolean
* extra.turbo - always false (Kick has no turbo)
* extra.emotes - { '4148074': 'HYPERCLAP' } or null
* extra.kickBadges - raw Kick badge array (identity.badges plus selected badges_v2)
* extra.kickBadgesV2 - identity.badges_v2 (global/level badges)
* extra.level - Kick watch-time level from selected badges_v2, or null
* extra.verified - boolean
* extra.slug - sender slug
* extra.identity - raw Kick identity object
* extra.repliesTo - reply metadata when present
*/
console.log('New message', data);
});
// Register listeners before connecting so initial messages are not missed.
kick.on('error', (error) => {
console.error('Kick connection/API error', error.message, error.code);
});
// Resolves after the selected chatroom subscription is acknowledged.
await kick.connect();
// To send a message (POST /public/v1/chat, max 500 characters).
kick.send('test message');
// Kick Public API HTTP 401 (Bearer send / loadUser). Live Pusher read does not use a token.
kick.on('refresh-token', (errorDetails) => {
kick.setConfig({
accessToken: 'new',
});
});
// Disconnect from the socket server.
await kick.disconnect();
} catch (e) {
console.log(e);
}
}Fetch and Set Kick User Information
In cases where you do not know the userId, channel or username, you can use the loadUser() function to set the config for you.
Requires accessToken only (no clientId). This function will NOT overwrite any previously set properties. It does not set chatroomId — the official channels API has no chatroom id. connect() resolves chatroomId from the Kick slug (GET https://kick.com/api/v2/channels/{slug}). If that unofficial lookup fails (Cloudflare), pass chatroomId in setConfig.
await kick.loadUser();Kick connection and diagnostics
Since 3.0.19, each connection asks
POST https://web.kick.com/api/v1/realtime/connection for the current public
Pusher application key and cluster, requesting the pusher provider. This
replaces the retired application that returned code 4001 in
Broadcaster #818.
If discovery cannot be fetched or decoded (for example CORS, HTTP/network
failure, a timeout or invalid JSON),
Chinterface logs DISCOVERY ERROR with usingFallback: true and uses the built-in
public configuration verified on 26 November 2026. This fallback can itself
become outdated; a 4001 failure includes the server reason and needs updated
configuration. A successfully decoded response that lacks usable Pusher
credentials (including an unsupported provider) fails explicitly without fallback.
There is no XBC/Kick client secret or new OAuth scope involved in chat reading.
Optional advanced settings in setConfig:
pusherKey: explicit public application key; skips discovery.pusherCluster: optional cluster override. With an explicit key, defaults tous2; otherwise uses the discovered cluster (or the fallback'sus2).connectionTimeout: milliseconds per lookup/discovery, socket handshake and subscription stage; default15000.
connect() resolves and emits connected only after acknowledgement for
chatrooms.<id>.v2. Missing channel/chatroomId rejects configuration validation
without emitting error. Failures after validation emit error with available
code, status, message and retryable fields. With automatic reconnect
enabled, recoverable startup failures keep the original connect() promise
pending through backoff/retry until subscription succeeds. Each request,
handshake and subscription attempt remains bounded by connectionTimeout.
Terminal failures, failures with reconnect: false, and disposal reject that
promise. This preserves Kick Chat Viewer's startup ownership: a temporary drop
before subscription must not cause it to dispose the service and cancel retries. Socket failures do
not emit refresh-token; the existing authenticated API's token-refresh handling
is unchanged. Pusher 4000-4099 and subscription rejection stop retries with the
same parameters. Recoverable failures use backoff and rediscover/resubscribe;
reconnect: false disables this. disconnect() cancels pending startup and
clears owned timers/socket callbacks; callers should handle a pending
connect() rejection when disposing.
Build and automated checks for this change:
yarn build
yarn test:kick
yarn test:token-refresh
yarn test:super-chat
yarn test:live-eventsWith the viewer's Node 24 toolchain, the optional integration check reads its existing logger/transform and connection owner without changing the viewer checkout:
node test/node/kick-viewer-logging.test.js /path/to/kick-chatIt exercises the candidate modern bundle through the actual viewer logging adapter and startup/disposal contract using synthetic socket data. This is not a live viewer runtime test.
Kick diagnostics use stable [KICK ...] labels and metadata including
attemptId, stage and elapsedMs. Important labels include RESOLVE CHATROOM
START/DONE/ERROR, DISCOVERY START/DONE/ERROR, CONNECT, SOCKET OPEN,
HANDSHAKE DONE, SUBSCRIBE, CONNECTED, FRAME RECEIVED/ERROR, EMIT MESSAGE,
MESSAGE ERROR, SOCKET ERROR, CONNECT ERROR, DISCONNECTED, RECONNECT,
RECONNECT SUPPRESSED and DISCONNECT. Failures retain available HTTP/Pusher
codes, sanitized reasons and retry information. Browser WebSocket errors may
provide no further cause. Logs omit tokens, authorization/cookies and message
bodies; repeated malformed-frame/message errors are summarized on the first
occurrence and every 100 occurrences per connection attempt. Logging failures
cannot interrupt delivery.
In Kick Chat Viewer these labels flow through its existing adapter under
[KICK CHAT VIEWER] [CHINTERFACE] in the viewer console/Broadcaster session
logs. The viewer's existing enhanced logging (DevDebug equal to 1) enables
routine connection/message traces; failures and abnormal closes remain visible
when it is off. In a standalone browser consumer, window.DEBUGLOG = true
enables the standard Chinterface logger. error events and rejected promises
remain available independently of the logging flag.
For pre-publication testing, build Chinterface with yarn build, then copy
dist/ contents into the viewer's
node_modules/@splitmedialabs/chinterface/dist/. Rebuild/reload the viewer to
consume the copied bundle. Nico performs the manual live test: successive
messages appear on Kick and in the viewer, recovery/cleanup work, and the new
traces appear with enhanced logging enabled. This local copy does not change
its dependency manifest or lockfile. Update the consumer dependency only after
the fixed scoped package has been published.
Accessing Kick chatroom events
Chinterface provides a pass-through for Kick Pusher chatroom events. This is useful when you want to listen to chat clears, deletes, or bans. Callbacks receive the parsed JSON data object.
cheer / clearchat / timeout / ban are Twitch TMI names and will not fire on Kick.
// Chat was cleared — remove all messages (Twitch equivalent: clearchat)
kick.clientOn('App\\Events\\ChatroomClearEvent', (data) => {
// Remove all messages for the channel
});
// A viewer sent a chat message (also available via on('message'))
// kick.clientOn('App\\Events\\ChatMessageEvent', (data) => {});
// A chat message was deleted — remove that message from the UI
// kick.clientOn('App\\Events\\MessageDeletedEvent', (data) => {});
// A user was banned or timed out — remove that user's messages
// kick.clientOn('App\\Events\\UserBannedEvent', (data) => {});
// A user ban/timeout was lifted
// kick.clientOn('App\\Events\\UserUnbannedEvent', (data) => {});
// A message was pinned in chat
// kick.clientOn('App\\Events\\PinnedMessageCreatedEvent', (data) => {});
// A pinned message was removed
// kick.clientOn('App\\Events\\PinnedMessageDeletedEvent', (data) => {});
// A user subscribed or renewed
// kick.clientOn('App\\Events\\SubscriptionEvent', (data) => {});
// A user gifted one or more subs
// kick.clientOn('App\\Events\\GiftedSubscriptionsEvent', (data) => {});
// Follower count / follow activity on the channel
// kick.clientOn('App\\Events\\FollowersUpdatedEvent', (data) => {});
// Another channel hosted this channel
// kick.clientOn('App\\Events\\StreamHostEvent', (data) => {});
// Chatroom settings changed (slow mode, sub-only, etc.)
// kick.clientOn('App\\Events\\ChatroomUpdatedEvent', (data) => {});
// A chat poll was created or updated
// kick.clientOn('App\\Events\\PollUpdateEvent', (data) => {});
// A channel reward was redeemed
// kick.clientOn('App\\Events\\RewardRedeemedEvent', (data) => {});YouTube
This interface polls the YouTube API every interval milliseconds. New messages arrive periodically.
REMEMBER. YouTube auth tokens expire every 1 hour. You MUST listen for the refresh-token event and update the
config value when you encounter this event.
Setup and Usage
// YouTube
import chinterface from 'chinterface';
async function youtube() {
const youtube = chinterface.service('youtube');
try {
// Set the default config values.
await youtube.setConfig({
// Main configuration
accessToken: '', // REQUIRED.
liveChatId: 'EiEKGFVDVW1mV2tPSWxoek1fZDA2cXpvc2lBQRIFL2xpdmU', // REQUIRED. If unknown, set accessToken and make a request to loadChatId() before connecting.
// Settings
parseEmoticon: false, // Default: true [convert emoticons to images]
parseUrl: false, // Default: true [convert URLs to anchor tags]
formatMessages: false, // Default: true [process message and convert emoticons; body will be null if false]
interval: 7000, // Default: 5000 [time in ms to check for next set of messages]
maxResults: 500, // Default: 200 [the number of messages to return each check]
profileImageSize: 32, // Default: 64 [size in pixels to return profile images at]
});
// If you do not know the liveChatId, set accessToken and make a request to this function.
// If you already know the liveChatId, this function is NOT required.
await youtube.loadChatId();
// Start fetching new messages.
youtube.connect();
// To receive and listen for new, formatted messages.
youtube.on('message', (data) => {
/**
* `data` will always return the following structure:
*
* {string} id - The chat message ID; generated by YouTube.
* {string} username
* {string} body - The processed message.
* {string} raw - The unprocessed message, direct from the service.
* {number} timestamp - The time in milliseconds.
* {Object} extra - Service-specific information.
*/
console.log('New message', data);
});
// To send a message.
youtube.send('test message');
// Listen for the refresh token event.
youtube.on('refresh-token', () => {
// Your refresh token logic here...
const accessToken = 'new';
youtube.setConfig({
accessToken,
});
// Start fetching messages again.
// If preferred, you can call youtube.fetchMessages() directly to avoid the connect logic.
youtube.connect();
});
// Listen out for any API errors so to react accordingly.
youtube.on('error', (error) => {
switch (error.errors[0].reason) {
case 'liveChatDisabled':
// lets just destroy the interface
break;
case 'liveChatEnded':
// lets disconnect
break;
}
});
// Disconnect from the socket server.
await youtube.disconnect();
} catch (e) {
// This will typically return the error detail as listed here: https://developers.google.com/youtube/v3/live/docs/errors
console.log(e);
}
}Chinterface provides a set of unique events and functions that assist in the display and handling of messages for YouTube.
Fetch and Set Live Chat ID
In cases where you do not know the liveChatId, you can use the loadChatId() function to set the config for you.
Requires accessToken. This function will NOT overwrite any previously set properties.
await youtube.loadChatId();User Events
The YouTube interface emits a number of different events for actions including message deletion, user banning, chat ending and many more.
This interface will also emit an 'error' event for every 'Error detail' listed here: https://developers.google.com/youtube/v3/live/docs/errors You will receive the error object in the payload.
// An API error occurred
youtube.on('error', (errorDetails) => {
console.log('API error', errorDetails);
});
// The user's token has expired
youtube.on('refresh-token', (errorDetails) => {
console.log('Token expired', errorDetails);
});
// A message is deleted
youtube.on('delete-message', (messageId) => {
console.log('Deleted Message (ID): ', messageId);
});
// A user is banned
youtube.on('user-banned', (data) => {
/**
* `data` will always return the following structure:
*
* {object} bannedUserDetails
* ** {string} channelId - The author's channel ID
* ** {string} channelUrl - The author's channel URL
* ** {string} displayName - The author's username
* ** {string} profileImageUrl - The author's avatar
* {string} banType - The type of ban, permanent or temporary
* {integer} banDurationSeconds - Length of time the ban is in effect for, only present if banType === temporary
*/
console.log('User banned: ', data);
});
// Chat ended
youtube.on('chat-ended', () => {
console.log('Chat has finished.');
youtube.disconnect();
});
// New super chat event
youtube.on('super-chat', (data) => {
/**
* `data` will always return the following structure:
*
* {string} id - The liveChatMessage id
* {string} publishedAt - ISO 8601 timestamp
* {string} type - 'superChatEvent' or 'superStickerEvent'
* {object} author - Supporter channel details
* ** {string} channelId
* ** {string} channelUrl
* ** {string} displayName
* ** {string} profileImageUrl
* ** {boolean} isVerified
* ** {boolean} isChatModerator
* ** {boolean} isChatOwner
* ** {boolean} isChatSponsor
* {object} superChat - Payment details
* ** {string|integer} amountMicros
* ** {string} currency
* ** {string} amountDisplayString - Formatted amount with currency symbol
* ** {string} userComment - Comment text (empty for super stickers)
* ** {integer} tier
* ** {boolean} isSuperSticker - Present and true for superStickerEvent
* ** {object} superStickerMetadata - Present for superStickerEvent
*/
console.log('Super chat: ', data);
});
// Jewels gift event (live chat giftEvent)
youtube.on('gift', (data) => {
/**
* `data` will always return the following structure:
*
* {string} id - Live chat message id (may repeat when comboCount updates)
* {string} publishedAt - ISO 8601 timestamp
* {string} type - 'giftEvent'
* {object} author - Viewer who redeemed Jewels
* {object} gift
* ** {string} giftName
* ** {number} jewelsAmount
* ** {string} giftUrl - Gift image/asset URL
* ** {number} giftDurationSeconds
* ** {number} giftDurationNanos
* ** {string} altText
* ** {string} language
* ** {boolean} hasVisualEffect
* ** {number} comboCount - 0 if not a combo
*/
console.log('Gift: ', data);
});
// Other live-chat system events (same on youtubeLive):
// membership-gift, membership-gift-received, new-sponsor,
// member-milestone, poll, message-retracted, sponsor-only-modeDebug triggers (QA)
Send these as live chat text (prefix match). Works on youtube and youtubeLive.
| Chat body | Result |
|---|---|
| XBCTriggerSuperChatEvent | Emits super-chat with sample $5.00 payload |
| XBCTriggerSuperChatEvent Hello | Same; superChat.userComment = Hello |
| XBCTriggerGiftEvent | Emits gift with sample Rose / Jewels payload |
| XBCTriggerGiftEvent Nice! | Emits gift with sample Rose / Jewels payload (extra text does not change the gift payload) |
In every case the original chat line is also emitted as a normal message
with its full, unmodified text (the XBCTrigger… prefix included). This lets
debug triggers appear in chat views while still firing the fake event.
YouTube Live
This interface streams live chat messages using YouTube's liveChatMessages.streamList API over HTTP GET streaming (fetch). New messages arrive with lower latency than the polling youtube service.
Works in browser apps (including UMD imports). Uses the same host and auth as the REST YouTube API.
REMEMBER. YouTube auth tokens expire every 1 hour. You MUST listen for the refresh-token event and update the config value when you encounter this event.
The message payload and all other events (delete-message, user-banned, chat-ended, super-chat, etc.) use the same structure as the youtube service.
Setup and Usage
// YouTube Live (browser)
import ChinterfaceModule from 'chinterface/dist/chinterface.umd.js';
const chinterface = ChinterfaceModule.default || ChinterfaceModule;
async function youtubeLive() {
const youtubeLive = chinterface.service('youtubeLive');
try {
// Set the default config values.
await youtubeLive.setConfig({
// Main configuration
accessToken: '', // REQUIRED.
liveChatId: 'EiEKGFVDVW1mV2tPSWxoek1fZDA2cXpvc2lBQRIFL2xpdmU', // REQUIRED. If unknown, set accessToken and make a request to loadChatId() before connecting.
// Settings
parseEmoticon: false, // Default: true [convert emoticons to images]
parseUrl: false, // Default: true [convert URLs to anchor tags]
formatMessages: false, // Default: true [process message and convert emoticons; body will be null if false]
maxResults: 500, // Default: 500 [max messages returned on initial stream connect; 200–2000]
profileImageSize: 32, // Default: 64 [size in pixels to return profile images at]
reconnect: true, // Default: true [auto reconnect if the stream ends]
streamBaseUrl: 'https://www.googleapis.com', // Default. Base URL for streamList HTTP streaming.
});
// If you do not know the liveChatId, set accessToken and make a request to this function.
// If you already know the liveChatId, this function is NOT required.
await youtubeLive.loadChatId();
// Start streaming live chat messages.
youtubeLive.connect();
// To receive and listen for new, formatted messages.
youtubeLive.on('message', (data) => {
/**
* `data` will always return the following structure:
*
* {string} id - The chat message ID; generated by YouTube.
* {string} username
* {string} body - The processed message.
* {string} raw - The unprocessed message, direct from the service.
* {number} timestamp - The time in milliseconds.
* {Object} extra - Service-specific information.
*/
console.log('New message', data);
});
// To send a message.
youtubeLive.send('test message');
// Listen for the refresh token event.
youtubeLive.on('refresh-token', () => {
// Your refresh token logic here...
const accessToken = 'new';
youtubeLive.setConfig({
accessToken,
});
// Reconnect the stream with the new token.
youtubeLive.connect();
});
// Listen out for any API errors so to react accordingly.
youtubeLive.on('error', (error) => {
switch (error.errors[0].reason) {
case 'liveChatDisabled':
// lets just destroy the interface
break;
case 'liveChatEnded':
// lets disconnect
break;
}
});
// Disconnect from the stream.
await youtubeLive.disconnect();
} catch (e) {
// This will typically return the error detail as listed here: https://developers.google.com/youtube/v3/live/docs/errors
console.log(e);
}
}YouTube vs YouTube Live
| | youtube | youtubeLive |
|---|---|---|
| Transport | REST polling | HTTP stream (/liveChat/messages/stream) |
| Latency | Periodic (interval, default 5s) | Push as messages arrive |
| Environment | Browser and Node.js | Browser and Node.js |
| Config | interval, maxResults | maxResults, reconnect, streamBaseUrl |
| Sending messages | REST API | REST API (same as youtube) |
Use youtubeLive when you need lower-latency chat via streamList. Use youtube for a simpler polling setup.
Fetch and Set Live Chat ID
In cases where you do not know the liveChatId, you can use the loadChatId() function to set the config for you.
Requires accessToken. This function will NOT overwrite any previously set properties.
await youtubeLive.loadChatId();User Events
The YouTube Live interface emits the same events as the youtube interface for actions including message deletion, user banning, chat ending and many more.
This interface will also emit an 'error' event for every 'Error detail' listed here: https://developers.google.com/youtube/v3/live/docs/errors You will receive the error object in the payload.
// An API error occurred
youtubeLive.on('error', (errorDetails) => {
console.log('API error', errorDetails);
});
// The user's token has expired
youtubeLive.on('refresh-token', (errorDetails) => {
console.log('Token expired', errorDetails);
});
// A message is deleted
youtubeLive.on('delete-message', (messageId) => {
console.log('Deleted Message (ID): ', messageId);
});
// A user is banned
youtubeLive.on('user-banned', (data) => {
console.log('User banned: ', data);
});
// Chat ended
youtubeLive.on('chat-ended', () => {
console.log('Chat has finished.');
youtubeLive.disconnect();
});
// New super chat event
youtubeLive.on('super-chat', (data) => {
/**
* Same nested structure as the `youtube` service super-chat event.
* See the YouTube super-chat listener documentation above.
*/
console.log('Super chat: ', data);
});This interface polls the Facebook Graph API every interval milliseconds. New comments arrive periodically from the /{live-video-id}/comments edge.
All requests use the latest Graph API version (v25.0 by default) against https://graph.facebook.com.
On each poll, the interface also checks the live video status and disconnects automatically when it is no longer LIVE or SCHEDULED_LIVE. After the first comments are received, subsequent polls pass a since timestamp so only newer comments are returned.
Setup and Usage
// Facebook
import chinterface from 'chinterface';
async function facebook() {
const facebook = chinterface.service('facebook');
try {
// Set the default config values.
await facebook.setConfig({
// Main configuration
liveVideoId: '1234567890', // REQUIRED. Live Video ID to poll comments for.
accessToken: 'page-access-token', // REQUIRED. Page access token for the broadcasting Page.
// Settings
version: 'v25.0', // Default: v25.0 [Graph API version]
parseUrl: false, // Default: true [convert URLs to anchor tags]
interval: 5000, // Default: 5000 [time in ms between comment polls]
videoId: '9876543210', // Optional; REQUIRED to send comments via send(). The underlying Video object ID.
});
// Fetches the token owner's id and name, and detects whether the token is a Page token.
// If you already know userId and username, this function is NOT required.
await facebook.loadUser();
// Start polling for comments.
await facebook.connect();
// To receive and listen for new, formatted messages.
facebook.on('message', (data) => {
/**
* `data` will always return the following structure:
*
* {string} id - The comment ID; generated by Facebook.
* {string} username
* {string} body - The processed message.
* {string} raw - The unprocessed message, direct from the service.
* {number} timestamp - The time in milliseconds.
* {Object} extra - Service-specific information.
* - {user_id} - int [sender's user id]
* - {image} - string [sender's profile image, or null]
* - {broadcaster} - boolean [if message is from the owner]
* - {attachment} - object [comment attachment, if any]
*/
console.log('New message', data);
});
// Sending is only available when loadUser() detects a Page access token
// and videoId is set.
facebook.send('test message');
// Graph code 190 / 102, error_subcode 463 / 467, or HTTP 401 (not 403).
facebook.on('refresh-token', (errorDetails) => {
facebook.setConfig({
accessToken: 'new',
});
facebook.connect();
});
// Stop polling.
await facebook.disconnect();
} catch (e) {
console.log(e);
}
}Fetch and Set User Information
In cases where you do not know the userId or username, you can use the loadUser() function to set the config for you.
Requires accessToken. This function will NOT overwrite any previously set properties. It also probes whether the token is a Page access token (required for send()).
await facebook.loadUser();Sending Comments
Posting comments requires:
- A Page access token (detected by
loadUser()) videoIdset to the underlying Video object ID (not the Live Video ID)
send() posts to /{videoId}/comments. If you need to post against the live video node directly, use sendMessageToPage(config, message) instead.
Events
// A new comment was received
facebook.on('message', (data) => {
console.log('New message', data);
});
// Polling started
facebook.on('connected', () => {
console.log('Connected');
});
// Polling stopped (manual disconnect or video no longer live)
facebook.on('disconnected', () => {
console.log('Disconnected');
});
// A Graph API error occurred during polling
facebook.on('error', (error) => {
console.error(error);
});
// The page/user token expired or was revoked (Graph 190/102, subcode 463/467)
facebook.on('refresh-token', (errorDetails) => {
console.log('Token expired', errorDetails);
});Note on Reactions & Stars: Facebook also exposes a
live_reactionsstreaming edge, and Stars are delivered via server-side Webhooks. This interface currently polls only live video comments.
