I've created my own discord bot for my server and i want to answer me if i say specific words who are in array tabHello :
var tabHello = ['Bonjour','Salut','Hello', 'Guten tag', 'Buenos Dias'];
var tabAnsw= ['Bonjour votre majesté.','Salutations jeune Douzien !','Ouais, ouais. T\'es qui déjà ?', 'Bonjour ' + message.author + ', comment vas-tu aujourd\'hui ?'];
if (message.content.indexOf('Hello') > 0 && message.isMentioned(client.user)){
var row = Math.floor(Math.random() * tabAnsw.length);
message.channel.sendMessage(tabAnsw[row]);
}
With this code, if i say "#bot Hello" he answers one value of tabAnsw array. But I want to answer me if i say one value of tabHello array.
And, if say "Hello #bot", he doesn't answer me.
Someone can help me ?
Sorry for my english :s
You could always just use a for loop.
var tabHello = ['Bonjour','Salut','Hello', 'Guten tag', 'Buenos Dias'];
var tabAnsw = ['Bonjour votre majesté.','Salutations jeune Douzien !','Ouais, ouais. T\'es qui déjà ?', 'Bonjour ' + message.author + ', comment vas-tu aujourd\'hui ?'];
var content = message.content.split(' ');
for(var x = 0; x < content.length; x++){
if(tabHello.includes(content[x]) && message.isMentioned(client.user)){
var row = Math.floor(Math.random() * tabAnsw.length);
message.channel.send(tabAnsw[row]);
}
}
This should do the trick
var tabHello = ['Bonjour','Salut','Hello', 'Guten tag', 'Buenos Dias'];
var tabAnsw= ['Bonjour votre majesté.','Salutations jeune Douzien !','Ouais, ouais. T\'es qui déjà ?', 'Bonjour ' + message.author + ', comment vas-tu aujourd\'hui ?'];
if (tabHello.indexOf(message.content) > -1 && message.isMentioned(client.user)){
var row = Math.floor(Math.random() * tabAnsw.length);
message.channel.sendMessage(tabAnsw[row]);
}
So instead of checking the message for the world hello, this checks if the message is contained within the Array.
I went and made this for you, it works with Eris I tried to convert it to discord.js, it should work but not 100% sure that it will.
var tabHello = ['bonjour', 'salut', 'hello', 'guten tag', 'buenos dias'];
var tabAnsw = ['Bonjour votre majesté.', 'Salutations jeune Douzien !', 'Ouais, ouais. T\'es qui déjà ?', 'Bonjour ' + message.author.username + ', comment vas-tu aujourd\'hui ?'];
for (i = 0; i < tabAnsw.length; i++) {
if (message.content.startsWith(client.user.mention) && message.content.toLowerCase().indexOf(tabHello[i])) {
var row = Math.floor(Math.random() * tabAnsw.length);
message.channel.sendMessage(tabAnsw[row]);
break;
}
}
I went and converted all content of tabHello to lowercase versions so later you can ignore your user's casing, for example, if John#1234 was to enter '#Bot HeLlO' it would still work because we are ignoring casing.
I have set up this small script so you can build your bot on top of this:
index.js:
const Discord = require('discord.js');
const client = new Discord.Client();
const config = require('./config.json');
const commands = require('./commands');
const prefix = config.prefix;
const commandExecuter = new commands();
client.on("ready", () => {
client.user.setGame('Minecraft');
var servers = client.guilds.array().map(g => g.name).join('.');
console.log('Bot started');
});
client.on('message', message => {
//Check if its a command
isBotCommand(message.content, (command) => {
//If it is, lets execute it if we can
if ( command ) {
commandExecuter.execute(message, client, command);
}
});
});
const isBotCommand = (message, callback) => {
//Get the first char of the message
let firstChar = message.charAt(0);
//If it does not equal our prefix answer that it's not a bot command
if (firstChar !== prefix) return callback(false)
//We got here, so it seems to be a command
return callback(message.substring(1));
}
client.login(config.token);
add a file "commands.js" to your root directory and paste the following:
const botCommandExecuter = function() {}
const findCommandFromStack = (command, callback) => {
//Find the command in the commands array
commands.some((iteratedCommand) => {
//If our keyword is inside the currently iterated command object we have a match
if ( iteratedCommand.keywords.indexOf(command) > -1 ) {
//Call the callback and break the loop
callback(iteratedCommand.action);
return true;
}
});
}
botCommandExecuter.prototype.execute = (messageInstance, client, command) => {
//Find the command
findCommandFromStack(command, (commandToExecute) => {
//Execute the command we found
commandToExecute(messageInstance, client);
});
}
//List of commands
const commands = [
{
keywords: ['Bonjour','Salut','Hello', 'Guten tag', 'Buenos Dias'],
action: (message, client) => {
var tabAnsw = ['Bonjour votre majesté.','Salutations jeune Douzien !','Ouais, ouais. T\'es qui déjà ?', 'Bonjour ' + message.author + ', comment vas-tu aujourd\'hui ?'];
var row = Math.floor(Math.random() * tabAnsw.length);
message.channel.sendMessage(tabAnsw[row]);
}
}
];
module.exports = botCommandExecuter;
There is still a lot of room for improvement and error handling, but I'll leave that up to you. Goodluck!
Related
I am very new to Javascript so please bear with me! When I try to execute my script it doesnt respond! It just keeps dropping on to the next line waiting for me to write node index.js AGAIN. I have posted 2 images in the Imgur album, the first one is me writing node index.js and the second is me pressing enter and the response. Literally blank.
I would like some help as I feel like this is the last step to get my bot up and running! :D.
https://imgur.com/a/bRFFKKf
Here is my index.js
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const {token} = require('./token.json');
var jsonconfig = require("./config.json")
var jsonconfig,DISCORD_ID
var CMDS = jsonconfig.CMDS
var prefix = 'p!'
client.on("message", message => {
var args = message.content.split(" ")
args.forEach((a, b) => {
args[b] = a.replace("`", "")
args[b] = args[b].replace(".", "")
args[b] = args[b].replace("`", "")
args[b] = args[b].replace(`"`, "")
args[b] = args[b].replace(`'`, "")
})
var args = message.content.split(" ")
if (message.author.bot == false) {
if (message.content.startsWith("$")) {
if (message.channel.id != CMDS && message.author.id != DISCORD_ID) {
message.reply("stop using cmds here idiot. <#" + CMDS + ">")
return;
}
}
args.forEach((a, b) => {
args[b] = a.replace("`", "")
args[b] = args[b].replace(".", "")
args[b] = args[b].replace("`", "")
args[b] = args[b].replace(`"`, "")
args[b] = args[b].replace(`'`, "")
})
switch (args[0]) {
case prefix + "pois":
var id = parseInt(args[1])
if (id) {
fetch(`https://www.rolimons.com/uaid/` + id).then(res => res.text()).then(res => {
//// clog(res)
if (res != 'Uaid not found, try again later') {
var search = res,
first = 'uaid_details'
var second = `owner_list`;
var itemdat = JSON.parse(search.substring(search.indexOf(first) + first.length, search.indexOf(second)).replace(";", "").replace("=", "").replace("var", ''))
// clog(itemdat)
var search = res,
first = 'item_details'
var second = `uaid_details`;
var itemname = JSON.parse(search.substring(search.indexOf(first) + first.length, search.indexOf(second)).replace(";", "").replace("=", "").replace("var", ''))
var search = res,
first = 'owner_list'
var second = `lucky_cat_uaid`;
var owners = JSON.parse(search.substring(search.indexOf(first) + first.length, search.indexOf(second)).replace(";", "").replace("=", "").replace("var", ''))
message.reply(`Checking be patient bozo...`)
var em = new discord.messageEmbed()
.setFooter("Archs")
.setURL("https://www.rolimons.com/item/" + args[1])
.setColor("#ffc0cb")
.setThumbnail("https://www.roblox.com/thumbs/asset.ashx?width=420&height=420&assetid=" + itemdat["asset_id"])
.setTitle(`UAID ` + args[1])
.setURL(`https://www.rolimons.com/uaid/` + args[1])
.setAuthor(itemname.name, `https://www.roblox.com/thumbs/asset.ashx?width=420&height=420&assetid=` + itemdat["asset_id"])
if (itemdat.serial) {
em.addField('SERIAL', itemdat.serial)
}
em.addField('OWNER', (itemdat.owner_name || `Hidden/Deleted`))
em.addField(`Last Traded`, itemdat["updated_relative_string"])
message.reply(em)
if (itemdat["updated_relative_string"].search(`month`) != -1 || itemdat["updated_relative_string"].search(`year`) != -1) {
message.channel.send(`Since the current owner has had it for more than a month, we have deemed this uaid(${args[1]}) as CLEAN :white_check_mark:`)
} else {
comped_detected = false
Object.keys(owners).forEach(x => {
var item = owners[x][0]
if (item && parseInt(x) + 2628000 >= Date.now() / 1000) {
fetch(`https://avatar.roblox.com/v1/users/${item}/avatar`).then(res => res.json().catch(err => { })).then(avatar => {
avatar.assets.forEach(a => {
if (badassets[a.id] != undefined) {
comped_detected = true
}
})
fetch("https://inventory.roblox.com/v1/users/" + item + "/assets/collectibles?sortOrder=Asc&limit=100").then(res => res.json().catch(err => { })).then(p => {
// clog(p)
var amt = 0
if (p.data) {
p.data.forEach(l => {
amt = amt + itemdata[l.assetId][4]
})
if (amt < 5000) {
comped_detected = true
}
}
})
})
}
})
}
}
}
)}
}
}
client
.login(token)
.catch(consola.error)
});
Again sorry if this sounds very dumb, I just started Javascript (node). Oh and one more thing! I am trying for it to work on discord with a discord command. Thanks for any help.
First off, if you're using intents, I assume you're using discord.js v13. The client.on("message" in that case would be client.on("messageCreate".
You don't need to input node index.js in repl.it. Instead, go to the 3 dots on your file like below and click on "Show Hidden Files". Once you see the .replit file, go into it and write on the first line: run = "npm start". Then, go into package.json (not package-lock.json) and write the code on the other screenshot (I highlighted the code so it's easier for you to read). That should fix all your problems! If you need additional reference, I have pasted some very helpful YouTube tutorials that I definitely recommend to watch.
Tutorial - Command handler and help command
Tutorial - How to use Discord.js v13 in repl.it
Your code seems to be in the form:
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const {token} = require('./token.json');
var jsonconfig = require("./config.json")
var jsonconfig,DISCORD_ID
var CMDS = jsonconfig.CMDS
var prefix = 'p!'
client.on("message", message => {
// stuff
})
so basically it seems to attach some kind of listener, and then reaches the end. So it does nothing...
I'm trying to code a fighting discord bot game but I ran into troubles lately!
Everything works with reactions.
So basically what i want to do is : roll a dice to determine the one who starts. The winner rolls 2 dices to determine the damages he will do and then its player 2's turn.
Until here, everything works.
What i would like it to do is loop this last part when the first player rolls the 2 dices to inflict damages.
I tried placing while loops userhealth<=0 here and there, but it never works.
I know it has to do with promises and stuff like that, but Im still lost.
A little help would be appreciated!
Here is the code:
const { ReactionCollector } = require('discord.js');
function rolldice(numero){
return Math.floor(Math.random() * numero + 1);
}
function premier(msg,user){
diceroll1 = rolldice(20)
diceroll2 = rolldice(20)
msg.channel.send(`${msg.author.tag} a eu : ${diceroll1} \n\n ${user.tag} a eu : ${diceroll2}`)
if(diceroll1 > diceroll2){
msg.channel.send(`${msg.author.tag} gagne`)
return msg.author.id
}
else if(diceroll1 < diceroll2){
msg.channel.send(`${user.tag} gagne`)
return user.id
}
else{
msg.channel.send(`Vous avez fait égalité. On recommence le tirage.`)
premier(msg,user)
}
}
function attaque1(msg, user){
damagedice1 = rolldice(6)
damagedice2 = rolldice(6)
somme = damagedice1 + damagedice2
return {somme,damagedice1,damagedice2}
}
function bagarre(msg,user,winner,user1health,user2health,fighter1,fighter2){
if(winner === msg.author.id){
msg.channel.send(`Joueur 1 Clique sur 🎲 pour determiner les dégats que tu vas infliger.`).then((riposte) => {
riposte.react('🎲')
var atksmme = attaque1(msg,user)
const filter1 = (reaction, user) => {
return ['🎲'].includes(reaction.emoji.name) && user.id === fighter1;
};
const collector1 = riposte.createReactionCollector(filter1,{
max: 1
});
collector1.on('collect',(collected,reason) => {
user2health = user2health - atksmme.somme
msg.channel.send(`${msg.author.tag} inflige ${atksmme.somme} de dégâts à ${user.tag}! (${atksmme.damagedice1} + ${atksmme.damagedice2})`)
msg.channel.send(`Il reste ${user2health} points de vie à ${user.tag}`)
if(user2health<=0) return msg.channel.send('Vous avez perdu')
collector1.stop()
msg.channel.send(`Joueur 2 Clique sur 🎲 pour determiner les dégats que tu vas infliger.`).then((riposte1) => {
riposte1.react('🎲')
var atk2smme = attaque1(msg,user)
const filter2 = (reaction, user) => {
return ['🎲'].includes(reaction.emoji.name) && user.id === fighter2;
};
const collector2 = riposte1.createReactionCollector(filter2,{
max: 1
});
collector2.on('collect',(collected,reason) => {
user1health = user1health - atk2smme.somme
msg.channel.send(`${user.tag} inflige ${atk2smme.somme} de dégâts à ${msg.author.tag}! (${atk2smme.damagedice1} + ${atk2smme.damagedice2})`)
msg.channel.send(`Il reste ${user1health} points de vie à ${msg.author.tag}`)
if(user1health<=0) return msg.channel.send('Vous avez perdu')
collector2.stop()
})
})
})
})
}
else if(winner === user.id){
var atksmme = attaque1(msg,user)
user1health = user1health - atksmme.somme
msg.channel.send(`${user.tag} inflige ${atksmme.somme} de dégâts à ${msg.author.tag}! (${atksmme.damagedice1} + ${atksmme.damagedice2})`)
msg.channel.send(`Il reste ${user1health} points de vie à ${msg.author.tag}`)
}
}
module.exports = {
name: 'fight',
args : true,
usage : '#<user>',
async execute(msg,args) {
//VARIABLES
const { client } = msg;
var diceroll1;
var diceroll2;
var damagedice1;
var damagedice2;
var user1health = 12;
var user2health = 12;
var winner;
//checks if the username to fight is in the msg
var author1 = msg.author.username;
var user = msg.mentions.users.first();
if(!user) return msg.reply("you did not specify who you would like to fight!");
//checks if the users is trying to fight themselves
if(user.id == msg.author.id) return msg.reply('you cannot fight yourself!');
//checks if the user is trying to fight the bot
if(user.bot == true)
return msg.reply('you cannot fight a bot!');
//saves the two user ids to variables
var fighter1 = msg.author.id;
var fighter2 = user.id;
var challenged = user.toString();
msg.channel.send(`${challenged}, tu veux te battre?`).then((bataille) => {
bataille.react('🎲')
const filter = (reaction, user) => {
return ['🎲'].includes(reaction.emoji.name) && user.id === fighter2;
};
const collector = bataille.createReactionCollector(filter,{
max: 1
});
collector.on('collect',(collected,reason) => {
winner = premier(msg,user)
bagarre(msg,user,winner,user1health,user2health,fighter1,fighter2)
})
})
}}
Okay, there's a lot of weird things about this.
First of all, there are a lot of unused variables. Please use a proper IDE like Visual Studio Code that informs you about these things.
Second, you should be using await instead of then in most cases. (dont just replace then with await - see javascript async tutorials for good examples)
Third, this is just all a mess. You will have to divide your code into more functions: Create a function to initiate an attack from one user to another. That code should be usable for both player 1 and 2 so that no code is copypasted for both players. Then you can just call that function after one player has made their turn to start the next turn for the other player.
I have the following script that takes the inputs on Google Forms, makes a document with those inputs, and sends an e-mail with the document attached. It works properly, but I needed to filter some of the responses, but I don't know how to filter data in an event.
One of the questions on the forms is asking what kind of document people want:
Right now, I have only done the script for the 2nd option (Licença Especial em Pecúnia). I need to filter the data from the forms, so when I choose the 1st option (Substituição de Chefia) it generates a different document from a different template. Right now, the function afterSubmit(e) is triggered on form submit.
Excuse the portuguese names of vars and consts, the important ones for this questions I changed to english.
function afterSubmit(e) {
const info = e.namedValues;
const pdfFileLP = createPDFLP(info);
const url = e.namedValues['Anexos ao ofício'][0];
function getIdFromUrl(url) {return url.match(/[-\w]{25,}$/);};
var idAnexo = getIdFromUrl(url);
const nrof = e.namedValues['Numeração do ofício'][0];
function pdfAnexado(idAnexo,nrof) {return DriveApp.getFileById(idAnexo).setName("Anexos do ofício of. " + nrof + "-PGE/PRF.pdf");};
var pdfAnexo = pdfAnexado(idAnexo);
eprotocolo(e.namedValues['Expresso do solicitante'][0],nrof,pdfFileLP,pdfAnexo);
}
function eprotocolo(email,ofi,pdfFileLP,pdfAnexo){
var EmailTemp = HtmlService.createTemplateFromFile("mailLP");
EmailTemp.mail = email;
var htmlMessage = EmailTemp.evaluate().getContent();
GmailApp.sendEmail("estag.pedron#pge.pr.gov.br","Of. " + ofi + "-PGE/PRF",
"SEU EMAIL NÃO SUPORTA O FORMATO HTML, FAVOR RESPONDER ESTE E-MAIL PARA SOLUCIONAR O PROBLEMA OU ENTRAR EM CONTATO PELO TELEFONE (41)3281-6392.",{
from: "procuradoriafuncional#gmail.com", name: "Gerador de ofícios da PRF", htmlBody: htmlMessage,
replyTo: email, cc: email,
attachments: [pdfFileLP, pdfAnexo]
});
}
function createPDFLP(info) {
const pdfFolder = DriveApp.getFolderById("1mgNPhM9f2U0BWrDK0FAfCYyq968rJ3E8");
const tempFolder = DriveApp.getFolderById("1FfW3Jn9hHARpBU8t8szlQ2YwR9OPR1ZV");
const templateChefia = DriveApp.getFileById("1qP3A8O27Ms8OuybaqrQ6jQBB_PQpo-RhDU9xjIw_a44");
const templateLP = DriveApp.getFileById("1lRab5lPdbRcdl4gaI3zonFseE180cNu4-hWaovamerc");
const newTempFileLP = templateLP.makeCopy(tempFolder);
const openDocLP = DocumentApp.openById(newTempFileLP.getId());
const bodyLP = openDocLP.getBody();
bodyLP.replaceText("{of}", info['Numeração do ofício'][0]);
bodyLP.replaceText("{data}", info['Data do ofício'][0]);
bodyLP.replaceText("{serv}", info['Nome completo'][0]);
bodyLP.replaceText("{rg}", info['Número do RG'][0]);
bodyLP.replaceText("{autos}", info['Numero dos autos'][0]);
bodyLP.replaceText("{prazo}", info['Prazo'][0]);
bodyLP.replaceText("{procurador}", info['Procurador solicitante'][0]);
bodyLP.replaceText("{orgao}", info['GRHS de destino'][0]);
openDocLP.saveAndClose();
const blobPDFLP = newTempFileLP.getAs(MimeType.PDF);
const pdfFileLP = pdfFolder.createFile(blobPDFLP).setName("Of. " + info['Numeração do ofício'][0] + "-PGE/PRF.pdf");
tempFolder.removeFile(newTempFileLP);
return pdfFileLP;}
If anyone was curious, I did a simple if statement at the end:
function createPDFLP(info) {
const pdfFolder = DriveApp.getFolderById("1mgNPhM9f2U0BWrDK0FAfCYyq968rJ3E8");
const tempFolder = DriveApp.getFolderById("1FfW3Jn9hHARpBU8t8szlQ2YwR9OPR1ZV");
const templateChefia = DriveApp.getFileById("1qP3A8O27Ms8OuybaqrQ6jQBB_PQpo-RhDU9xjIw_a44");
const templateLP = DriveApp.getFileById("1lRab5lPdbRcdl4gaI3zonFseE180cNu4-hWaovamerc");
const tipo = info['Tipo de ofício'][0];
if(tipo == "Licença Especial em Pecúnia"){
const newTempFileLP = templateLP.makeCopy(tempFolder);
const openDocLP = DocumentApp.openById(newTempFileLP.getId());
const bodyLP = openDocLP.getBody();
bodyLP.replaceText("{of}", info['Numeração do ofício'][0]);
bodyLP.replaceText("{data}", info['Data do ofício'][0]);
bodyLP.replaceText("{serv}", info['Nome completo'][0]);
bodyLP.replaceText("{rg}", info['Número do RG'][0]);
bodyLP.replaceText("{autos}", info['Numero dos autos'][0]);
bodyLP.replaceText("{prazo}", info['Prazo'][0]);
bodyLP.replaceText("{procurador}", info['Procurador solicitante'][0]);
bodyLP.replaceText("{orgao}", info['GRHS de destino'][0]);
openDocLP.saveAndClose();
const blobPDFLP = newTempFileLP.getAs(MimeType.PDF);
const pdfFileLP = pdfFolder.createFile(blobPDFLP).setName("Of. " + info['Numeração do ofício'][0] + "-PGE/PRF.pdf");
tempFolder.removeFile(newTempFileLP);
return pdfFileLP;
} else if (tipo == "Substituição de Chefia") {
const newTempFileSC = templateChefia.makeCopy(tempFolder);
const openDocSC = DocumentApp.openById(newTempFileSC.getId());
const bodySC = openDocSC.getBody();
bodySC.replaceText("{of}", info['Numeração do ofício'][0]);
bodySC.replaceText("{data}", info['Data do ofício'][0]);
bodySC.replaceText("{servi}", info['Nome completo'][0]);
bodySC.replaceText("{rg}", info['Número do RG'][0]);
bodySC.replaceText("{autos}", info['Numero dos autos'][0]);
bodySC.replaceText("{prazo}", info['Prazo'][0]);
bodySC.replaceText("{procurador}", info['Procurador solicitante'][0]);
bodySC.replaceText("{orgao}", info['GRHS de destino'][0]);
bodySC.replaceText("{periodo}", info['Período que o autor alega que ocupou cargo de chefia'][0]);
openDocSC.saveAndClose();
const blobPDFSC = newTempFileSC.getAs(MimeType.PDF);
const pdfFileLP = pdfFolder.createFile(blobPDFSC).setName("Of. " + info['Numeração do ofício'][0] + "-PGE/PRF.pdf");
tempFolder.removeFile(newTempFileSC);
return pdfFileLP;
}
}
So already hello to all & especially to those who will take the trouble to help me, I have a project to verify the user thanks to a hash decryption challenge system (base64) & that when they are successful its giving them a role to check, I did a good part of it but its not right I don't understand my mistake! the bot connects, 0 code errors, but the verification does not work I would like the verification to be done in the channel & not in the DM! thank you
const Discord = require('discord.js')
const client = new Discord.Client();
const prefix = "&";
let rawdata = fs.readFileSync('config.json');
let object = JSON.parse(rawdata);
var channel_id = object['verification_channelID']
var guild_id = object['guild_ID']
var role_name = object['verification_role_name']
var server_invite = object['server_invite']
var token = object['bot_token']
var questions = object['questions']
var dict = {};
var encodingQuestions = []
questions.forEach(element => {
encodingQuestions.push(element)
});
client.on('ready', function(){
console.log("Login : " + client.user.tag);
})
client.on('guildMemberAdd', member => {
var uname = member.user.username
var disc = member.user.discriminator
var memberID = member.user.id
var rand = Math.random();
rand *= encodingQuestions.length;
rand = Math.floor(rand);
var question = encodingQuestions[rand]
dict[uname] = [Buffer.from(question, 'base64').toString('utf-8'), 3];
const embed = new Discord.MessageEmbed()
.setTitle(uname + "#" + disc)
.setColor(0x1e90ff)
.addField(uname='Welcome', value='Welcome <#' + memberID + '> Déchiffrer le code , vous avez 3 essais ! Utilisez ``&answer {decoded message}`` ', inline=false)
.addField(uname='Question', value=question, inline=false)
member.send(embed)
member.guild.channels.cache.get(channel_id).send("Welcome <#" + memberID + "> Regarder vos DM pour accédez au serveur !")
});
client.on('message', message => {
var memberid = message.author.id;
var memberuname = message.author.username;
var messagecontent = message.content;
var messageID = message.id;
var disc = message.author.discriminator;
if (!message.content.startsWith(prefix)) return;
if (message.content.startsWith(prefix + 'answer') && message.channel.type === "dm"){
var msg = message.toString().replace('&answer ', '')
for (var key in dict){
if (key == message.author.username){
if (msg == dict[key][0]){
message.channel.send("Vous avez passer le test !")
var role = client.guilds.cache.get(guild_id).roles.cache.find(role => role.name === role_name)
client.guilds.cache.get(guild_id).members.cache.get(message.author.id).roles.add(role);
var memberID = message.author.id
client.channels.cache.get(channel_id).send("Trés bien <#" + memberID + "> vous avez réussis le test avec succèes !")
delete dict[key];
} else{
dict[key][1] = dict[key][1] - 1
if (dict[key][1] == 0){
memberID = message.author.id
message.channel.send("Vous avez pas réussis le test vous allez êtres exclus ! Revenir sur Paradox : " + server_invite)
client.channels.cache.get(channel_id).send("<#" + memberID + "> Vous avez échoué le test...")
setTimeout(function(){
client.guilds.cache.get(guild_id).members.cache.get(message.author.id).kick()
}, 5000)
} else{
message.channel.send("Réessayer !")
}
}
}
}
}
})
client.login(token);
The database config.json :
{
"bot_token": "TOKEN",
"verification_channelID": "",
"guild_ID": "",
"verification_role_name": "",
"server_invite": "",
"questions": ["eW91IHBhc3NlZA==", "dGhpcyB3YXMgZWFzeQ==", "dGhhbmtzIGZvciBqb2luaW5n", "ZW5qb3kgeW91ciBzdGF5", "dGhhbmtzIGZvciBub3QgYmVpbmcgYW5vbnltb3Vz", "ZW5qb3kgeW91ciBzdGF5", "aW52aXRlIHlvdXIgZnJpZW5kcyE="]
}
You should use:
client.on('guildMemberAdd', member => {
var uname = member.user.username
var disc = member.user.discriminator
var memberID = member.user.id
var rand = Math.random();
rand *= encodingQuestions.length;
rand = Math.floor(rand);
var question = encodingQuestions[rand]
dict[uname] = [Buffer.from(question, 'base64').toString('utf-8'), 3];
const embed = new Discord.MessageEmbed()
.setTitle(uname + "#" + disc)
.setColor(0x1e90ff)
.addField('Welcome', 'Welcome <#' + memberID + '> Déchiffrer le code , vous avez 3 essais ! Utilisez ``&answer {decoded message}`` ', false)
.addField('Question', question, false)
member.send(embed)
member.guild.channels.cache.get(channel_id).send("Welcome <#" + memberID + "> Regarder vos DM pour accédez au serveur !")
});
I updated the embed part, you should use .addField('coucou', 'salut', true);instead of .addField(name='coucou', value='name', inline=true). This is the javascript function parameters syntax.
when I execute this function it displays me the following error:
"JavaScript execution exceeded timeout" how I can solve this problem by using settimeout () or what?
I retrieve 3000 line from json file.
applyChanges_PhrasesTypes: function(employees, callback) {
//alert("fonction apply chamges est lancer PhrasesTypes");
this.db.transaction(
function(tx) {
var l = employees.length;
var sql =
"INSERT OR REPLACE INTO PhrasesTypes (IdPhrase, IdPhraseES, IdRubrique, IdTypeTravauxAffichage, Phrase, AidePhrase, AvertissementPhrase,OrdrePhrase,QuotationParDefaut,Published) " +
"VALUES (?,?,?,?,?,?,?,?,?,?)";
//alert('Inserting or Updating in local database: PhrasesTypes');
var e;
for (var i = 0; i < l; i++)
{
e = employees[i];
log(i);
//log("Ligne "+ i +" est inserer de id PhrasesTypes = "+e.IdPhrase);
var params = [e.IdPhrase, e.IdPhraseES, e.IdRubrique, e.IdTypeTravauxAffichage, e.Phrase, e.AidePhrase, e.AvertissementPhrase,e.OrdrePhrase,e.QuotationParDefaut,e.Published];
tx.executeSql(sql, params);
}
log('sync_PhrasesType shronization terminée avec (' + l + ' items sync_PhrasesTypeshronié)');
},
this.txErrorHandler_PhrasesTypes,
function(tx)
{
callback();
}
);
}
#lgor: here is my code but only 2000 insert line, and terminates with an error,
JavaScript execution exceeded timeout javascript
InsertPortion: function(tx)
{
var l = Math.min(gEmployees.length, gIter + 300);
log('aaaaaaaaaaaaaaaaaaaaaaaa---'+l)
for (; gIter<l ; gIter++)
{
log('do insert here');
var sql =
"INSERT OR REPLACE INTO PhrasesTypes (IdPhrase, IdPhraseES, IdRubrique, IdTypeTravauxAffichage, Phrase, AidePhrase, AvertissementPhrase,OrdrePhrase,QuotationParDefaut,Published) " +
"VALUES (?,?,?,?,?,?,?,?,?,?)";
//alert('Inserting or Updating in local database: PhrasesTypes');
var e;
e = gEmployees[gIter];
log(gIter);
//log("Ligne "+ i +" est inserer de id PhrasesTypes = "+e.IdPhrase);
var params = [e.IdPhrase, e.IdPhraseES, e.IdRubrique, e.IdTypeTravauxAffichage, e.Phrase, e.AidePhrase, e.AvertissementPhrase,e.OrdrePhrase,e.QuotationParDefaut,e.Published];
tx.executeSql(sql, params);
}
if (gIter < gEmployees.length)
{
log('sync_PhrasesType shronization terminée avec (' + gIter+ ' items sync_PhrasesTypeshronié)');
setTimeout(dao3.InsertPortion(tx), 100);
}
else
{
gEmployees = null;
gIter = 0;
}
},
applyChanges_PhrasesTypes: function(employees, callback) {
//alert("fonction apply chamges est lancer PhrasesTypes");
this.db.transaction(
function(tx)
{
gIter = 0;
gEmployees = employees;
dao3.InsertPortion(tx);
},
this.txErrorHandler_PhrasesTypes,
function(tx)
{
callback();
}
);
},
Consider converting the loops in your code to async calls.
Take a look at https://github.com/caolan/async