SchneebNabs
SchneebNabs

Reputation: 11

How would I go about programming a "stop/start" command for a chatbot in discord.js?

The problem: I have no clue how to go about it, and when I try to code in "if (command === stop/start)", the console log displays an error "can't run commands before initialization". But, I have to put the trigger words before the commands of the bot will not work at all.

console.clear();

const prefix = "au>";
const Me = "865241446335512616";
const Secondary = "589180215956078612"
const Zach = "755977853518086244"
const AEIOU = "792278833877221416"


const Discord = require("discord.js");
const fs = require('fs');
const chalk = require('chalk');
const ytdl = require('ytdl-core');
const GIFEncoder = require('gifencoder')
const Canvas = require ('canvas')
const client = new Discord.Client();
const hi = require("./chatbot/hi.js")
const horny = require("./chatbot/horny.js")
const cute = require("./chatbot/cute.js")
const funny = require("./chatbot/funny.js")
const loli = require("./chatbot/loli.js")
const food = require("./chatbot/food.js")
const drink = require("./chatbot/drink.js")
const hotdog = require("./chatbot/hotdog.js")


client.commands = new Discord.Collection();


const sleep = function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

const getRandomInt = function getRandomInt(max) {
    return Math.floor(Math.random() * Math.floor(max));
}


var totalCommands = 0;
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
async function load() {
    await console.log(chalk.green('AEIOU, Here to sing for you!'))
    await console.log('\n\n');
    await console.log('Booting up ' + chalk.cyan(__filename));
    await sleep(250);
    await console.log(chalk.bgCyan(chalk.black('[Command Loader]')), 'Loading Abilities...');
    await sleep(1000);
    for (const file of commandFiles) {
        const command = require(`./commands/${file}`);
        client.commands.set(command.name, command);
        await sleep(10);
        await console.log(chalk.bgGreen(chalk.black('[Command Loader]')), 'Got this one! ' + chalk.magentaBright(file));
        totalCommands++;
    }
    console.log(chalk.cyan(totalCommands), 'commands loaded');

    client.login("TOKEN_HERE");

}


load();

console.log(chalk.yellow(commandFiles))


client.once('ready', () => {
    console.log(chalk.blueBright('AEIOU, here to talk to you!'))
});

process.on('unhandledRejection', error => console.error('Uncaught Promise Rejection', error));
client.on("message", async message => {

    if (message.author.id == client.user.id) { return }

    var msg = [];
    var placeholder = message.content.toLowerCase().split(' ');

    placeholder.forEach(string => {
        string = string.replace(',', '');
        string = string.replace('?', '');
        string = string.replace('!', '');
        string = string.replace('"', '');
        msg.push(string);
    });

  

    if (msg.some(r => hi.messages.includes(r))) {
        return message.channel.send(hi.responses[getRandomInt(hi.responses.length)]);
    }


    if (msg.some(r => funny.messages.includes(r))) {
        return message.channel.send(funny.responses[getRandomInt(funny.responses.length)]);
    }

    if (msg.some(r => drink.messages.includes(r))) {
        return message.channel.send(drink.responses[getRandomInt(drink.responses.length)]);
    }

    if (msg.some(r => food.messages.includes(r))) {
        return message.channel.send(food.responses[getRandomInt(food.responses.length)]);
    }


    if (msg.some(r => cute.messages.includes(r))) {
        return message.channel.send(cute.responses[getRandomInt(cute.responses.length)]);
    }

    if (msg.some(r => horny.messages.includes(r))) {
        return message.channel.send(horny.responses[getRandomInt(horny.responses.length)]);
    }

    if (msg.some(r => loli.messages.includes(r))) {
        return message.channel.send(loli.responses[getRandomInt(loli.responses.length)]);
    }

    if (message.mentions.has(client.user)) {
        message.channel.send("Hi! I'm AEIOU, and I do have a prefix. It's `au>[command]`. Thanks for mentioning me!")
    }


  

    const commandBody = message.content.slice(prefix.length);
    const args = commandBody.split(' ');
    const command = args.shift().toLowerCase();

    if (!message.content.startsWith(prefix) || message.author.bot) return;



    if (command == 'credit' || command == 'credits') {
        client.commands.get('credits').execute(message, args, Discord, client);
    }

    if (command == 'help' || command == 'menu') {
        client.commands.get('help').execute(message, args, Discord, client);
    }

    if (command == 'link' || command == 'invite') {
        client.commands.get('invite').execute(message, args, Discord, client);
    }

    if (command == 'headpat' || command == 'pat') {
        client.commands.get('pet').execute(message, args, Discord, client);
    }


    if (command === "repeat") {
            const echoMessage = args.join(" ");
            message.delete();
            message.channel.send(echoMessage);
    };

    if (command == 'suggest') {
        const suggestionmsg = args.join(' ');
        if (!args.length) {
            return message.channel.send(`You didn't provide a suggestion, ${message.author}!`);
        } else {
            client.users.cache.get(me).send(message.author.tag + ' suggests: ' + suggestionmsg);
            message.channel.send("Thanks for your suggestion, and for helping with my development! I'm always looking for ways to be a better bot!");
            console.error();
        }
    }

});

I removed the actual key, and any names that aren't bots.

Upvotes: 1

Views: 156

Answers (1)

Alixy Mizuki
Alixy Mizuki

Reputation: 91

You can add a database wheres it has a key for enable/disable and you can put the condition and then put the i assumed a chat if statement inside that condition scope

for example

let db = require('quick.db');
let chatStatus = db.get('chatStatus')

// inside message event
if(chatStatus === null) chatStatus = false

if(chatStatus === true) 
{

  if (msg.some(r => hi.messages.includes(r))) {
    return message.channel.send(hi.responses[getRandomInt(hi.responses.length)]);
  }

  /*
  other chat code
  */

  if (message.mentions.has(client.user)) {
    message.channel.send("Hi! I'm AEIOU, and I do have a prefix. It's `au>[command]`. Thanks for mentioning me!")
  }

}

// code for enabling or disabling it
if (command === "status") {
  let status = db.get('chatStatus')
  if(status === null) status = false


  if(args[0] === undefined) return message.channel.send('true/false')
  
  if(args[0] == 'true') {
    db.set('chatStatus', true)
    message.channel.send(`Successfully set Chatbot to ${args[0]}`);
  }
  if(args[0] == 'false') {
    db.set('chatStatus', false)
    message.channel.send(`Successfully set Chatbot to ${args[0]}`);
  }
};

P.S: if theres a better way or remove some useless variables, whoever are you freely edit this answer

Upvotes: 1

Related Questions