I am wanting to integrate the "vote" command of my bot, with the api of top.gg, I want something similar to the command below. this command is the "work" command of my bot, so that you have a base, I would like to modify it so that, when voting for my bot, it delivers "6k of coins" to the user who voted. do you have an explanation of how I can do it? I will leave my code for the work command below, so you can have an idea.
async run({ message, args, prefix, author }, t) {
if (!args[0]) {
User.findOne({ idU: message.author.id }, async (err, user) => {
let xp = Math.floor(Math.random() * 90) + 1;
let work = user.work.cooldown;
let cooldown = 1.44e7;
let money = Math.ceil(user.work.level * 2 * user.work.coins + 400);
let nextlevel = user.work.nextLevel * user.work.level;
if (work !== null && cooldown - (Date.now() - work) > 0) {
return message.quote(
`<:daily:842204620977864734> Você deve esperar **${moment
.duration(cooldown - (Date.now() - work))
.format("h [hora(s)], m [minuto(s)] e s [segundos]")
.replace("minsuto(s)", "minuto(s)")}** até poder trabalhar novamente`
);
} else {
if (user.work.exp + xp > nextlevel) {
message.quote(
`Parabéns, sua empresa acaba de subir para o level **${
user.work.level + 1
}**.`
);
await User.findOneAndUpdate(
{ idU: message.author.id },
{
$set: {
"work.cooldown": Date.now(),
"work.exp": 0,
coins: user.coins + money,
"work.level": user.work.level + 1,
},
}
);
} else {
message.quote(
`<:work:846536054399303700><:coins_k:846487970612903976> Você trabalhou com sucesso e obteve **${money.toLocaleString()} coins** e **${xp} de XP**.`
);
await User.findOneAndUpdate(
{ idU: message.author.id },
{
$set: {
"work.cooldown": Date.now(),
"work.exp":
user.work.exp + xp > nextlevel ? 0 : user.work.exp + xp,
coins: user.coins + money,
},
}
);
}
}
});
return;
}
You can check if the user has voted to your bot usinghttps://top.gg/api/bots/:bot_id/check?userId=userid endpoint
const fetch = require("node-fetch"); // import node-fetch module
const botId = client.user.id; // get the client (bot) id
const uId = message.author.id; // get the author id
const url = `https://top.gg/api/bots/${botId}/check?userId=${uId}`; // api endpoint
fetch(url, { method: "GET", headers: { Authorization: "your top.gg bot token" }})
.then((res) => res.text())
.then((json) => {
var isVoted = JSON.parse(json).voted;
if (isVoted === 0) {
return message.channel.send("you haven't voted yet");
}
message.channel.send("thank you for voting");
});
Note that this code is not perfect.
You can get your top.gg bot token from https://top.gg/bot/your-bot-id/webhooks
Source: https://docs.top.gg/api/bot/#individual-user-vote
By updating the post, I managed to get the desired result, I will leave the code below to others who have the same question!
const botId = client.user.id; //
const uId = message.author.id; // get the author id
const url = `https://top.gg/api/bots/${botId}/check?userId=${uId}`; // api endpoint
fetch(url, {
method: "GET", headers: { Authorization: "top.gg token" },
})
.then((res) => res.text())
.then((json) => {
let isVoted = JSON.parse(json).voted;
User.findOne({ idU: message.author.id }, async (err, user) => {
//================= Imports =================//
let cooldown = 4.68e7;
let coins = Math.floor(Math.random() * 5000);
let vote = user.vote;
let atual = user.coins;
let time = cooldown - (Date.now() - vote);
if (isVoted !== null && cooldown - (Date.now() - vote) > 0) {
return message.channel.send(`**Você já votou em mim hoje!**\n\nVolte em **${moment
.duration(time)
.format(
"h [Horas] m [Minutos] e s [Segundos]"
)}**`);
}
message.channel.send(`**Vote em mim em:** https://top.gg/bot/762320527637217312/vote **e receba até 5K de coins de forma aleatória!**`);
await User.findOneAndUpdate(
{ idU: message.author.id },
{ $set: { coins: coins + atual, vote: Date.now() } }
);
});
});
Related
const Invites = new Collection();
const guildInvites = new Map()
client.on('inviteCreate', async invite => {
const invites = await invite.guild.invites.fetch();
const codeUses = new Map();
invites.each(inv => codeUses.set(inv.code, inv.uses, inv.inviter));
guildInvites.set(invite.guild.id, codeUses);
})
client.once('ready', () => {
client.guilds.cache.forEach(guild => {
guild.invites.fetch()
.then(invites => {
const codeUses = new Map();
invites.each(inv => codeUses.set(inv.code, inv.uses, inv.inviter));
guildInvites.set(guild.id, codeUses);
})
.catch(err => {
console.log("OnReady Error:", err)
})
})
})
client.on('guildMemberAdd', async member => {
const cachedInvites = guildInvites.get(member.guild.id)
const newInvites = await member.guild.invites.fetch();
try {
const usedInvite = newInvites.find(inv => cachedInvites.get(inv.code) < inv.uses < inv.inviter);
const embed0 = new MessageEmbed()
.setTitle("Invite Logs")
.setColor("GREEN")
.setDescription(`Ο/Η ${member} (${member.user.username}) μπήκε στον server από την πρόσκληση (${usedInvite.code || "δεν υπάρχει πλέον"}) του ${usedInvite.inviter} (${usedInvite.inviter.username}) **αλλά είναι Fake**`)
var fake22 = (Date.now() - member.user.createdAt < 1000*60*60*config.invite_faketime*1) //return client.channels.cache.get(config.invite_logs).send({embeds: [embed0] }),db.add(`total_${usedInvite.inviter.id}`, 1),db.add(`fake_${usedInvite.inviter.id}`, 1)
const embed = new MessageEmbed()
.setTitle("Invite Logs")
.setColor("GREEN")
.setDescription(`Ο/Η ${member} (${member.user.username}) μπήκε στον server από την πρόσκληση (${usedInvite.code || "δεν υπάρχει πλέον"}) του ${usedInvite.inviter} (${usedInvite.inviter.username})`)
client.channels.cache.get(config.invite_logs).send({embeds: [embed] })
if (usedInvite.inviter) {
db.set(`invites_${member.guild.id}.${member.id}.inviter`, usedInvite.inviter.id);
if (fake22) {
total = db.add(`invites_${member.guild.id}.${usedInvite.inviter.id}.total`, 1);
_fake = db.add(`invites_${member.guild.id}.${usedInvite.inviter.id}.fake`, 1);
}
else {
total = db.add(`invites_${member.guild.id}.${usedInvite.inviter.id}.total`, 1);
regular = db.add(`invites_${member.guild.id}.${usedInvite.inviter.id}.regular`, 1);
}}
//console.log(`The code ${usedInvite.code} was just used by ${member.user.username}. ${usedInvite.inviter.username}`)
} catch(err) {
}
newInvites.each(inv => cachedInvites.set(inv.code, inv.uses));
guildInvites.set(member.guild.id, cachedInvites);
});
**
we have user 1
user 2
user 3
i am user 1
i invite user 2 and i see in logs that user 1 invites user 2
but after i make invite link from user 2 and i invite user 3
but i see in logs tha user 1 invites user 3
**
can someone help me to cashed the right invite ?
I'm getting memory leak warning in the console for my Electron app, i don't know what to do to increase limit. It's causing it everytime i run the app.
Does the error is linked to uiohook? Or did i miss something here?
How can i use emitter.setMaxListeners() in my case? I have no clue of how to fix it, and hwo to increase the memory leak.
[3452:1014/104426.056:ERROR:service_worker_storage.cc(1904)] Failed to delete the database: Database IO error
(node:21792) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 terminate-timer listeners added to [EventEmitter]. Use emitter.setMaxListeners() to increase limit
(Use `electron --trace-warnings ...` to show where the warning was created)
(node:21792) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 set-activity listeners added to [EventEmitter]. Use emitter.setMaxListeners() to increase limit
Electron
const electron = require('electron');
const BrowserWindow = electron.BrowserWindow;
const dialog = electron.dialog;
const desktopCapturer = electron.desktopCapturer;
const idle = electron.powerMonitor;
const remote = electron.remote;
const notification = electron.Notification;
const globalShortcut = electron.globalShortcut;
const screen = electron.screen;
const ipcMain = electron.ipcMain;
const app = electron.app;
const isDev = require('electron-is-dev');
const path = require('path');
const activeWindows = require('electron-active-window');
const activeWindowPage = require('active-win');
const BMParser = require('bookmark-parser');
const axios = require('axios');
const uiohook = require('uiohook-napi');
const { autoUpdater } = require("electron-updater");
const debug = require('debug')('Franz:ipcApi:autoUpdate');
const dns = require("dns");
const activity = { is_mouse: 0, is_keyboard: 0 };
const headers = {
'Content-Type': 'application/json;charset=UTF-8',
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Origin": "*",
"Accept": "application/json"
}
const sessionUser = null;
let updateInterval = null;
app.disableHardwareAcceleration();
electron.powerSaveBlocker.start('prevent-app-suspension');
//electron.commandLine.appendSwitch ("disable-http-cache");
// Change App Name on Windows
if (process.platform === 'win32')
{
app.setAppUserModelId('Rubii');
}
let apiEndpoint = "http://creaz:81/xorix/api"; // Brian
let frameUrl = 'http://localhost:3000'; // Brian
//if (isDev) { // or if(process.env.NODE_ENV)
// apiEndpoint = "http://creaz:81/xorix/api";
// frameUrl = 'http://localhost:3000';
//}
var internetAvailable = require("internet-available");
let isConnected = false;
let counterInternet = 0;
let allowSendInternetNotification = 1;
async function liveInternetCheck() {
var userSessionCheck = await getSessionUser();
// Most easy way
internetAvailable({
domainName: "rubii.com",
// Provide maximum execution time for the verification
timeout: 10000,
// If it tries 10 times and it fails, then it will throw no internet
retries: 10
}).then(() => {
// Available Internet
isConnected = true;
counterInternet++;
if(counterInternet > 3 && allowSendInternetNotification == 0) {
allowSendInternetNotification = 1;
}
}).catch(() => {
// Not available internet
isConnected = false;
if(isConnected == false && userSessionCheck && allowSendInternetNotification == 1) {
var message = 'Your internet has been disconnected! Please login again';
new notification({ title: 'Ooops', body: message }).show();
// Logout the user in the other end
win.webContents.send("terminate-timer", "hello");
allowSendInternetNotification = 0;
counterInternet = 0;
}
});
}
autoUpdater.on("update-available", (_event, releaseNotes, releaseName) => {
const dialogOpts = {
type: 'info',
buttons: ['Ok'],
title: 'Update Available',
message: process.platform === 'win32' ? releaseNotes : releaseName,
detail: 'A new version download started. The app will be restarted to install the update.'
};
dialog.showMessageBox(dialogOpts);
updateInterval = null;
});
autoUpdater.on("update-downloaded", (_event, releaseNotes, releaseName) => {
const dialogOpts = {
type: 'info',
buttons: ['Restart'],
title: 'Application Update',
message: process.platform === 'win32' ? releaseNotes : releaseName,
detail: 'A new version has been downloaded. Restart the application to apply the updates.'
};
dialog.showMessageBox(dialogOpts).then((returnValue) => {
if (returnValue.response === 0) autoUpdater.quitAndInstall()
});
});
function checkUpdate() {
updateInterval = setInterval(() => autoUpdater.checkForUpdates(), 600000);
}
let win;
ipcMain.on('close-me', (evt, arg) => {
new notification({ title: 'Ooops', body: 'We hope to see you again!' }).show();
app.quit()
});
function determineScreenShotSize() {
var screenSize = screen.getPrimaryDisplay().workAreaSize
return {
width: screenSize.width,
height: screenSize.height
}
}
async function takeScreenshot() {
var user = await getSessionUser();
var timer = await getSessionTimer();
if (user && timer) {
if (timer.timer == 1) {
//console.log('Gathering screens...');
//console.log(app.getPath('pictures'));
const thumbSize = determineScreenShotSize();
const workaroundTimestamp = Date.now();
const options = {
types: ['screen'],
thumbnailSize: { ...thumbSize, workaroundTimestamp }
};
desktopCapturer.getSources(options).then((sources) => {
console.log('Sources received:' + sources.length);
sources.forEach(function (source) {
const sourceName = source.name.toLowerCase();
//console.log(sourceName);
if (['entire screen', 'screen 1'].includes(sourceName)) {
var the_screenshot = source.thumbnail.toPNG();
var data = {
user_id: user.id,
company_id: timer.company_id,
image: the_screenshot.toString('base64')
}
axios.post(apiEndpoint + "/desktop/save_screenshots", data, {
headers: headers
})
.then((response) => {
// console.log(response);
})
.catch((error) => {
//console.log(error);
})
}
})
}).catch(console.error);
}
}
}
function saveSoftware() {
(async () => {
var options = [];
var software = await activeWindowPage();
var user = await getSessionUser();
var timer = await getSessionTimer();
if (user && timer) {
if (timer.timer == 1) {
software.user = user;
software.timer = timer;
axios.post(apiEndpoint + "/desktop/save_app", software, {
headers: headers
})
.then((response) => {
//console.log(response);
})
.catch((error) => {
//console.log(error);
})
}
}
})();
}
function getSessionUser() {
return win.webContents.executeJavaScript('sessionStorage.getItem("user");', true)
.then(result => {
if (result) {
return JSON.parse(result);
}
});
}
function getSessionTimer() {
return win.webContents.executeJavaScript('sessionStorage.getItem("timer");', true)
.then(result => {
if (result) {
return JSON.parse(result);
}
});
}
async function generateActivity() {
win.webContents.send("set-activity", activity);
// We reset after we send it
activity.is_mouse = activity.is_keyboard = 0;
}
function secondsToHms(d) {
d = Number(d);
var h = Math.floor(d / 3600);
var m = Math.floor(d % 3600 / 60);
var s = Math.floor(d % 3600 % 60);
var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
return hDisplay + mDisplay + sDisplay;
}
function createWindow() {
win = new BrowserWindow({
width: 1200,
height: 900,
frame: true,
webPreferences: {
webSecurity: false,
nodeIntegration: true,
enableRemoteModule: true,
contextIsolation: false,
backgroundThrottling: false
}
});
//win.loadURL('https://desktop.rubii.com');
win.loadURL(frameUrl, { "extraHeaders": "pragma: no-cache\n" });
// http://localhost:3000
//win.webContents.openDevTools();
//win.removeMenu(); // Brian
// or set the Menu to null
//win.setMenu(null); // Brian
// Reload cache
win.webContents.reloadIgnoringCache();
// Keyboard activity
uiohook.uIOhook.on('keydown', (e) => {
//console.log('Keyboard!')
activity.is_keyboard = 1;
})
// Mouse activity
uiohook.uIOhook.on('mousemove', (e) => {
//console.log('mouse');
activity.is_mouse = 1;
})
// Start listener for keyboard and mouse
uiohook.uIOhook.start();
win.on('close', function () {
win = null;
})
}
app.whenReady().then(createWindow).then(checkUpdate);
app.on('window-all-closed', function () {
app.quit();
});
app.on('activate', function () {
if (win == null) {
createWindow();
}
})
setInterval(takeScreenshot, 10 * 60 * 1000); // 10 minutes
setInterval(saveSoftware, 5 * 1000); // 5 seconds
setInterval(generateActivity, 1 * 1000);
setInterval(function() { liveInternetCheck(); }, 10 * 1000); // 10 seconds
Render
ipcRenderer.on("terminate-timer", function (event, data) {
// Logout if there is no internet connection
handleLogout();
});
// Set activity if there were any keyboard, mouse
ipcRenderer.on("set-activity", function (event, data) {
// If the timer is on
if(timer) {
setActivity(data);
}
});
I've made a coin system and am trying to read how many coins the user has, but for some reason it's coming back as 'undefined', done anyone know why?
else if (command === 'coins') {
const userData = await CoinSystem.find({userID : message.member.user.id});
if (!userData.length) {
const createdData = new CoinSystem({
userID : message.member.user.id,
userName : message.member.user.tag,
coins : 0
})
await createdData.save().catch(e => console.log(e));
await message.channel.send("You have 0 coins.");
return;
}
if (userData.length) {
await message.channel.send(await userData.find(coins));
}
Creating the data.
const mongoose = require('mongoose');
const coinSchema = new mongoose.Schema({
userID : {
type : mongoose.SchemaTypes.String,
required : true
},
userName : {
type : mongoose.SchemaTypes.String,
required : true
},
coins : {
type : mongoose.SchemaTypes.Number,
required : true,
default : 0
}
})
module.exports = mongoose.model('CoinSystem', coinSchema)
First, try using await CoinSystem.findOne({userID : message.member.user.id}); instead of await CoinSystem.find({userID : message.member.user.id});
Second, try using (!userData) and (userData) instead of (!userData.length) and (userData.length)
Third, try using
await message.channel.send({ content: `${userData.coins}` });
instead of await message.channel.send(await userData.find(coins));
The final code is:
const userData = await CoinSystem.findOne({userID : message.member.user.id});
if (!userData) {
const createdData = new CoinSystem({
userID : message.member.user.id,
userName : message.member.user.tag,
coins : 0
})
await createdData.save().catch(e => console.log(e));
await message.channel.send({ content: "You have 0 coins."});
return;
}
if (userData) {
await message.channel.send({ content: `You have ${userData.coins} coins` });
}
Notes --> the reason of using:
message.channel.send({ content: `You have ${userData.coins} coins` })
instead of:
message.channel.send(`You have ${userData.coins} coins`)
is because of Discord.js v13.
If yours is discord.js v12, then u should use:
message.channel.send(`You have ${userData.coins} coins`)
I'm developing a discord.js moderation bot, but when I run it I get this error.
Here is the code:
var Discord = require('discord.js')
const fs = require("fs")
const { PREFIX } = require("../../config")
const db = require('quick.db')
const { stripIndents } = require("common-tags");
module.exports = {
config: {
name: "help",
description: "Help Menu",
usage: "1) m/help \n2) m/help [module name]\n3) m/help [command (name or alias)]",
example: "1) m/help\n2) m/help utility\n3) m/help ban",
aliases: ['h']
},
run: async (bot, message, args) => {
let prefix;
if (message.author.bot || message.channel.type === "dm") return;
try {
let fetched = await db.fetch(`prefix_${message.guild.id}`);
if (fetched == null) {
prefix = PREFIX
} else {
prefix = fetched
}
} catch (e) {
console.log(e)
};
if(message.content.toLowerCase() === `${prefix}help`){
var log = new Discord.MessageEmbed()
.setTitle("**Help Menu: Main**")
.setColor(`#d9d9d9`)
.addField(`**👑Moderation**`, `[ \`${prefix}help mod\` ]`, true)
.addField(`**⚙️Utility**`, `[ \`${prefix}help utility\` ]`, true)
message.channel.send(log);
}
else if(args[0].toLowerCase() === "mod") {
var commandArray = "1) Ban \n2) Kick\n3) Whois\n4) Unban\n5) Warn\n6) Mute\n7) Purge\n8) Slowmode \n9) Nick \n10) Roleinfo"
var commandA2 = "11) Rolememberinfo\n12) Setmodlog\n13) Disablemodlog\n14) Lock (Lock the channel)\n15) Unlock (Unlock the channel)\n16) Lockdown (Fully Lock the whole server. [FOR EMRGENCIES ONLY]) \n17) Hackban\\forceban <id>"
pageN1 = "**\n💠Commands: **\n`\`\`js\n" + commandArray + "\`\`\`";
pageN2 = "**\n💠Commands: **\n`\`\`js\n" + commandA2 + "\`\`\`";
let pages = [pageN1, pageN2]
let page = 1
var embed = new Discord.MessageEmbed()
.setTitle('**Help Menu: [Moderation]👑**')
.setColor("#d9d9d9") // Set the color
.setFooter(`Page ${page} of ${pages.length}`, bot.user.displayAvatarURL())
.setDescription(pages[page-1])
message.channel.send({embed}).then(msg => {
msg.react('⬅').then( r => {
msg.react('➡')
// Filters
const backwardsFilter = (reaction, user) => reaction.emoji.name === '⬅' && user.id === message.author.id
const forwardsFilter = (reaction, user) => reaction.emoji.name === '➡' && user.id === message.author.id
const backwards = msg.createReactionCollector(backwardsFilter, {timer: 6000})
const forwards = msg.createReactionCollector(forwardsFilter, {timer: 6000})
backwards.on('collect', (r, u) => {
if (page === 1) return r.users.remove(r.users.cache.filter(u => u === message.author).first())
page--
embed.setDescription(pages[page-1])
embed.setFooter(`Page ${page} of ${pages.length}`, bot.user.displayAvatarURL())
msg.edit(embed)
r.users.remove(r.users.cache.filter(u => u === message.author).first())
})
forwards.on('collect', (r, u) => {
if (page === pages.length) return r.users.remove(r.users.cache.filter(u => u === message.author).first())
page++
embed.setDescription(pages[page-1])
embed.setFooter(`Page ${page} of ${pages.length}`, bot.user.displayAvatarURL())
msg.edit(embed)
r.users.remove(r.users.cache.filter(u => u === message.author).first())
})
})
})
}
else if(args[0].toLowerCase() === "util") {
var embed = new Discord.MessageEmbed()
.setTitle('**Help Menu: [Utility]**')
.setColor("#d9d9d9") // Set the color
.setDescription("```js" + `1) Prefix [${prefix}help prefix for more info]\n 2) Help [${prefix}help for more info]` + "```")
} else {
const embed = new Discord.MessageEmbed()
.setColor("#d9d9d9")
.setAuthor(`${message.guild.me.displayName} Help`, message.guild.iconURL())
.setThumbnail(bot.user.displayAvatarURL())
let command = bot.commands.get(bot.aliases.get(args[0].toLowerCase()) || args[0].toLowerCase())
if (!command) return message.channel.send(embed.setTitle("**Invalid Command!**").setDescription(`**Do \`${prefix}help\` For the List Of the Commands!**`))
command = command.config
embed.setDescription(stripIndents`
** Command -** [ \`${command.name.slice(0, 1).toUpperCase() + command.name.slice(1)}\` ]\n
** Description -** [ \`${command.description || "No Description provided."}\` ]\n
** Usage -** [ \`${command.usage ? `\`${command.usage}\`` : "No Usage"}\` ]\n
** Examples -** [ \`${command.example ? `\`${command.example}\`` : "No Examples Found"}\` ]\n
** Aliases -** [ \`${command.aliases ? command.aliases.join(" , ") : "None."}\` ]`)
embed.setFooter(message.guild.name, message.guild.iconURL())
return message.channel.send(embed)
}
}
}
If someone could help with this issue it would be great because I don't know what to do. I already searched on internet but I still don't know what I need to do to solve this error. All this code is for help function, when someone calls -pks help the bot should show embed telling all his functions
Here is my index.js file:
const { Client, Collection } = require('discord.js');
const { PREFIX, TOKEN } = require('./config');
const bot = new Client({ disableMentions: 'everyone' });
const fs = require("fs");
const db = require('quick.db');
bot.commands = new Collection();
bot.aliases = new Collection();
["aliases", "commands"].forEach(x => bot[x] = new Collection());
["console", "command", "event"].forEach(x => require(`./handler/${x}`)(bot));
bot.categories = fs.readdirSync("./commands/");
["command"].forEach(handler => {
require(`./handler/${handler}`)(bot);
});
bot.on('message', async message => {
let prefix;
try {
let fetched = await db.fetch(`prefix_${message.guild.id}`);
if (fetched == null) {
prefix = PREFIX
} else {
prefix = fetched
}
} catch {
prefix = PREFIX
};
try {
if (message.mentions.has(bot.user.id) && !message.content.includes("#everyone") && !message.content.includes("#here")) {
message.channel.send(`\nMy prefix for \`${message.guild.name}\` is \`${prefix}\` Type \`${prefix}help\` for help`);
}
} catch {
return;
};
});
bot.login(TOKEN);
I'm trying to make a trivia command for my bot and I want to make it so that it sends a message after the amount of time for the collection it says "Times up".
This is what I have written so far:
const Discord = require("discord.js")
exports.run = async(client, message, args) => {
const collector = new Discord.MessageCollector(message.channel, m => m.author.id === message.author.id, {
time: 10000
});
number = 1;
var random = Math.floor(Math.random() * (number - 1 + 1)) + 1;
switch (random) {
case 1:
{
message.channel.send("Case 1");
collector.on('collect', message => {
if (message.content == "1") {
return message.channel.send("Correct!");
} else {
message.channel.send("wrong!");
}
});
collector.on('end', message => {
message.channel.send("times up!")
});
}
}
};
When I do this it says send of undefined for the end event.
I've also tried this below, but it does nothing:
const Discord = require("discord.js")
exports.run = async(client, message, args) => {
const collector = new Discord.MessageCollector(message.channel, m => m.author.id === message.author.id, {
time: 10000
});
number = 1;
var random = Math.floor(Math.random() * (number - 1 + 1)) + 1;
switch (random) {
case 1:
{
message.channel.send("Case 1");
collector.on('collect', message => {
if (message.content == "1") {
return message.channel.send("correct!");
} else {
message.channel.send("wrong!");
}
});
collector.stop('end', message => {
message.channel.send("times up!");
});
}
}
};
The last thing I tried was this, but I got .stop of undefined:
const Discord = require("discord.js")
exports.run = async(client, message, args) => {
const collector = new Discord.MessageCollector(message.channel, m => m.author.id === message.author.id, {
time: 10000
});
number = 1;
var random = Math.floor(Math.random() * (number - 1 + 1)) + 1;
switch (random) {
case 1:
{
message.channel.send("Case 1");
collector.on('collect', message => {
if (message.content == "1") {
return message.channel.send("correct!");
} else {
message.channel.send("wrong!");
}
}).stop(["times up"]);
}
}
};
Also, how could I make the collection stop after the "Correct!" spot?
Try using:
collector.on('end', (collected, reason) => {
message.channel.send("times up!")
});
Like in the docs: https://discord.js.org/#/docs/main/stable/class/MessageCollector?scrollTo=e-end