Back to Dev Hub

TideBot

Channel Points Redemption Tracker — Twitch + Discord

A two-bot system that tracks Twitch channel point redemptions (like "Hydrate!") and syncs them to a Discord leaderboard. Uses EventSub webhooks, MongoDB, and mutual keep-alive pings for 24/7 uptime on free hosting.

Not just for hydrate! — This system works with any Twitch channel point custom reward. Hydrate is just the example. You can track "Push-ups", "Song Request", "Shoutout", or any custom redeem you create. Just swap the REWARD_ID in your .env to point at whichever reward you want to count.

Features

Leaderboard

Top 10 redeemers displayed in Discord with a slash command or legacy text command.

EventSub Webhooks

Real-time Twitch notifications via EventSub — no polling, instant redemption capture.

MongoDB Storage

Persistent storage with deduplication. Every redemption is logged with timestamps and cost.

Stream Status Sync

Detects when you go live/offline and updates the Discord bot's presence and embed in real-time.

Mutual Keep-Alive

Both bots ping each other every 10s to prevent free-tier hosting from sleeping.

Any Custom Reward

Works with any channel point reward — just change the REWARD_ID. Track hydrates, push-ups, song requests, anything.

Commands
CommandPlatformDescription
/leaderboardDiscordShow top 10 redeemers
/score [username]DiscordLook up a specific user's redemption count and recent history
/linksDiscordPost clickable Watch (Twitch) + TikTok buttons
/rpDiscordPost or update the rich-presence embed with stream status
!leaderboardDiscordLegacy text command for the leaderboard
Step-by-Step Setup

Create a Twitch Application

Go to the Twitch Dev Console, create an app, and note your Client ID and Client Secret.

Create a Discord Application

Go to the Discord Developer Portal, create a bot, and copy the token.

Set Up MongoDB

Create a free cluster on MongoDB Atlas. Get your connection string (SRV format) and append your database name.

Create Your Channel Point Reward

On Twitch, create a custom channel point reward (e.g. "Hydrate!", "Push-ups", etc). Copy the reward ID from the Twitch API or use the auth helper.

Authorize the Twitch Bot

Run node twitch-auth.js url to get an OAuth link. Authorize as the broadcaster, then exchange the code: node twitch-auth.js exchange YOUR_CODE

Configure Both .env Files

Fill in twitch-bot/.env and discord-bot/.env with your tokens, IDs, and MongoDB URI. See the file explorer below for the full template.

Deploy Both Bots

