Saving variable of a message in discord.js - javascript

i like to save my sended DM to a user in a local variable. How can I do this?
I would like to react on that message, but if I use .then() after or before the required .catch()-block, the log says "Cannot send messages to this user", without it, I can send the message..
Thank you!!
Code:
client.users.cache
.get(memb.id)
.send(emb5)
.catch((msb) => {
write("Error");
})
.then((msg) => {
msg.react(one);
});
one is the emoji...

If you are in an async function you can put the message in a variable like this:
const user = await client.users.fetch(mem.id); // Fetching the user
const awaitedMessage = await user.send(emb5); // Send the message to the user
awaitedMessage.react(one); // React the sent message

Related

How to get "snowflake" value for user_id?

I'm trying to write a command that messages a specified user. The user can type something like /warn #user insert warning here. Here is the code:
const user = await client.users
.fetch(interaction.options.getString("user"))
.catch(console.error);
const embed = new MessageEmbed()
.setColor("#FCE100")
.setTitle(`⚠️ Warning!`)
.setDescription(`${interaction.options.getString("warning")}`);
await user.send({ embeds: embed }).catch(() => {
interaction.channel.send("Error: user not found");
});
Here's the error I'm getting:
user_id: Value "<#!9872345978#####>" is not snowflake.
How do I get the correct "snowflake" value to actually be able to DM the user?
You have to use getUser instead of getString and also change your user option type to "USER" to make it work!

How to save a message in a variable, only to delete it later?

I have been trying to find a way to save a message as a variable. After it is saved as variable, I will delete the variable. I am making a page-based command for my bot, where each page has a custom reaction that does a custom action. I decided to make a simple navigator for the first page. In the navigator, you react with an emoji and the bot sends a message telling you to choose a page and wait for your message. When the bot receives your message, I want the bot to delete the message it sent.
My code looks like this.
let qsend = message.channel.send("Choose a page to go to.");// sends the bot's message
// bot receives my message!
qsend.delete() // deletes the bot's message
When I run it, I get the error: UnhandledPromiseRejectionWarning: TypeError: qsend.delete is not a function.
I've tried many different solutions, but still nothing.
Sending a message returns a promise. You need to either await it or use Promise#then()
Using Async/Await
// Inside an async function
// .on('message' async message => ... For example
let qsend = await message.channel.send("Choose a page to go to.");
qsend.delete();
Using Promise#then()
message.channel.send("Choose a page to go to.")
.then(qsend => qsend.delete())
.catch(console.error);
Discord.JS Documentation on Message#delete() and Async/Await
message.channel.send() returns a promise (see here). To delete it shortly after, you should send the message, await the response and delete the returned message after that time.
message.channel.send('Foo bar')
.then(msg => msg.delete())
.catch(/* Error handling if the message isn't sent or returned.*/);

How to make discord bot send scraped message?

