Embed not sending discord js - node.js

For some reason this code below is not sending a embed to the reports channel tried what i could to fix it it will not send tried client.channels.cache.get(Channel).send(embed); that gave me a error tried it multipole ways and it still won't send
const Discord = require("discord.js");
module.exports = {
name: 'report',
usage: '%report <reason>',
description: 'reports a person',
async execute(client, message, args) {
let user = message.mentions.users.first() || await message.guild.members.cache.get(args[0])
if (!user) return message.reply(`Please mention a user to report`)
let reason = args.slice(1).join(" ")
if (!reason) return message.reply(`Please enter a reason`)
let Avatar = user.displayAvatarURL();
let Channel = client.channels.cache.find(c => c.name == 'reports')
if (!Channel) return message.reply(`Thier is no Valid channel to send a report please contact a staff member`)
const embed = new Discord.MessageEmbed()
.setTitle('New Report')
.setDescription(`The member ${message.author.tag} has reported ${user.tag}`)
.setColor("RED")
.setThumbnail(Avatar)
.addFields({
name: "Member ID,",
value: `${message.author.id}`,
inline: true
}, {
name: "Member Tag,",
value: `${message.author.tag}`,
inline: true
}, {
name: "Reported ID,",
value: `${user.id}`,
inline: true
}, {
name: "Reported Tag,",
value: `${user.tag}`,
inline: true
}, {
name: "Reason,",
value: `${reason}`,
inline: true
})
client.channels.cache.get(Channel);
message.channel.send(`Successfully sent the report!`)
}
}
function findChannel(client, channelName) {
var channelId = client.channels.cache.find(c => c.name.toLowerCase().includes(channelName.toLowerCase())).id;
}

Try
let Channel = message.guild.channels.cache.find(c => c.name == 'reports')
if (!Channel) return message.reply(`Thier is no Valid channel to send a report please contact a staff member`)
Channel.send(embed)
message.channel.send(`Successfully sent the report!`)

Related

Cannot read properties of undefined error in discord.js node js

const { SlashCommandBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, EmbedBuilder } = require('discord.js');
const fetch = require('node-fetch');
module.exports = {
data: new SlashCommandBuilder()
.setName('quiz')
.setDescription('Starts a Quiz!')
.addStringOption(option =>
option.setName('category')
.setDescription('Category of questions.')
.setRequired(true)
.addChoices(
{ name: 'History', value: '23' },
{ name: 'Arts', value: '25' },
{ name: 'Comics', value: '29' },
{ name: 'Computer', value: '18' },
{ name: 'Animals', value: '27' },
{ name: 'Films', value: '11' },
))
.addStringOption(option =>
option.setName('difficulty')
.setDescription('The difficulty of questions.')
.setRequired(true)
.addChoices(
{ name: 'Easy', value: 'easy' },
{ name: 'Medium', value: 'medium' },
{ name: 'Hard', value: 'hard' },
))
.addStringOption(option =>
option.setName('type')
.setDescription('Type of questions.')
.setRequired(true)
.addChoices(
{ name: 'Multiple Choice', value: 'multiple' },
{ name: 'True / False', value: 'boolean' },
)),
async execute(interaction) {
const category = interaction.options.getString('category');
const difficulty = interaction.options.getString('difficulty');
const type = interaction.options.getString('type');
const response = await fetch(`https://opentdb.com/api.php?amount=12&category=${category}&difficulty=${difficulty}&type=${type}`);
const data = await response.json()
var length = data.results.length;
var random = Math.floor(Math.random() * length);
let randomQuestion = data.results[random];
console.log(randomQuestion);
let question = randomQuestion.question;
const correctAnswer = randomQuestion.correct_answer;
const questionEmbed = new EmbedBuilder()
.setDescription(question)
const multipleAnswersRow = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId('first')
.setLabel('Click me!')
.setStyle(ButtonStyle.Primary),
new ButtonBuilder()
.setCustomId('second')
.setLabel('Click me!')
.setStyle(ButtonStyle.Primary),
new ButtonBuilder()
.setCustomId('third')
.setLabel('Click me!')
.setStyle(ButtonStyle.Primary),
new ButtonBuilder()
.setCustomId('fourth')
.setLabel('Click me!')
.setStyle(ButtonStyle.Primary),
new ButtonBuilder()
.setCustomId('last')
.setLabel('Stop')
.setStyle(ButtonStyle.Danger),
);
const booleanAnswersRow = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId('first')
.setLabel('Click me!')
.setStyle(ButtonStyle.Primary),
new ButtonBuilder()
.setCustomId('second')
.setLabel('Click me!')
.setStyle(ButtonStyle.Primary),
new ButtonBuilder()
.setCustomId('third')
.setLabel('Click me!')
.setStyle(ButtonStyle.Danger)
);
if(type == 'multiple'){
interaction.reply({embeds: [questionEmbed], components: [multipleAnswersRow]});
}
else if(type == 'boolean'){
interaction.reply({embeds: [questionEmbed], components: [booleanAnswersRow]});
}
},
};
Error -
undefined
Error executing quiz
TypeError: Cannot read properties of undefined (reading 'question')
at Object.execute (C:\Projects\Work Projects\Programmers Bot\commands\quiz.js:53:39)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async Object.execute (C:\Projects\Work Projects\Programmers Bot\events\interactionCreate.js:16:4)
I as trying to make a quiz command and it had an option to choose if you want to get questions as true/false or multiple choice based, when running the commands if i run the multiple choice question, it's working perfectly and when i try true/false it gives me this error,
i have used same question variable for both type of questions.
I hope someone can help me resolve this issue.
OpenTDB categories start from 9 (General Knowledge). Supplying a category of 8 or less may lead to the following response:
{ response_code: 1, results: [] }
Where response code 1 means:
Code 1: No Results Could not return results. The API doesn't have enough questions for your query. (Ex. Asking for 50 Questions in a Category that only has 20.)
Ensure you supply a category id of 9 or higher and check for the response code
// Change category accordingly
const response = await fetch(`https://opentdb.com/api.php?amount=12&category=9&difficulty=easy`);
const data = await response.json()
if (data.response_code !== 0) throw `Error Code: ${data.response_code}`;
if (!data.results.length) throw "No Questions!";
const random = Math.floor(Math.random() * data.results.length);
const randomQuestion = data.results[random];
const { question } = randomQuestion;
const correctAnswer = randomQuestion.correct_answer;
Consider using my package "open-trivia-db" to make working with OpenTDB alot faster:
import { Category, getQuestions } from 'open-trivia-db';
const questions = await getQuestions({
amount: 50, // 1 - 50
difficulty: 'easy', // or 'medium' or 'hard'
type: 'multiple', // or 'boolean (true/false)
category: Category.allNames.SCIENCE_COMPUTERS
});
// questions[0].value and questions[0].correctAnswer
If you want to make an entire trivia game with points and leaderboards, I've also written discord-trivia
import { TriviaCommandBuilder, TriviaManager } from 'discord-trivia';
const cmd = new TriviaCommandBuilder();
const trivia = new TriviaManager({
theme: 'Red'
});
module.exports = {
data: cmd.toBuilder(),
async execute(interaction) {
const game = trivia.createGame(interaction, cmd.getOptions(interaction));
game
.start()
.catch(console.error);
},
};
For both libraries, you may need to swap the import/export syntax for require() depending on your environment setup

Not able to get the value of a custom attribute in hyperledger-fabric using cid.getAttributeValue function

