How to send GuildDelete to specific channel? - discord.js

I need to send my guildDelete and guildCreate in specific channel there is a code:
client.on("guildDelete", (guild, msg) => {
client.channels.get(`707291237782257776`).send(heh)
var heh = (`
Я **Ушел** :outbox_tray: с сервера **${guild.name}**. Информация о нем:
Акроним и ID: **${guild.nameAcronym} | ${guild.id}**
Основатель: **${guild.owner} (\`${guild.owner.user.tag}\`)**
Количество участников: **${guild.memberCount}**
Роли: **${guild.roles.size}**
Каналы: **${guild.channels.size}**
Создана: **${guild.createdAt.toString().slice(4, -32)}**
Иконка: ${guild.iconURL}
**Это наш ${client.guilds.size}-ый сервер!**`),
bot
setTimeout(() => {
console.log(`Leaved a guild: ${guild.name} | ${guild.id}`);
}, 1000);
});
Error: TypeError: client.channels.get is not a function

Since discord.js v12 you now need to use cache to access the channels collection, you also have other properties you can't access in your code since you didn't use cache:
client.on("guildDelete", (guild, msg) => {
client.channels.cache.get(`707291237782257776`).send(heh)
var heh = (`
Я **Ушел** :outbox_tray: с сервера **${guild.name}**. Информация о нем:
Акроним и ID: **${guild.nameAcronym} | ${guild.id}**
Основатель: **${guild.owner} (\`${guild.owner.user.tag}\`)**
Количество участников: **${guild.memberCount}**
Роли: **${guild.roles.cache.size}**
Каналы: **${guild.channels.cache.size}**
Создана: **${guild.createdAt.toString().slice(4, -32)}**
Иконка: ${guild.iconURL}
**Это наш ${client.guilds.cache.size}-ый сервер!**`),
bot
setTimeout(() => {
console.log(`Leaved a guild: ${guild.name} | ${guild.id}`);
}, 1000);
});

Related

Discord javascript problem for my bot Cannot read property

