File Type: TS
Lines: 316
Size: 8.7 KB
Generated: 9/4/2025, 1:03:43 PM
This TypeScript file implements a bot that monitors a Twitch channel and posts notifications to Twitter and Bluesky when the channel goes live. It uses the axios library for HTTP requests, twitter-api-v2 for Twitter integration, and @atproto/api for Bluesky integration. The bot reads configuration from a JSON file and maintains state in a local file to avoid redundant notifications.
Key Components:
- Configuration (
Configinterface): Defines the structure for the configuration file, including Twitch API credentials, Twitter API keys, Bluesky credentials, check interval, and a message template. - Stream Status (
StreamStatusinterface): Represents the status of the Twitch stream, including whether it's live, the title, game, viewer count, and thumbnail URL. - Bot State (
BotStateinterface): Stores the bot's state, including the last known stream status and the last notification time. This is persisted to a file (bot-state.json) to maintain state across restarts. TwitchStreamBotClass:- Constructor: Initializes the bot with the configuration, Twitter and Bluesky clients, and loads the bot state.
loadConfig(configPath: string): Config: Reads and parses the configuration file from the specified path. Handles potential errors during file reading or JSON parsing.loadState(): BotState: Loads the bot state from thebot-state.jsonfile. If the file doesn't exist, it initializes a new state.saveState(): void: Saves the bot state to thebot-state.jsonfile.getTwitchAccessToken(): Promise<void>: Obtains a Twitch access token using the client ID and client secret.getStreamStatus(): Promise<StreamStatus>: Retrieves the stream status from the Twitch API. It handles token expiration and retries the request if necessary.formatMessage(streamStatus: StreamStatus): string: Formats the notification message using the configured template and the stream status.postToTwitter(message: string): Promise<void>: Posts the message to Twitter using thetwitter-api-v2library.postToBluesky(message: string): Promise<void>: Posts the message to Bluesky using the@atproto/apilibrary. It handles authentication if necessary.handleStreamStart(streamStatus: StreamStatus): Promise<void>: Handles the event when the stream goes live. It posts notifications to Twitter and Bluesky and updates the bot state.handleStreamEnd(): Promise<void>: Handles the event when the stream ends. It updates the bot state.checkAndNotify(): Promise<void>: Checks the stream status and posts notifications if the status has changed.start(): Promise<void>: Starts the bot by authenticating with the services, performing an initial check, and setting up periodic checks usingsetInterval.
Workflow:
- Initialization: The bot loads the configuration and state from files.
- Authentication: The bot authenticates with the Twitch, Twitter, and Bluesky APIs.
- Periodic Checks: The bot periodically checks the stream status using the Twitch API.
- Notification: If the stream status changes (goes live or ends), the bot posts a notification to Twitter and Bluesky.
- State Management: The bot updates its state to reflect the current stream status and saves the state to a file.
Dependencies:
axios: For making HTTP requests to the Twitch API.twitter-api-v2: For interacting with the Twitter API.@atproto/api: For interacting with the Bluesky API.node:fs: For reading and writing files (configuration and state).node:path: For constructing file paths.
Strengths:
- Clear separation of concerns: The code is well-organized into functions and classes, making it easy to understand and maintain.
- Error handling: The code includes error handling for various operations, such as loading the configuration file, obtaining the Twitch access token, and posting to Twitter and Bluesky.
- State management: The bot maintains state to avoid redundant notifications.
- Asynchronous operations: The code uses asynchronous operations to avoid blocking the main thread.
- Configuration-driven: The bot's behavior is configured through a JSON file, making it easy to customize.
Potential Improvements:
- More robust error handling: Consider adding more specific error handling and logging for different types of errors. For example, distinguish between network errors and API errors.
- Rate limiting: Implement rate limiting to avoid exceeding the API limits of Twitter and Bluesky.
- Configuration validation: Add validation to the configuration file to ensure that it contains all the required fields and that the values are valid.
- Logging: Implement a more comprehensive logging system to track the bot's activity and errors. Consider using a dedicated logging library.
- Dependency Injection: Consider using dependency injection to make the code more testable.
- Environment Variables: Instead of relying solely on a config file, consider using environment variables for sensitive information like API keys and secrets. This is generally a more secure practice.
- Health Checks: Implement a health check endpoint that can be used to monitor the bot's status.
- Consider using a dedicated task scheduler: Instead of
setInterval, a task scheduler library could provide more control and flexibility over the timing of checks.
Usage:
- Install the dependencies:
npm install axios twitter-api-v2 @atproto/api - Create a configuration file (e.g.,
config.json) with the required credentials. - Run the bot:
ts-node twitch-alert.ts
This analysis provides a comprehensive overview of the twitch-alert.ts file, including its purpose, key components, workflow, strengths, potential improvements, and usage. It should be helpful for developers who want to understand, modify, or extend the bot's functionality.
Description generated using AI analysis



Twitch Stream Notification Bot
A TypeScript bot that automatically monitors your Twitch stream and posts notifications to both X (Twitter) and Bluesky when you go live.
Features
Prerequisites
Installation
Clone or download the script files
Install dependencies:
Or with Bun:
API Setup
1. Twitch API Setup
http://localhost:3000(this won't actually be used)2. X (Twitter) API Setup
http://localhost:30003. Bluesky API Setup
yourname.bsky.social) and app passwordConfiguration
Create a
config.jsonfile in your project directory:{ "twitch": { "clientId": "your_twitch_client_id", "clientSecret": "your_twitch_client_secret", "channelName": "your_twitch_username" }, "twitter": { "appKey": "your_twitter_api_key", "appSecret": "your_twitter_api_secret", "accessToken": "your_twitter_access_token", "accessSecret": "your_twitter_access_secret" }, "bluesky": { "identifier": "your.handle.bsky.social", "password": "your_app_password" }, "checkInterval": 60000, "messageTemplate": "🔴 LIVE NOW! \n\n📺 {title}\n🎮 Playing: {game}\n👥 {viewerCount} viewers\n\n🔗 {url}" }Message Template Variables
You can customize the
messageTemplatewith these placeholders:{channelName}- Your Twitch username{title}- Stream title{game}- Game/category being played{viewerCount}- Current viewer count{url}- Direct link to your Twitch channelConfiguration Options
checkInterval: How often to check stream status in milliseconds (60000 = 1 minute)messageTemplate: The message format posted to social mediaUsage
Make sure your config.json is properly filled out
Run the bot:
Or with Bun:
The bot will start monitoring and show status messages:
When you go live, you'll see:
To stop the bot, press
Ctrl+CHow It Works
Troubleshooting
Common Issues
403 Error on Twitter/X:
Twitch Authentication Issues:
Bluesky Authentication Issues:
Bot not detecting stream changes:
File Structure
Security Notes
config.jsonfile private and never commit it to version controlLicense
This project is open source and available under the MIT License.
Support
If you encounter issues: