Await reply in private message discord.js - javascript

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 :)

Related

Delete Button/Component of a specifc message (discord.js)

I am now trying in vain to remove buttons from a bot message. I have created a command for this purpose. When executing it, it should at best remove a specific, the last or at least all buttons that are on a specific message.
I have tried various things, but in all attempts the buttons are not removed.
module.exports = {
category: 'Utilities',
description: 'Delete Buttons',
permissions: ['ADMINISTRATOR'],
callback: async ({ client, message }) => {
const channel = client.channels.cache.get('the channel id')
channel.messages.fetch('the message id').then(msg => msg.edit({components: []}));
console.log(msg)
}
}
When I try to do this, I get the following console error:
TypeError: Cannot read properties of undefined (reading 'messages')
When I try this, I neither get a console log, nor does the bot do anything ...
const { Client, Message } = require("discord.js");
module.exports = {
category: 'Utilities',
description: 'Delete Buttons',
permissions: ['ADMINISTRATOR'],
callback: async ({ client, message }) => {
client.on('ready', async () => {
const channel = client.channels.cache.get('the channel id')
channel.messages.fetch('the message id').then(msg => {
msg.edit({ components: [] })
});
},
)}
}
Maybe one of you knows a solution or an idea. :)
Thanks a lot!
When I try this, I neither get a console log, nor does the bot do anything
The second example does not do anything because you are creating a ready event handler on running your command. Meaning, it's waiting for the bot to once again be "ready", i.e. the state of having logged in to the API as it does on startup. But your bot is already ready, and will not become ready again until the next time it restarts, so nothing will happen.
As for the first example, the error you are getting suggests channel is undefined, meaning either:
A) You have the incorrect channel ID
- OR -
B) The specified channel is no longer in the channel cache
If you are 100% sure the ID is correct, we can assume the issue you are having is the latter (the channel not being in the cache). There are many ways to solve this, but one simple way is to simply fetch the channel similar to how you are trying to fetch the message. Here's an example:
const channel = await client.channels.fetch('the channel id');
const msg = await channel.messages.fetch('the message id');
msg.edit({components: []});
That should fix the issue. If it doesn't, then the issue is much more complicated and not enough information has been provided. Also note that in the above example, I swapped Promise syntax for async/await since you are using an async function anyways; I did this just to make this answer more readable, you can choose whichever format you prefer.

Sudo command (discord.js)

Im trying to make a sudo command but the user i mention in args 0's Profile picture wont show.
async execute(client, message, args) {
if (!message.member.hasPermission("MANAGE_WEBHOOKS")) {
return message.channel.send(`You don't have permission to execute this command.`)}
message.delete();
let user =
message.mentions.members.first() ||
message.guild.members.cache.get(args[0]) ||
message.member.id();
if (!user) return message.channel.send("Please provide a user!");
const webhook = await message.channel.createWebhook(user.displayName, {
avatar: user.user.displayAvatarURL(),
channel: message.channel.id
});
await webhook.send(args.slice(1).join(" ")).then(() => {
webhook.delete();
});
}
A couple of things:
Your declaration of user (let user =) is a bit misleading when you are fetching a member object from the cache. I would recommend changing it to member instead for coherency.
Smallketchup82 is correct. Because you are getting a member object you would need to use the .user attribute to get anything pertaining to the user portion (username, tag, discriminator, and avatar).
If you were to follow the above advice you could do something like:
avatar: member.user.avatarURL()
I'm not entirely sure of which method gets the user's avatar as I have only worked with discordjs v13. However, its most likely one of the two:
member.user.displayAvatarURL()
member.user.avatarURL()

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");

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!

Discord.js open DM stream with certain user by ID

Is there any option to open a DM stream or something like that with certain user by ID.
What do I mean?
It's like ssh terminal function, when I enter command to bot like:
me: DM#{user.id}
bot: {connection established message}
/**--------------------------------------------
# and for now, every message from me, bot will deliver to {user.id} until I
# don't send `{message_stop}` command, for example:
----------------------------------------------*/
me: "Hi, how are you?" -> client.fetchUser('user_id')
me: "Are you ok?"
me: -stop command
Without using -prefix every time in the beginning of each message?
Or probably implement this function like that:
Creating a channel on server(guild) and every message that I write there, will be delivered to a certain user?
The actual question is, if it's possible then how should I manipulate with client.on('trigger') state to achieve such result?
As for now, I have written the command, which DMs message to user, based on prefix in the begging of each message like:
me: dm#user_id: Hello!
me: dm#user_id: How are you?
Probably I should store session data (user.id) somewhere, to help bot understood that I want to communicate only with specific user?
I receive this answer in Discord.js discord. So it's possible with MessageCollector. I'm using this guide for building my bot with dynamic commands. So here is my code:
module.exports = {
name: 'direct',
description: 'Ping!',
args: true,
execute(message, args, client) {
const u = message.content.split(/(?<=^\S+)#/)[1];
console.log(message.content);
message.channel.send(`Connection established: ${message.author.id}`);
const filter = m => m.content.includes('discord');
const collector = message.channel.createMessageCollector(filter, {
maxMatches: 10,
time: 30000,
errors: ['time']
});
collector.on('collect', m => {
console.log(`${Date.now()} Collected ${m.content}`);
client.fetchUser('user_id').then((user) => {
return user.send(`${m.content}`);
});
});
collector.on('end', collected => {
message.channel.send(`Connection cancelled with ${message.author.id}. You send ${collected.size} messages`);
console.log(`${Date.now()} Collected ${collected.size} items`);
if (collected.size === 0) {
console.log('here');
}
});
}
};
You just enter command name (direct) in this case, and then every message that incudes discord DMs to user_id 10 times or for 30 seconds. You could use arguments, if you want to change it. Hope it helps anyone.
Also, I'm very thankful to Monbrey#4502 from Discord.js community for providing this information.

Categories

Resources