Channel Rename Logs Discord.js v12 - discord.js

client.on("channelDelete", async function(channel) {
const loggg = client.channels.cache.get("channel.id");
const logs = await channel.guild.fetchAuditLogs({ limit: 1, type: 'CHANNEL_DELETE' });
const log = logs.entries.first();
if (!log) return;
loggg.send(`channelDeleted: ${channel} ${log.executor.tag} ${channel.type}`);
});
Can someone help me to convert it to channel rename logs with old and new channel and executor

Related

Discord bot not coming online despite no error messages?

I have recently spent a long time making a discord ticket bot, and all of a sudden now, it isnt turning on. There are no error messages when I turn the bot on, and the webview says the bot is online. I am hosting on repl.it
Sorry for the long code, but any genius who could work this out would be greatly appreciated. Thanks in advance.
const fs = require('fs');
const client = new Discord.Client();
const prefix = '-'
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles){
const command = require(`./commands/${file}`)
client.commands.set(command.name, command);
}
require('./server.js')
client.on("ready", () => {
console.log('Bot ready!');
client.user.setActivity('-help', { type: "LISTENING"} ).catch(console.error)
})
client.on("message", async (message) => {
if (message.author.bot) return;
const filter = (m) => m.author.id === message.author.id;
if (message.content === "-ticket") {
let channel = message.author.dmChannel;
if (!channel) channel = await message.author.createDM();
let embed = new Discord.MessageEmbed();
embed.setTitle('Open a Ticket')
embed.setDescription('Thank you for reaching out to us. If you have a question, please state it below so I can connect you to a member of our support team. If you a reporting a user, please describe your report in detail below.')
embed.setColor('AQUA')
message.author.send(embed);
channel
.awaitMessages(filter, {max: 1, time: 1000 * 300, errors: ['time'] })
.then ( async (collected) => {
const msg = collected.first();
message.author.send(`
>>> ✅ Thank you for reaching out to us! I have created a case for your inquiry with out support team. Expect a reply soon!
❓ Your question: ${msg}
`);
let claimEmbed = new Discord.MessageEmbed();
claimEmbed.setTitle('New Ticket')
claimEmbed.setDescription(`
New ticket created by ${message.author.tag}: ${msg}
React with ✅ to claim!
`)
claimEmbed.setColor('AQUA')
claimEmbed.setTimestamp()
try {
let claimChannel = client.channels.cache.find(
(channel) => channel.name === 'general',
);
let claimMessage = await claimChannel.send(claimEmbed);
claimMessage.react('✅');
const handleReaction = (reaction, user) => {
if (user.id === '923956860682399806') {
return;
}
const name = `ticket-${user.tag}`
claimMessage.guild.channels
.create(name, {
type: 'text',
}).then(channel => {
console.log(channel)
})
claimMessage.delete();
}
client.on('messageReactionAdd', (reaction, user) => {
const channelID = '858428421683675169'
if (reaction.message.channel.id === channelID) {
handleReaction(reaction, user)
}
})
} catch (err) {
throw err;
}
})
.catch((err) => console.log(err));
}
})
client.login(process.env['TOKEN'])
Your problem could possibly be that you have not put any intents. Intents look like this:
const { Client } = require('discord.js');
const client = new Client({
intents: 46687,
});
You can always calculate your intents with this intents calculator: https://ziad87.net/intents/
Side note:
If you are using discord.js v14 you change client.on from message to messageCreate.

Discord.js interaction calculate latency

I just started building a Discord bot and I'm trying to get a client-side API latency from the moment when client use the bot's command until they receive a response. In other words, from client to server and server to client. Is that possible?
const axios = require('axios');
module.exports = {
data: new SlashCommandBuilder()
.setName('bored')
.setDescription('Send a random things to do'),
async execute(interaction) {
const url = 'http://www.example.com';
let response;
try {
response = await axios.get(url);
console.log(response.data);
} catch (err) {
console.error(err);
}
const embed = new MessageEmbed()
.setDescription(response.data.activity)
await interaction.reply({embeds: [embed]});
}
}
To get the API latency you can use:
const ping = client.ws.ping;
To get the Bot latency you need to calculate the difference in time between the timestamp of the interaction and the current time.
const botLatency = Date.now() - interaction.createdTimestamp;

TypeError: Cannot read properties of null (reading 'id')

