Cannot get Discord.js to embed THEN delete - javascript

EDIT: Trying to make it more clear. I want the embed listed below in the part where it says EMBED GOES HERE.
Unsure if i can even do that. My structure is calling externally for files named in example: test.js through swap args. Creating a very rough command handler.
module.exports = {
name: 'test',
description: "Embed",
execute(message, args){
message.delete();
message.channel.send(`**EMBED GOES HERE**`).then(async sentMessage => {
await sentMessage.delete({ timeout: 10000 });
});
}
}
Where this is the embed.
"embed": {
"title": "Test",
"thumbnail": 'google.com',
"url": "google.com",
"description": 'test',
"color": 16763981,
"footer": {
}

An embed is a specially formatted JSON object, which can be easily assigned to any variable. However, the data portion of channel.send is also an object, so in the end it will be an object nested in an object. (The second one, I will create inline) This may be a bit confusing, because an embed is an option, not part of the content.
let myEmbed = {
title: "Test",
thumbnail: { url: 'google.com'},
url: "google.com",
description: 'test',
color: 16763981,
footer: { }
};
message.channel.send({embed: myEmbed }).then(async sentMessage => {
await sentMessage.delete({ timeout: 10000 });
message.delete();
});

Related

Why do I get channels link instead of attachment?

I'm trying to make a bot. When I type ".test" bot waits for a file. After receiving it, he must send me a Discord link from which I can download the same file. But he only refers to the message where I've sent the file.
Before that, I somehow did it and started experimenting something. After that I was unable to get the same result.
There is my code:
module.exports = {
commands: 'test',
callback: (message, arguments, text) => {
const msg_filter = (m) => m.author.id === message.author.id;
message.channel.awaitMessages({ filter: msg_filter, max: 1, time: 60000})
.then((collected) => {
console.log(collected.first())
console.log(collected.first().attachment)
console.log(collected.first().url)
console.log("finish")
}).catch('Error. No respond.')
}
}
Console output:
//First
attachments: Collection(1) [Map] {
'myId' => MessageAttachment {
attachment: 'https://cdn.discordapp.com/attachments/914907287603261510/myId/sample.pdf',
name: 'sample.pdf',
id: 'myId',
size: 3028,
url: 'https://cdn.discordapp.com/attachments/914907287603261510/myId/sample.pdf',
proxyURL: 'https://media.discordapp.net/attachments/914907287603261510/myId/sample.pdf',
height: null,
width: null,
contentType: 'application/pdf',
ephemeral: false
}
},
//Second
undefined
//Third
https://discord.com/channels/901476184532062209/914907287603261510/917789424857780224
collected is a collection that contains every message that got caught by channel.awaitMessages(), so collected.first() is a message.
To access this message's attachments, which is a collection, you would need to do collected.first().attachments (beware of the plural).
With this in mind, you can manage every attachment in a for-each loop, or just get the first attachment via collected.first().attachments.first()

google docs api documents.get multiple fields ? (nodejs)

How can I select multiple fields when using the documents.get ?
Right now I am getting the documenmt like this:
const doc = await docs.documents.get({
documentId: copiedFile.data.id,
fields: 'body/content'
});
which returns this:
"data": {
"body": {
"content": [...]
}
}
However, I need to also get the inlineObject and the only way so far I have been able to do so, is by removing the fields proeprty completely
const doc = await docs.documents.get({
documentId: copiedFile.data.id,
});
Then I get this:
"data": {
"title": "Some document title",
"body": {
"content": [...]
},
"headers": {
},
"footers": {
},
"documentStyle": {
},
"namedStyles": {
},
"lists": {
},
"revisionId": "some-long-id",
"suggestionsViewMode": "SUGGESTIONS_INLINE",
"inlineObjects": {
},
"documentId": "some-long-id"
}
But I am really only interested in data.body.content and data.inlineObjects
When selecting everything the response is many thousands of lines of json larger, which I don't want.
I have tried fields: ['body/content', 'inlineObjects'] but that only returns body.content and not the inlineObjects - also the documentation doesn't mention this syntax anywhere, it was just to experiment.
I think it doesn't return any inlineObjects when you don't have any inlineObjects in the document. To confirm if the actual format is working and the statement above is true, try using other fields where a value is confirmed to be returned such as revisionId or title.
Test:
const doc = await docs.documents.get({
documentId: copiedFile.data.id,
fields: 'body/content,inlineObjects'
});
Output:

discord bot problem embed thumbnail attachment

I am not very experienced in javascript and I have a problem to display my attached image.
when someone type #1 bot send an embed with caracteristics and i want post the image too !
I don't know if I formatted it wrong or if I should load the image first. So the image is my local folder in the same directory as my index.js file
I had problems with color too! I didn't manage to modify it! I didn't manage to modify it
I would have liked to be able to change the color of the name title or description but I don't know if it's possible my tests were unsuccessful
Could you help me a little bit please? Here is my code. Thanks in advance.
const { token, prefix } = require('../config.json');
const Discord = require('discord.js');
const client = new Discord.Client();
// Listen to the Bot being ready
client.once('ready', () => onClientReady());
function onClientReady()
{
// Listen to Messages in the channel
client.on('message', (message) => onMessageReceived(message));
}
// Upon a message being received, handle how we interact
function onMessageReceived(message)
{
if(message.author.bot) return;
if (message.content.toLowerCase().includes('#1'))
message.channel.send({ embed: {
color: 3447003,
title: "SpaceShips #1 New_York",
url: "http://google.com",
description: "RANK: 74 / SCORE: 121",
Thumbnail: (url="attachment://000793.jpg"),
fields: [{
name: "__**POWER**__",
value: "A-G 0: **39**",
"inline": true
},
{
name: "__**POWER**__",
value: "E-W: **76**",
"inline": true
},
{
name: "__**AUTONOMY**__",
value: "EY-W Nrg: **74**",
"inline": true
},
{
name: "__**AUTONOMY**__",
value: "B-P 0 Nrg: **73**",
"inline": true
},
{
name: "__**DISPLACEMENT**__",
value: "L-A: **79**",
"inline": true
},
{
name: "__**DISPLACEMENT**__",
value: "3D-V: **67**",
"inline": true
},
{
name: "__**SPECIALS**__",
value: "EM-W: **34**",
"inline": true
},
{
name: "__**SPECIALS**__",
value: "3D-W: **42**",
"inline": true
}
],
}
});
}
client.login(token);
If your working with python, and just want to send an image, try this:
await channel.send(file=discord.File('my_image.png'))
You may simply add an image value to the embed object you're sending like so:
message.channel.send({ embed: {
color: 3447003,
title: "SpaceShips #1 New_York",
url: "http://google.com",
description: "RANK: 74 / SCORE: 121",
thumbnail: {
url: "attachment://000793.jpg"
},
}
}); // Removed fields to clear up the clutter, you may add them like before!
As far as color is concerned it's a RGB value you may Google up the value for the colour you like and replace it!
If you want only send the image then here i suppose (Node.Js)
const path = require('path');
const Discord = require('discord.js');
let pic = path.resolve('test.jpg')
// the picture, if you console.log it will send the path of the file for example mine /src/image/test.jpg
message.channel.send(new Discord.MessageAttachment(pic))
In fact it isn't possible in local to put an image in a embed... we only can put attach file...
Si I used an web link and hosted my images on a server and it works!
Thanks for your help.

writeFile output issues. Didn't show what I expected to see

I don't understand how can I write the file like this:
{
"726623241984278589": {
"322366672625467392": {
"Moderation": "Kick",
"Target": "Bobo#1601",
"Moderator": "Bobosky#3914",
"Reason": "Testing",
"ID": "#XLR6RV8M"
}
}
}
Here is the my code of fs.writeFile:
const TargetMemberID = TargetMember.id
data[message.guild.id] = {
TargetMemberID: {
Moderation: 'Kick',
Target: `${TargetMember.user.tag}`,
Moderator: `${message.author.tag}`,
Reason: `${Reason}`,
ID: `#${ID}`
}
}
fs.writeFile("./data.json", JSON.stringify(data), (err) => {
if (err) console.log(err);
});
but it out put like this:
{
"726623241984278589": {
"TargetMemberID": {
"Moderation": "Kick",
"Target": "Bobo#1601",
"Moderator": "Bobosky#3914",
"Reason": "Testing",
"ID": "#XLR6RV8M"
}
}
}
so this is not what I expected to see. I want to see the TargetMemberID above replaced by the number just like what I expected as the first json code.
Any clue on it?
I've tried making the writing part as
data[message.guild.id[TargetMember.id]]
but it doesn't work.
PS : I didn't put all my codes such as the definding part of TargetMember, Reason etc. All of those are based on discord.js.
In JavaScript, object keys are strings, so when you write TargetMemberID as key, it's the same as writing "TargetMemberID". If you want the key to be the value of TargetMemberID, you need to add square brackets around it. And this way you could also just use TargetMember.id, you don't need a new variable for this.
Also, you don't need to use template literals in those values, you can just pass them as below.
data[message.guild.id] = {
[TargetMember.id]: {
Moderation: 'Kick',
Target: TargetMember.user.tag,
Moderator: message.author.tag,
Reason: Reason,
ID: ID,
}
}
You could also use the shorthand syntax, when the object key and the variable is the same:
data[message.guild.id] = {
[TargetMember.id]: {
Moderation: 'Kick',
Target: TargetMember.user.tag,
Moderator: message.author.tag,
// same as Reason: Reason
Reason,
// same as ID: ID
ID,
}
}

Discord Bot - Downloading JSON file from a website and extract certain elements of it

I'm working on a command that will automatically fetch a file from a link once a day and extract two of the elements in it and send that as a message in a channel.
My issue here is that I'm having issues actually getting the file downloaded. I've been trying several different functions to fetch the file but nothing has worked so far. I have attached one of the functions I've tried below.
async function getQuote () {
const url = "https://quotes.rest/qod?category=inspire";
const path = Path.resolve(__dirname, 'temp', 'qod.json')
const writer = fs.CreateWriteStream(path)
const response = await axios({
url,
method: 'GET',
responseType: 'stream'
})
response.data.pipe(writer)
getQuote();
return new Promise((resolve, reject) => {
writer.on('finish', resolve)
writer.on('error', reject)
})
}
fs.readFile('./temp/qod.json', 'utf8', function (err, data) {
if (err) throw err;
var obj = JSON.parse(data);
msg.channel.send(data);
})
The file I'm trying to work with here looks something like this:
{
"success": {
"total": 1
},
"contents": {
"quotes": [
{
"quote": "What you do speaks so loudly that I cannot hear what you say.",
"length": "61",
"author": "Ralph Waldo Emerson",
"tags": [
"action",
"inspire",
"leadership",
"management",
"tod"
],
"category": "inspire",
"language": "en",
"date": "2020-08-23",
"permalink": "https://theysaidso.com/quote/ralph-waldo-emerson-what-you-do-speaks-so-loudly-that-i-cannot-hear-what-you-say",
"id": "eZ0NtMPtGp8c5eQJOBfJmweF",
"background": "https://theysaidso.com/img/qod/qod-inspire.jpg",
"title": "Inspiring Quote of the day"
}
]
},
"baseurl": "https://theysaidso.com",
"copyright": {
"year": 2022,
"url": "https://theysaidso.com"
}
}
It wants to download as a json file, but when visiting the link, it is listed as a xml document.
How would I go about getting this downloaded and extracting two lines from it? If you're wondering, the two lines are the quote and author lines.
Thanks!
I copy your code and run my local machine and everythin fine.
Limitations are like mirages created by your own mind. When you realise that limitation do not exist, those around you will also feel it and allow you inside their space. - Stephen Richards
Looks like you are trying to write the result to a file and then read from the file which is not efficient. Here's a much simpler way of doing it.
async function getQuote() {
const url = "https://quotes.rest/qod?category=inspire";
const response = await axios(url);
const result = response.data;
/*
result =
{
"success": {
"total": 1
},
"contents": {
"quotes": [
{
"quote": "Limitations are like mirages created by your own mind. When you realise that limitation do not exist, those around you will also feel it and allow you inside their space. ",
"length": "171",
"author": "Stephen Richards",
"tags": [
"inspire",
"motivational",
"positive-thinking",
"self-empowerment",
"self-help",
"self-improvement",
"wealth",
"wealth-creation"
],
"category": "inspire",
"language": "en",
"date": "2020-08-24",
"permalink": "https://theysaidso.com/quote/stephen-richards-limitations-are-like-mirages-created-by-your-own-mind-when-you",
"id": "OLSVpLiSwrWplvCcFgPPiweF",
"background": "https://theysaidso.com/img/qod/qod-inspire.jpg",
"title": "Inspiring Quote of the day"
}
]
},
"baseurl": "https://theysaidso.com",
"copyright": {
"year": 2022,
"url": "https://theysaidso.com"
}
}
*/
//this is an array of quote objects
const quotes = result.contents.quotes;
//extracting first quote object from the array
const quoteObject = quotes[0];
//extracting quote text and author from quote object
const quote = quoteObject.quote;
const author = quoteObject.author;
//the >>> will make it look like a quote in discord.
console.log(`>>> ${quote}\n- ${author}`);
//send the formatted quote to the channel
msg.channel.send(`>>> ${quote}\n- ${author}`);
//if for some reason you want to save the result to a file
fs.writeFile(filePath, result, function(err) {
if (err) throw err;
console.log('Saved!');
});
}
getQuote();
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
I would suggest simply reading the quote to an object, then creating a string using interpolation and send it on the discord channel:
async function getQuote () {
const url = "https://quotes.rest/qod?category=inspire";
console.log("getQuote: Reading quote...");
// Get the response as an object
const response = await axios({
url,
method: 'GET'
})
// Use destructuring to get the quote and author
let { quote, author } = response.data.contents.quotes[0];
// Format our quote
let data = `${quote} - ${author}`;
// Add a console.log for debugging purposes..
console.log("getQuote: Sending quote:", data);
// Send the quote on the channel
msg.channel.send(data);
}
Todays quote would then look like so:
Limitations are like mirages created by your own mind. When you realise that limitation do not exist, those around you will also feel it and allow you inside their space. - Stephen Richards

Categories