The words my bot is told are not remembered in the database. I am using MongoDB atlas for my bot's database, and my bot uses discord.js

Viewed 33

I know I ask a lot of questions, but I need to figure this out.

I made a MongoDB atlas database and wrote code that connects my database to my bot. However, after shutting off my bot, it doesn't remember any words that are told to it. Here's my code (sensitive stuff removed):


const Discord = require("discord.js");
const { Client, Intents, MessageEmbed } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MEMBERS, Intents.FLAGS.GUILD_BANS, Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS, Intents.FLAGS.GUILD_INTEGRATIONS, Intents.FLAGS.GUILD_WEBHOOKS, Intents.FLAGS.GUILD_INVITES, Intents.FLAGS.GUILD_VOICE_STATES, Intents.FLAGS.GUILD_PRESENCES, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_MESSAGE_REACTIONS, Intents.FLAGS.GUILD_MESSAGE_TYPING, Intents.FLAGS.DIRECT_MESSAGES, Intents.FLAGS.DIRECT_MESSAGE_REACTIONS, Intents.FLAGS.DIRECT_MESSAGE_TYPING],
});
const TOKEN = ""
const fetch = import('node-fetch')

const possibleAnswers = ['Im sad :(', 'Im annoyed', 'Im happy!','Im okay']

const possibleMeals = ["Eat some fruit!","Eat some icecream!","Eat a salad!","Eat some spahgetti!","Go out to a restaurant of your choice"]

const possibleCodeInfo = ["Arrays indexes start at 0 in most languages, but some start at 1, like Julia!", 
"Else if statements allow for mutliple conditions!",
"Many AI's require a database during its creation!",
"Lua is a frontend and backend language!",
"C# is 22 years old!",
"People used to use punchcards to code!",
"Objects store data in properties!",
"React allows you to write javascript in HTML!",
"HTML is not a coding language, its a markup language!",
"Unity uses C# for its engine!"]

const mongoose = require("mongoose");
const { Database} = require("D:/discordbot2/memorysave.json")

if (!Database) return;
mongoose.connect("mongodb+srv://user:<password>@uwubot.jr4ot.mongodb.net/?retryWrites=true&w=majority", {
  useNewUrlParser: true,
useUnifiedTopology: true
   }).then(() => {
    console.log("The client is now connected to the database.")
   }).catch((err) =>  {
    console.log(err)
   })

let chain = {}
  function generateChain(str){
    const textArr = str.split(' ');
    let x = textArr.indexOf("<@998859763385389137>") 
    if (x != -1) textArr.splice(x, 1) 

    for (let i = 0; i < textArr.length; i++) {
      let word = textArr[i].toLowerCase().replace(/[\W_]/, "") 
      if (!chain[word]) chain[word] = []
      if (textArr[i + 1]) chain[word].push(textArr[i + 1].toLowerCase().replace(/[\W_]/, ""))
    
    }
}
function generateSentence(chain){
    const words = Object.keys(chain)
    let word = words[Math.floor(Math.random() * words.length)]
    let output = ''
for (let i = 0;  i < (Math.floor(Math.random() * words.length)); i++){
    output += word + ' '
    word = words[(Math.floor(Math.random() * words.length))]
    if (!word || !chain.hasOwnProperty(word)) {
    word = words[Math.random() * Math.floor(Math.random() * words.length)]
    } 
    }

    return output
}
client.on("ready", () => {
  console.log(`Logged in as ${client.user.tag}!`)

  // slash command stuff
  const guildId = '847395379019513876'
  const guild = client.guilds.cache.get(guildId)
  let commands

  if (guild) {
    commands = guild.commands
  } else {
    commands = client.application?.commands
  }
})

client.on("message", msg => {
  if (msg.mentions.users.first() == client.user) {
    generateChain(msg.content)
    msg.reply(generateSentence(chain))
  }
  switch (msg.content){
    case('how are you?'):
    msg.reply(possibleAnswers[Math.floor(Math.random()*possibleAnswers.length)]);
    break;
    case('what should i eat?'):
    msg.reply(possibleMeals[Math.floor(Math.random()*possibleMeals.length)]);
    break;
    case('tell me a code fact'):
    msg.reply(possibleCodeInfo[Math.floor(Math.random()*possibleCodeInfo.length)]);
    break;
    //end
  } 
  
})

client.on('interactionCreate', async (interaction) => {
  if(!interaction.isCommand()) return;
}) 

client.login(TOKEN)

Did I write my code wrong? Am I used something thats deprecated? I appreciate any help that can be offered, because I am stumped.

1 Answers

That's because you are just creating a connection to your database. You aren't telling mongoose to save or load anything. First of, you need to create a Schema, which is a model of how the data will be saved in mongoose.

In another file, do this:

const mongoose = require(`mongoose`);

const Schema = mongoose.Schema({
 userID: String,
 words: Array,
})
module.exports = mongoose.model(`userWords`, Schema)

In your original file:

Import the schema at the top of the file: const schema = require('your_path/Schema.js')

In the place where you want to get the data:

// Load the data for that user
const savedUserWords = await schema.findOne({userID: msg.author.id)}

// if there is no data you will need to create it first
if(!savedUserWords) {

 // create an Array with the words that the user has told.
 const usedWords = ["word_1", "word_2", "word_3"];
 
 // Then create the schema and pass the words.
 const createSchema = new schema({
  userID: msg.author.id,
  words: usedWords
 })
 // Save the schema
 createSchema.save().catch(err => console.log(err));
}

// If there is already existent data for that user, you can get the saved words by doing:
const userData = savedUserWords.words

// If you want to add new words to the already existent data, you can do it this way:
savedUserWords.words.push("word");
savedUserWords.save().catch(err => console.log(err));
Related