How to edit an Embed Author? - javascript

I want to edit the author of an embed sent by my bot.
The message is sent by this code :
task_chan.send('', {
embed: {
color: task_colors[0x808080],
title: 'Tache n°1',
thumbnail: {
url: 'https://...'
},
author: {
name: 'Tache à prendre',
icon_url: 'https://zupimages.net/up/20/12/xqsf.jpg'
},
fields:[{
name: "Tache à faire :",
value: "...",
},{
name: 'Avancement de la tache :',
value: 'Non commencée'
}]
}
})
To edit the message I've tried :
taken.embeds[0].author.icon_url = util.avatarURL
taken.embeds[0].author.name = util.username
taken.edit(new Discord.RichEmbed(taken.embeds[0]));
taken contain the message to edit and util an user.
And it only change the name…
I don't understand why but author.icon_url is undefined between these two code samples.
I hope you can help me :)

method channel.send return a promise, so you can use .then(msg=> to get a message object.
let testEmbed = {
color: task_colors[0x808080],
title: 'Tache n°1',
thumbnail: {
url: 'https://...'
},
author: {
name: 'Tache à prendre',
icon_url: 'https://zupimages.net/up/20/12/xqsf.jpg'
},
fields:[{
name: "Tache à faire :",
value: "...",
},{
name: 'Avancement de la tache :',
value: 'Non commencée'
}]
}
}
task_chan.send({embed:testEmbed}).then(msg => {
testEmbed.name = 'LOL'
testEmbed.iconURL = 'SOMEURL'
msg.edit({embed:testEmbed})
})
I would recommend that you use the built-in methods for creating embeds, in my opinion it is more convenient.

Related

Uncaught ReferenceError: test is not defined, calling onclick in codepen

