I want to get the URL of a posted attachment on Discord channel.
The URL gets logged but this error is thrown:
url = message.attachments.first().url;
^
TypeError: Cannot read property 'url' of undefined
at Client.<anonymous> (C:\...\discord\tutbot\index.js:34:38)
This is my current code:
client.on("message", message => {
if (message.channel.id != "595178696118108190") return;
var content = message.content;
var url;
url = message.attachments.first().url;
console.log("haha" + url);
});
If there are no attachments with the message, message.attachments will be an empty Collection. Collection.first() will then return undefined. When you try to read the url property of the expected attachment, your error is thrown because it's undefined.
Check to make sure that there are attachments prior to reading expected properties.
client.on("message", message => {
if (message.channel.id !== "595178696118108190") return;
if (message.attachments.size !== 0) { // Attachments are present.
const firstAttachment = message.attachments.first();
console.log(`haha ${firstAttachment.url}`);
}
});
Related
I try to do a anti link bot discord that only who have the VIEW_AUDIT_LOG permission can send link this is my code :
client.on("messageCreate", message => {
const { member } = message;
let blacklisted = ['http://', 'www.', 'https://'];
let foundInText = false;
if(!member.permissions.has(Permissions.FLAGS.VIEW_AUDIT_LOG)) {
for (var i in blacklisted) {
if (message.content.toLowerCase().includes(blacklisted[i].toLowerCase())) foundInText = true;
}
if (foundInText) {
const logembed = new MessageEmbed()
.setColor("DARK_AQUA")
.addField(' with message :', ` ${message.content} `, true)
if(!message.member.roles.cache.has("929434049011941386")) {
message.guild.channels.cache.get('941704496185221221').send({ content: `<#${message.author.id}> tried to send links in <#${message.channel.id}>`, embeds: [logembed] });;
message.delete();
message.channel.send("No links here, " + `${message.author}`);
}
}
}
});
but it give this error when he delete a message with link :
if(!member.permissions.has(Permissions.FLAGS.VIEW_AUDIT_LOG)) {
^
TypeError: Cannot read properties of null (reading 'permissions')
ok so here's my guess....you're hitting this event handler twice or more times...the first time is the message the user typed. you will get their member info, if you console.log(message.member). The second time through, you'll be getting another event, which is the message(s) you send as a handler.
So the easy solution is to add something like this at or near the top of this event handler:
if (message.author.bot) return;
this basically tests to see if it's a bot or not that's calling your event. It's also good hygiene to ensure you're not accepting/reacting to other bots, which could result in spam you likely don't want.
I have sign up page and when user press the button got some errors if there are any. But when inputs are correct and there is no errors, i got an another error:
Unhandled Rejection (TypeError): Cannot read property 'data' of undefined
Heres my code:
try {
const response = await signup(body);
push('/login');
} catch (error){
if (error.response.data.validationErrors) {
setErrors(error.response.data.validationErrors);
}
}
try {
const response = await signup(body);
push('/login');
} catch (error){
if (error?.response?.data?.validationErrors) {
setErrors(error?.response?.data?.validationErrors);
}
}
please try this as the condition does not getting data from the response so you can use the fallback
I think there is no object called "data" in your response. Try to log your response and see whether there is an object called "data".
Purpose: To ban unauthorised users who kick members out of my server.
Code:
client.on("guildMemberRemove", async member => {
const FetchingLogs = await member.guild.fetchAuditLogs({
limit: 1,
type: "MEMBER_KICK",
});
const kickLog = FetchingLogs.entries.first();
if (!kickLog) {
return console.log(red(`${member.user.tag} was kicked in ${member.guild.name} but nothing was registered in the audit log...`));
}
const { executor, target, createdAt } = kickLog
if (target.id === member.id) {
console.log(greenBright(`${member.user.tag} got kicked in ${member.guild.name}, by ${executor.tag}`));
} else if (target.id === executor.id) {
return
}
if (executor.id !== client.user.id) {
member.guild.member(executor).ban({
reason: `Unauthorised Kick`
}).then(member.guild.owner.send(`**Unauthorised Kick By:** ${executor.tag} \n**Victim:** ${target.tag} \n**Time:** ${createdAt.toDateString()} \n**Sentence:** Ban.`)).catch();
}
})
Result: It bans the executor but it still throws this error:
(node:10272) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'ban' of null
Could you please tell me why this is happening and what I could to remove this error. All help appreciated ;)
This is the offending line:
member.guild.member(executor).ban(....
You supply member.guild.member an executor object and it returns null, then it tries to call the function ban on a null object and you get the error.
Maybe try sending it the executor.id instead, like so:
member.guild.member(executor.id).ban
If you want to ban somebody from a guild you can do this by writing:
member.guild.members.ban(executor.id, { reason: "/* Your reason */" })...
Sources:
https://discord.js.org/#/docs/main/stable/class/GuildMemberManager?scrollTo=ban
and my experience with discord.js
I'm trying to get the messages of an array of channel ids, and this is the code. The console.log does log the channel objects, so I know they're in there. However, on running this, it returns the TypeError "Cannot read property 'messages' of undefined"
console.log(filtered_channel_ids);
filtered_channel_ids.forEach((element) => {
const channel = client.channels.cache.get(element);
if (channel.messages) {
channel.messages
.fetch({limit: 10})
.then((message) => console.log(message.content));
}
});
I've also tried catching the error, but it still won't return anything.
I am facing the below issue where I am trying to save JSON data coming from my API into an array of my Model object. However, when I console.log the array it prints "undefined". I even tried to print a simple array and it still says "undefined". I am not sure if I am missing anything here. My code is given below. Can some one please help as I am new to Angular 2 and TypeScript.
results : Array<Recipes> = new Array(20);
sample = ['one','two','three'];
getResults(): Observable<Recipes[]>{
return this.http.get('<my API here which works perfectly.>')
.map(this.extractData)
.catch(this.handleErrorObservable);
}
private extractData(res: Response) {
let body = res.json();
console.log(this.sample); **---> This prints undefined in console**
console.log(body);
console.log(body.pagination.count);
let total_no_of_results = body.pagination.count;
let no_of_results;
for(no_of_results = 0; no_of_results < total_no_of_results; no_of_results++) {
//this.results[no_of_results] = new Recipes();
this.results[no_of_results] = body.data[no_of_results].embed_url; **---> This gives "Cannot set property '0' of undefined" error and program exits**
//this.results.push(image);
}
console.log(this.results);
return this.results;
}
private handleErrorObservable (error: Response | any) {
console.error(error.message || error);
return Observable.throw(error.message || error);
}
If you want to use this inside extractData you need
.map(this.extractData.bind(this))
or
.map((data) => this.extractData(data))
otherwise this won't point to the current class' instance.