Create Channel Switch Logger - discord

I'm trying to create a channel switch logger which allows me to specify a channel where the messages get posted.
So, for example, I create a TextChannel called "Channel Switches". When now a user changes voice channel, it should appear a message in this Channel. (eg. <USER> left channel <CHANNEL> and joined <CHANNEL>.)
MY PROBLEM IS: I get no errors and the Bot is not responding...
Here my first try:
var Discord = require('discord.js');
var logger = require("winston");
var auth = require("./auth.json");
// Configure logger settings
logger.remove(logger.transports.Console);
logger.add(new logger.transports.Console, {
colorize: true
});
logger.level = "debug";
// Initialize Discord Bot
var bot = new Discord.Client({
token: auth.token,
autorun: true
});
bot.on("ready", function(evt) {
logger.info("Connected");
logger.info("Logged in as: ");
logger.info(bot.username + " – (" + bot.id + ")");
console.log("Logged in as ${client.user.tag}!");
});
bot.on('voiceStateUpdate', (oldMember, newMember) => {
let newUserChannel = newMember.voiceChannel
let oldUserChannel = oldMember.voiceChannel
if (!oldUserChannel && newUserChannel) {
bot.channels.get('475330828466126848').send("User went form Channel" + oldUserChannel.name + "to the new" +
newUserChannel.name + "Channel");
}
});

Your bot does not respond because the client is not initialized correctly. You're creating the client like this:
var bot = new Discord.Client({
token: auth.token, // <--
autorun: true // <--
});
The problem is that these arguments do not exist in discord.js, as stated by the Client docs.
To log into your bot, please use Client.login():
var bot = new Discord.Client();
bot.login(auth.token);

Related

Deleting old message when Discord.JS sends new message

I'm trying to make a music bot with DiscordJS. It sends a message again when it switches to new music. When it is too much, it causes pollution. How can I set the old message to be deleted and the new message to remain when I switch to a new song or skip a song?
Code:
const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle, Client } = require('discord.js');
const ms = require('ms');
/**
* #param {Client} client
*/
module.exports.run = async (client, player, track) => {
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
const row = new ActionRowBuilder()
.addComponents(
new ButtonBuilder()
.setCustomId('loop')
.setEmoji(`🔁`)
.setStyle(ButtonStyle.Secondary),
new ButtonBuilder()
.setCustomId('volume-')
.setEmoji(`🔉`)
.setStyle(ButtonStyle.Danger),
new ButtonBuilder()
.setCustomId('p/p')
.setEmoji(`⏯️`)
.setStyle(ButtonStyle.Secondary),
new ButtonBuilder()
.setCustomId('volume+')
.setEmoji(`🔊`)
.setStyle(ButtonStyle.Success),
new ButtonBuilder()
.setCustomId('skip')
.setEmoji(`⏭️`)
.setStyle(ButtonStyle.Secondary),
);
const embed = new EmbedBuilder()
.setAuthor({
name: `Now Playing`,
iconURL: track.info.requester.displayAvatarURL(),
})
.setColor('Blue')
.setDescription(
`
**Track**: [${track.info.title}](${track.info.uri})
`,
)
const channel = client.channels.cache.get(player.textChannel)
await channel?.send({ embeds: [embed], components: [row] })
};
When I switch to the new song, I want the old message to be deleted. I tried removing some lines but it didn't work.
You could store an object that contains channel IDs and message IDs somewhere else in your code:
let songMessages = {
'channel-id-here':'message-id-here',
'another-channel-id':'another-message-id',
// etc
}
Instead of sending a new message at the bottom of your run() function, you could first check for an existing message in the current channel, and if there is one, you can delete it.
// assuming you're able to access the songMessages object globally
const channel = client.channels.cache.get(player.textChannel)
if(songMessages[channel.id]) {
let oldMessage = await channel.messages.fetch(songMessages[channel.id])
await oldMessage.delete()
}
let message = await channel?.send({ embeds: [embed], components: [row] })
songMessages[channel.id] = message.id
You'll have to make sure you remove the data from the object after the bot stops playing music as well.

How to ban user on pinging someone?

