Discord.js get motd - javascript

How do I get a MOTD of a Minecraftserver and put it into a embed?
If I type /status in. The Discord-Bot should reply the motd of the server replaysucht.de:255655 in a embed.

const serverInfo = require('minecraft-server-util');
let embed = new MessageEmbed()
.setTitle("Server Information")
.setTimestamp()
serverInfo.status('replaysucht.de') //default port: 25565
.then((response) => {
embed
.setDescription(response.description.descriptionText)
message.channel.send(embed)
})
.catch((error) => {
throw error;
});
For this example you need minecraft-server-util so make sure you've installed and defined it.
So in the code we create an embed embed. You can change the embed look to what you want, this was just an example. With serverInfo.status('replaysucht.de') we fetch all the information you need, for your problem. We get the MOTD from response by using .then after we fetched the information. The exact MOTD is stored in response.description.descriptionText. If the bot can fetch that without any problems, the embed gets sent in the channel, otherwise it will throw an error.
As the most Minecraft Servers have special and animated characters in their MOTD's it will be displayed like:
§f§f §7•§8● §eReplaySucht §8✕ §7we code for you §4:heart: §8✕ §e1§8.§e8 §8●§7•
§4Info §8» §cKurze Wartungsarbeiten!
inside the embed description.

Related

How can i send embeds message with message url in discord.js

I was wondering how can I send a embeds with message URL (this where it gonna send a message embeds)
I was been told to do this:
message.channel.messages.fetch(id_of_message)
And split the link into /, and get each individual element you want and you can start fetching every element to get to the message
The mentions channel method is not working when I do this:
const channel = (message
? message.mentions.channels.first()
: interaction.options.getChannel('channel'))
if (!channel || channel.type !== 'GUILD_TEXT') {
return message.reply({content: 'please tag a channel'})
}
I believe what you are asking is how to send a Message Embed through a Webhook.
A Webhook on Discord is just a URL you can interact with to send messages to a Discord channel.
You can create a webhook like this:
You will need to paste this URL in place of the placeholder URL. The following code should be placed at the top of your file!
const { WebhookClient, MessageEmbed } = require("discord.js");
const Hook = new WebhookClient({ url: 'https://discord.com/api/webhooks/XXXXXXXXX/XXXXXXXX' });
If you would like to actually send a Message Embed to that hook you can do so like this:
Hook.send({
embeds: [
new MessageEmbed()
.setTitle('Test Embed!')
.setDescription('This is a test!')
]
});

How can I pull data from an API into a Discord Embed Message?

I am trying to pull data from an API using GET to display that information in a nice Discord Embed message that updated frequently. How can I use the information it gives me and display it in a discord embed?
Also, how can I make it so that an ID is instead shown as a Name instead of the ID itself?
The APIs I want to use are all here in this repo https://github.com/ToontownRewritten/api-doc
Just use node-fetch or JavaScript fetch() function
Here is an example (this is a very simplified example and probably will need big adjustments to work properly with your API, as an API requires authentication and no headers were mentioned on this fetch request):
fetch('url')
.then((response) => {
return response.json()
})
.then((data) => {
console.log(data)
const embed = new Discord.MessageEmbed()
.setTitle('hi')
.setDescription(data)
message.channel.send(embed)
})
.catch((err) => {
// Do something for an error here
})
You change this to your needs, but just to give you a general idea.

How to react on a specific message?

Hey I have an Embed and I want that my Bot reacts with a Custom Emoji to it, but when I try it with my example of Code The bBot will react to every message that is send. Here's my Code:
bot.on("message", (message) => {
if (message.content.startsWith(prefix + "set")) {
const exampleEmbed = new Discord.MessageEmbed()
.setColor('#0099ff')
.setTitle('React to gain acess to the Role "Test"')
.setAuthor('Name')
.setThumbnail('123')
.setTimestamp()
.setFooter('Name');
message.channel.send(exampleEmbed);
if (message.channel.send(exampleEmbed)) {
message.react('123')
}
}
})
The last part is very confusing I know but I tried everything, even this :-)
There is something that you should note. When you are attempting to react, you don't define a message. This will give you an error because the bot's trying to react to a message that doesn't exist (To the bot) and isn't defined. I've added some code below that takes the sent message and reacts on it
message.channel.send(exampleEmbed)
.then(m => m.react('123'));
This method takes the Message Promise given from the sent message and reacts to said message