Please help me.
C:\Users\ASUS\Desktop\matthe-guard\jahky.js:428
newChannel.cache.roles.cache.forEach(async function (jahky) {
^
TypeError: Cannot read property 'roles' of undefined
at Client. (C:\Users\ASUS\Desktop\matthe-guard\jahky.js:428:22)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
client1.on("channelUpdate", async (oldChannel, newChannel) => {
let entry = await newChannel.guild.fetchAuditLogs({ type: 'CHANNEL_UPDATE' }).then(audit => audit.entries.first());
if (!entry || !entry.executor || Date.now() - entry.createdTimestamp > 10000 || !newChannel.guild.channels.cache.has(newChannel.id)) return;
if (matthe1.bots.includes(entry.executor.id)) return;
if (matthe1.owners.includes(entry.executor.id)) return;
if (matthe1.guvenlid.includes(entry.executor.id)) return;
if (newChannel.type !== "category" && newChannel.parentID !== oldChannel.parentID) newChannel.setParent(oldChannel.parentID);
if (newChannel.type === "category") {
newChannel.edit({ name: oldChannel.name, });
} else if (newChannel.type === "text") {
newChannel.edit({ name: oldChannel.name, topic: oldChannel.topic, nsfw: oldChannel.nsfw, rateLimitPerUser: oldChannel.rateLimitPerUser });
} else if (newChannel.type === "voice") { newChannel.edit({ name: oldChannel.name, bitrate: oldChannel.bitrate, userLimit: oldChannel.userLimit, }); };
oldChannel.permissionOverwrites.forEach(perm => {
let thisPermOverwrites = {}; perm.allow.toArray().forEach(p => { thisPermOverwrites[p] = true; }); perm.deny.toArray().forEach(p => { thisPermOverwrites[p] = false; });
newChannel.createOverwrite(perm.id, thisPermOverwrites);
});
newChannel.cache.roles.cache.forEach(async function (jahky) {
if (jahky.permissions.has("ADMINISTRATOR") || jahky.permissions.has("BAN_MEMBERS") || jahky.permissions.has("MANAGE_GUILD") || jahky.permissions.has("KICK_MEMBERS") || jahky.permissions.has("MANAGE_ROLES") || jahky.permissions.has("MANAGE_CHANNELS")) {
jahky.setPermissions(0).catch(err => { });
}
});
newChannel.members.ban(member.id, { reason: `İzinsiz Kanal Güncellemek!` });
let channel = client1.channels.cache.get(ayarlar1.log2)
if (!channel) return console.log('Kanal Günceleme Koruma Logu Yok!');
const jahky = new Discord1.MessageEmbed()
.setTimestamp()
.setColor(ayarlar1.color)
.setFooter(ayarlar1.footer)
.setDescription(`
**İzinsiz Kanal Güncellendi!**
**Yetkili Bilgisi**
**${entry.executor.tag}** **||** **${entry.executor.id}**
**Kanal Bilgisi**
**${oldChannel.name}** **||** **${oldChannel.id}**
**Yetkili sunucudan yasaklandı! Rollerdeki tüm yetkiler kapatıldı.**`)
channel.send({ embed: jahky })
return client1.users.cache.get(ayarlar1.sahip).send(`**Sunucuda kanal güncellendi! Güncelliyen kişinin bilgileri :** \n**Kullanıcı Adı :** \`\`${entry.executor.tag}\` **Kullanıcı idsi :** \`${entry.executor.id}\`\`\n**Kanal İdsi :** \`\`${oldChannel.name}\`\` **Kanal İdsi :** \`\`${oldChannel.id}\`\``)
});
GuildChannel#cache does not exist. You can simply remove it and continue with your property chain.
newChannel.roles.cache.forEach(...)
// ^ no cache

How to stop commands when breaking when :"overloaded"

I have a few commands that follow this same code, just some things changed, the code is for -dog command, which works fine within moderation (not spamming the command, maybe running it every 5 seconds) but when it does get spammed it will often spit a odd error into the terminal, I was wondering if there is anyway to fix this or improve it. Thanks!
Language: Discord.js V12
const Discord = require('discord.js');
const url = 'https://www.reddit.com/r/lookatmydog/hot/.json?limit=100'
module.exports = {
name: 'dog',
description: 'sends a dog!',
execute(message, args) {
https.get(url, (result) => {
var body = ''
result.on('data', (chunk) => {
body += chunk
})
result.on('end', () => {
var response = JSON.parse(body)
var index = response.data.children[Math.floor(Math.random() * 99) + 1].data
if (index.post_hint !== 'image') {
var text = index.selftext
const textembed = new Discord.MessageEmbed()
.setTitle(subRedditName)
.setColor('RANDOM')
.setDescription(`[${title}](${link})\n\n${text}`)
.setURL(`https://reddit.com/${subRedditName}`)
message.channel.send(textembed)
}
var image = index.preview.images[0].source.url.replace('&', '&')
var link = 'https://reddit.com' + index.permalink
var subRedditName = index.subreddit_name_prefixed
if (index.post_hint !== 'image') {
const textembed = new Discord.RichEmbed()
.setTitle(subRedditName)
.setColor('RANDOM')
.setDescription(`[${title}](${link})\n\n${text}`)
.setURL(`https://reddit.com/${subRedditName}`)
message.channel.send(textembed)
}
console.log(image);
const imageembed = new Discord.MessageEmbed()
.setTitle('Here is a dog, how nice!')
.setImage(image)
.setColor('RANDOM')
message.channel.send(imageembed)
}).on('error', function (e) {
console.log('Got an error: ', e)
})
})
},
}```
The error I got writing this was:
```C:\Users\-\Desktop\Corn Flakes\commands\Fun\dog.js:26
.setDescription(`[${title}](${link})\n\n${text}`)
^
ReferenceError: title is not defined
at IncomingMessage.<anonymous> (C:\Users\manof\Desktop\Corn Flakes\commands\Fun\dog.js:26:45)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (internal/streams/readable.js:1327:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21)```

TypeError: Cannot read property 'roles' of undefined at Object.module.exports.run

I am trying to make a tempmute command which saves data to JSON then reads it every 3 seconds to see is the time experied. I made the mute command but I recive an error TypeError: Cannot read property 'roles' of undefined. I delete the if(!message.member.roles.has("675376537272582154")) return message.channel.send('Bu komutu kullanabilmek için「🔪」Mute Premission rolüne sahip olmasınız.') but this time it said TypeError: Cannot read property 'members' of undefined. Can someone help me?
Information
Discord.js Version: v11.6.1
Node.js Version: 12.0.0
Code
const { RichEmbed } = require('discord.js');
const fs = require('fs');
module.exports.run = async (message, args, bot) => {
if(!message.member.roles.has("675376537272582154")) return message.channel.send(`Bu komutu kullanabilmek için \`「🔪」Mute Premission\` rolüne sahip olmasınız.`);
let toMute = message.mentions.member.first() || message.guild.members.get(args[0])
if(!toMute) return message.channel.send(`:x: Susturulacak kullanıcıyı etiketlemelisin!`)
let timeMute = args[1]
if(!timeMute) return message.channel.send(':x: Susturma süresini dakika cinsinden yazmalısın!')
if(isNaN(args[1])) return message.channel.send(':x: Senin de bildiğin gibi süre sadece sayı olabilir!')
let reason = args.slice(2).join(" ")
if(!reason) return message.channel.send(':x: Susturma sebebini yazmalısın!')
if(toMute.id === message.author.id) return message.channel.send(`:x: Kendini susturamazsın bea!`)
if(toMute.roles.has('675376537272582154')) return message.channel.send(`:x: \`「🔪」Mute Premission\` rolüne sahip olan birini susturamazsın!`)
let role = message.guild.roles.find(x => x.name === '「🔇」Muted')
if(!role) return message.channel.send(':x: `「🔇」Muted` adlı rolü bulamıyorum!')
if(toMute.roles.has(role.id)) return message.channel.send(':x: Bu kullanıcı zaten susturulmuş!')
let modlog = message.guild.channels.find(c => c.name === '『🔰』punishment')
if(!modlog) return message.channel.send(':x: Mod-Log kanalını bulamıyorum!')
const embed = new RichEmbed()
.setTitle('Susturma')
//.setThumbnail(`${toMute.avatarURL}`)
.setDescription(`**Susturlan Kişi: \`${toMute.tag}\`** \n **ID Numarası: \`${toMute.id}\`**\n **Susturan Yetkili: \`${message.author.tag}\`**\n **Süre: \`${timeMute}\`** **Sebep: \`${reason}\`** `)
.setColor("#ff0000")
.setFooter('Kurallara Uymayanın Sonu')
.setTimestamp();
bot.mutes[toMute.id] = {
guild: message.guild.id,
time: Date.now() + parseInt(args[1]) * 10000
}
await toMute.addRole(role)
fs.writeFile("./mutes.json", JSON.stringify(bot.mutes, null, 4), err => {
if(err) throw err;
modlog.send(embed)
})
}
module.exports.conf = {
enabled: true,
guildOnly: true,
aliases: ['sustur'],
permLevel: 0
};
module.exports.help = {
name: 'mute',
description: 'Sustur gitsin',
usage: '!sustur #kullanıcı süre sebep'
}
member and guild are most likely undefined because your bot is receiving a DM message. Check if the message is from a guild before continuing with your code:
module.exports.run = async (message, args, bot) => {
if(!message.guild) return
// rest of code
}