What i want to achieve is to call generateDocx and generatePDF with two separate buttons, trying it some versions ago didn't give me any problems so i am a bit dumbfounded.
I tried to use
onclick
event listener
dummy function to see if maybe the position was the problem
I have this up on codepen, so it could be the website per se that gives me the problem, at this point i am really clueless
Codepen link
EDIT: if i remove "import * as converter from "https://cdn.skypack.dev/docx-pdf#0.0.1";" at least id downloads the docx
const { AlignmentType, Document, HeadingLevel, Packer, Paragraph, TabStopPosition, TabStopType, TextRun } = docx;
import * as converter from "https://cdn.skypack.dev/docx-pdf#0.0.1";
import * as underscore from "https://cdn.skypack.dev/underscore#1.13.6";
const test = {
id: "1",
informazioniBase: {
nome: "Lorenzo",
cognome: "Dombo",
label: "???",
img: "",
email: "lorenzoemail#l.com",
telefono: "+3932731444",
url: "https://urlpersonale.com",
riassunto: "Riassunto candidato",
luogo: {
indirizzo: "Via Criso laso 12",
codicePostale: "00133",
citta: "Roma",
provincia: "Roma",
codicePaese: "IT",
regione: "Lazio"
},
social: [{
network: "Twitter",
username: "user",
url: "https://twitter.com/user"
}]
},
lavoro: [{
attivo: true,
nomeAzienda: "Majormajor",
posizioneLavorativa: "Programmatore",
url: "https://azienda.com",
dataInizio: "11/12/2010",
dataFine: "dataDiFine",
descrizione: "Questa è una prova, utilizza dei doppi a capo come segnale per andare a capo, poiché tramite un JSON è difficile capire quando andare, però sono sicuro di poter automatizzare questo compito facilmente, QUESTO PROBLEMA E' STATO RISOLTO MA TENGO IL TESTO PER LA SUA LUNGHEZZA",
Riassunto: "riassunto"
}],
educazione: [{
attivo: false,
luogo: "università",
url: "https://università.com/",
area: "Informatica",
TipoLaurea: "Magistrale",
dataInizio: "9/10/2019",
dataFine: "9/10/2024",
voto: "110",
note: "Questa è una prova, utilizza degli a capo come segnale per \nappunto andare a capo, poiché tramite un JSON è difficile capire \nnquando andare, però sono sicuro di poter automatizzare \nquesto compito facilmente, QUESTO PROBLEMA E' STATO RISOLTO MA TENGO IL TESTO PER LA SUA LUNGHEZZA"
}],
certificati: [
{
certificante: "certificante",
certificato: "nome Certificato"
},
{
certificante: "certificante2",
certificato: "nome Certificato2"
}
],
skills: ["Angular", "Java", "Javascript?", "HTML"],
lingue: [
{
lingua: "Inglese",
livello: "C1",
},
{
lingua: "Italiano",
livello: "Madrelingua",
}
],
progetti: [{
nome: "progetto",
descrizione: "Questa è una prova, utilizza degli a capo come segnale per \nappunto andare a capo, poiché tramite un JSON è difficile capire \nnquando andare, però sono sicuro di poter automatizzare \nquesto compito facilmente, QUESTO PROBLEMA E' STATO RISOLTO MA TENGO IL TESTO PER LA SUA LUNGHEZZA",
riassunto: "riassunto",
paroleChiave: [
"HTML",
"CSS",
"JavaScript"
],
dataInizio: "data inizio",
dataFine: "data fine",
url: "https://progetto.com/",
ruolo: "ruolo",
tipo: "applicazione / sviluppo"
}]
};
class DocumentCreator {
create([lavoro, educazione, skills, certificati, lingue, progetti]) {
const document = new Document({
sections: [{
children: [
new Paragraph({
text: `${test.informazioniBase.nome} ${test.informazioniBase.cognome}`,
heading: HeadingLevel.TITLE,
}),
this.createContactInfo(test.informazioniBase.telefono, test.informazioniBase.url, test.informazioniBase.email, test.informazioniBase.luogo),
this.createHeading("Educazione"),
...educazione
.map((educazioneSingola) => {
const arr = [];
arr.push(
this.createInstitutionHeader(educazioneSingola.luogo,
this.createPositionDateText(educazioneSingola.dataInizio, educazioneSingola.dataFine, educazioneSingola.attivo)
),
);
arr.push(this.createRoleText(`${educazioneSingola.TipoLaurea} - ${educazioneSingola.voto}`));
arr.push(new Paragraph({ text: educazioneSingola.note }))
return arr;
})
.reduce((prev, curr) => prev.concat(curr), []),
this.createHeading("Esperienze Lavorative"),
...lavoro
.map((lavoroSingolo) => {
const arr = [];
arr.push(
this.createInstitutionHeader(
lavoroSingolo.nomeAzienda,
this.createPositionDateText(lavoroSingolo.dataInizio, lavoroSingolo.dataFine, lavoroSingolo.attivo),
),
);
arr.push(this.createRoleText(lavoroSingolo.posizioneLavorativa));
arr.push(new Paragraph({ text: lavoroSingolo.descrizione }))
return arr;
})
.reduce((prev, curr) => prev.concat(curr), []),
this.createHeading("Progetti"),
...progetti
.map((progettoSingolo) => {
const arr = [];
arr.push(
this.createInstitutionHeaderNoDate(progettoSingolo.nome),
);
arr.push(this.createRoleText(`${progettoSingolo.ruolo} - ${progettoSingolo.tipo}`));
const bulletPoints = this.splitParagraphIntoBullets(progettoSingolo.descrizione);
bulletPoints.forEach((bulletPoint) => {
arr.push(this.createBullet(bulletPoint));
});
arr.push(
this.createRoleTextUnderlined("Tecnologie Utilizzate")
);
arr.push(this.createSkillList(progettoSingolo.paroleChiave))
return arr;
})
.reduce((prev, curr) => prev.concat(curr), []),
this.createHeading("Skills,Certificati e Lingue"),
this.createSubHeading("Skills"),
this.createSkillList(skills),
this.createSubHeading("Certificati"),
...this.createAchivementsList(certificati),
this.createSubHeading("Lingue"),
...this.createLanguageList(lingue)
],
}],
});
return document;
}
createContactInfo(numerotelefono, url, email, luogo) {
return new Paragraph({
alignment: AlignmentType.CENTER,
children: [
new TextRun(`Telefono: ${numerotelefono} | LinkedIn: ${url} | Email: ${email}`),
new TextRun({
text: `${luogo.indirizzo}, ${luogo.citta}`,
break: 1,
}),
],
});
}
createHeading(text) {
return new Paragraph({
text: text,
heading: HeadingLevel.HEADING_1,
thematicBreak: true,
break: 1
});
}
createSubHeading(text) {
return new Paragraph({
text: text,
heading: HeadingLevel.HEADING_2,
break: 2
});
}
createInstitutionHeader(institutionName, dateText) {
return new Paragraph({
tabStops: [
{
type: TabStopType.RIGHT,
position: TabStopPosition.MAX,
},
],
children: [
new TextRun({
text: institutionName,
bold: true,
}),
new TextRun({
text: `\t${dateText}`,
bold: true,
}),
],
});
}
createInstitutionHeaderNoDate(institutionName) {
return new Paragraph({
tabStops: [
{
type: TabStopType.RIGHT,
position: TabStopPosition.MAX
},
],
children: [
new TextRun(
{
text: institutionName,
bold: true
}
),
],
});
}
createRoleText(roleText) {
return new Paragraph({
children: [
new TextRun({
text: roleText,
italics: true,
}),
],
});
}
createRoleTextUnderlined(roleText) {
return new Paragraph({
children: [
new TextRun({
text: roleText,
underline: {}
}),
],
});
}
createBullet(text) {
return new Paragraph({
text: text,
bullet: {
level: 0,
},
});
}
// tslint:disable-next-line:no-any
createSkillList(skills) {
return new Paragraph({
children: [new TextRun(skills.map((skill) => skill).join(", ") + ".")],
});
}
// tslint:disable-next-line:no-any
createAchivementsList(certificati) {
return certificati.map(
(certificato) =>
new Paragraph({
text: `${certificato.certificante} - ${certificato.certificato}`,
bullet: {
level: 0,
},
}),
);
}
// tslint:disable-next-line:no-any
createLanguageList(lingue) {
return lingue.map(
(lingua) =>
new Paragraph({
text: `${lingua.lingua} - ${lingua.livello}`,
bullet: {
level: 0,
},
}),
);
}
createInterests(interests) {
return new Paragraph({
children: [new TextRun(interests)],
});
}
splitParagraphIntoBullets(text) {
console.log(text)
return text.split("\n\n");
}
// tslint:disable-next-line:no-any
createPositionDateText(dataInizio, dataFine, attivo) {
const dataFineTesto = attivo ? "Attuale" : dataFine;
console.log(`${dataInizio} - ${dataFineTesto}`)
return `${dataInizio} - ${dataFineTesto}`;
}
};
function generateDocx() {
console.log("etra")
const documentCreator = new DocumentCreator();
const doc = documentCreator.create([test.lavoro, test.educazione, test.skills, test.certificati, test.lingue, test.progetti]);
docx.Packer.toBlob(doc).then((blob) => {
console.log(blob);
saveAs(blob, `${test.informazioniBase.nome} ${test.informazioniBase.cognome}.docx`);
console.log("Document created successfully");
});
};
function generatePDF() {
const doc = this.create([this.test.lavoro, this.test.educazione, this.test.skills, this.test.certificati, this.test.lingue, this.test.progetti]);
converter(doc, 'output.pdf', function (err, result) {
if (err) {
console.log("Converting Doc to PDF failed", err);
}
console.log("Converting Doc to PDF succesfull", result);
});
};
<h1>Tasto genera WORD</h1>
<button type="button" onclick="generateDocx()">GENERA</button>
<button type="button" onclick="test()">GENERA PDF</button>