I want to make an a discord bot that sends a scraped message.
I expected it to send the message but it gave me an error:
throw new DiscordAPIError(request.path, data, request.method, res.status);
DiscordAPIError: Cannot send an empty message
I tried to use message.channel.send(); but it doesn't seem to work.
Code:
let data = await page.evaluate(() => {
let Name = document.querySelector('div[id="title"]').innerText;
let Description = document.querySelector('div[id="content"]').innerText;
return {
Name,
Description
}
});
console.log(data);
message.channel.send(data);
debugger;
await browser.close();
The problem is that you shouldn't send the dictionary directly. While message.channel.send only accepts StringResolvable or APIMessage, data as a dictionary is neither. For more information, see the documentation.
Instead, you can convert data to a string first. The following is one of the solutions.
// Convert using JSON.stringify
message.channel.send(JSON.stringify(data));
Full code example (I tried it on https://example.com and thus there are different queries):
let data = await page.evaluate(() => {
let Name = document.querySelector('h1').innerText;
let Description = document.querySelector('p').innerText;
return {
Name,
Description
}
});
console.log(data);
message.channel.send(JSON.stringify(data));
Message sent by the bot without errors being thrown:
{"Name":"Example Domain","Description":"This domain is for use in illustrative examples in documents. You may use this domain in literature without prior coordination or asking for permission."}
If you expect a different message, just make sure that the argument you are passing to message.channel.send is acceptable or errors might be thrown.

Private message to user

How to make a bot be able to send a private message to a specific person? (using user ID)
no, message.author is not what I need!
I'm using discord.js and node.js
client.users.fetch('123456789').then((user) => {
user.send("My Message");
});
Dont forget replace "123456789" with the user id :D
Make sure this code is inside of an async function
// Getting the user object
const user = await <Client>.users.fetch('userID');
if (user) user.send('message').catch(error => {
// code if error occurs
});
This can be done with the User.send() method.
Here's an example of how it can be done by fetching the user
Make sure this is an async function, or the await will return an error.
const user = await <client>.users.fetch("USER ID"); // Replace <client> with your client variable (usually client or bot)
user.send("Message to send");

Await reply in private message discord.js

So, this works ALMOST as intended. I have the bot private messaging the user who uses the correct command in the correct channel of the server. Instead of clogging up the server with profile creation messages, I have the bot do profile creation privately. I know/think the problem is with the message.channel.awaitMessages, because it only sees the replies in the original channel on the server where the command was put into place.
I am not sure what I should replace the message.channel.awaitMessages with in order for it to pick up on the reply in the private message conversation rather than the original profile creation channel on the server.
I have not tested the sql message yet. I haven't tested what I have but I am pretty sure it won't work. I want the reply that is given by the user in the private message to be inserted (updated maybe?) into a mysql database I have already set up and properly got working. The users ID and username has been put into this table with the rest of the profile related questions being null at this moment. As they reply to these questions, those fields can be filled out/updated. Any ideas/suggestions are welcome!
module.exports.run = async (bot, message, args) => {
if(message.channel.id === '460633878244229120') return message.author.send(`Greetings, ${message.author.username}! FIRST QUESTION, **What is the name of your Brawler or Character?**`)
.then(function(){
message.channel.awaitMessages(response => message.content, {
max: 1,
time: 5000,
errors: ['time'],
})
.then((collected) => {
message.author.send(`Your Name is: ${collected.first().content}`);
var sql = (`UPDATE profile SET name = '${message.content}' WHERE id = ${message.author.id}`);
})
.catch(function(){
message.author.send('Please submit a name for your character. To restart Profile creation, please type "!profilecreate" command in Profile Creation channel on the server.');
});
});
}
Thanks in advance for your time!
I don't use SQL so, since the question is not specifically on that, don't ask me.
When you're using message.channel.awaitMessages, message is still the first one that you passed in the module.exports.run function, not the one that comes from send(). When send is resolved, it passes a new message, that you have to include in the arguments of the function you put inside then: so, instead of .then(function() {}) you'll need something like .then(function(new_message_sent_in_private) {})
This should fix the problem:
module.exports.run = async (bot, message, args) => {
if(message.channel.id === '460633878244229120') return message.author.send(`Greetings, ${message.author.username}! FIRST QUESTION, **What is the name of your Brawler or Character?**`)
.then((newmsg) => { //Now newmsg is the message you sent
newmsg.channel.awaitMessages(response => response.content, {
max: 1,
time: 5000,
errors: ['time'],
}).then((collected) => {
newmsg.channel.send(`Your Name is: ${collected.first().content}`);
var sql = (`UPDATE profile SET name = '${message.content}' WHERE id = ${message.author.id}`);
}).catch(() => {
newmsg.channel.send('Please submit a name for your character. To restart Profile creation, please type "!profilecreate" command in Profile Creation channel on the server.');
});
});
}
Let me now if that worked :)

Categories

Resources