Deploy each bot separately (they're independent services). Set the CALLBACK_URL to your Twitch bot's public URL and the peer URLs to each other.

Verify EventSub

On first start, the Twitch bot auto-subscribes to EventSub. Check logs for "EventSub subscription created" confirmations.

Source Code Explorer

Click folders to expand, click files to view source. All secrets replaced with example values.

hydrate-counter/
twitch-bot/
.env
# MongoDB (Full SRV from Atlas) MONGODB_URI=mongodb+srv://user:[email protected]/hydratebot?retryWrites=true&w=majority # Twitch API (From Twitch Dev Console) TWITCH_CLIENT_ID=your_client_id_here TWITCH_CLIENT_SECRET=your_client_secret_here BROADCASTER_ID=000000000 # Twitch Reward — change this to ANY custom reward you want to track REWARD_ID=your_reward_uuid_here # Server/Webhook CALLBACK_URL=https://your-twitch-bot.onrender.com WEBHOOK_SECRET=your_random_secret_string PORT=3001 # Peer ping URL (Discord bot) — keeps both services awake TWITCH_PEER_URL=https://your-discord-bot.onrender.com # OAuth tokens (from twitch-auth.js) TWITCH_USER_ACCESS_TOKEN=your_access_token TWITCH_REFRESH_TOKEN=your_refresh_token
package.json
{ "name": "twitch-hydrate-bot", "version": "1.0.0", "description": "Twitch bot for channel point redemptions via EventSub", "main": "twitch.js", "scripts": { "start": "node twitch.js", "auth": "node twitch-auth.js" }, "dependencies": { "axios": "^1.6.0", "dotenv": "^16.3.1", "express": "^4.18.2", "mongodb": "^6.21.0" }, "engines": { "node": ">=18.0.0" } }
twitch.js
require('dotenv').config(); const express = require('express'); const axios = require('axios'); const crypto = require('crypto'); const { updateUser, connectDB, setStreamLive } = require('./db.js'); const app = express(); // Health & keep-alive endpoints app.get('/health', (req, res) => res.status(200).send('OK')); app.get('/ping', (req, res) => res.status(200).send('pong')); // Verify EventSub webhook signatures function verifyEventSubSignature(req) { const messageId = req.headers['twitch-eventsub-message-id']; const timestamp = req.headers['twitch-eventsub-message-timestamp']; const signature = req.headers['twitch-eventsub-message-signature']; const message = messageId + timestamp + req.rawBody.toString('utf8'); const expected = 'sha256=' + crypto.createHmac('sha256', WEBHOOK_SECRET) .update(message).digest('hex'); return crypto.timingSafeEqual(Buffer.from(expected), Buffer.from(signature)); } // EventSub webhook handler app.post('/eventsub', express.raw({ type: 'application/json' }), async (req, res) => { req.rawBody = req.body; if (!verifyEventSubSignature(req)) return res.status(403).send('Forbidden'); const payload = JSON.parse(req.rawBody.toString('utf8')); const messageType = req.headers['twitch-eventsub-message-type']; // Handle challenge verification if (messageType === 'webhook_callback_verification') { return res.status(200).send(payload.challenge); } const subType = payload.subscription?.type; const event = payload.event; // Channel point redemption — works with ANY reward if (subType === 'channel.channel_points_custom_reward_redemption.add') { const total = await updateUser(event.user_id, event.user_login, event.reward.cost, event.id); console.log(`Redemption: ${event.user_login} — total: ${total}`); } else if (subType === 'stream.online') { await syncStreamStatusFromApi(); } else if (subType === 'stream.offline') { await setStreamLive(false, null); } res.status(200).send('OK'); }); // Auto-subscribe to EventSub on startup async function subscribeToEvents() { const token = await getAppAccessToken(); await createEventSubSubscription(token, 'channel.channel_points_custom_reward_redemption.add', '1', { broadcaster_user_id: BROADCASTER_ID, reward_id: REWARD_ID }); await createEventSubSubscription(token, 'stream.online', '1', { broadcaster_user_id: BROADCASTER_ID }); await createEventSubSubscription(token, 'stream.offline', '1', { broadcaster_user_id: BROADCASTER_ID }); } // Start server, connect DB, subscribe to events async function start() { await connectDB(); app.listen(PORT, async () => { await syncStreamStatusFromApi(); await subscribeToEvents(); setInterval(syncStreamStatusFromApi, 5 * 60 * 1000); // Ping Discord peer to keep it awake if (TWITCH_PEER_URL) setInterval(() => fetch(TWITCH_PEER_URL + '/ping').catch(() => {}), 10000); }); } start();
twitch-auth.js
/** * OAuth helper — run from CLI to get user tokens. * Usage: * node twitch-auth.js url → prints the authorize URL * node twitch-auth.js exchange <code> → exchanges code for tokens * node twitch-auth.js refresh <token> → refreshes an expired token */ require('dotenv').config(); const axios = require('axios'); const SCOPES = ['channel:manage:redemptions', 'channel:read:redemptions'].join(' '); function buildAuthorizeUrl() { const params = new URLSearchParams({ client_id: process.env.TWITCH_CLIENT_ID, redirect_uri: process.env.CALLBACK_URL || 'http://localhost:3001', response_type: 'code', scope: SCOPES, force_verify: 'true', }); return `https://id.twitch.tv/oauth2/authorize?${params}`; } async function exchangeCode(code) { const response = await axios.post('https://id.twitch.tv/oauth2/token', null, { params: { client_id: process.env.TWITCH_CLIENT_ID, client_secret: process.env.TWITCH_CLIENT_SECRET, code, grant_type: 'authorization_code', redirect_uri: process.env.CALLBACK_URL, }, }); console.log(`TWITCH_USER_ACCESS_TOKEN=${response.data.access_token}`); console.log(`TWITCH_REFRESH_TOKEN=${response.data.refresh_token}`); } async function refreshToken(token) { const response = await axios.post('https://id.twitch.tv/oauth2/token', null, { params: { client_id: process.env.TWITCH_CLIENT_ID, client_secret: process.env.TWITCH_CLIENT_SECRET, grant_type: 'refresh_token', refresh_token: token, }, }); console.log(`TWITCH_USER_ACCESS_TOKEN=${response.data.access_token}`); console.log(`TWITCH_REFRESH_TOKEN=${response.data.refresh_token}`); } const [,, cmd, arg] = process.argv; if (cmd === 'url') console.log(buildAuthorizeUrl()); else if (cmd === 'exchange') exchangeCode(arg); else if (cmd === 'refresh') refreshToken(arg); else console.log('Usage: node twitch-auth.js [url|exchange|refresh] [arg]');
db.js
require('dotenv').config(); const { MongoClient, ServerApiVersion } = require('mongodb'); let usersCollection, redemptionsCollection, metaCollection; async function connectDB() { const client = new MongoClient(process.env.MONGODB_URI, { serverApi: { version: ServerApiVersion.v1, strict: true }, }); await client.connect(); const db = client.db('hydratebot'); usersCollection = db.collection('users'); redemptionsCollection = db.collection('redemptions'); metaCollection = db.collection('meta'); await redemptionsCollection.createIndex({ redemptionId: 1 }, { unique: true }); await usersCollection.createIndex({ userId: 1 }, { unique: true }); console.log('Connected to MongoDB'); } async function updateUser(userId, username, cost, redemptionId) { // Deduplicates via unique redemptionId index await redemptionsCollection.insertOne({ redemptionId, userId, username, cost, createdAt: new Date() }); const result = await usersCollection.updateOne( { userId }, { $inc: { count: 1 }, $set: { username, updatedAt: new Date() } }, { upsert: true } ); const doc = await usersCollection.findOne({ userId }); return doc?.count ?? 0; } async function getLeaderboard() { return usersCollection.find({}).sort({ count: -1 }).limit(10).toArray(); } async function setStreamLive(isLive, title) { await metaCollection.updateOne( { _id: 'stream' }, { $set: { live: isLive, title, updatedAt: new Date() } }, { upsert: true } ); } async function getStreamLive() { const doc = await metaCollection.findOne({ _id: 'stream' }); return { live: doc?.live ?? false, title: doc?.title ?? null }; } module.exports = { connectDB, updateUser, getLeaderboard, setStreamLive, getStreamLive };
discord-bot/
.env
# Discord Bot DISCORD_TOKEN=your_discord_bot_token DISCORD_CHANNEL_ID=000000000000000000 # MongoDB (same cluster as twitch-bot) MONGODB_URI=mongodb+srv://user:[email protected]/hydratebot?retryWrites=true&w=majority # Optional: parse redemption messages from another bot DISCORD_REDEMPTION_BOT_ID=000000000000000000 DISCORD_ALLOW_DB_WRITE=false # Presence links TWITCH_STREAM_URL=https://www.twitch.tv/your_channel TIKTOK_URL=https://www.tiktok.com/@your_channel # Peer ping URL (Twitch bot) — mutual keep-alive DISCORD_PEER_URL=https://your-twitch-bot.onrender.com # Server port PORT=3000
package.json
{ "name": "discord-hydrate-bot", "version": "1.0.0", "description": "Discord bot for redemption leaderboards and stream presence", "main": "bot.js", "scripts": { "start": "node bot.js" }, "dependencies": { "discord.js": "^14.14.1", "dotenv": "^16.3.1", "mongodb": "^6.21.0" }, "engines": { "node": ">=18.0.0" } }
bot.js
require('dotenv').config(); const http = require('http'); const { Client, GatewayIntentBits, EmbedBuilder, REST, Routes, SlashCommandBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, ActivityType } = require('discord.js'); const { getLeaderboard, connectDB, getStreamLive, getUserWithRedemptions } = require('./db.js'); const discordClient = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent], }); // Slash commands: /leaderboard, /score, /links, /rp discordClient.once('clientReady', async () => { console.log('Discord bot ready!'); startPresencePolling(); const commands = [ new SlashCommandBuilder().setName('leaderboard').setDescription('Show top 10 redeemers'), new SlashCommandBuilder().setName('links').setDescription('Twitch + TikTok buttons'), new SlashCommandBuilder().setName('rp').setDescription('Post/update stream status embed'), new SlashCommandBuilder().setName('score').setDescription('Look up a user score') .addStringOption(o => o.setName('username').setDescription('Twitch username').setRequired(true)), ].map(c => c.toJSON()); const rest = new REST({ version: '10' }).setToken(process.env.DISCORD_TOKEN); const channel = await discordClient.channels.fetch(process.env.DISCORD_CHANNEL_ID); await rest.put(Routes.applicationGuildCommands(discordClient.user.id, channel.guild.id), { body: commands }); }); // Presence: shows "Streaming" with Twitch link when live function startPresencePolling() { setInterval(async () => { const { live, title } = await getStreamLive(); discordClient.user.setPresence({ activities: [{ name: title || 'your channel', type: ActivityType.Streaming, url: process.env.TWITCH_STREAM_URL }], status: 'online', }); }, 30000); } // Command handler discordClient.on('interactionCreate', async (interaction) => { if (!interaction.isChatInputCommand()) return; if (interaction.commandName === 'leaderboard') { const lb = await getLeaderboard(); const lines = lb.map((d, i) => `${i+1}. ${d.username}: ${d.count} redeems`); const embed = new EmbedBuilder().setTitle('Leaderboard - Top 10') .setDescription(lines.join('\n') || 'No redemptions yet!').setColor('#00FF00'); await interaction.reply({ embeds: [embed] }); } if (interaction.commandName === 'score') { const username = interaction.options.getString('username'); const user = await getUserWithRedemptions(username); // Shows count + recent redemption history await interaction.reply({ embeds: [buildScoreEmbed(user)] }); } if (interaction.commandName === 'links') { const row = new ActionRowBuilder().addComponents( new ButtonBuilder().setLabel('Watch').setURL(process.env.TWITCH_STREAM_URL).setStyle(ButtonStyle.Link), new ButtonBuilder().setLabel('TikTok').setURL(process.env.TIKTOK_URL).setStyle(ButtonStyle.Link), ); await interaction.reply({ components: [row] }); } }); // Health server + peer ping http.createServer((req, res) => { if (req.url === '/ping') return res.end('pong'); res.end('OK'); }).listen(process.env.PORT || 3000); if (process.env.DISCORD_PEER_URL) { setInterval(() => fetch(process.env.DISCORD_PEER_URL + '/ping').catch(() => {}), 10000); } async function start() { await connectDB(); await discordClient.login(process.env.DISCORD_TOKEN); } start();
db.js
// Same DB module as twitch-bot — shared MongoDB cluster // Exports: connectDB, getLeaderboard, getStreamLive, getUserWithRedemptions // (identical to twitch-bot/db.js with added getUserWithRedemptions) async function getUserWithRedemptions(username) { const user = await usersCollection.findOne({ username: username.toLowerCase() }); if (!user) return null; const redemptions = await redemptionsCollection .find({ username: username.toLowerCase() }) .sort({ createdAt: -1 }).limit(5).toArray(); return { ...user, redemptions: redemptions.map(r => ({ date: r.createdAt, cost: r.cost })) }; }
Free Hosting Options

Both bots need to be deployed separately. These platforms work great for always-on Node.js services.

Join the Community
ThePurpleFox Discord
Support & Demos

Get help setting up, see the bots in action on a live server, and request features.

  • Live bot demos
  • Setup help & support
  • Feature requests