Discord.js permissionOverwrites not working but no error at all

I've been working on a ticket bot for our company and ended up not being able to update a user's permissions per channel.
I cannot find any problems and the code is working apart of the permissions perfectly. I'm using DiscordJS 12.5.1.
Here's my code:
module.exports = {
name: 'ticket',
category: 'Ticket',
description: 'Creates a new ticket.',
aliases: ['new'],
usage: 'new',
userperms: [],
botperms: [],
run: async (client, message, args, prefix) => {
const discord = require('discord.js');
message.guild.channels
.create(
`ticket-${message.author.username}-${message.author.discriminator}`,
{
permissionOverwrites: [
{
id: message.author.id,
allow: ['CREATE_INSTANT_INVITE'],
allow: ['SEND_MESSAGES'],
allow: ['ATTACH_FILES'],
allow: ['CONNECT'],
allow: ['ADD_REACTIONS'],
allow: ['VIEW_CHANNEL'],
},
],
type: 'text',
// parent: 'category id',
},
)
.then(async (channel) => {
let category = client.channels.cache.find(
(c) => c.name == '➣ Online Tickets' && c.type == 'category',
);
if (!category) throw new Error('Category channel does not exist');
channel.setParent(category.id);
// channel.permissionOverwrites.create(message.author.id, {VIEW_CHANNEL: true, SEND_MESSAGES: false});
// channel.permissionOverwrites.create(message.guild.roles.everyone, {VIEW_CHANNEL: false});
var embedParent = new discord.MessageEmbed()
.setTitle(`Beste, ${message.author.username}`)
.setDescription(
'Een van onze medewerkers helpt je z.s.m! Laat alvast een bericht achter zodat wij je zo goed mogelijk kunnen helpen. Om U zo goed mogelijk te kunnen helpen komen nu enkele vragen, gelieve deze te beantwoorden.\nReageer met 1️⃣ voor een technische vraag \nReageer met 2️⃣ voor boekhouding en juridische vragen.\nReageer met 3️⃣ voor een samenwerking.\nReageer met 4️⃣ voor overige vragen. \n\n ***LET OP: Als U errors krijgt op uw server, kunt U het beste een ticket aanmaken op de website: snip ***',
)
.setColor('007BFF')
.setFooter(
'© OnlineNode.nl 2021 - Ticket Systeem',
'https://media.discordapp.net/attachments/735827815521452133/830082858470604870/logo_400x400.png',
)
.setTimestamp();
channel.send(embedParent).then(function (embedParent) {
embedParent.react('1️⃣');
embedParent.react('2️⃣');
embedParent.react('3️⃣');
embedParent.react('4️⃣');
//embedParent.react("5️⃣")
});
message.guild.channels.cache
.find((c) => c.name == '🗃┃-discord-logs')
.send('New ticket has been submitted!');
});
},
};
Your permissionOverwrites array has an object where you repeat the allow key several times:
{
permissionOverwrites: [
{
id: message.author.id,
allow: ['CREATE_INSTANT_INVITE'],
allow: ['SEND_MESSAGES'],
allow: ['ATTACH_FILES'],
allow: ['CONNECT'],
allow: ['ADD_REACTIONS'],
allow: ['VIEW_CHANNEL'],
},
],
type: 'text',
}
As an object can't have two keys with the same name, it's basically the same as this:
{
permissionOverwrites: [
{
id: message.author.id,
allow: ['VIEW_CHANNEL'],
},
],
type: 'text',
}
allow is an array of the permissions that are allowed for the user or role:
{
permissionOverwrites: [
{
id: message.author.id,
allow: [
'ADD_REACTIONS',
'ATTACH_FILES',
'CONNECT',
'CREATE_INSTANT_INVITE',
'SEND_MESSAGES',
'VIEW_CHANNEL',
],
},
],
type: 'text',
}
Another error is that when you set the parent of the channel with the setParent method, it overwrites the permissions you just added and sets them to the same as the parent channel.
The setParent method accepts an options object as its second parameter. One of its properties is lockPermissions. It tells whether to lock the permissions to what the parent's permissions are and its default value is true. To prevent synchronising permissions, you can set it to false instead, like this:
channel.setParent(category.id, { lockPermissions: false });
As Zsolt Meszaros mentioned, your permissions will need to be in an array.
message.guild.channels
.create(
`ticket-${message.author.username}-${message.author.discriminator}`,
{
permissionOverwrites: [
{
id: message.author.id,
allow: [
'ADD_REACTIONS',
'ATTACH_FILES',
'CONNECT',
'CREATE_INSTANT_INVITE',
'SEND_MESSAGES',
'VIEW_CHANNEL',
],
},
],
type: 'text',
// parent: 'category id',
},
)
Another thing, it is possible that your bot is setting the permissions, but then soon after inside your code, you changed the category the channel belongs in:
channel.setParent(category.id);
Also, I'm not sure, but there might be a chance that after you change the category, the permissions are being removed and then copied from what the category's permissions are, so you'll have to set the category before setting the permissions.

