Why is reaction.message undefined? - javascript

Why is reaction.message not defined? I have guild in other files and it work fine. Error: TypeError: Cannot read property 'guild' of undefined. And the error is here: message.guild.channels
module.exports = (client, Discord, chalk, message, args) => {
const channelId = '799339037306912808'
const getEmoji = (emojiName) =>
client.emojis.cache.find((emoji) => emoji.name === emojiName)
const emojis = {
golden_ticket: 'rules',
}
const handleReaction = (reaction, user, add) => {
if (user.id === '799652033509457940') {
return
}
const emoji = reaction._emoji.name
const { guild } = reaction.message
const userName = user.username
const userId = guild.members.cache.find((member) => member.id === user.id)
const categoryId = '802172599836213258';
if (add) {
reaction.users.remove(userId)
message.guild.channels
.create(`${userName}`, {
type: 'text',
permissionOverwrites: [
{
allow: 'VIEW_CHANNEL',
id: userId
}
],
})
.then((channel) => {
channel.setParent(categoryId)
})
} else {
return;
}
}
client.on('messageReactionAdd', (reaction, user) => {
if (reaction.message.channel.id === channelId) {
handleReaction(reaction, user, true)
}
})
}

Related

How to add reactions to an embed message

const { Client, Message, MessageEmbed, Intents } = require("discord.js");
module.exports = {
name: "sbfeedback",
/**
* #parom {Client} client
* #parom {Message} message
* #parom {String[]} args
*/
async execute(client, message, args) {
const questions = [
"What feedback would you like to give?",
"Anything else you would like to add?"
];
let collectCounter = 0;
let endCounter = 0;
const filter = (m) => m.author.id === message.author.id;
const appStart = await message.author.send(questions[collectCounter++]);
const channel = appStart.channel;
const collector = channel.createMessageCollector(filter);
message.delete({timeout: 100})
collector.on("collect", () => {
if (collectCounter < questions.length) {
channel.send(questions[collectCounter++]);
} else {
channel.send("Thank you for your feedback! If you would like to suggest anything else please do so with `-sbfeedback`.");
collector.stop("fulfilled");
}
});
const appsChannel = client.channels.cache.get("886099865094983691");
collector.on("end", (collected, reason) =>{
if (reason === "fulfilled") {
let index = 1;
const mappedResponses = collected
.map((msg) => {
return `${index++}) ${questions[endCounter++]}\n-> ${msg.content}`;
})
.join("\n\n");
appsChannel.send(
new MessageEmbed()
.setAuthor(message.author.tag, message.author.displayAvatarURL({ dynamic: true}))
.setTitle("!")
.setDescription(mappedResponses)
.setColor(`RANDOM`)
.setTimestamp()
);
message.react('πŸ‘').then(() => message.react('πŸ‘Ž'));
}
});
},
appsChannel.send returns a Promise and once it's resolved, you can grab the sent message, so you can add your reactions:
collector.on('end', (collected, reason) => {
if (reason === 'fulfilled') {
let index = 1;
const mappedResponses = collected
.map((msg) => {
return `${index++}) ${questions[endCounter++]}\n-> ${msg.content}`;
})
.join('\n\n');
appsChannel
.send(
new MessageEmbed()
.setAuthor(
message.author.tag,
message.author.displayAvatarURL({ dynamic: true }),
)
.setTitle('!')
.setDescription(mappedResponses)
.setColor(`RANDOM`)
.setTimestamp(),
)
.then((sent) => {
sent.react('πŸ‘');
sent.react('πŸ‘Ž');
});
}
});

Discord.js: Add role to message sender

i am trying to make a discord.js bot that adds a role to a user when they type: +rolename .
This is what I have come up with:
const { Client } = require("discord.js");
const { config } = require("dotenv");
const fs = require('fs');
const client = new Client({
partials: ['MESSAGE', 'CHANNEL', 'REACTION']
});
config({
path: __dirname + "/.env"
});
client.on("ready", () => {
console.log(`Hi, ${client.user.username} is now online!`);
client.user.setStatus('online');
client.user.setActivity('me getting developed', { type: "WATCHING"})
.then(() => console.log('bot status set'))
.catch(console.error);
});
client.on("message", (message) => {
if (message.content.startsWith("+")) {
var args = message.content.split(' ');
if (args.length == 1) {
console.log(`message is created -> ${message}`);
const { guild } = message;
var passrole = args[0];
var roleid = passrole.substring(1);
var role = message.guild.roles.cache.find((role) => {
return role.name == roleid;
});
console.log('role found')
var authoruser = message.author.id;
if (!role) {
message.reply('this role does not exist')
console.log('role does not exist')
return;
}
console.log(target)
authoruser.roles.add(role)
console.log("role added")
} else {
message.reply('invalid argument length passed')
return;
}
} else {
return;
}
});
client.login(process.env.TOKEN);
When running the code i get the following error:
TypeError: Cannot read property 'add' of undefined
This doesn't happen when I use this code and type +test #DiscordName#0001:
const { Client } = require("discord.js");
const { config } = require("dotenv");
const fs = require('fs');
const client = new Client({
partials: ['MESSAGE', 'CHANNEL', 'REACTION']
});
config({
path: __dirname + "/.env"
})
client.on("ready", () => {
console.log(`Hi, ${client.user.username} is now online!`);
client.user.setStatus('online');
client.user.setActivity('me getting developed', { type: "WATCHING"})
.then(presence => console.log('bot status set'))
.catch(console.error);
});
client.on("message", (message) => {
let target = message.mentions.members.first();
if (message.content.startsWith("+")) {
var args = message.content.split(' ');
if(args.length == 2){
console.log(`message is created -> ${message}`);
const { guild } = message;
var passrole = args[0]
var roleid = passrole.substring(1);
var role = message.guild.roles.cache.find((role) => {
return role.name == roleid;
})
console.log('role found')
if (!role) {
message.reply('role does not exist')
console.log('role does not exist')
return;
}
console.log(target)
target.roles.add(role)
console.log("role added")
} else {
message.reply('invalid argument length passed')
return;
}
} else {
return;
}
});
client.login(process.env.TOKEN);
My question is: How can I add the role to the message author.
Thanks in advance
The problem is that your authoruser is the users id (= string) not the member. You cannot add roles to users. Also if you get the role's id and not the name of the role you can add the role with the role's id.
client.on("message", message =>{
if (message.content.startsWith("+")) {
var args = message.content.split(' ');
if (args.length !== 1) {
message.reply('invalid argument count passed');
return;
}
if (!message.member ||!message.guild) {
message.reply('can only be used in guilds');
return;
}
console.log(`message is created -> ${message}`);
const { guild } = message;
var passrole = args[0];
var roleid = passrole.substring(1);
// If you get the role's id then you won't need this
var role = message.guild.roles.cache.find((role) => role.name == roleid);
if (!role) {
message.reply('this role does not exist');
console.log('role does not exist');
return;
}
console.log('role found');
console.log(target);
message.member.roles.add(role);
// If you get the role's id use this:
message.member.roles.add(roleid);
console.log('role added');
});

i want to make the command that makes changes in the roles work in dm's in javasript

I made a bot that verifies people with API and stores the data in mongoose but I want the code to work in discord DMS but I have no clue how to make it give roles in a specific server when the command is run in DMS this is my code:
const fetch = require('node-fetch')
const ignSchema = require('../schemas/ign-schema')
const mongo = require('../mongo')
module.exports = {
commands: ['verifyme'],
minArgs: 0,
maxArgs: null,
expectedArgs: "<minecraft name>",
callback: async(message, arguments, text) => {
const playerName = arguments.join(' ')
fetch(`https://api.hypixel.net/player?key=MYAPIKEY&name=${playerName}`)
.then(response => response.json())
.then(async data => {
player = data
const target = message.author
const author2 = message.author.tag
const uuid = data["player"]["uuid"]
const discordid = data["player"]["socialMedia"]["links"]["DISCORD"]
let verifyRole = message.guild.roles.cache.find(role => role.name === '[Verified]');
let memberTarget = message.guild.members.cache.get(target.id);
const guildId = message.guild.id
const userId = message.author.id
const UUID = uuid
const _id = UUID
if (discordid == author2) {
await mongo().then(async mongoose => {
try {
const results2 = await ignSchema.findOne({
_id,
})
const {
UUID,
userData,
discordName
} = results2
if (UUID == uuid) {
if (author2 == discordName) {
if (message.member.roles.cache.some(role => role.name === "[Verified]")) {
message.reply('you are already verified')
} else {
memberTarget.roles.add(verifyRole)
message.reply('welcome back')
}
} else {
message.reply(`you already used this minecraft account to verify ${discordName}, if you want to change this please contact <#390929478790152192>`)
mongoose.connection.close()
return
}
} else {}
} catch {
const userData = {
timestamp: new Date().getTime(),
}
await mongo().then(async(mongoose) => {
try {
await ignSchema.findOneAndUpdate({
_id
}, {
UUID,
discordName: author2,
HypixelName: playerName,
userId: userId,
guildId: guildId,
$push: {
userData: userData
},
}, {
upsert: true
})
memberTarget.roles.add(verifyRole)
message.reply('you are succesfully verified')
} finally {
mongoose.connection.close()
}
})
}
})
} else {
message.reply(`change your linked discord account in hypixel from ${discordid} to ${author2},`)
}
console.log(`${discordid}`)
})
},
}
and this is the error I get:
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'roles' of null
If there is more than one server the bot is in, this is not possible without making major assumptions as to the guild they are in.
If there is only one server, message.guild.roles can be changed to client.guilds.cache.get('your_servers_id').roles.

Permission overwrite isn't setting permissions

I don't know why is permissionOverwrites not working for me. No error here. No permissions will change for anyone. I think the problem is here: {allow: 'VIEW_CHANNEL', id: userId,}. I think the problem will be in the id. I hope someone finds out where I made a mistake.
module.exports = (client, Discord, chalk, message, args) => {
const channelId = '799339037306912808'
const getEmoji = (emojiName) =>
client.emojis.cache.find((emoji) => emoji.name === emojiName)
const emojis = {
golden_ticket: 'rules',
}
const handleReaction = (reaction, user, add) => {
if (user.id === '799652033509457940') {
return
}
const emoji = reaction._emoji.name
const { guild } = reaction.message
const userName = user.username
const userId = guild.members.cache.find((member) => member.id === user.id)
const categoryId = '802172599836213258';
if (add) {
reaction.users.remove(userId)
reaction.message.guild.channels
.create(`${userName}`, {
type: 'text',
permissionOverwrites: [
{
allow: 'VIEW_CHANNEL',
id: userId,
}
],
})
.then((channel) => {
channel.setParent(categoryId)
channel => ticketChannelId = channel.id;
message.ticketChannelId.send('cs');
})
} else {
return;
}
}
client.on('messageReactionAdd', (reaction, user) => {
if (reaction.message.channel.id === channelId) {
handleReaction(reaction, user, true)
}
})
}
Here, it is better to specify the type of the overwrite. Plus, "allow" should be an array.
permissionOverwrites: [
{
allow: [ 'VIEW_CHANNEL' ],
id: userId,
type: 'member'
}
],
it should resolve your issue. Note that by default, your channel will be readable by everyone, use:
permissionOverwrites: [
{
deny: ['VIEW_CHANNEL'],
id: reaction.message.guild.id,
type: 'role'
},
{
allow: ['VIEW_CHANNEL'],
id: userId,
type: 'member'
}
],
so everyone can't see the channel except admins and the user

How to successfully update a MongoDB schema in Discord.js?

I have been trying to make a function where I tell the bot what channel to deploy the points system in. I am also using MongoDB so that when my bot restarts, it remembers what channel the points system was set in. However, I am getting errors such as 404: Not Found and it does not even update the schema, so as a result, I am looking for available solutions. Here's my code:
const {
prefix,
} = require('./config.json')
const Discord = require('discord.js')
var date = new Date().toLocaleString();
module.exports = (client) => {
const Mongo = require('mongoose')
const LeaderboardSequence = require('./leaderboard.js')
const SLSchema = require('./setLeaderboard.js')
const mongoose = require('mongoose')
mongoose.connect('insert URL here', {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false
});
client.on('message', async message => {
if (message.content === `${prefix}setLeaderboardChannel`) {
// Destructure the guild and channel properties from the message object
const { guild, channel } = message
// Use find one and update to either update or insert the
// data depending on if it exists already
await SLSchema.findOneAndUpdate(
{
_id: guild.id,
},
{
_id: guild.id,
channelId: channel.id,
},
{
upsert: true,
}
)
message.reply(`The points channel has been set to <#${channel.id}>!`)
}
});
client.on('message', async message => {
const { guild, channel } = message
const channelId = await SLSchema.find({channelId: channel.id})
if (message.channel.id = channelId) {
if (message.attachments.size > 0) {
message.react('πŸ”Ό')
message.react('πŸ”½')
} else {
message.delete()
}
}
})
client.on('messageReactionAdd', async (reaction, user) => {
const { guild, channel } = message
const channelId = await SLSchema.find({channelId: channel.id})
if (reaction.partial) await reaction.fetch()
if (reaction.message.partial) await reaction.message.fetch()
if (reaction.message.channel.id !== channelId) return;
if (user.id === client.user.id) return;
if (reaction.message.author.id === user.id) return reaction.users.remove(user)
if (reaction.emoji.name === "πŸ”Ό") {
await LeaderboardSequence.findOneAndUpdate({ userid: reaction.message.author.id, guildID: reaction.message.guild.id }, { $inc: { points: 1 } }, { upsert: true , new: true , setDefaultsOnInsert: true })
} else if (reaction.emoji.name === "πŸ”½") {
await LeaderboardSequence.findOneAndUpdate({ userid: reaction.message.author.id, guildID: reaction.message.guild.id }, { $inc: { points: -1 } }, { upsert: true , new: true , setDefaultsOnInsert: true})
}
});
client.on('messageReactionRemove', async (reaction, user) => {
const { guild, channel } = message
const channelId = await SLSchema.find({channelId: channel.id})
if (reaction.partial) await reaction.fetch()
if (reaction.message.partial) await reaction.message.fetch()
if (reaction.message.channel.id !== channelId) return;
if (reaction.message.author.id === user.id) return reaction.users.remove(user)
if (user.id === client.user.id) return;
if (reaction.emoji.name === "πŸ”Ό") {
await LeaderboardSequence.findOneAndUpdate({ userid: reaction.message.author.id, guildID: reaction.message.guild.id }, { $inc: { points: -1 } }, { upsert: true , new: true , setDefaultsOnInsert: true })
} else if (reaction.emoji.name === "πŸ”½") {
await LeaderboardSequence.findOneAndUpdate({ userid: reaction.message.author.id, guildID: reaction.message.guild.id }, { $inc: { points: 1 } }, { upsert: true , new: true , setDefaultsOnInsert: true})
}
});
client.on('message', async message => {
if (message.content === `${prefix}leaderboard`) {
const Users = await LeaderboardSequence.find({guildID: message.guild.id}).sort({ points: -1 })
const embedArray = []
for (var i = 0; i < Users.length % 10 + 1; i++) {
const leaderboard = new Discord.MessageEmbed()
.setTitle(`Here is ${message.guild}'s points leaderboard!`)
.setColor("RANDOM")
.setThumbnail("https://pbs.twimg.com/media/D7ShRPYXoAA-XXB.jpg")
let text = ""
for (var j = 0; j < 10; j++) {
if (!Users[ i * 10 + j ]) break;
text += `${i * 10 + j + 1}. <#${Users[ i * 10 + j ].userid}>: ${Users[ i * 10 + j ].points}\n`
}
leaderboard.setDescription(text)
.setFooter("By (username) and (username), for everyone with the magic of discord.js.")
.setTimestamp()
embedArray.push(leaderboard)
}
paginate(message, embedArray)
}
});
const reactions = ['◀️', '⏸️', '▢️']
async function paginate(message, embeds, options) {
const pageMsg = await message.channel.send({ embed: embeds[0] })
await pageMsg.react(reactions[0])
await pageMsg.react(reactions[1])
await pageMsg.react(reactions[2])
let pageIndex = 0;
let time = 30000;
const filter = (reaction, user) => {
return reactions.includes(reaction.emoji.name) && user.id === message.author.id;
};
if (options) {
if (options.time) time = options.time
}
const collector = pageMsg.createReactionCollector(filter, { time: time });
collector.on('collect', (reaction, user) => {
reaction.users.remove(user)
if (reaction.emoji.name === '▢️') {
if (pageIndex < embeds.length-1) {
pageIndex++
pageMsg.edit({ embed: embeds[pageIndex] })
} else {
pageIndex = 0
pageMsg.edit({ embed: embeds[pageIndex] })
}
} else if (reaction.emoji.name === '⏸️') {
collector.stop()
} else if (reaction.emoji.name === '◀️') {
if (pageIndex > 0) {
pageIndex--
pageMsg.edit({ embed: embeds[pageIndex] })
} else {
pageIndex = embeds.length-1
pageMsg.edit({ embed: embeds[pageIndex]})
}
}
});
collector.on('end', () => pageMsg.reactions.removeAll().catch(err => console.log(err)));
}``
}
In the question, I did not mention that I was also checking for the points channel through an if statement:
(const { guild, channel } = message
const channelId = await SLSchema.find({channelId: channel.id}))
But this does not work as well.
Here is the schema:
const { Schema, model } = require('mongoose')
// We are using this multiple times so define
// it in an object to clean up our code
const reqString = {
type: String,
required: true,
}
const SLSchema = Schema({
_id: reqString, // Guild ID
channelId: reqString,
})
module.exports = model('setLeaderboard', SLSchema)
In the first piece of code, I have pasted the entire script so you guys have an understanding of the thing I am trying to pull off here.

Categories