ChatSage is an AI-powered chatbot designed for Twitch chat environments in any language. It provides contextually relevant responses based on chat history, user queries, and real-time stream information (current game, title, tags).
- Features (Core Capabilities)
- Adding ChatSage to Your Channel
- Usage Examples
- Development Prerequisites
- Getting Started
- Running the Bot
- Configuration
- Twitch Token Management
- Docker
- Connects to specified Twitch channels via IRC.
- Fetches real-time stream context (game, title, tags, thumbnail images) using the Twitch Helix API.
- Utilizes Google's Gemini 2.5 Flash LLM for natural language understanding and response generation.
- Maintains conversation context (history and summaries) per channel.
- Supports custom chat commands with permission levels.
- Configurable bot language settings for multilingual channel support.
- Configurable through environment variables.
- Includes structured logging suitable for production environments.
- Web-based channel management interface for streamers to add/remove the bot.
Streamers can now easily add or remove ChatSage from their channel using the web interface:
-
Visit the ChatSage Management Portal:
- Go to ChatSage Management Portal
- Click on "Login with Twitch"
-
Authorize the Application:
- You'll be redirected to Twitch to authorize ChatSage
- Grant the required permissions
- This process is secure and uses Twitch's OAuth flow
-
Manage the Bot:
- Once logged in, you'll see your dashboard
- Use the "Add Bot to My Channel" button to have ChatSage join your channel
- Use "Remove Bot from My Channel" if you want to remove it
-
Bot Joining Time:
- After adding the bot, it should join your channel within a few minutes
- If the bot doesn't join after 10 minutes, please try removing and adding again
- Important: if the bot is not responding, grant it mod status with the command "/mod ChatSageBot"
-
User Interaction:
- Viewers can interact with ChatSage by mentioning it:
@ChatSageBot hello
(the username will be updated to reflect the new name, ChatSage, when Twitch allows me) - Or by using various commands like
!ask
,!translate
, etc.
- Viewers can interact with ChatSage by mentioning it:
For a complete list of available commands and their usage, please visit Bot Commands Documentation.
ChatSage understands the flow of conversation. For example, the !lurk
command provides a polite, contextual send-off.
Scenario: The chat is discussing making dinner.
User:
!lurk going to make some pasta
ChatSageBot:
@user, enjoy making the pasta! Hope it turns out delicious. We'll be here when you get back!
This demonstrates how the bot can craft personalized responses based on both the command and the user's provided reason.
- Node.js (Version 22.0.0 or later recommended)
- npm (or yarn)
-
Clone the repository:
git clone [https://github.com/detekoi/chatsage.git](https://github.com/detekoi/chatsage.git) cd chatsage
-
Install dependencies:
npm install
(Or
yarn install
if you prefer Yarn) -
Configure environment variables:
- Copy the example environment file:
cp .env.example .env
- Edit the
.env
file and fill in your credentials and settings. Refer to the comments within.env.example
for details on each variable (Twitch bot username/token, Twitch application client ID/secret, Gemini API key, channels to join, etc.). Do not commit your.env
file.
- Copy the example environment file:
-
Development: Uses Node's built-in watch mode for automatic restarts on file changes. Enables human-readable ("pretty") logs by default if
PINO_PRETTY_LOGGING=true
in.env
.npm run dev
-
Production: Runs the bot using standard
node
. Outputs structured JSON logs suitable for log aggregation systems.npm start
ChatSage is configured primarily through environment variables. The required and optional variables are documented in the .env.example
file. Key variables include:
TWITCH_BOT_USERNAME
: Username for the bot's Twitch account.TWITCH_CHANNELS
: Comma-separated list of channels to join. Used as fallback if Firestore channel management is unavailable.TWITCH_CHANNELS_SECRET_NAME
: Resource name for the channels list in Google Secret Manager. Used as fallback if Firestore channel management is unavailable.GEMINI_API_KEY
: Your API key for the Google Gemini service.TWITCH_CLIENT_ID
,TWITCH_CLIENT_SECRET
: Credentials for your registered Twitch application (used for Helix API calls).TWITCH_BOT_REFRESH_TOKEN_SECRET_NAME
: Resource name for the refresh token in Google Secret Manager.STREAM_INFO_FETCH_INTERVAL_SECONDS
: How often to refresh stream context data.LOG_LEVEL
: Controls the verbosity of logs.
Ensure all required variables are set in your environment or .env
file before running the bot.
ChatSage uses a secure token refresh mechanism to maintain authentication with Twitch:
-
Prerequisites for Token Generation:
- Twitch Application: Ensure you have registered an application on the Twitch Developer Console. Note your Client ID and generate a Client Secret.
- OAuth Redirect URI: In your Twitch Application settings, add
http://localhost:3000
as an OAuth Redirect URL. The Twitch CLI specifically uses this as the first redirect URL by default. - Twitch CLI: Install the Twitch CLI on your local machine.
-
Configure Twitch CLI:
- Open your terminal or command prompt.
- Run
twitch configure
. - When prompted, enter the Client ID and Client Secret from your Twitch Application.
-
Generate User Access Token and Refresh Token using Twitch CLI:
- Run the following command in your terminal. Replace
<your_scopes>
with a space-separated list of scopes required for your bot. For ChatSage, you need at leastchat:read
andchat:edit
.(You can add other scopes if your bot's custom commands need them, e.g.,twitch token -u -s 'chat:read chat:edit'
channel:manage:polls channel:read:subscriptions
) - The CLI will output a URL. Copy this URL and paste it into your web browser.
- Log in to Twitch using the Twitch account you want the bot to use.
- Authorize your application for the requested scopes.
- After authorization, Twitch will redirect your browser to
http://localhost:3000
. The CLI, which temporarily runs a local server, will capture the authorization code and exchange it for tokens. - The CLI will then print the
User Access Token
,Refresh Token
,Expires At
(for the access token), and theScopes
granted.
- Run the following command in your terminal. Replace
-
Store the Refresh Token Securely:
- From the Twitch CLI output, copy the Refresh Token. This is the crucial token your bot needs for long-term authentication.
- Store this Refresh Token securely in Google Secret Manager.
-
Google Secret Manager Setup:
- Create a Google Cloud Project if you don't have one.
- Enable the Secret Manager API in your project.
- Create a new secret in Secret Manager to store the Twitch Refresh Token you just obtained.
- Note the Resource Name of this secret. It will look like
projects/YOUR_PROJECT_ID/secrets/YOUR_SECRET_NAME/versions/latest
. - Set this full resource name as the value for the
TWITCH_BOT_REFRESH_TOKEN_SECRET_NAME
environment variable in your bot's configuration (e.g., in your.env
file or Cloud Run environment variables). - Ensure the service account running your ChatSage application (whether locally via ADC or in Cloud Run) has the "Secret Manager Secret Accessor" IAM role for this secret.
-
Authentication Flow in ChatSage:
- On startup, ChatSage (specifically
ircAuthHelper.js
) will use theTWITCH_BOT_REFRESH_TOKEN_SECRET_NAME
to fetch the stored refresh token from Google Secret Manager. - It will then use this refresh token, along with your application's
TWITCH_CLIENT_ID
andTWITCH_CLIENT_SECRET
, to obtain a fresh, short-lived OAuth Access Token from Twitch. - This access token is used to connect to Twitch IRC.
- If the access token expires or becomes invalid, the bot will use the refresh token to automatically obtain a new one.
- If the refresh token itself becomes invalid (e.g., revoked by Twitch, user password change), the application will log a critical error, and you will need to repeat the token generation process (Steps 3-4) to get a new refresh token.
- On startup, ChatSage (specifically
The web interface uses a separate OAuth flow to allow streamers to manage the bot in their channel:
-
Firebase Functions Setup:
- The web UI is built with Firebase Functions and Hosting.
- It uses Twitch OAuth to authenticate streamers.
- When a streamer adds or removes the bot, it updates a Firestore collection.
- The bot periodically checks this collection to determine which channels to join or leave.
-
Environment Variables for Web UI:
TWITCH_CLIENT_ID
: Twitch application client ID.TWITCH_CLIENT_SECRET
: Twitch application client secret.CALLBACK_URL
: The OAuth callback URL (your deployed function URL).FRONTEND_URL
: The URL of your web interface.JWT_SECRET_KEY
: Secret for signing authentication tokens.SESSION_COOKIE_SECRET
: Secret for session cookies.
This approach provides better security by using standard OAuth flows and official tools, and not storing sensitive tokens directly in configuration files where possible. It also gives streamers control over adding or removing the bot from their channel.
EventSub for Serverless Deployment (Optional)
This project supports Twitch's EventSub to enable a "scale-to-zero" serverless deployment on platforms like Google Cloud Run. This significantly reduces hosting costs by only running the bot when a channel it's in is live.
- How it works: The bot subscribes to
stream.online
events. When a streamer goes live, Twitch sends a webhook that starts the bot instance. The bot stays active while the stream is live and scales down to zero instances when all monitored channels are offline. - Cost Savings: This model can reduce hosting costs significantly.
To enable this feature, set the following in your deployment environment (e.g., Cloud Run):
LAZY_CONNECT=1
: Enables the scale-to-zero logic.TWITCH_EVENTSUB_SECRET
: A long, random, secret string you create to secure your webhook endpoint.PUBLIC_URL
: The public-facing URL of your deployed service (e.g.,https://your-service.a.run.app
).
-
Deploy with EventSub Variables: Deploy your application with the environment variables listed above. For Cloud Run, you would use
gcloud run deploy
with--set-env-vars
. -
Subscribe to Events: After deploying, run the management script to subscribe all your channels to the
stream.online
event.node scripts/manage-eventsub.js subscribe-all
-
Verify Subscriptions: You can check that the subscriptions were created successfully:
node scripts/manage-eventsub.js list
This setup ensures the bot only consumes resources when it needs to be active in a live channel.
A Dockerfile
is provided for building a container image of the application.
-
Build the image:
docker build -t chatsage:latest .
-
Run the container: You need to pass the environment variables to the container. One way is using an environment file:
docker run --rm --env-file ./.env -it chatsage:latest
(Ensure your
.env
file is populated correctly)