how to detect an embed and then resend it (discord.js)

so what i am trying to do is detect when a bot sends an embed in a channel, and when it does detect this, to take that embed and resend it the same as it was sent as.
For example, if the bot detects an embed sent in one channel, it will send that exact same embed in another channel. But the reason for this is because I want to take the embeds from multiple bots.
in discordjs.guide it says to use this code:
const receivedEmbed = message.embeds[0];
const exampleEmbed = new Discord.MessageEmbed(receivedEmbed).setTitle('New title');
channel.send(exampleEmbed);
but this has not worked for me
You need to replace channel in the line channel.send(exampleEmbed); with an actual reference to a channel. Since you will be using the message event handler, you can get the channel the message was sent in using message.channel.
I have also added in a check to ensure that the message was sent by a bot and contains an embed.
client.on('message', message => {
// check to ensure message was sent by bot and contains embed
if (!message.author.bot || !message.embeds[0]) return;
const receivedEmbed = message.embeds[0];
const exampleEmbed = new Discord.MessageEmbed(receivedEmbed).setTitle('New title');
// send in same channel
message.channel.send(exampleEmbed);
// send in different channel
client.channels.fetch(/* Channel ID */).then(channel => {
channel.send(exampleEmbed);
});
// alternatively, you can use this (but the function must be asynchronous)
const channel = await client.channels.fetch(/* Channel ID */);
channel.send(exampleEmbed);
});
For more information on valid properties and methods, read the Discord.js docs.
The following code will check if the message has any embeds and will resend the first one.
if (message.embeds) {
message.channel.send({ embed: message.embeds.first() || message.embeds[0] })
};
const embed = message.embeds[0];
const editedEmbed = embed
.setTitle('Edited!')
.addField('Test Field!', 'This is a test', true);
message.channel.send(editedEmbed);
This worked perfectly fine for me.
The problem will be that you don't have a TextChannel selected. (message.channel)

How to assign a postgres query to a variable in node.js, Discord bot and postgres integration?