Discord.js - Give role a all channel

Hello I would like to create an order (! Giverole) so that it gives the roles (mute) to all the channels of the server or to be made the order.
client.on('message', message => {
if(message.content.startsWith(prefix + "giverole")) {
var mute_role = message.guild.roles.find(r => r.name == 'mute', {READ_MESSAGES: true, SEND_MESSAGES: false})
if (!mute_role) return message.channel.send(`**${message.author.username}**, role not found`)
message.guild.channels.overwritePermissions(channel => channel.addRole(mute_role));
var lock_embed = new Discord.RichEmbed()
.setColor("#ffad33")
.setDescription(":lock: **Salon bloqué pour les gens mute**")
message.channel.send(lock_embed)
thank you in advance
At the fist - try always get role with role ID, its more safely.
If I understand your question correctly and you need a certain role on all channels to establish certain rights. So you can use this code.
client.on('message', message => {
if(message.content.startsWith(prefix + "giverole")) {
let muteRole = message.guild.roles.get('ROLEID')
if (!muteRole) return message.channel.send(`**${message.author.username}**, role not found`)
message.guild.channels.map(channel => {
if(channel.type === 'text') {
channel.overwritePermissions(muteRole, {
VIEW_CHANNEL: true,
SEND_MESSAGES: false
})
.then(console.log)
.catch(console.log);
}
})
let lock_embed = new Discord.RichEmbed()
.setColor("#ffad33")
.setDescription(":lock: **Salon bloqué pour les gens mute**")
message.channel.send(lock_embed)
}
})
```

Data gets overwritten on new records Ionic 4

So basically I'm trying to achieve a reports card and I'm making a data query per each subject the student have. Unfortunately all the fields are getting replaced instead of leaving the previous one as it is. I may think this is some sort of Ionic limitation, so please would love insight in what I'm doing wrong and how to achieve what I'm trying to do.
Provider:
tipos(data) {
return new Promise((resolve, reject) => {
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let params: HttpParams = this.serialize(data);
this.http.post('https://xyz.ec/app/app/tipos', params, { headers: headers })
.subscribe(res => {
//console.log(res);
resolve(JSON.parse(JSON.stringify(res)));
}, (err) => {
reject(err);
});
});
}
actividades_det(data) {
return new Promise((resolve, reject) => {
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let params: HttpParams = this.serialize(data);
this.http.post('https://xyz.ec/app/app/actividades-detalle', params, { headers: headers })
.subscribe(res => {
//console.log(res);
resolve(JSON.parse(JSON.stringify(res)));
}, (err) => {
reject(err);
});
});
}
TS File:
export class NotasIndPage {
data: any = { uid: '' };
mdata: any = {uid:'',idm: '' };
pdata: any = {idpa:'' };
matdata: any = { uid:'',idm: '',idp:'' };
tipdata: any = { uid:'',idm: '',idpe:'',idpa:'',idt:'' };
tipos: any =[];
items: any =[];
mat: any =[];
par: any =[];
submitted = false;
toast: any;
uid: any;
id: any;
idpe: any;
idpa: any;
mnombre: any;
pnombre: any;
constructor(
public userData: UserData,
public router: Router,
public toastController: ToastController,
private storage: Storage,
public route: ActivatedRoute) {
}
ionViewWillEnter() {
this.storage.get('sess').then((val) => {
if(val){
this.data.uid=val;
this.uid=val;
this.route.params.subscribe(params => {
this.id = params['idm'];
this.idpe = params['idpe'];
this.idpa = params['idpa'];
});
this.matdata.idm=this.id;
this.mdata.idm=this.id;
this.mdata.uid=this.uid;
this.pdata.idpa=this.idpa;
this.userData.parcial(this.pdata).then(datpa => {this.par = datpa; this.pnombre=this.par[0].nombre;});
this.userData.materia(this.mdata).then(datma => {this.mat = datma; this.mnombre=this.mat[0].nombre;});
//Bloque de carga de datos en formulario
this.userData.tipos(this.data)
.then(dat => {
this.tipos = dat;
for(let i=0;i<this.tipos.length;i++){
this.tipdata.uid=this.uid;
this.tipdata.idm=this.id;
this.tipdata.idpe=this.idpe;
this.tipdata.idpa=this.idpa;
this.tipdata.idt=dat[i].id_tipo;
console.log(this.uid+" - "+this.id+" - "+this.idpe+" - "+this.idpa+" - "+dat[i].id_tipo);
this.userData.actividades_det(this.tipdata).then(datt => {this.items = datt; console.log(datt);});
}
});
//Fin de bloque de carga de datos
}else{
this.router.navigateByUrl('/login');
}
});
}
HTML file:
<ion-card *ngFor="let tipo of tipos" >
<ion-card-header>
<ion-card-subtitle>Id: {{tipo.id_tipo}} </ion-card-subtitle>
<ion-card-title>{{tipo.nombre}}</ion-card-title>
</ion-card-header>
<ion-card-content>
<ng-container *ngFor="let item of items" ><ion-label class="under" *ngIf="item.id_actividad!=0" > {{item.nombre}} - {{item.nota}} : {{item.descripcion}}<br></ion-label></ng-container>
</ion-card-content>
</ion-card>
Image of how the the report card is designed
The problem is when you update this.items. You are in a for-loop, so each value will erase last value. A solution could be to add a property to tipos this way:
this.userData.tipos(this.data)
.then(dat => {
this.tipos = dat;
for(let i=0;i<this.tipos.length;i++){
// ...
this.userData.actividades_det(this.tipdata).then(datt => {this.tipos[i].items = datt; console.log(datt);});
}
});
and then use it in html:
<ng-container *ngFor="let item of tipo.items" ><ion-label class="under" *ngIf="item.id_actividad!=0" > {{item.nombre}} - {{item.nota}} : {{item.descripcion}}<br></ion-label></ng-container>

Resources