.env
MONGODB_URI=
mongodb+srv://user:[email protected]/hydratebot?retryWrites=true&w=majority
TWITCH_CLIENT_ID=
your_client_id_here
TWITCH_CLIENT_SECRET=
your_client_secret_here
BROADCASTER_ID=
000000000
REWARD_ID=
your_reward_uuid_here
CALLBACK_URL=
https://your-twitch-bot.onrender.com
WEBHOOK_SECRET=
your_random_secret_string
PORT=
3001
TWITCH_PEER_URL=
https://your-discord-bot.onrender.com
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();
app.get('/health', (req, res) => res.status(200).send('OK'));
app.get('/ping', (req, res) => res.status(200).send('pong'));
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));
}
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'];
if (messageType === 'webhook_callback_verification') {
return res.status(200).send(payload.challenge);
}
const subType = payload.subscription?.type;
const event = payload.event;
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');
});
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 });
}
async function start() {
await connectDB();
app.listen(PORT, async () => {
await syncStreamStatusFromApi();
await subscribeToEvents();
setInterval(syncStreamStatusFromApi, 5 * 60 * 1000);
if (TWITCH_PEER_URL) setInterval(() => fetch(TWITCH_PEER_URL + '/ping').catch(() => {}), 10000);
});
}
start();
twitch-auth.js
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) {
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 };
.env
DISCORD_TOKEN=
your_discord_bot_token
DISCORD_CHANNEL_ID=
000000000000000000
MONGODB_URI=
mongodb+srv://user:[email protected]/hydratebot?retryWrites=true&w=majority
DISCORD_REDEMPTION_BOT_ID=
000000000000000000
DISCORD_ALLOW_DB_WRITE=
false
TWITCH_STREAM_URL=
https://www.twitch.tv/your_channel
TIKTOK_URL=
https://www.tiktok.com/@your_channel
DISCORD_PEER_URL=
https://your-twitch-bot.onrender.com
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],
});
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 });
});
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);
}
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);
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] });
}
});
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
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 })) };
}