So I was updating my bot to discord.js v13 and apparently my logging system has now broke, for some reason it can't read the ID of the guild where this log is occurring.
banAdd.js
const { MessageEmbed} = require("discord.js");
const {red_light} = require("../../other/colors.json");
const Channel = require('../../models/ModerationModel.js');
module.exports = async (bot, guild, user) => {
const guildDB = await Channel.findOne({
guildId: guild.id
}, async (err, guild) => {
if(err) console.error(err)
if (!guild) {
const newGuild = new Channel({
guildId: guild.id,
modChannel: null,
msgChannel: null
});
await newGuild.save().then(result => console.log(result)).catch(err => console.error(err));
}
});
const modChannel = guild.channels.cache.get(guildDB.modChannel);
if (!modChannel) {
return console.log(`No message channel found`);
}
let mEmbed = new MessageEmbed()
.setAuthor(`Member Unbanned`, user.displayAvatarURL({dynamic : true}))
.setColor(red_light)
.setDescription(`${user} ${user.tag}`)
.setThumbnail(`${user.displayAvatarURL({dynamic : true})}`)
.setFooter(`ID: ${user.id}`)
.setTimestamp()
modChannel.send({embeds:[mEmbed]});
}
Error
/home/runner/switch-beta-test/events/guild/banRemove.js:13
guildId: guild.id,
^
TypeError: Cannot read properties of null (reading 'id')
at /home/runner/switch-beta-test/events/guild/banRemove.js:13:27
at /home/runner/switch-beta-test/node_modules/mongoose/lib/model.js:5074:18
at processTicksAndRejections (node:internal/process/task_queues:78:11)
I have no idea why this is not working as it works in previous versions but updating to discord.js V13 completely broke this system. I tried looking at any possible solution but I can't find a single solution.
The cause of this error was because guild can no longer be defined during a users ban or unban, guild and user should be replaced with ban in both the unban and ban logs.
CODE
const { MessageEmbed} = require("discord.js");
const {red_light} = require("../../other/colors.json");
const Channel = require('../../models/ModerationModel.js');
module.exports = async (bot, ban) => {
const guildDB = await Channel.findOne({
guildId: ban.guild.id
}, async (err, guild) => {
if(err) console.error(err)
if (!guild) {
const newGuild = new Channel({
guildId: ban.guild.id,
modChannel: null,
msgChannel: null
});
await newGuild.save().then(result => console.log(result)).catch(err => console.error(err));
}
});
const modChannel = ban.guild.channels.cache.get(guildDB.modChannel);
if (!modChannel) {
return console.log(`No message channel found`);
}
let mEmbed = new MessageEmbed()
.setAuthor(`Member Unbanned`, ban.user.displayAvatarURL({dynamic : true}))
.setColor(red_light)
.setDescription(`${ban.user} ${ban.user.tag}`)
.setThumbnail(`${ban.user.displayAvatarURL({dynamic : true})}`)
.setFooter(`ID: ${ban.user.id}`)
.setTimestamp()
modChannel.send({embeds:[mEmbed]});
}
After this the error should no longer show.
The error says that the guild variable is empty doesn't have a value null and when you do guild.id you're trying to access a property that don't exist
Make sure that the guild variable is assigned to a value
Probably they add some changes to the new version of npm package go check the docs

DM Specific User ID on Discord.js Bot

i'm new to coding bots and i need help on how to add a command on messaging a certain person a customized message. this is what i have so far. what should i do?
const Discord = require('discord.js');
const config = require("./Data/config.json")
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] })
client.once('ready', () => {
console.log('Ready!');
});
client.login('TOKEN');
client.on('message', async message => {
if (message.author.bot) return;
let prefix = '??'
if (!message.content.startsWith(prefix)) return;
let args = message.content.slice(prefix.length).trim().split("/ +/g");
let msg = message.content.toLowerCase();
let cmd = args.shift().toLowerCase();
if (msg.startsWith(prefix + 'ping')) {
message.channel.send('pong');
}
if (msg.startsWith(prefix + 'hello')) {
message.channel.send('hewwo uwu');
}
});
To fetch a user by id, you can use bot.users.fetch()
To direct message a user, you can use User.send():
const user = await client.users.fetch(userId);
user.send("This is a DM!");
This simple function will easily resolve the user (you can provide a user object or user ID so it’s very helpful)
async function DMUser(resolvable, content, client) {
const user = client.users.resolve(resolvable)
return user.send(content)
}
//returns: message sent, or error
//usage: DMUser(UserResolvable, "content", client)
Related links:
UserManager.resolve
User.send
UserResolvable

Randompuppys wont get images off of reddit on discord.js

I am trying to get a Discord.js bot to grab images from Reddit and post them in a channel but It keeps saying that there is no content to send, I was wondering if someone could point out what I did wrong.
(I am using a command handler)
Code:
const randomPuppy = require('random-puppy');
const snekfetch = require('snekfetch');
module.exports = {
name: "reddit",
category: "info",
description: "Sends subreddit images",
run: async (client, Message, args, subreddit) => {
let reddit = [
"dankmemes",
"meme"
]
randomPuppy(subreddit).then(url => {
snekfetch.get(url).then(async res => {
await Message.channel.send({
file: [{
attachment: res.body,
name: 'image.png'
}]
});
}).catch(err => console.error(err));
});
}
}
When I tried using random-puppy to get images from r/dankmemes, a lot of them were GIFs or videos. Make sure you're using the right extension and increasing the restRequestTimeout to allow time for the file to send.
The property file in Discord.js' MessageOptions was deprecated in v11 and was removed in v12. You should use files instead.
snekfetch is deprecated and you should use node-fetch instead.
Use this to initialise your client which will set the timeout to 1 minute instead of the default 15 seconds:
const client = new Client({restRequestTimeout: 60000})
In your command file:
// returns .jpg, .png, .gif, .mp4 etc
// for more info see https://nodejs.org/api/path.html#path_path_extname_path
const {extname} = require('path')
const fetch = require('node-fetch')
/* ... */
// in your run function
// you can use thens if you want but I find this easier to read
try {
const url = await randomPuppy(subreddit)
const res = await fetch(url)
await Message.channel.send({
files: [{
attachment: res.body,
name: `image${extname(url)}`
}]
})
} catch (err) {
console.error(err)
}

Resources