Unable to write and read values in a database, using Discord.js - javascript

I'm trying to allow staff to reply to the last DM using ~reply <message> rather than ~dm <userID> <message>, but firstly, I have to save the user's ID in a database to know who was the last DM user, but I'm facing an ERROR here, I'm confused of why this may be happening, but please note, I'm really new to databases, I'd apricate some help!
My code (Not all, just what I'm using for the command.):
I added ">>" before the line the ERROR is.
const { Client, Collection, Intents, MessageEmbed } = require('discord.js');
const client = new Client({partials: ['MESSAGE', 'CHANNEL', 'REACTION'], ws: { intents: Intents.ALL } });
const Database = require('#replit/database');
const db = new Database();
client.on('message', async message => {
//Dm checker
if (message.channel.type === 'dm') {
>> let lastDM = await db.get(`dm_${message.author.id}`)
if (lastDM === null) lastDm = `dm_NONE`
if (message.author.id == client.user.id) return;
if (message.author.id == '818749579369512978') return message.channel.send("This chat has been Blacklisted by the developer (<#"+ BOT_OWNER +">)");
const embed1 = new MessageEmbed()
.setTitle("New message!")
.setAuthor(`Name: \`${message.author.username}\` ID: \`${message.author.id}\` `)
.setColor("GRAY")
.setFooter("Dm message")
.addField("Message:", `\`\`\`${message.content}\`\`\``, false);
const embed2 = new MessageEmbed()
.setTitle("New reply!")
.setAuthor(`Name: \`${message.author.username}\` ID: \`${message.author.id}\` `)
.setColor("GRAY")
.setFooter("Dm reply")
.addField("Reply:", `\`\`\`${message.content}\`\`\``, false);
if (lastDM === `dm_${message.author.id}`) {
client.channels.cache.get("920895881656532992").send(`You got a reply!`, embed2)
console.log(lastDM)
} else {
await db.set(`dm_${message.author.id}`).then(
client.channels.cache.get("920895881656532992").send(`I was DMed!`, embed1),
console.log(lastDM)
)
}
}
The ERROR:
(node:703) UnhandledPromiseRejectionWarning: SyntaxError: Failed to parse value of dm_612110791683866644, try passing a raw option to get the raw value
at /home/runner/DwaCraft-Main-bot-Fixed/node_modules/#replit/database/index.js:36:17
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async Client.get (/home/runner/DwaCraft-Main-bot-Fixed/node_modules/#replit/database/index.js:20:12)
at async Client.<anonymous> (/home/runner/DwaCraft-Main-bot-Fixed/main.js:116:18)
(node:703) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
Note: I'm using replit's databases.

I'm answering my own question as I found a way to do it, but I still don't get what the Error is as anything else works fine, anyway, I soon realized that my code really doesn't make since, so I fixed it, here is the code:
const { MessageEmbed } = require('discord.js');
const Database = require('#replit/database');
const db = new Database();
client.on('message', async message => {
//Dm checker
if (message.channel.type === 'dm') {
let lastDM = await db.get(`lastDM`)
if (!lastDM) lastDM = `NONE`
if (message.author.id == client.user.id) return;
if (message.author.id == '818749579369512978') return message.channel.send("This chat has been Blacklisted by the developer (<#"+ BOT_OWNER +">)");
const embed = new MessageEmbed()
.setTitle("New message!")
.setAuthor(`Name: \`${message.author.username}\` ID: \`${message.author.id}\` `)
.setColor("GRAY")
.setFooter("Dm message")
.addField("Message:", `\`\`\`${message.content}\`\`\``, false);
await db.set(`lastDM`, message.author.id).then(
client.channels.cache.get("920895881656532992").send(`Someone messaged me.`, embed),
console.log(lastDM)
)
}
And reply command:
const { MessageEmbed } = require('discord.js');
const Database = require('#replit/database');
const db = new Database();
module.exports = {
name: 'reply',
category: 'Owner',
description: 'Replys to last DM.',
aliases: [],
usage: 'Reply <message>',
userperms: ['BOT_OWNER'],
botperms: [],
run: async (client, message, args) => {
if (message.author.bot) return;
let lastDM = await db.get(`lastDM`);
let msg = args.slice(0).join(' ')
if (!lastDM) return message.channel.send("There was no any resent DMs.")
if (!msg) return message.channel.send("I can't send air, please state a message.")
if (!isNaN(lastDM)) {
client.users.cache.get(lastDM).send(msg)
.catch (err => {
return message.channel.send("Failed to send DM, as the user has blocked me or they have DMs closed!")
})
}
}
}
I wish I somehow helped someone that uses replit's databases

Related

Node.js - Discord.js v14 - fetching a channel returns undefined / does not work

Attempting to define channel with this code will return undefined.
const { Events, InteractionType, Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
],
})
module.exports = {
name: Events.InteractionCreate,
async execute(interaction) {
if(interaction.type == InteractionType.ApplicationCommand){
const command = interaction.client.commands.get(interaction.commandName);
if (!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(`Error executing ${interaction.commandName}`);
console.error(error);
}
}
else if(interaction.isAutocomplete()){
const command = interaction.client.commands.get(interaction.commandName);
if(!command) {
console.error(`No command matching ${interaction.commandName} was found.`);
return;
}
try{
await command.autocomplete(interaction);
} catch(error) {
console.error(error);
}
}
else if(interaction.isButton()){
console.log(client.channels);
const channel = await client.channels.fetch('1074044721535656016 ');
console.log(client.channels);
console.log(channel);
}
},
};
const channel = await client.channels.fetch('1074044721535656016 '); Is the main line here.
At the bottom and top of the code is where the important stuff for this question is. I believe I am not properly using the fetch method.
As evidenced by console.log(client.channels); I'm trying to look at the channels cache, but for some reason the channel isn't there, hence I'm using fetch() instead of cache.get().
Thank you for the help!
Other info:
Running npm list shows:
discord.js#14.7.1, dotenv#16.0.3
Node.js v19.6.0
How I got my channel id
Error Message:
ChannelManager {} //<--- this is from the first console.log
node:events:491
throw er; // Unhandled 'error' event
^
Error: Expected token to be set for this request, but none was present
Is the problem because the channel is undefined or because it hasn't resolved yet?
Check your channel ID it may be formatted like:
guild id / channel id
Use interaction.client instead of making a new client object. The interaction already has its own client object with the related properties.

Auto Reaction Roles / Discord.js Bot

So I'm having a slight issue getting my auto roles to work I have been trying to sort it via message.js and in the reactionrole.js but its still giving the same issue wondering if anyone can help would be appreciated as I have looked up about it via tutorials and apart from a few differences due to different text / details it does has not helped
Also Iā€™m using Command handler V2 if that helps
Error
(node:7712) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'roles' of undefined at Object.execute (\commands\other\reactionrole.js:6:46) at module.exports (\events\guild\message.js:46:25) at Client.emit (events.js:376:20) at MessageCreateAction.handle
(node_modules\discord.js\src\client\actions\MessageCreate.js:31:14) at Object.module.exports [as MESSAGE_CREATE] (node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32) at WebSocketManager.handlePacket (\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22) at WebSocketShard.onMessage (\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10) at WebSocket.onMessage \node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (events.js:376:20) (Use `node --trace-warnings ...` to show where the warning was created) (node:7712) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function
without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode).
(rejection id: 1) (node:7712) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
reactionrole.js
module.exports = {
name: 'reactionrole',
description: 'Sets Up Roles!',
async execute(message, args, Discord, client){
const channel = '860952043845058570'
const vgmembers = message.guild.roles.cache.find(role => role.name === "VG Members");
const vgamembers = message.guild.roles.cache.find(role => role.name === "VG-A Members");
const vghmembers = message.guild.roles.cache.find(role => role.name === "VG-H Members");
const vgmembersEmoji = `<:VG:860965732057219122>`;
const vgamembersEmoji = `<:VGA:860964110434566154>`;
const vghmembersEmoji = `<:VGH:860964110371913748>`;
let embed = new Discord.MessageEmbed()
.setColor('#e42643')
.setTitle('What Family Are You In')
.setDescription('Select The Emjoi Of The Alliance You Are In \n\n'
+ `${vgmembersEmoji} If Your A VG Member\n`
+ `${vgamembersEmoji} If Your A VG-A Member\n`
+ `${vghmembersEmoji} If Your A VG-H Member`);
let messageEmbed = await message.channel.send(embed);
messageEmbed.react(yellowTeamEmoji);
messageEmbed.react(blueTeamEmoji);
client.on('messageReactionAdd', async (reaction, user) => {
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (user.bot) return;
if (!reaction.message.guild) return;
if (reaction.message.channel.id == channel) {
if (reaction.emoji.name === vgmembersEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.add(vgmembers);
}
if (reaction.emoji.name === vgamembersEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.add(vgamembers);
}
if (reaction.emoji.name === vghmembersEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.add(vghmembers);
}
} else {
return;
}
});
client.on('messageReactionRemove', async (reaction, user) => {
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
if (user.bot) return;
if (!reaction.message.guild) return;
if (reaction.message.channel.id == channel) {
if (reaction.emoji.name === vgmembersEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.remove(vgmembers);
}
if (reaction.emoji.name === vgamembersEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.remove(vgamembers);
}
if (reaction.emoji.name === vghmembersEmoji) {
await reaction.message.guild.members.cache.get(user.id).roles.remove(vghmembers);
}
} else {
return;
}
});
}
}
message.js
require("dotenv").config();
const { Console, time } = require('console');
const cooldowns = new Map();
module.exports = async (Discord, client, message) => {
const prefix = process.env.PREFIX;
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const cmd = args.shift().toLowerCase();
const command = client.commands.get(cmd) || client.commands.find((a) => a.aliases && a.aliases.includes(cmd));
if (!command) return message.channel.send("This Command Doesn't Exist!");
if (command === "reactionrole"){
client.commands.get('reactionrole').execute(message, Discord, client);
}
if(!cooldowns.has(command.name)){
cooldowns.set(command.name, new Discord.Collection());
}
const current_time = Date.now();
const time_stamps = cooldowns.get(command.name);
const cooldown_amount = (command.cooldown) * 1000;
//If time_stamps has a key with the author's id then check the expiration time to send a message to a user.
if(time_stamps.has(message.author.id)){
const expiration_time = time_stamps.get(message.author.id) + cooldown_amount;
if(current_time < expiration_time){
const time_left = (expiration_time - current_time) / 1000;
return message.reply(`Please wait ${time_left.toFixed(1)} more seconds before using ${command.name}`);
}
}
//If the author's id is not in time_stamps then add them with the current time.
time_stamps.set(message.author.id, current_time);
//Delete the user's id once the cooldown is over.
setTimeout(() => time_stamps.delete(message.author.id), cooldown_amount);
if(command) command.execute(client, message, args, Discord);
}
In your message.js you have
if(command) command.execute(client, message, args, Discord);
While in reactionrole.js you have
async execute(message, args, Discord, client){
This simply means that the value names are mismatched.
There are 3 ways to fix this.
Changing the order in your command file
Probably the best way to fix this.
Simply change the beginning of reactionrole.js to:
module.exports = {
name: 'reactionrole',
description: 'Sets Up Roles!',
async execute(client, message, args, Discord){
//the rest of the code
Change your Command Handler output
This isn't advised, as you probably have other command files that already use the current format, but still possible.
Simply change the last line in message.js to
if(command) command.execute(message, args, Discord, client);
But that might mean having to change all the command files along with it.
Reformat the output and input
One of the best solutions is to use Objects.
In message.js change the last line to
if(command) command.execute({ client, message, args, Discord });
In command files, change the execute property to
async execute({ client, message, args, Discord }){
This will also allow you to only take specific properties in command files, and change the order in which you take them.
Examples:
You can leave out the client, args and Discord properties if it's a simple response like so:
async execute({ message }){
You can change the order without a penalty
async execute({ message, args, Discord, client }){
This will still work, even though the order changed.
The only thing you have to watch out for with this method is the capitalization.
If you were to type discord instead of Discord it wouldn't work.
Use any method you prefer, and a happy coding!
message.guild seems to be undefined
Are you in direct (private) messages?

Discord.js v12 Ban Command - UnhandledPromiseRejectionWarning: RangeError [EMBED_FIELD_VALUE]: MessageEmbed field values may not be empty

I'm having some issues with a ban command I made, and I'm not quite sure why. Everything here looks like it works but I'm getting a lot of errors in the console every time I try to run the ban command. When you run the command it should both ban the user, send a message to the logs channel, and store the punishment info using quick.db. Does anybody see something I'm doing wrong?
The code:
const { MessageEmbed } = require("discord.js");
const convertToMS = require('../lib/convertTime');
const embedStruc = require('../lib/embedStructure');
const e = require('../embeds.json');
const consola = require("consola");
const db = require("quick.db");
const validateUser = (guild, id) => {
let userID = id;
if (userID.indexOf('<#!') > -1) {
userID = userID.split('<#!')[1];
userID = userID.slice(0, -1)
} else if (userID.indexOf('<#') > -1) {
userID = userID.split('<#')[1];
userID = userID.slice(0, -1)
}
const actualMember = guild.members.cache.get(userID);
if (!actualMember) return false;
return actualMember.id;
}
module.exports = {
name: 'ban',
description: 'Bans a user',
alias: [],
async execute(message, args, client, prefix, logsChannel) {
if(!message.member.hasPermission("ADMINISTRATOR")) return;
if (args.length === 0) {
return message.channel.send(
new MessageEmbed()
.setColor(e.red)
.setDescription(
`:x: **Invalid Arguments**\n` +
`\`${prefix}ban [#mention/user id] (reason)\``
)
).catch();
}
let punishedUser = validateUser(message.guild, args[0]);
if (!punishedUser) {
return message.channel.send(
new MessageEmbed()
.setColor(e.red)
.setDescription(
`:x: **Invalid User**`
)
).catch();
}
let reason = 'No reason provided';
if (args.length > 1) {
let tempArgs = args.join(' ').split(' ');
await tempArgs.shift();
await tempArgs.shift();
reason = tempArgs.join(' ');
}
const bannedUser = message.guild.members.cache.get(punishedUser);
const banID = db.add(`${message.guild.id}.base`, 1).base;
if (!bannedUser.bannable) {
return message.channel.send(
new MessageEmbed()
.setColor(e.red)
.setDescription(`:x: Unable to ban <#!${bannedUser.id}>.`)
);
}
await bannedUser.send(
embedStruc.userBan(
reason,
message.guild.name,
banID
)
).catch(() => {});
await bannedUser.ban(`Banned for "${reason}" by ${message.author.tag}`)
.catch(() => {
return message.channel.send(
new MessageEmbed()
.setColor(e.red)
.setDescription(`:x: Unable to ban <#!${bannedUser.id}>.`)
);
});
message.channel.send(
new MessageEmbed()
.setColor(e.default)
.setDescription(
`:scream: <#!${bannedUser.id}> was banned.`
)
).catch();
logsChannel.send(
embedStruc.logsBan(
bannedUser.id,
message.author.id,
reason,
Date.now(),
banID
)
).catch();
db.set(`${message.guild.id}.punishments.${banID}`, {
user: bannedUser.id,
moderator: message.author.id,
reason,
time: Date.now(),
ID: banID,
type: "BAN"
});
db.push(`${message.guild.id}.${bannedUser.id}.punishments`, banID);
},
};
Error:
(node:23906) UnhandledPromiseRejectionWarning: RangeError [EMBED_FIELD_VALUE]: MessageEmbed field values may not be empty.
at Function.normalizeField (/Users/evandeede/Downloads/modbot/node_modules/discord.js/src/structures/MessageEmbed.js:432:23)
at /Users/evandeede/Downloads/modbot/node_modules/discord.js/src/structures/MessageEmbed.js:452:14
at Array.map (<anonymous>)
at Function.normalizeFields (/Users/evandeede/Downloads/modbot/node_modules/discord.js/src/structures/MessageEmbed.js:451:8)
at MessageEmbed.addFields (/Users/evandeede/Downloads/modbot/node_modules/discord.js/src/structures/MessageEmbed.js:266:42)
at MessageEmbed.addField (/Users/evandeede/Downloads/modbot/node_modules/discord.js/src/structures/MessageEmbed.js:257:17)
at Object.logsBan (/Users/evandeede/Downloads/modbot/lib/embedStructure.js:163:10)
at Object.execute (/Users/evandeede/Downloads/modbot/commands/ban.js:98:24)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:23906) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:23906) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Apart from your current error, your ban function will not work:
await bannedUser.ban(`Banned for "${reason}" by ${message.author.tag}`)
You will have to put the reason in as an object, since your able to put in an amount of days too, as shown in the docs here
await bannedUser.ban({ reason: `Banned for "${reason}" by ${message.author.tag}` })

Unhandled rejection: DiscordAPIError: Invalid Form Body when trying a ban command

When I have the ban command running I get this error and I have guildMember.ban in there so I don't know why I'm getting this error.
DICT_TYPE_CONVERT: Only dictionaries may be used in a DictType
DiscordAPIError: Invalid Form Body
Here is the code:
const { version, MessageEmbed } = require("discord.js");
const Discord = require("discord.js");
const errors = require("../events/error.js");
const moment = require("moment")
exports.run = async (client, message, [mention, ...reason]) => { // eslint-disable-line no-unused-vars
if (message.mentions.members.size === 0)
return message.reply("Please mention a user to ban.");
if (!message.guild.me.hasPermission("BAN_MEMBERS"))
return message.reply("");
let guildMember = message.guild.member(message.mentions.users.first())
guildMember.ban(reason.join(" ")).then(member => {
message.reply(`${member.user.username} was succesfully banned.`);
});
};
guildMember.ban() accepts an options object and reason.join(" ") is a string. You need to change it to an object having a key of reason:
guildMember.ban({reason: reason.join(" ")})

Discord bot not responding to commands (Javascript)

I'm doing my first discord bot from a github repository. It connects to discord, and logs into the server, but won't respond to !help commands etc.
It's not my code so I'm not super familiar with it, but the code for the commands seems to be fine.
if (command.content === '!create' && !game) {
createGame(command)
} else if (command.content === '!start' && game && !game.started) {
command.delete()
game.start()
} else if (command.content === '!help') {
command.channel.send(`!create: Create a new game\n!start: Start the game previously created`)
}if (message.content === 'restartthebot') {
if (message.author.id !== 'Owners ID') return;
message.channel.send('Restarted.').then(() => {
process.exit(1);
})
};
I get this error message in my terminal console
(node:2611) UnhandledPromiseRejectionWarning: ReferenceError: command is not defined
at Client.<anonymous> (/Applications/werewolf-discord-master 2/src/index.js:63:3)
at Client.emit (events.js:327:22)
at WebSocketManager.triggerClientReady (/Applications/werewolf-discord-master 2/src/node_modules/discord.js/src/client/websocket/WebSocketManager.js:431:17)
at WebSocketManager.checkShardsReady (/Applications/werewolf-discord-master 2/src/node_modules/discord.js/src/client/websocket/WebSocketManager.js:415:10)
at WebSocketShard.<anonymous> (/Applications/werewolf-discord-master 2/src/node_modules/discord.js/src/client/websocket/WebSocketManager.js:197:14)
at WebSocketShard.emit (events.js:315:20)
at WebSocketShard.checkReady (/Applications/werewolf-discord-master 2/src/node_modules/discord.js/src/client/websocket/WebSocketShard.js:475:12)
at WebSocketShard.onPacket (/Applications/werewolf-discord-master 2/src/node_modules/discord.js/src/client/websocket/WebSocketShard.js:447:16)
at WebSocketShard.onMessage (/Applications/werewolf-discord-master 2/src/node_modules/discord.js/src/client/websocket/WebSocketShard.js:301:10)
at WebSocket.onMessage (/Applications/werewolf-discord-master 2/src/node_modules/ws/lib/event-target.js:132:16)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:2611) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:2611) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
any help would be much appreciated as I'm on a bit of a time crunch here. I'm not at all familiar with Javascript so I'm sorry if this is a stupid question!
///EDIT///
here's the entire code.
'use strict'
const config = require("./config.json")
const fs = require('fs')
const readline = require('readline')
const Discord = require('discord.js')
const client = new Discord.Client()
const pkg = require('../package.json')
client.on('ready', () => {console.log('ready')});
client.login(config.token)
client.on("message", function(message) {
});
// Initialize the bot
getToken().then((token) => {
console.log('Successfully get token. Connecting...')
client.login(token)
})
/**
* Read the Discord Bot Token from config.json or ask it to the user and save it.
* #returns string
*/
async function getToken () {
// Create an empty structure
let config = {}
// Try to read the token field from the config file
try {
config = require('./config.json')
if (config.token) { return Promise.resolve(config.token) }
console.log('The field "token" is empty or doesn\'t exist.')
} catch (err) {
console.warn("The file config.json doen't exist. Creating one ...")
}
// Ask the token to the user
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
config.token = await new Promise(resolve => {
rl.question('What is your Discord Token ? ', (answer) => {
rl.close()
resolve(answer)
})
})
// Save the token in the config file
fs.writeFileSync('./src/config.json', JSON.stringify(config))
return Promise.resolve(config.token)
}
// ==== Bot events ==== //
let games = []
let generalChannel = {}
// Display a message when the bot comes online
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag} dude!`);
command.channel.send("heck yeah I'm here");
});
client.on('message', command => {
// Allow commands only in general
if (generalChannel.id !== command.channel.id) { return }
// Verify is the author own a game. If he do, he can't create a new one.
// The owner is the only who can start a game
let game = games.find(g => g.owner.id === command.author.id)
if (command.content === '!create' && !game) {
createGame(command)
} else if (command.content === '!start' && game && !game.started) {
command.delete()
game.start()
} else if (command.content === '!help') {
command.channel.send(`!create: Create a new game\n!start: Start the game previously created`)
}if (message.content === 'restartthebot') {
if (message.author.id !== 'Owners ID') return;
message.channel.send('Restarted.').then(() => {
process.exit(1);
})
};
// TODO: Remove this command in prod
if (command.content === '!clear') {
command.channel.fetchMessages().then(messages => {
messages.forEach(m => {
m.delete()
})
})
}
})
client.on('messageReactionAdd', (msgReaction, user) => {
if (user.id === client.user.id) { return } // If it's the bot itself, ignore
// Find the game the message is a attached to
// Only on game creation message
// TODO: Check the reaction type
let game = games.find(g => g.message.id === msgReaction.message.id)
if (game && user.id !== game.owner.id) {
game.addPlayer(user)
}
})
client.on('messageReactionRemove', (msgReaction, user) => {
// Find the game the message is a attached to
let game = games.find(g => g.message.id === msgReaction.message.id)
if (game) {
game.removePlayer(user)
}
})
// ==== Bot functions ==== //
const Game = require('./Game')
/**
* Create a Game object in the games array and send a creation game message
* #param {Discord.Message} command
*/
function createGame (command) {
command.channel.send(
new Discord.RichEmbed()
.setTitle('Create a game')
.setDescription(`Want to join ?\n 1/6`)
.setColor(0xFF0000)
).then(message => {
message.react('šŸ‘')
games.push(new Game(message, command.author))
command.delete()
})
}
You're not supposed to use command, but instead msg
For example, you wrote command.channel.send("heck yeah I'm here");
Instead, it should be msg.channel.send("heck yeah I'm here");
And instead of:
client.on('message', command => {
//code here
})
it should be:
client.on('message', msg => {
//code here
})
Hope this helped.

Categories