I prepared an sending random images discord bot. bot works smoothly but instead of just sending an image, it randomly sends all images in the folder. I need your help.(12 images available, prefix: !! ) codes;
const Discord = require('discord.js');
const client = new Discord.Client();
const settings = require('./settings.json');
var prefix = settings.prefix;
client.on('ready', () => {
console.log(`${client.user.tag} ready!`);
});
client.on('message', msg => {
if (msg.content.toLowerCase() === prefix + 'xgif' )
number = 12;
imageNumber = Math.floor (Math.random() * (number -1 + 1)) + 1;
msg.channel.send ( {files: ["./images/" + imageNumber + ".gif"]})
});
client.login(TOKEN HERE)
You have numerous problems leading to this. First, your if statement isn't scoped properly. Your code is the functional equivalent of:
if (msg.content.toLowerCase() === prefix + 'xgif' ) {
number = 12;
}
imageNumber = Math.floor (Math.random() * (number -1 + 1)) + 1;
msg.channel.send ( {files: ["./images/" + imageNumber + ".gif"]})
So what is happening is number is not always set to 12, and the last two lines execute with every single message, including messages that come from the bot itself. You need to:
1. scope your if statement correctly.
2. ignore all bot message.
client.on('message', msg => {
if(msg.author.bot) return; // Ignore bots!
if (msg.content.toLowerCase() === prefix + 'xgif' ) {
number = 12;
imageNumber = Math.floor (Math.random() * (number -1 + 1)) + 1;
msg.channel.send ( {files: ["./images/" + imageNumber + ".gif"]})
} // End of if scope
}
Unlike Python, for one example, JavaScript and all other C-style syntax languages do not use white space to indicate scope. An if statement with no brackets only includes the next single statement in it's scope.
Related
I've made a "working" dice roll function on my bot. Works fine for what I need, but was wondering how I could make it so depending on what is said in discord it rolls.
So saying !rolld6 would use 6 in var response instead of 20.
if (message.content.toLowerCase().includes("!rolld20")) {
const ayy = client.emojis.cache.find(emoji => emoji.name === "diceroll");
var response = [Math.floor(Math.random() * ((20 - 1) + 1) + 1)];
message.channel.send(`${ayy}` + `Rolling.`)
.then(msg => {
setTimeout(function() {
msg.edit(`${ayy}` + `Rolling..`)
}, 1000);
setTimeout(function() {
msg.edit(`${ayy}` + `Rolling...`)
}, 2000)
setTimeout(function() {
msg.edit(`${ayy}` + `Rolling....`)
}, 3000)
setTimeout(function() {
msg.edit(`${ayy}` + " Rolled... " + response + " " + `${ayy}`).then().catch(console.error)
}, 4000)
})
return;
}
Not even sure what I would search to figure this out so any help is greatly appreciated!
Use a regular expression instead of .includes, and then extract the digits after the d to randomize.
You don't need to subtract 1, then add 1 right after that - those cancel out, nor do you need to put the result into an array - interpolating just the random number generated into the message will work fine.
const match = message.content.match(/!rolld(\d+)/i);
if (match) {
const die = match[1];
const response = 1 + Math.floor(Math.random() * die);
const ayy = client.emojis.cache.find(emoji => emoji.name === "diceroll");
My bot are sends random gifs but not embed. I wanna sends random gifs with embed. How can I this ?
Codes:
if (msg.author.bot) return;
if (msg.content.toLowerCase() === prefix + 'xgif' ) {
number = 100;
imageNumber = Math.floor (Math.random() * (number -1 + 1)) + 1;
client.channels.cache.get(`channelID`).send( {files: ["./images/" + imageNumber + ".gif"]})
}
You need to first do
const { RichEmbed } = require('discord.js')
That'll get RichEmbed for you. Then, do
const embed = new RichEmbed()
There's a lot of things you can do to change the embed. There's
.setColor(hexidecimal)
.setThumbnail(normally user.displayAvatarURL)
.setFooter(whatever you want)
.setTimestamp()
.setDescription(whatever you want)
.setAuthor(whatever you want)
.addField(stuff)
I want the message to be sent to a specific channel when I give the command. I want the user to encounter an error if the command was not run on a particular channel. I need your help.
if (msg.author.bot) return;
if (msg.content.toLowerCase() === prefix + 'xgif' ) {
number = 100;
imageNumber = Math.floor (Math.random() * (number -1 + 1)) + 1;
client.channels.get(`channelID`).send( {files: ["./images/" + imageNumber + ".gif"]})
}
Error: TypeError: client.channels.get is not a function
Since discord.js v12 you need to use the cache property to access channels collection, so you need to replace
client.channels.get(`channelID`).send( {files: ["./images/" + imageNumber + ".gif"]})
with
client.channels.cache.get(`channelID`).send( {files: ["./images/" + imageNumber + ".gif"]})
I'm trying to make a number guessing game on JS for a web dev training I'm on. The problem is that it always prints the keyInYNStrict without giving an another chance for the user. Ignore the fact that the strings and variables are not in English. Basically I want the keyInYNStrict to only come after the arvaus == arvattava is true and the game has ended.
const minLuku = 1;
const maxLuku = 30;
const readlineSync = require('readline-sync');
let arvaus, arvattava, arvaustenLkm
do {
arvaus = readlineSync.question('Ajattelen numeroa 1 ja 30 välillä. Arvaapa vaan');
arvaustenLkm = 1;
arvattava = Math.floor(Math.random() * (maxLuku + 1 - minLuku)) + minLuku
kelvollinen = !isNaN(arvaus) && arvaus > 0 && arvaus < 31;
if (!kelvollinen) {
console.log('Elä viitsi! Laita nyt jokin oikea numero.');
}
else if (arvaus < arvattava){
arvaustenLkm++;
console.log('Kokeile suurempaa lukua.');
} else if (arvaus > arvattava){
arvaustenLkm++;
console.log('Kokeile pienempää lukua.');
} else if (arvaus == arvattava){
console.log('Hienoa. arvasit oikein ' + arvaustenLkm + ' arvauksella.')
}
} while (readlineSync.keyInYNStrict('Haluatko arvata uudestaan?'))
You'll need two while loops nested. The first is to repeat the guessing until the number has been found, the second to ask if the user wished to play again. This becomes clearer if you break a single game into a function, and then wrap "Play again?" around that function.
The following is untested. Notice I also pulled out the "Invalid guess" check to separate it from the game logic. I think that also improves readability, and allows for the option of checking for some other exit condition should the user wish to end early.
EDIT: As I'm thinking about it, there's another problem: Do you want to reset the hidden number each guess? That's probably not consistent with expectations. I've modified the code to reflect.
const minLuku = 1; // Lower bound
const maxLuku = 30; // Upper bound
const readlineSync = require('readline-sync');
let arvaus, arvattava, arvaustenLkm
do {
// Number of guesses
arvaustenLkm = 1;
//Target number
arvattava = Math.floor(Math.random() * (maxLuku + 1 - minLuku)) + minLuku
do {
// User's guess
arvaus = readlineSync.question('Ajattelen numeroa 1 ja 30 välillä. Arvaapa vaan');
// Bad guess test
if (isNaN(arvaus) || arvaus < minLuku || arvaus > maxLuku) {
console.log('Elä viitsi! Laita nyt jokin oikea numero.');
continue;
}
if (arvaus < arvattava){
arvaustenLkm++;
console.log('Kokeile suurempaa lukua.');
} else if (arvaus > arvattava){
arvaustenLkm++;
console.log('Kokeile pienempää lukua.');
} else if (arvaus == arvattava){
console.log('Hienoa. arvasit oikein ' + arvaustenLkm + ' arvauksella.')
}
} while (arvaus != arvattava)
} while (readlineSync.keyInYNStrict('Play again?'))
I'm creating a discord bot and part of its commands is to roll dice with different values (d6, d10, d20, d100). I've set it up like this:
const Discord = require('discord.js');
const client = new Discord.Client();
function commandIs (str, msg){
return msg.content.toLowerCase().startsWith("!" + str)
} //Function that shortens all response commands.
client.on ('message', message => {
if(commandIs("rolld6", message)){
var result = Math.floor(Math.random() * ((6 - 1) + 1) + 1);
message.channel.sendMessage (result);
} //rolls a d6
if(commandIs("rolld10", message)){
var result = Math.floor(Math.random() * ((10 - 1) + 1) + 1);
message.channel.sendMessage (result);
} //rolls a d10
if(commandIs("rolld20", message)){
var result = Math.floor(Math.random() * ((20 - 1) + 1) + 1);
message.channel.sendMessage (result);
} //rolls a d20
if(commandIs("rolld100", message)){
var result = Math.floor(Math.random() * ((100 - 1) + 1) + 1);
message.channel.sendMessage (result);
} //rolls a d100
})
client.login('<Discord bot token>'); //Bot token so it can login to Discord
The issue I have is when I send '!rolld100', the bot answers as if I sent '!rolld10' and '!rolld100' at the same time since 10 is in 100.
Any possible fixes? I'm also new to javascript so if you could explain what your solution does it would help me a lot.
The code seems to be a little complicated with duplicated code. You can simplify this down to a few lines of code by using a regular expression
const Discord = require('discord.js');
const client = new Discord.Client();
client.on ('message', message => {
const rollMatch = message.match(/roll(\d+)\s/)
if (rollMatch) {
const sides = Number(rollMatch)
var result = Math.floor(Math.random() * sides + 1);
message.channel.sendMessage (result);
}
})
client.login('<Discord bot token>'); //Bot token so it can login to Discord
Now if you want to do it your way. You basically would need to do
if(commandIs("rolld100", message)){ }
else if(commandIs("rolld10", message)){ }
else if(commandIs("rolld20", message)){ }
else if(commandIs("rolld6", message)){ }