I'm making a Twitch and Discord bot, but now I have a problem.
I want to check if the streamer is live and send a console.log() if it is live, but I am not able to do that.
require("dotenv").config();
const Discord = require('discord.js');
const { MessageAttachment } = require('discord.js');
const Canvas = require('canvas');
const { createCanvas, loadImage } = require('canvas');
const fs = require('fs');
const customCommandsFile = 'commands/custom_commands.json';
let customCommands = {};
const intents = ["GUILDS", "GUILD_MEMBERS", "GUILD_MESSAGES"];
const client = new Discord.Client({intents: intents, ws:{intents: intents}});
const { StaticAuthProvider } = require('twitch-auth');
const TwitchAPI = require('twitch');
const tmi = require('tmi.js');
const twitchClient = new tmi.Client({
options: {
debug: true
},
identity: {
username: process.env.USERNAME,
password: process.env.PASSWORD
},
channels: [ '#errxino' ]
});
const clientId = process.env.TWITCH_CLIENT_ID;
const accessToken = process.env.TWITCH_ACCESS_TOKEN;
const authProvider = new StaticAuthProvider(clientId, accessToken, ['channel:manage:broadcast', 'user:edit:broadcast', 'channel:moderate', 'chat:edit', 'chat:read']);
const twitch = new TwitchAPI({ authProvider });
// FUNCTIONS
function createCustomCommand(command, response) {
// Agrega el comando personalizado al objeto customCommands
customCommands[command] = response;
// Escribe el objeto customCommands en un archivo JSON
fs.writeFile('commands/custom_commands.json', JSON.stringify(customCommands), err => {
if (err) {
console.error(err);
return;
}
const channel = client.channels.cache.find(c => c.name === "log-twitchbot");
if (!channel) {
console.error(`No se encontró el canal de Discord con el nombre "log-twitchbot".`);
return;
}
// Actualiza los comandos personalizados en twitchClient
twitchClient.removeAllListeners('message');
twitchClient.on('message', async (channel, tags, message, self) => {
if (self) return;
if (message.startsWith('!')) {
const args = message.slice(1).split(' ');
const command = args[0];
// Verifica si el comando personalizado existe y lo ejecuta si lo hace
if (customCommands[command]) {
twitchClient.say(channel, customCommands[command]);
}
}
});
});
}
function clearCustomCommands() {
customCommands = {};
fs.writeFileSync('commands/custom_commands.json', JSON.stringify(customCommands));
}
fs.readFile(customCommandsFile, (err, data) => {
if (err) {
console.error(err);
return;
}
customCommands = JSON.parse(data);
});
// TWITCH BOT
twitchClient.connect();
twitchClient.on('connected', (address, port) => {
// Busca el canal de Discord por su nombre
const channel = client.channels.cache.find(c => c.name === "log-twitchbot");
if (!channel) {
console.error(`No se encontró el canal de Discord con el nombre "log-twitchbot".`);
return;
}
// Envía un mensaje de inicio de sesión a un canal de Discord
const embed = new Discord.MessageEmbed()
.setColor('#00FF09')
.setAuthor({ name: 'ErrXino.tv', iconURL: 'https://i.imgur.com/gTmSG8Z.png' })
.setFields(
{ name: 'Twitch bot:', value: 'equis_bot'},
{ name: 'Estado:', value: 'Iniciado✅'},
)
.setTimestamp()
.setFooter({ text: 'ErrXino.tv', iconURL: 'https://i.imgur.com/gTmSG8Z.png' });
channel.send({ embeds: [embed] })
return;
});
twitchClient.on('message', async (channel, tags, message, self) => {
if (self) return;
const args = message.slice(0).split(' ');
const command = args[0].toLowerCase(); // convertimos el comando a minúsculas
if (args[0].startsWith('!')){
console.log(command)
if (customCommands[command]) { // comprobamos si el comando existe
twitchClient.say(channel, customCommands[command]); // enviamos el contenido del comando
}
}
});
// DISCORD BOT
client.on('ready', () => {
// Busca el canal de Discord por su nombre y se une a él
const channel = client.channels.cache.find(c => c.name === "log-twitchbot");
if (!channel) {
console.error(`No se encontró el canal de Discord con el nombre "log-twitchbot".`);
return;
}
const embed = new Discord.MessageEmbed()
.setColor('#00FF09')
.setAuthor({ name: 'ErrXino.tv', iconURL: 'https://i.imgur.com/gTmSG8Z.png' })
.setFields(
{ name: 'Discord bot:', value: `${client.user.tag}`},
{ name: 'Estado:', value: 'Iniciado✅'},
)
.setTimestamp()
.setFooter({ text: 'ErrXino.tv', iconURL: 'https://i.imgur.com/gTmSG8Z.png' });
channel.send({ embeds: [embed] })
client.user.setActivity("canal de ErrXino", {
type: "STREAMING",
url: "https://www.twitch.tv/errxino"
});
return;
});
client.login(process.env.DISCORD_TOKEN);
I have tried with 'getStreamByUser', or with 'channel', but neither work. I was using 'const TwitchAPI = require('twitch-api-v5');' to make the API call.