Me and my friend have started talking about a business venture.
We decided on using Discord as the platform.
I am a novice coder and know a bit about: Discord.js, Java, HTML.
Here’s the process:
We have a website where a subscription could be bought.
Once the subscription is purchased we want a code to be generated.
And use that code to verify the person who bought the subscription.
The generated code will allow the person to enter the server.
The generated code will have to be read by the Discord.js bot and assign a role.
Any suggestions on where to start or what to do will be great.
If needed I will provide some of the code and things I have thought of using. Trying to find a way to generate a code and integrate it in Discord.js and HTML is what I am struggling with.
(Edited after this...)
So I have started doing this and came across 2 problems.
bot.on('message', async message => {
if (message.author.bot) return;
if (message.channel.id === "*********************") {
if (message.content === "/clear") return;
let MessageContent = message.content;
client.query(`SELECT * FROM public."GeneratedCodes" WHERE generated_codes = '${MessageContent}'`)
.then(results => {
if (MessageContent === results.rows) {
let msg = message.reply(`***Code worked!*** ${results.rows}`)
msg.then(message => {
message.delete({
timeout: 3000
})
})
} else {
let msg = message.reply("Code ***DIDN'T*** work :(")
msg.then(message => {
message.delete({
timeout: 3000
})
})
}
})
.catch(e => console.log(e))
}
});
So I want to make a query (I have already setup the postgresql) where the query must find a value equal to message.content, But I can't compare message.content to results.rows, how could I store client.query(SELECT * FROM public."GeneratedCodes" WHERE generated_codes = '${MessageContent}') into a variable that could be compared to another variable?
Ok so this was one hell of a ride, but I figured it out...
Just a side-note, for you reading this answer... This is tricky so watch the videos and ask if you need help.
So here is the answer step by step:
1. Firstly you need to set up a Postgres database, use the link below:
https://www.youtube.com/watch?v=KH4OsSCZJUo&t
2. Secondly, I needed to import randomly generated codes using a .csv file,
Using the website linked below:
https://www.randomcodegenerator.com/en/home
It's easier importing a .csv file to Postgres. Using the following video to do so:
https://www.youtube.com/watch?v=KTcEg35Xd38
3. Once you have the Postgres database setup do the following:
-Start by watching this video on how to use the npm install pg library and how to connect your node.js to your Postgres database:
https://youtu.be/ufdHsFClAk0
After which you can use this code to guide you through the discord message.content to authenticate that the code inserted is valid in the database:
bot.on('message', async message => {
let EmbedCodeMessageInvalid = new Discord.MessageEmbed()
.setColor("#00A9B7")
.setTitle("Verification Code:")
.setDescription(`${message.author.username}, your code is INVALID | :)`)
.setFooter(`VirtualKicksBot | Virtualkick.co.za`, "https://cdn.shopify.com/s/files/1/0269/8146/6177/files/Mooi_large.jpg");
let EmbedCodeMessageValid = new Discord.MessageEmbed()
.setColor("#00A9B7")
.setTitle("Verification Code:")
.setDescription(`${message.author.username}, your code is VALID. Welcome to the channel | :)`)
.setFooter(`VirtualKicksBot | Virtualkick.co.za`, "https://cdn.shopify.com/s/files/1/0269/8146/6177/files/Mooi_large.jpg");
if(message.author.bot) return;
if(message.channel.id === "**********************"){
if(message.content === "/clear") return;
let MessageContent = message.content;
await client.query(`SELECT * FROM public."GeneratedCodes" WHERE generated_codes = $1`, [`${MessageContent}`])
.then(results => {
let CodeMessage = JSON.stringify(results.rows);
let SubCodedMessage = CodeMessage.substring(21, 31)
if(MessageContent === SubCodedMessage){
let msg = message.reply({ embed: EmbedCodeMessageValid })
msg.then(message => {
message.delete({timeout: 5000});
})
message.delete({timeout: 5000});
message.guild.members.cache.get(message.author.id).roles.add("713016390998687766");
}else{
let msg = message.reply({ embed: EmbedCodeMessageInvalid });
msg.then(message => {
message.delete({timeout: 5000})
})
message.delete({timeout: 5000})
}
})
.catch(e => console.log(e))
}
});
4. I'll go through the code segment by segment:
~The first line is `bot.on('message' => async message {}) :
What this does is it calls the discord bot when a message is sent in the server.
~The lines from 2 - 11 are embeds that were created to make the message that the bot sends back look a bit better (If you guys want me to give an in-depth tutorial on how to do this, please comment and I'll do it).
~From line 12 - 14 are if statements that set a criterium so that is it is met or net the code will run or not:
-First if: if(message.author.bot) return; If the message is sent by a bot the program won't run.
-Second if: if(message.channel.id === "720993727811813406") if you want the bot only to run this code in a specific channel.
-Third if: if(message.content === "/clear") return; If you have a bulk delete or other command it won't run the code if the message has the command in the message.
~Line 15 let MessageContent = message.content; stores the message sent in the server into a variable tho be used later.
~Line 16 await client.query(SELECT * FROM public."GeneratedCodes" WHERE generated_codes = $1, [${MessageContent}]) this is where your query is made. Note that we want to see if the message content is in the database. IF you get confused go watch the video on how to use Postgres node.js integration video which was listed above.
~Lines 17 - 34:
=> So what happens in this segment is as follows:
The .then(results = {CODE_IN_HERE}), returns a promise and results is the variable that is used to return the client.query so when you console.log(results.rows) it will return as follows: ({COULOMB_NAME: 'QUERY_RESULT'}).
So what you should do to be able to read and compare the query result is to make a variable and JSON.stringify(VARIABLE_X) and let VARIABLE_X_SUB = VARIABLE_X.substring(begin value, end value), this allows you to compare MessageContent (Which is message.content) to the query result.
4. After you have compared the query result to the MessageContent using an IF statement you could do what you want with the bot like sending those Embeds to the channel or giving roles to users.
If you have any questions please ask and I will try and make a video to better explain this!

Categories

Resources