Other than the 3 attributes hf.EnrollmentId, hf.type and hf.Affiliation, I've created a custom attribute named email and added it as attrs:[{name: 'email', value: rahul18#gmail.com, ecert: true}] and it was successfully added to the attribute list.
In my chaincode, i'm able to get the enrollmentId by using the following command : cid.GetAttributeValue(ctx.GetStub(), "hf.EnrollmentID") but i'm not able to get the email using the same method cid.GetAttributeValue(ctx.GetStub(), "email")
Any help would be appreciated regarding why the first one is working and the second isn't
Does getAttributeValue not support custom made attributes?
Here is an example that may be helpful. A previous stackoverflow contribution helped me with a similar situation. I don't have the link for it right now, but thanks anyway.
First of all, you state that you have added attributes successfully. Here is some code as an example which I had placed in the code file for registering users.
//create user attr array
let registerAttrs = [];
let registerAttribute = {
name: "recycler",
value: config.recycler,
ecert: true,
};
registerAttrs.push(registerAttribute);
const secret = await ca.register({
affiliation: config.affiliation,
enrollmentID: config.recycler,
role: "client",
attrs: registerAttrs,
},
adminUser
);
The contract code is able to find the value of "recycler" using the following code. Of particular importance is the getCurrentUserId() function.
async getCurrentUserId(ctx) {
let id = [];
id.push(ctx.clientIdentity.getID());
var begin = id[0].indexOf("/CN=");
var end = id[0].lastIndexOf("::/C=");
let userid = id[0].substring(begin + 4, end);
return userid;}
async getCurrentUserType(ctx) {
let userid = await this.getCurrentUserId(ctx);
// check user id; if admin, return type = admin;
// else return value set for attribute "type" in certificate;
if (userid == "admin") {
return userid;
}
return ctx.clientIdentity.getAttributeValue(userid);}
The user type returned from the getCurrentUserType function is subsequently examined further up in the contract code, as shown in the following example.
async readTheAsset(ctx, id) {
let userType = await this.getCurrentUserType(ctx);
const buffer = await ctx.stub.getState(id);
const asset = JSON.parse(buffer.toString());
asset.userType = userType;
asset.userID = ctx.clientIdentity.getID();
if (asset.userType === "recycler") {
throw new Error(`The record cannot be read by ${asset.userType} `);
}
return asset;}
I feel sure that this code should solve your issue, as there is a lot of similarity.
const updateObj = {
enrollmentID : userName,
type:'client',
affiliation:'' ,
attrs: [{name: 'email', value: email, ecert: true}, {name: 'orgId', value: orgId, ecert: true}, {name: 'userId', value: userName, ecert: true}] ,
}
const response = await identityService.update(userName, updateObj ,adminUser)
const clientUser = await provider.getUserContext(userIdentity, userName);
const reenrollment = await caClient.reenroll(clientUser,
[{
name: 'email',
optional: false
},
{
name: 'orgId',
optional: false
},
{
name: 'userId',
optional: false
}
]);

Error cannot read property 'users' of undefined discord.js

Hi I'm getting an error that I'm unable to figure out why it's happening. I'm trying to get the guild owner message.guild.owner.user.tag but it's giving me a type error Cannot read property 'user' of undefined.
Heres what I'm working with:
module.exports = new Command({
name: "server",
description: "Shows server info",
permission: "SEND_MESSAGES",
async run(message, args, client) {
const embed = new Discord.MessageEmbed();
const created = moment(message.guild.createdAt).format('LL');
{
embed
.setTitle(`${message.guild.name}`)
.setThumbnail(message.guild.iconURL({ dynamic: true }))
.addFields(
{
name: "Total Members",
value: `${message.guild.memberCount}`,
inline: true
},
{
name: "Created on",
value: `${created}`,
inline: true
},
{
name: "Owner",
value: message.guild.owner.user.tag, // issue on this line
inline: false
},
{
name: "Verification Level",
value: `${message.guild.verificationLevel}`,
inline: false
}
);
message.reply({ embeds: [embed] });
}
}
});
Guild only provides an .ownerId property, to retrieve the User object of the owner you must fetch by the id.
const { guild } = message;
const { ownerId } = guild;
const owner = (await guild.members.fetch(ownerId)).user;
// owner.tag
Guild hasn't the property 'owner', you can only get the owner's user id like so:
message.guild.ownerId

HangMan Comand Within Command

So what I am trying to do here is when the command is used, the new channel is created, then the user mentions the channel and puts their word, then the hangman is sent within the channel they mentioned. But I get lost cause rn it's running everything at once, how do I make it listen for a new "command"?
const { hangman } = require('reconlx')
module.exports = {
name : 'hangman',
description: "Wanna play hangman?",
aliases: ['hang'],
execute(client, message, args, Discord) {
if(!message.member.hasPermission("MANAGE_MESSAGES")) return message.channel.send('You need manage messages permission.')
const channel = message.mentions.channels.first() || message.guild.channels.cache.get(args[0])
message.guild.channels.create(`HangMan`, {
type: 'text',
permissionOverwrites: [
{
id: message.guild.id,
deny: ['VIEW_CHANNEL']
},
{
id: message.author.id,
allow: ['VIEW_CHANNEL', 'SEND_MESSAGES', 'ADD_REACTIONS', 'ATTACH_FILES']
}
]
}).then(async channel => {
channel.send("Please mention a channel, then add your word. It should look something like this `#the game channel (your word)`")
message.reply(`Scroll to the very top of the server to add your word! <#${channel.id}>`)
})
if(message.content.includes('#')) {
message.reply('Hangman has started!')};
if(!channel) return message.channel.send('Please specify a channel')
const word = args.slice(1).join(" ")
if(!word) return message.channel.send('Please specify a word to guess.')
const hang = new hangman({
message: message,
word: word,
client: client,
channelID: channel.id,
})
hang.start();
}
}

