What does exports.run = async (client, message, args) => do Discord.js - async.js

in a previous question I got a very good answer but i don't understand what this means KEEP IN MIND THIS IS DISCORD.JS
exports.run = async (client, message, args) =>
the whole code is
const roles = {
':harrison:': '794924635778973716',
':banana': '794924670955814943',
}
exports.run = async (client, message, args) => {
await message.delete()
// because RoleManager.fetch is async
const rolesArray = await Promise.all(Object.entries(roles)
.map(async ([emoji, id]) => `${emoji} ${(await message.guild.roles.fetch(id)).toString()}`)
)
const embed = new MessageEmbed()
.setTitle('Roles')
.setDescription(`
Tip: *Double React to remove a role*
${rolesArray.join('\n')}
`)
.setColor(colors.purple)
.setFooter('Wilderbot')
message.channel.send(embed).then(async msg => {
const emojis = Object.keys(roles)
for (const emoji of emojis) await msg.react(emoji)
// only collect reactions that are the role emojis
const collector = msg.createReactionCollector(({emoji}) => emojis.includes(emoji.name))
collector.on('collect', ({emoji, message}, user) => {
message.guild.members.fetch(user).then(member => {
member.roles.add(roles[emoji.name])
})
})
collector.on('remove', ({emoji, message}, user) => {
message.guild.members.fetch(user).then(member => {
member.roles.remove(roles[emoji.name])
})
})
})
}

This looks like code for a relaction role command. "exports.run = async (client, message, args) =>" is used in conjunction to a command handler. the "async" part is telling javascript that this is an asyncronous function, therefore allowing the use of "await" and ".then".

Related

TypeError: Cannot read property 'user' of undefined discord.js

So I was trying to fix this thing for a few hours now, and I have no idea what I'm doing wrong.
This thing should execute itself when member joins the guild
const { Discord, MessageEmbed } = require("discord.js")
module.exports = {
name: "guildMemberAdd",
run: async ({bot, member}) => {
const welcome = new MessageEmbed()
.setDescription(`
<:nezuko_peek:974066160108732517> — New friend just showed up: <#${member.user.id}>
Welcome fellow adventurer in **Jasmine Dragon**! What brings you in these sides? <:girl_love:973968823449436190> Here, go to <#972618593294512128> to introduce yourself and talk with us in <#971800237507248158>!
`)
.setImage("https://64.media.tumblr.com/01a9f72f062feaafa60cdbf80f9ba729/tumblr_inline_orgoyznIM51sd5e91_500.gif")
.setColor("#F7DF79")
.setFooter({ text: "Thank you for joining and enjoy your stay!" })
member.guild.channels.cache.get("971800237507248158").send({ content: `<#&974343947105206382>`, embeds: [welcome] })
}
}
Here's my event handler
const { getFiles } = require("../util/functions")
module.exports = (bot, reload) => {
const {client} = bot
let events = getFiles("./events/", ".js")
if (events.length === 0){
console.log("No events to load")
}
events.forEach((f, i) => {
if (reload)
delete require.cache[require.resolve(`../events/${f}`)]
const event = require(`../events/${f}`)
client.events.set(event.name, event)
if (!reload)
console.log (`${i + 1}. ${f} loaded`)
})
if (!reload)
initEvents(bot)
}
function triggerEventHandler(bot, event, ...args){
const {client} = bot
try {
if (client.events.has(event))
client.events.get(event).run(bot, ...args)
else
throw new Error(`Event ${event} does not exist`)
}
catch(err){
console.error(err)
}
}
function initEvents(bot) {
const {client} = bot
client.on("ready", () => {
triggerEventHandler(bot, "ready")
})
client.on("messageCreate", (message) => {
triggerEventHandler(bot, "messageCreate", message)
})
client.on("guildMemberAdd", () => {
triggerEventHandler(bot, "guildMemberAdd")
})
}
And here's my index.js
const Discord = require("discord.js")
require("dotenv").config()
const { MessageEmbed, MessageActionRow, MessageSelectMenu } = require("discord.js")
const slashcommands = require("./handlers/slashcommands")
const client = new Discord.Client({
intents: [
"GUILDS",
"GUILD_MESSAGES",
"GUILD_MEMBERS"
]
})
// Bot config
let bot = {
client,
prefix: "i?",
owners: ["511889215672287242"]
}
// Handlers
client.commands = new Discord.Collection()
client.events = new Discord.Collection()
client.slashcommands = new Discord.Collection()
client.loadEvents = (bot, reload) => require("./handlers/events")(bot, reload)
client.loadCommands = (bot, reload) => require("./handlers/commands")(bot, reload)
client.loadSlashCommands = (bot, reload) => require("./handlers/slashcommands")(bot, reload)
client.loadEvents(bot, false)
client.loadCommands(bot, false)
client.loadSlashCommands(bot, false)
// Slash commands handler
client.on("interactionCreate", (interaction) => {
if (!interaction.isCommand()) return
if (!interaction.inGuild()) return interaction.reply("This command can only be used in a server")
const slashcmd = client.slashcommands.get(interaction.commandName)
if (!slashcmd) return interaction.reply("Invalid slash command")
if (slashcmd.perm && !interaction.member.permissions.has(slashcmd.perm))
return interaction.reply("You don not have permission for this command")
slashcmd.run(client, interaction)
})
module.exports = bot
client.login(process.env.TOKEN)
Other events like "ready" and "messageCreate" are working just fine so I'm not sure why it's not working.