Node.js - Express routing endpoint to Object Key Value inside array

I have a local server that I have created to learn and practice my backend coding. Right now its in the early stages of becoming a "netflix" style app. I have a code:
app.get("/movies/:title", (req, res) => {
res.json(movies.find((movie) => {
return movie.title === req.params.title
}));
});
that when I type this URL: localhost:8080/movies/:title (insert title name) it returns the desired movie form this array:
let movies = [
//1
{
title: 'Lord of the Rings',
actor: 'Orlando',
genre: 'adventure',
director: 'person'
} ,
//2
{
title: 'Harry Potter',
actor: 'Daniel Radcliffe',
genre: 'Fantasy',
director: 'person',
Movie_ID: "7"
} ,
//3
{
title: 'Imaginaerum',
actor: 'Toumas Holopainen',
genre: 'Fiction',
director: 'person',
Movie_ID: "1"
} ,
//4
{
title: 'Cloud Atlas',
actor: 'Person',
genre: 'Fantasy',
director: 'person'
}
However, when I try to do the same, but with the key value "actor" in this URL:
localhost:8080/movies/:actor (replace for actor name)
nothing shows up. Here is the code for that:
app.get("/movies/:actor", (req, res) => {
console.log(req.params)
res.json(movies.find(movie => {
return movie.actor === req.params.actor
}));
});
All help is greatly appreciated!
As #Đăng Khoa Đinh explained, these are the same routes, so your code doesn't know which end point to use.
Change one to:
/movies/actor/:actor/ and the other to /movies/title/:title or a similar change to get this working.

Sending Messages to members on join

Hi I want to get the bot to send a direct/private message to new users that join the server. It is able to post a welcome message on a channel but it doesnt work when i does in in private messages.
const Discord = require('discord.js');
const config = require('./config.json');
const bot = new Discord.Client();
const prefix = '*';
bot.on('ready', () => {
console.log('Bot Démarré');
bot.user.setActivity('Chill \'N Code (*help)', { type: 'WATCHING' });
bot.user.setStatus('online');
})
bot.on('guildMemberAdd', member => {
console.log(member.user.username + " a rejoint le serveur");
const embed = new Discord.MessageEmbed()
.setTitle("<EARLY_SUPPORTER:840512953928515595> Bienvenue " + member.user.username + " !")
.setImage('https://i.imgur.com/Kbl451j.gif')
.setDescription("__**Voici quelques informations utiles :**__")
.addFields(
{ name: '\u200B', value: '\u200B' },
{ name: '<:channel:840513546416554045> **Règlement**', value: 'Nous T\'invitions à lire le [règlement](https://discord.com/channels/836947422122344448/836947422173200410/836962049484390449]', inline: false },
{ name: '<:add_reaction:840512848266657792> **Rôles**', value: 'Tu peux prendre tes rôles [ici](https://discord.com/channels/836947422122344448/836947422617141290/837022973830496286)', inline: false },
{ name: '<:moderation:840528469317517333> **Devenir Staff**', value: 'Tu peux devenir staff [ici](https://forms.gle/rGV26bZytcx5atG28)', inline: false },
{ name: '\u200B', value: '\u200B' },
{ name: 'Github', value: '[Github](https://github.com/chillncode)', inline: false },
{ name: 'Twitter', value: '[Twitter](https://twitter.com/ChillNCode1)', inline: false }
)
.setFooter('Chill \'N Code', 'https://cdn.discordapp.com/icons/836947422122344448/d27317d317a5b260d0365f6ca0da5455.png');
member.send(embed);
console.log("message envoyé");
})
Make sure you have the SERVER MEMBERS INTENT enabled in the Discord Developer Portal

How to update an object inside an array inside an object with mongoose?

Let's say I want to update "numberOfUpVotes" where the title is "Een centrale plek voor alle ideeen". I want the new value of "numberOfUpVotes" to be stored in the database. How do I do that?
Right now my code doesn't give an error, but it also doesn't work. This is what I've tried:
Board.findOneAndUpdate(
{"ideas.numberOfUpVotes": 23},
{$set: {"numberOfUpVotes": 2}}, // $set
{new: true},
function (err, doc) {
if (err) return res.send(500, {error: err});
console.log("hallo");
});
This is my data:
{
collectionName: "Board",
boardName: "IdeaBoard Schiphol",
ideas: [
{
_id: ida1,
userId: id1,
title: 'Een centrale plek voor alle ideeen',
text: 'Een plek waar alle ideeen getoond worden op een scherm ofzo. Waar mensen dan op kunnnen stemmen via hun telefoon',
date: new Date('2019-04-12'),
numberOfUpVotes: 23,
},
{
_id: ida2,
userId: id1,
title: 'Een uber voor kerstbomen',
text: 'Bestaat zoiets al?',
date: new Date('2019-04-11'),
numberOfUpVotes: 1,
}
],
QRcode: 'Dit is een QRcode'
}
You can do this without mongoose, something like.
const board = {
collectionName: "Board",
boardName: "IdeaBoard Schiphol",
ideas: [
{
_id: 'ida1 (demo)',
userId: 'id1 (demo)',
title: 'Een centrale plek voor alle ideeen',
text: 'Verkort voor demonstratie',
date: new Date('2019-04-12'),
numberOfUpVotes: 23,
},
{
_id: 'ida2 (demo)',
userId: 'id1 (demo)',
title: 'Een uber voor kerstbomen',
text: 'Bestaat zoiets al?',
date: new Date('2019-04-11'),
numberOfUpVotes: 1,
}
],
QRcode: 'Dit is een QRcode'
};
// find the filtered record and update its value
// the found record is a reference, so the value
// is indeed changed within the object
board.ideas.filter(idea => idea.numberOfUpVotes === 23).shift().numberOfUpVotes = 2;
// QED
console.log(JSON.stringify(board, null, " "));
This is my final answer:
Board.update(
{"ideas._id": mongoose.Types.ObjectId("abc123")},
{$inc:{"ideas.$.numberOfUpVotes": 1}},
function (err, doc) {
if (err) return res.send(500, {error: err});
console.log("succes! (:");
})

Categories

Resources