Displaying leaderboard in embed

I am trying to create a leaderboard command for my Discord bot and having some trouble getting the data to display, my current code only displays the top user, you can see in the image there are 4 lines, this is because there are 4 entries in the database, so it's getting the information but not displaying all the data. Could someone point out what I am doing wrong/what I would need to change to fix this. (The blocked out bits in the photos is my username)
Code:
const top10 = db
.prepare(
'SELECT * FROM scores WHERE guild = ? ORDER BY points DESC LIMIT 10;',
)
.all(message.guild.id);
if (!top10) {
return;
}
for (const data of top10) {
let userNames = '';
for (let i = 0; i < top10.length; i++) {
const user = bot.users.cache.get(data.user).tag;
userNames += `\`${i + 1}\` ${user}\n`;
}
const level = `\`${data.level}\`\n`;
const xp = `\`${data.points.toLocaleString('en')}\`\n`;
const embed = new MessageEmbed()
.setAuthor(`Leaderboard for ${message.guild.name}`, message.guild.iconURL({ dynamic: true }))
.setColor(0x51267)
.addFields({ name: 'Top 10', value: userNames, inline: true },
{ name: 'Level', value: level, inline: true },
{ name: 'XP', value: xp, inline: true });
message.channel.send(embed);
return;
}
Current Output:
Desired Output:
From reading your code, I believe you made a mistake in the structuring of your code. From what it seems, your code gets the first item in top10, then adds that to the string as many times as the length of the top10 array. It then gets the level and xp for the first user, adds it to a string, then constructs this into an embed.
Here is the code revised so it should work as you intended:
let userNames = '';
let levels = '';
let xp = '';
for (let i = 0; i < top10.length; i++) {
const data = top10[i];
const user = (await bot.users.fetch(data.user)).tag;
userNames += `\`${i + 1}\` ${user}\n`;
levels += `\`${data.level}\`\n`;
xp += `\`${data.points.toLocaleString('en')}\`\n`;
}
const embed = new MessageEmbed()
.setAuthor(`Leaderboard for ${message.guild.name}`, message.guild.iconURL({ dynamic: true }))
.setColor(0x51267)
.addFields({ name: 'Top 10', value: userNames, inline: true },
{ name: 'Level', value: levels, inline: true },
{ name: 'XP', value: xp, inline: true });
message.channel.send(embed);
return;
You problem is, you just add \n to js object, so its no work.
As varian you can create 3 arrs with data, then, map db result push information to data.
And better use message.guild.members.chache.get for check if user on server, because, bot.users.cache.get(data.user).tag will return undined, after bot restart, if user don`t send any messages in handled bot channels.
const top10 = db.prepare('SELECT * FROM scores WHERE guild = ? ORDER BY points DESC LIMIT 10;').all(message.guild.id);
if (!top10) {
return;
}
let usersArr = [];
let levelArr = [];
let xpArr = [];
top10.forEach(dataUser, index => {
let findUser = message.guild.members.cache.get(dataUser.user);
if (findUser) {
usersArr.push(`\`${index + 1}\` ${user.tag}`);
levelArr.push(dataUser.level);
xpArr.push(dataUser.points.toLocaleString('en'));
}
});
const embed = new MessageEmbed()
.setAuthor(`Leaderboard for ${message.guild.name}`, message.guild.iconURL({ dynamic: true }))
.setColor(0x51267)
.addFields({ name: 'Top 10', value: usersArr.join('\n'), inline: true }, { name: 'Level', value: levelArr.join('\n'), inline: true }, { name: 'XP', value: xpArr.join('\n'), inline: true });
message.channel.send(embed);

Resources