is there a way to use the cache to keep something from .json not being repeated?
for example: in .json there are 5 messages
[
"hi"
"hello"
"hiii"
"test"
"OK"
]
I wanted it to start repeating only when the 5 options were already used
const Discord = require('discord.js');
const textest= require('../test.json')
exports.run = async (client, message, args) => {
var rand = textest[Math.floor(Math.random() * textest.length)];
const embed = new Discord.MessageEmbed()
.setColor('RANDOM')
.setDescription(rand)
await message.channel.send(embed);
}
You can make a table, for example:
var words = [];
And then push every word that has been used into that table.
An example of this would be:
const Discord = require('discord.js');
const textest= require('../test.json');
var words = [];
exports.run = async (client, message, args) => {
var rand = textest[Math.floor(Math.random() * textest.length)];
if (words.length >= textest.length) words = [];
if (words.length === (textest.length - 1)) words = [];
if (words.length > 0 && words.includes(rand)) rand = textest[Math.floor(Math.random() * textest.length)];
const embed = new Discord.MessageEmbed()
.setColor('RANDOM')
.setDescription(rand)
await message.channel.send(embed);
}
Related
I wrote the following code in Node.js:
const axios = require("axios");
const prompt = require("prompt-sync")();
let numRepo = prompt("Welcome, How many repositories to search? ");
numRepo = parseInt(numRepo);
while (!Number.isInteger(numRepo))
numRepo = parseInt(prompt("Please insert integer: "));
let n;
if (numRepo < 100) n = 1;
else n = numRepo % 100;
axios
.get(
`https://api.github.com/search/repositories?q=language:js&sort=stars&order=desc&per_page=${numRepo}&page=${n}`
)
.then((response) => {
let repo = [];
response.data.items.forEach((e) => repo.push(e));
console.log(repo);
})
.catch((error) => {
console.log(error);
});
I used the GitHub Search APi, and my goal is to write a function whose purpose is to check for each repository how much unused packaged it has.
How can this be done?
I dont know why but i followed the guide in discord.js about awaiting reactions but it seems it doesnt work on mine. I dont know why. Whenever i hit the emoji it doesnt collect it. I pretty much goes to every answered question here in stackoverflow but i still cannot fix it.
const { Client, Message, MessageEmbed } = require("discord.js");
module.exports = {
name: "error",
/**
* #param {Client} client
* #param {Message} message
* #param {String[]} args
*/
run: async (client, message, args) => {
message.delete({ timeout:2000 })
var randstr = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5);
var randnum = Math.floor(Math.random() * 100);
var comb = randstr + randnum;
var sayEmbed = new MessageEmbed()
.setTitle('Console Error #'+ '`' + comb + '`' + ' sent by ' + message.member.user.tag)
.setDescription('```' + args.join(" ") + '```')
.setTimestamp()
.setColor("BLACK")
.setTimestamp()
.setFooter("Copyright ©️ 2022, Mythic Realms, or its associates. All Rights Reserved.")
message.channel.send({embed: sayEmbed}).then(embedMessage => {
embedMessage.react('✅');
})
const filter = (reaction, user) => reaction.emoji.name === '✅' && user.id === message.author.id;
const collector = message.createReactionCollector(filter, { max: 1, time: 5 * 60 * 1000 });
collector.on('collect', () => {
message.clearReactions();
console.log('SUCCESS');
});
},
};
Please help with this bot :< thank you.
You're creating a message collector at message whereas the reaction itself is at embedMessage.
embedMessage.createReactionCollector would be the correct.
Plus, said embedMessage is within the scope of the message.send().then()
You can either assign the return value of the message.send() promise to embedMessage on the same level so it is accessible by the collector or set the collector inside the then() function from message.send()
const embedMessage = await message.send(...);
const collector = embedMessage.createReactionCollector(...);
or
message.send(...).then(embedMessage => {
const collector = embedMessage.createReactionCollector(...);
});
I'm using javascript and discord.js v12 n trying to make !inactive cmd, which get's the most inactive members from my server and then mute them. When I try to console.log(member) it says 'undefined' please help.
Code:
module.exports = {
name: "inactive",
description: "no",
async execute(message, args, command, client, Discord) {
if (!message.member.roles.cache.find(r => r.name === "Isäntä")) return message.channel.send("No perms")
let userit = new Map()
let time = ['21600000', '10800000', '7200000', '3600000', '14400000', '18000000']; //1-6h
let muterole = message.guild.roles.cache.find(r => r.name === 'Muted') //mute role
message.guild.members.cache.forEach(member => {
if(member.roles.highest != message.guild.roles.cache.get("706922406257754132")) return;
userit.set(member.id, member)
});
if(userit.size == 0) return message.channel.send("None of users met requirements")
const inactiveOnes = new Map()
userit.forEach(member => {
if (!member.lastMessage) return inactiveOnes.set(member.id, member)
if (member.lastMessage.createdTimestamp <= Date.now() - 1209600000) return;
inactiveOnes.set(member.id, member)
});
if(inactiveOnes.size == 0) return message.channel.send("None of users met requirements")
let random = Math.floor(Math.random() * 4)+1
let random_time = time[Math.floor(Math.random() * time.length)]
for(let i = 0; i < random; i++ ){
const keys = inactiveOnes.keys();
let random2 = Math.floor(Math.random() * keys)
const member = keys[random2];
console.log(member)
console.log(keys)
// member.roles.add(muterole.id)
message.channel.send(`${member} you have been muted for being inactive! (Time: ${random_time}ms)`)
setTimeout(() => {
// member.roles.remove(muterole.id)
message.channel.send(`${member} you have been unmuted!`)
}, random_time)
}
}
}
You missed a .length in the bottom for loop.
const keys = inactiveOnes.keys();
let random2 = Math.floor(Math.random() * keys.length);
const member = keys[random2];
console.log(member) console.log(keys)
Without .length, random2 is set to NaN, causing the problem.
As theusaf mentioned, you missed a .length when getting a random number.
const random2 = Math.floor(Math.random() * keys.length);
However, even if you get a number, member will still be undefined. This is because inactiveOnes.keys() doesn't return an array, it returns a MapIterator. If you'd like to use array functionality, you could do one of two things.
// 1:
const keys = inactiveOnes.keyArray();
// 2:
const keys = [...inactiveOnes.keys()];
I made a little command that makes it so if someone, for example, inputs &scramble apple, bot would send "The word is: paple". It works as intended but the current issue is that if someone sends "Apple" instead of "apple", the bot just crashes saying that it can't get the author of undefined
module.exports = {
name: 'scramble',
execute(message, args) {
const Discord = require('discord.js')
let givenword = args.slice(0).join(" ");
function scramble(givenword) {
var word = givenword.split("")
n = word.length
for(var i = n - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i+1));
var tmp = word[i];
word[i] = word[j]
word[j] = tmp;
}
return word.join("")
}
scrambledword = scramble(givenword)
const embed = new Discord.MessageEmbed()
.setTitle('Scramble time!')
.setColor("RANDOM")
.setDescription("The word is: " + scrambledword)
.setFooter('You have 30 seconds to try and guess it, the first person to answer correctly ')
message.channel.send({embed});
message.delete()
const filter = m => m.content.includes(givenword);
const collector = message.channel.createMessageCollector(filter, { time: 30000 });
collector.on('collect', m => {
console.log(`Collected ${m.content}`);
});
collector.on('end', collected => {
message.channel.send(`${collected.first().author} got the correct answer first! The answer was ${givenword}`);
console.log(`Collected ${collected.size} items`);
});
}
}
Can anyone give me a hand with this?
There are 2 errors there:
You need to handle case mis-match. I would suggest, before scrambling the word, making it lowercase and also making responses lower case before evaluating them.
var word= givenword.toLowercase().split("")
const filter = m => m.content.toLowercase().includes(give word)
You need to handle the case where no correct guesses are made. collected.first() is undefined because there are no winners. I would recommend checking for winners before printing the winner.
if (collected.length <= 0) {
// send no winner message
} else {
// send the winner message
}
I've been coding a Poll Command for my Discord Bot. It is in Discord.JS but when I am going to run the command, it does this error:
I've been trying to fix this issue for a while and it still does this issue. I've changed some lines of code, particularly line 65 and line 70-80.
Code:
const options = [
'🇦',
'🇧',
'🇨',
'🇩',
'🇪',
'🇫',
'🇬',
'🇭',
'🇮',
'🇯',
'🇰',
'🇱',
'🇲',
'🇳',
'🇴',
'🇵',
'🇶',
'🇷',
'🇸',
'🇹',
'🇺',
'🇻',
'🇼',
'🇽',
'🇾',
'🇿',
];
const pollLog = {};
function canSendPoll(user_id) {
if (pollLog[user_id]) {
const timeSince = Date.now() - pollLog[user_id].lastPoll;
if (timeSince < 1) {
return false;
}
}
return true;
}
exports.run = async (client, message, args, level, Discord) => {
if (args) {
if (!canSendPoll(message.author.id)) {
return message
.channel
.send(`${message.author} please wait before sending another poll.`);
} else if (args.length === 1) { // yes no unsure question
const question = args[0];
pollLog[message.author.id] = {
lastPoll: Date.now()
};
return message
.channel
.send(`${message.author} asks: ${question}`)
.then(async (pollMessage) => {
await pollMessage.react('👍');
await pollMessage.react('👎');
await pollMessage.react(message.guild.emojis.get('475747395754393622'));
});
} else { // multiple choice
args = args.map(a => a.replace(/"/g, ''));
const question = args[0];
const questionOptions = message.content.match(/"(.+?)"/g);
if (questionOptions.length > 20) {
return message.channel.send(`${message.author} Polls are limited to 20 options.`);
} else {
pollLog[message.author.id] = {
lastPoll: Date.now()
};
return message
.channel
.send(`${message.author} asks: ${question}
${questionOptions
.map((option, i) => `${options[i]} - ${option}`).join('\n')}
`)
.then(async (pollMessage) => {
for (let i = 0; i < questionOptions.length; i++) {
await pollMessage.react(options[i]);
}
});
}
}
} else {
return message.channel.send(`**Poll |** ${message.author} invalid Poll! Question and options should be wrapped in double quotes.`);
}
}
The reason some of the question is listed as choices is because you define question as args[0], which is simply the first word given. You can solve this by looping through the arguments and adding those that don't appear to be a choice into the question. See the sample code below.
const args = message.content.trim().split(/ +/g);
// Defining the question...
let question = [];
for (let i = 1; i < args.length; i++) {
if (args[i].startsWith('"')) break;
else question.push(args[i]);
}
question = question.join(' ');
// Defining the choices...
const choices = [];
const regex = /(["'])((?:\\\1|\1\1|(?!\1).)*)\1/g;
let match;
while (match = regex.exec(args.join(' '))) choices.push(match[2]);
// Creating and sending embed...
let content = [];
for (let i = 0; i < choices.length; i++) content.push(`${options[i]} ${choices[i]}`);
content = content.join('\n');
var embed = new Discord.RichEmbed()
.setColor('#8CD7FF')
.setTitle(`**${question}**`)
.setDescription(content);
message.channel.send(`:bar_chart: ${message.author} started a poll.`, embed)
.then(async m => {
for (let i = 0; i < choices.length; i++) await m.react(options[i]);
});
The Regex used is from this answer (explanation included). It removes the surrounding quotation marks, allows escaped quotes, and more, but requires a solution like this to access the desired capturing group.
Note that you'll still have to check whether there's a question and if choices exist, and display any errors as you wish.