I'm trying to make a discord bot on, when pinging the owner, auto bans the author that pinged the player. The issue is, it bans the player for saying anything, how would I make it that it'd only ban if they pinged the owner?
Here's the code.
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '<#329005206526361610>'
client.once('ready', () => {
console.log("Wary's Defender Bot is up");
});
function getUserFromMention(mention) {
if (!mention) return;
if (mention.startsWith('!')) {
mention = mention.slice(1);
}
if (mention.startsWith('<#329005206526361610') && mention.endsWith('>')) return {
// mention = mention.slice(2, -1),
return: client.users.cache.get(mention)
}
}
client.on('message', _message => {
// if(!_message.content.users.has('#warycoolio')) return;
const user = getUserFromMention(_message.content);
if(user) return;
console.log('found target')
var member = _message.author
var rMember = _message.guild.member(_message.author)
// ban7, 'lol.'
rMember.ban({ days: 7, reason: 'They deserved it'}); {
// Successmessage
console.log('target dead.')
}
});
You can do this by checking _message.mentions.users with .has() and passing in the guild owner's id.
Use .has() instead of checking message content, this will automatically check the Message#mentions collection.
Dynamically get the guild owner's id using Guild#ownerID.
client.on('message', _message => {
if (_message.mentions.users.has(_message.guild.ownerID)) {
_message.author.ban({ days: 7, reason: 'They deserved it'});
}
});
You could just do a quick check to see if the mentions include a mention to the owner of the server, and then ban the user.
client.on("message", _message => {
if (_message.mentions.users.first().id === "owner id") {
message.author.ban()
}
})

Bot readout for who used a command

Wanting to have a readout channel for my bot to keep track of what happens, just like a second console log. Want to be able to have it read out in the message the username of the person who used the command. Any ideas? Also, in a similar note, is there a way to copy the console readout and possibly just paste that instead?
var Scraper = require('images-scraper');
const google = new Scraper({
puppeteer: {
headless: true
},
})
module.exports = {
name: 'image',
description: 'Google image scraper',
async execute(message, args){
const readout = message.guild.channels.cache.find(c => c.name === 'bot-readout');
const image_query = args.join(' ');
if(!image_query) return message.channel.send('Please enter a valid image search.');
const image_results = await google.scrape(image_query, 1);
message.channel.send(image_results[0].url);
readout.send('Image sent');
}
}
I think you want
message.author.username (It gives username who sent the message)
or message.member (it gives user as a guildmember)
Just access the author property of the message object and include it via a template string into the message:
readout.send(`Image sent to ${message.author.username}`);
Ended up doing an embed system in a separate channel on my discord.
const Discord = require('discord.js');
module.exports = {
name: 'suggestionlog',
description: 'logs suggestion',
execute(message){
const readout = message.guild.channels.cache.find(c => c.name === 'bot-readout');
const embed = new Discord.MessageEmbed()
.setColor('FADF2E')
.setTitle(message.channel.name)
.setAuthor(message.author.username, message.author.displayAvatarURL({ dynamic: true }))
.setDescription(message);
readout.send(embed)
.catch((err)=>{
throw err;
});
}
}

How to check a users permissions in a certain server