how to interact with telegram bot scene in chat?

I made a bot which gets added to chat, on command the bot entering to scene in chat, but after first step it stop interacts.
What is the problem and how to fix it?
const createPayment = new Scenes.WizardScene(
"createPayment",
async (ctx) => {
ctx.session.myData = {};
await ctx.reply("");
return ctx.wizard.next();
},
async (ctx) => {
ctx.session.myData.requisites = ctx.message.text;
await ctx.reply("");
return ctx.wizard.next();
},
async (ctx) => {
ctx.reply("");
return ctx.wizard.leave();
}
);
const stage = new Scenes.Stage([createPayment]);
bot.use(session());
bot.use(stage.middleware());
bot.command("test", async (ctx) => {
await ctx.scene.enter("createPayment");
});

How to check to see if a reaction is posted in discord.js

I have a discord.js bot that I would like to have a gateway entry on. It works that when they react to a reaction on a message, they get a role. How would I be able to accomplish that?
Hope you find this useful :)
flutter.on('guildMemberAdd', async member => {
let welcomeRole = member.guild.roles.find(role => {return role.id==="ROLE ID"});
await member.addRole(welcomeRole);
Promise.resolve(flutter.channels.get("CHANNEL ID")).then(async welcome => {
const msg = `Welcome to the community. :emojiName: We are **please** that you have joined us!`;
Promise.resolve(welcome.send(msg)).then(async message => {
flutter.on('messageReactionAdd', async (reaction, user) => {
if(user === message.author.bot) return;
if(reaction.emoji.name === "👍") {
let role = member.guild.roles.find(role => {return role.id==="ROLE TO REMOVE ID"});
await member.removeRole(role);
let roleTwo = member.guild.roles.find(role => {return role.id==="ROLE TO ADD ID"});
await member.addRole(roleTwo);
}
});
});
});
});
Wherever you see the word flutter just change it with your bots client name.
Example:
const Discord = require("discord.js");
const client = new Discord.Client();
Best of luck~

How can I promise so that way I can use sentMessage in this area. DISCORD.JS

How can I replace [the message the bot sent] with sentMessage?
client.guilds.get("588125693225992195")
.channels
.find(ch => ch.name === 'order-requests')
.send(richemb)
.then(sentMessage => sentMessage.react('🗑'))
.catch(() => console.error('Failed to react.'))
const filter = (reaction) => reaction.emoji.name === '🗑'
message.awaitReactions(filter)
.then([themessagethebotsent].delete(0500))
.catch(console.error);```
The scope of sentMessage is within the then() callback. This means that it can't be accessed outside of that callback.
You have two main solutions. Keeping your current setup, you could place the code that needs sentMessage inside the callback. Or, you could use the keyword await for a better flow. Note that it can only be used in async functions.
Example 1:
const guild = client.guilds.get('588125693225992195');
const channel = guild.channels.find(ch => ch.name == 'order-requests');
channel.send(richemb)
.then(sentMessage => {
sentMessage.react('🗑');
message.awaitReactions(reaction => reaction.emoji.name === '🗑')
.then(() => sentMessage.delete(0500));
})
.catch(console.error);
Example 2:
const guild = client.guilds.get('588125693225992195');
const channel = guild.channels.find(ch => ch.name === 'order-requests');
try {
const sentMessage = await channel.send(richemb);
await sentMessage.react('🗑');
await sentMessage.awaitReactions(reaction => reaction.emoji.name === '🗑');
await sentMessage.delete(0500);
} catch(err) {
console.error(err);
}

Koa.js always get Not Found 404

I develop in Koa and I use Firebase to messaging, because of a real-time database. When I want to get messages from firebase I get Not found, but in console.log() it shows me.
This is my function to getConversation(Messages)
async getConversation(conversationName, callback) {
var ref = await admin.database().ref(`messages/${conversationName}`)
await ref.on('value', (snapshot, prevChildKey) => {
var newPost = snapshot.val()
let values = Object.values(newPost)
callback(values)
})
}
Then I call it in another controller like this
async getMessages(ctx) {
const id = ctx.params.id
const nameOfConversation = await ctx.db.Conversation.findById(id)
await firebaseIndex.fbController.getConversation(nameOfConversation.name, response => {
console.log(response)
ctx.body = response //TODO
})
}
At the last, I call it in routes.
router.get('/getConversation/:id', middlewares.isAuthenticate, controllers.userConversation.getMessages)
I always get body Not found.
Do anybody know how I can solve it?
I solved it.
async getMessages(ctx) {
const id = ctx.params.id
const nameOfConversation = await ctx.db.Conversation.findById(id)
ctx.body = await new Promise((resolve, reject) => {
firebaseIndex.fbController.getConversation(nameOfConversation.name, async response => {
resolve(response)
})
})
}
ctx.body has to have a Promise.

Resources