如何用tmi.js为Node.js聊天机器人实现Uptime命令?代码求助
Hey there, let's fix that uptime command for your tmi.js bot! The issue with your current code is that the chat event in tmi.js doesn't include an uptime parameter by default—you have to calculate or fetch that value yourself, depending on what kind of uptime you're aiming for.
First, let's clear up why your existing code fails:
Your code tries to pull an
uptimeargument from thechathandler, but tmi.js'schatevent only passes(channel, userstate, message, self)—there's no built-in uptime data here. That's why it's not working!
Below are two common solutions, depending on whether you want to show the bot's own uptime or the Twitch channel's live stream uptime.
Option 1: Track the Bot's Own Uptime
If you want to display how long your bot has been running (not the stream itself), this is a simple, API-free solution:
- First, capture the bot's start time at the top of your script:
const tmi = require('tmi.js'); // Record when the bot starts running const botStartTime = Date.now(); const client = new tmi.Client({ connection: { secure: true, reconnect: true }, channels: ['YOUR_CHANNEL_NAME'] // Replace with your channel (lowercase, no @) }); client.connect();
- Add the
chatevent listener to handle the!uptimecommand and calculate the duration:
client.on('chat', (channel, userstate, message, self) => { // Ignore messages sent by the bot itself if (self) return; // Check if the message is the !uptime command if (message.toLowerCase() === '!uptime') { const uptimeMs = Date.now() - botStartTime; // Convert milliseconds to human-readable hours/minutes/seconds const hours = Math.floor(uptimeMs / (1000 * 60 * 60)); const minutes = Math.floor((uptimeMs % (1000 * 60 * 60)) / (1000 * 60)); const seconds = Math.floor((uptimeMs % (1000 * 60)) / 1000); // Send the formatted uptime to chat client.say(channel, `Bot has been online for ${hours}h ${minutes}m ${seconds}s`); } });
Option 2: Fetch the Twitch Channel's Live Uptime
If you want to show how long the stream itself has been live (this is what most viewers expect from an !uptime command), you'll need to use the Twitch Helix API to pull real-time stream data.
Step 1: Get Twitch API Credentials
You'll need two things from the Twitch Developer Console:
- A Client ID (create a new application to get this)
- A Bearer Token (generate one using your Client ID—Twitch has a quick tool for temporary testing tokens)
Step 2: Implement the API Call in Your Bot
const tmi = require('tmi.js'); // Use node-fetch for API calls (install with `npm install node-fetch` or use native fetch in Node.js 18+) const fetch = require('node-fetch'); // Replace with your Twitch API credentials and channel name const TWITCH_CLIENT_ID = 'YOUR_CLIENT_ID'; const TWITCH_BEARER_TOKEN = 'YOUR_BEARER_TOKEN'; const CHANNEL_NAME = 'YOUR_CHANNEL_NAME'; // Lowercase, no @ const client = new tmi.Client({ connection: { secure: true, reconnect: true }, channels: [CHANNEL_NAME] }); client.connect(); client.on('chat', (channel, userstate, message, self) => { if (self) return; if (message.toLowerCase() === '!uptime') { // Fetch stream data from Twitch Helix API fetch(`https://api.twitch.tv/helix/streams?user_login=${CHANNEL_NAME}`, { headers: { 'Client-ID': TWITCH_CLIENT_ID, 'Authorization': `Bearer ${TWITCH_BEARER_TOKEN}` } }) .then(res => res.json()) .then(data => { if (data.data.length === 0) { // Stream is offline client.say(channel, `${CHANNEL_NAME} is not live right now!`); } else { // Calculate uptime from the stream's start time const streamStartTime = new Date(data.data[0].started_at); const uptimeMs = Date.now() - streamStartTime.getTime(); const hours = Math.floor(uptimeMs / (1000 * 60 * 60)); const minutes = Math.floor((uptimeMs % (1000 * 60 * 60)) / (1000 * 60)); const seconds = Math.floor((uptimeMs % (1000 * 60)) / 1000); client.say(channel, `${CHANNEL_NAME} has been live for ${hours}h ${minutes}m ${seconds}s`); } }) .catch(err => { console.error('Error fetching stream data:', err); client.say(channel, 'Sorry, I couldn\'t check the uptime right now.'); }); } });
Quick Notes
- For the Twitch API option, keep your credentials secure! Use environment variables (like
process.env.TWITCH_CLIENT_ID) instead of hardcoding them in public code. - If you're using Node.js 18 or later, you can skip installing
node-fetchand use the nativefetchfunction directly.
内容的提问来源于stack exchange,提问作者matty70988