So I am making a DM command and I want to make it so when the user uses the command it will check the users permissions in a certain server. This is my current code:
bot.on("message", async msg => {
if(msg.channel.type === "dm") {
if(msg.content.startsWith(";announce")) {
if(msg.author.guilds.cache.has("396085313618837526").hasPermission("BAN_MEMBERS")) {
if(!msg.content.split(" ").slice(1).join(" ")) {
msg.reply("I cannot send an announcement without `args`. Please type the command like this: `;announce [MESSAGE]`.")
} else {
let Question1 = new Discord.MessageEmbed()
.setDescription("What channel do you want me to send this in? Please give me the Channel ID (# coming soon).")
msg3 = await msg.channel.send(Question1)
const filter = (m) => m.author.id === msg.author.id
msg.channel.awaitMessages(filter, { max: 1, time: 30000 })
.then(async collected => {
const msg2 = collected.first()
if (!msg2.content) {
msg.reply("You need to give me args. Please retry the command.")
msg2.delete()
} else {
let SendAnnouncement = new Discord.MessageEmbed()
.setTitle("New announcement!")
.setDescription(msg.content.split(" ").slice(1).join(" "))
.setFooter("This announcement has flown in from: " + msg.author.tag)
bot.channels.cache.get(msg2.content).send(SendAnnouncement)
let SuccessfullySent = new Discord.MessageEmbed()
.setDescription("Successfully sent the announcement to <#" + msg2.content + ">!")
msg3.edit(SuccessfullySent)
msg2.delete()
}
})
}
} else {
let error = new Discord.MessageEmbed()
.setDescription("You must have a certain permission to do this. If your roles have just been changed, please type `retry` now so I can check again.")
ERRMSG = await msg.channel.send(error)
const filter = (m) => m.author.id === msg.author.id
msg.channel.awaitMessages(filter, { max: 1, time: 30000 })
.then(async collected => {
const msg2 = collected.first()
if(msg2.content === "retry") {
if(msg.member.hasPermission("BAN_MEMBERS")) {
if(!msg.content.split(" ").slice(1).join(" ")) {
msg.reply("I cannot send an announcement without `args`. Please type the command like this: `;announce [MESSAGE]`.")
} else {
let Question1 = new Discord.MessageEmbed()
.setDescription("What channel do you want me to send this in? Please give me the Channel ID (# coming soon).")
msg3 = await ERRMSG.edit(Question1)
msg2.delete()
const filter = (m) => m.author.id === msg.author.id
msg.channel.awaitMessages(filter, { max: 1, time: 30000 })
.then(async collected => {
const msg2 = collected.first()
if (!msg2.content) {
msg.reply("You need to give me args. Please retry the command.")
msg2.delete()
} else {
let SendAnnouncement = new Discord.MessageEmbed()
.setTitle("New announcement!")
.setDescription(msg.content.split(" ").slice(1).join(" "))
.setFooter("This announcement has flown in from: " + msg.author.tag)
bot.channels.cache.get(msg2.content).send(SendAnnouncement)
let SuccessfullySent = new Discord.MessageEmbed()
.setDescription("Successfully sent the announcement to <#" + msg2.content + ">!")
msg3.edit(SuccessfullySent)
msg2.delete()
}
})
}
} else {
let error2 = new Discord.MessageEmbed()
.setDescription("I still could not find your permissions. Please retry when you have the correct permissions.")
ERRMSG.edit(error2)
msg2.delete()
}
}
})
}
}
}
})
This gives me the error:
(node:347) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'cache' of undefined
(node:347) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:347) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
This just throws this error but I am not sure how I can check the actual permissions in this discord server. How can I manipulate this feature into my Discord Bot?
Well, first of all, you would want to get the guild object of the guild you're referring to, and obviously check if that guild even exists. something that could be done using:
const guildObject = client.guilds.cache.get('place guild id here'); // gets the guild object of the id provided
if (!guildObject) return console.log('Guild could not be found!'); // Would console log in the case that the guild you've provided does not exist.
From there on, we could use the guild object we've found to check if the message author actually exists in this guild, which can be done using
const memberObject = guildObject.member(message.author.id)
if (!memberObject) return console.log('User could not be found in the provided guild!');
Finally, we could determine whether or not the user has the wanted permissions using:
if (!memberObject.hasPermission('Permission here')) return console.log('User does not have the corresponding permissions needed!')
The error you get comes from this line:
if(msg.author.guilds.cache.has("396085313618837526").hasPermission("BAN_MEMBERS"))
What are you checking with this line of code? If the author has permission?
You can check if the author has permission by doing:
if(msg.guild.member(msg.author).hasPermission("BAN_MEMBERS"))

I can't user guild for my bot (I'm at the beginning with discord.js)

When i try to run this code:
bot.sendMessage({
to: channelID,
message: message.guild.name
});
I got Cannot read property 'name' of undefined.
This error happen always i try to use guild.
Here's my full bot code:
var Discord = require('discord.io');
var logger = require('winston');
var auth = require('./auth.json');
var verificationUser;
// Configure logger settings
logger.remove(logger.transports.Console);
logger.add(new logger.transports.Console, {
colorize: true
});
logger.level = 'debug';
// Initialize Discord Bot
var bot = new Discord.Client({
token: auth.token,
autorun: true
});
bot.on('ready', function (evt) {
logger.info('Connected');
logger.info('Logged in as: ');
logger.info(bot.username + ' - (' + bot.id + ')');
});
bot.on('message', function (user, userID, channelID, message, evt) {
if (message.substring(0, 21) == '<#' + bot.id + '>') {
var args = message.substring(22).split(' ');
var cmd = args[0];
switch(cmd) {
case 'help':
bot.sendMessage({
to: channelID,
message: "Istruction for make the verification:\n1 - Mention me and write 'verification'.\n2 - Mention me your Mazebert id.\n3 - Play a suicide play without build tower, just waiting the death.\n4 - Mention me and text 'check'.\n5 - Finish!"
});
break;
case 'verification':
bot.sendMessage({
to: channelID,
message: "<#"+ userID + ">For starting the verification you have to write your Mazebert id. You can take it in your profile, is the numerical code in the url."
});
bot.sendMessage({
to: channelID,
message: message.guild.name
});
verificationUser = userID;
break;
}
}
});
I'm at the start with discord bot in js so i can't understand why i get this error.
The proper way of using on message is like this
bot.on("message", async message => {
and not
bot.on('message', function (user, userID, channelID, message, evt) {
As you are specifying extra parameters which would return undefined if you try to access them later on.
And you can check the properties of the message object here

Resources