Checking If There Is A Channel Containing A Word? - javascript

For some reason which I don't know, my code is not realising that there is a channel that contains the message senders username.
To use this bot, you DM the bot, and then it creates a channel that is named your tag. An example, is that my discord tag is Llama#0729 and it creates a channel named llama0729. The issue is that when the code runs, before making the channel it checks to make sure that there is no channel that contains any part of the user's username. It always makes a channel though.
if (msg.channel.type == "dm") {
if (!client.guilds.cache.get('720571393636434031').channels.cache.find(channel => channel.name == msg.author.username.toLowerCase())) {
client.guilds.cache.get('720571393636434031').channels.create(msg.author.tag, {type: 'text'}).then((channel) => {
channel.setParent('778216162403942401');
});
};
} else {
console.log('A Channel For ', msg.author.tag, 'Has Already Been Made.');
return;
};

When you're checking to see if any channels exist, you should compare their tag not their username. I've slightly modified your code and also removed the # from their tag.
var newChannelName = msg.author.tag.replace("#", "").toLowerCase();
if (msg.channel.type == "dm") {
if (!client.guilds.cache.get('720571393636434031').channels.cache.find(channel => channel.name == newChannelName)) {
client.guilds.cache.get('720571393636434031').channels.create(newChannelName, {type: 'text'}).then((channel) => {
channel.setParent('778216162403942401');
})
.catch(error => {
console.log(error);
});
}
else
{
console.log('A Channel For ' + newChannelName + ' Has Already Been Made.');
return;
}
}

Related

Having an issue with randomization in Discord JS

so i've been trying to make it so that every time the user sends a message there's a 50/50 chance that the bot reacts with an emoji, however the number is only picked every time i restart the bot. any ideas on how i can make it pick the number every time the command is triggered?
i tried to use setInterval but that didn't work so idk
here code;
const userID = "user id"
let random = Math.floor(Math.random()*2)
client.on('messageCreate', (message) => {
if(random === 1) {
if(message.author.id === userID) {
message.react('emoji');
}
}
});
Simply, define the random variable inside the messageCreate event.
Example:
const userID = "user id";
client.on('messageCreate', (message) => {
let random = Math.floor(Math.random() * 2);
if (random === 1) {
if (message.author.id === userID) {
message.react('emoji');
}
}
});
If you define random inside of the messageCreate event it means that a new random number is generated each time the even is called.
const userID = "user id"
client.on('messageCreate', (message) => {
let random = Math.floor(Math.random()*2)
if(random === 1) {
if(message.author.id === userID) {
message.react('emoji');
}
}
});
As Tyler2P has already shown an example, just wanted to explain why this works.
Thanks

Discord.js v13 why is my tempmute command not working?

I've made a tempmute command for my discord bot and it almost works. It has quite a few foolproofing measures like preventing the bot from muting themselves, not working if the time isn't specified and such. I am using the npm ms package to deal with the mute duration (https://www.npmjs.com/package/ms). when instead of specifying an amount of time I type in gibberish it works as intended and replies with the correct message. The problem is that when I type in a 100% correct command it responds asthough I didn't specify the time correctly instead of muting the user for that amount of time. here's how it looks. Any ideas as to why that is?
My code is here:
const ms = require('ms');
const { Permissions, MessageActionRow, UserFlags } = require('discord.js');
module.exports = {
name: 'tempmute',
description: "Temporarily mutes a user",
execute(message, args)
{
const target = message.mentions.members.first();
let muteRole = message.guild.roles.cache.find(role => role.name === "muted");
if(message.member.permissions.has(Permissions.FLAGS.MODERATE_MEMBERS))
{
if(target)
{
let memberTarget = message.guild.members.cache.get(target.id);
if(target.id == 'myBotsID')
{
message.reply("I can't mute myself.")
}
else if(message.member == target)
{
message.reply("You can't mute yourself!")
}
else if(memberTarget.permissions.has(Permissions.FLAGS.MODERATE_MEMBERS))
{
message.channel.send(`<#${memberTarget.user.id}> has been muted for ${ms(ms(args[1]))}`);
}
else
{
if(!args[1])
{
return message.reply("Time not specified.")
}
else
{
let time = ms(args[1])
memberTarget.roles.add(muteRole.id);
try {
message.reply("<#" + memberTarget.user.id + ">" + "has been muted for " + ms(ms(args[1])).catch(console.error))
setTimeout(function () {
memberTarget.roles.remove(muteRole.id);
}, time);
} catch (err) {
message.reply("Can't transform that into milliseconds `"+args[1]+"`")
return
}
}
}
}
else
{
message.reply("You have to mention a valid member of this server.")
}
}
else
{
message.reply("You can't use that.")
}
}
}
Okay so I figured it out. Here's the problematic code:
try {
message.reply("<#" + memberTarget.user.id + ">" + "has been muted for " + ms(ms(args[1])).catch(console.error))
setTimeout(function () {
memberTarget.roles.remove(muteRole.id);
}, time);
} catch (err) {
message.reply("Can't transform that into milliseconds `"+args[1]+"`")
return
}
IDK why but the ".catch(console.error))" (which is a leftover code and shouldn't be there in the first place) caused it to behave differently aka treat everything as an incorrectly specified time and returned the corresponding message instead of muting the member for the specified amount of time. After removing that short part of code everything is working as intended.

Reason after blacklisting command Discord.js

I want to add a reason to my blacklists (with the command !blacklist {userid} {reason}) which are visible in the embeds below like .addField ("💬 Reason:", somecode) how can I fix this?
if (command === "blacklist") {
if(!config["allowed-users"].includes(message.member.id)) return;
const user = client.users.cache.get(args[0]);
if(!user) {
return message.channel.send("This user does not exist")
}
if(blacklist.has(user.id)) {
return message.channel.send("This user is already on the blacklist")
}
blacklist.set(user.id, 'blacklisted');
let set = db.fetch(`g_${message.guild.id}`);
var embed = new Discord.MessageEmbed()
.setTitle(":warning: Blacklisted :warning:")
.setColor('#fc5a03')
.addField("👮 Moderator:", message.author.tag)
.addField("👤 User:", user.username)
.addField("🆔 User ID:", user.id)
.addField("🕒 Blacklisted on:", message.createdAt)
.setFooter("© 2020 - 2021 GlobalChat", "https://cdn.discordapp.com/avatars/759021875962576916/cc32b2b08fdd52ae86294516d34532c5.png?size=128")
.setThumbnail(user.avatarURL({ dynamic:true }))
.addField("Unblacklist?", "Please contact <#267818548431290369> or <#331736522782932993>");
client.guilds.cache.forEach(g => {
try {
client.channels.cache.get(db.fetch(`g_${g.id}`)).send(embed);
} catch (e) {
return;
}
});
}
First you'll want to check if there is no reason, this can be simple done by checking, for both approaches, if the second argument is undefined, like so
if (args[1] === undefined) {
const reason = "No reason.";
}
This solution will work for both approaches, since if the second argument is undefined there can be no more after it
You could take reason as an argument.
Inside the command add
const reason = args[1];
OR if you wanted to have the rest of the blacklist args dedicated to the reason you could add something along the lines of
let reason = ""
for (let i = 1; i < args.length; i++) {
// It's very important that i starts as 1, so we do not take the first argument into account for the reason
reason += args[i];
}
And then you can add to the embed
.addField("💬 Reason:", reason);
If you went with the first approach, the blacklist command would work like this
!blacklist 012345678910111213 the_reason_here
// or
!blacklist 012345678910111213 reason
The limitation to this approach is that a multi word reason isn't very intuitive.
If you went with the second approach though, the blacklist command would work like this
!blacklist 012345678910111213 The reason the user was banned and it can go on and on and on as long as the writer wants
You'll want to fetch the reason in the same way that you fetched the user id, like this:
const reason = args[1];
After that, in order to make sure that the reason doesn't show as undefined, you'll want to add a check in the form of an if statement, like this:
if (!reason) {
reason = "No reason";
}
After that, add .addField("💬 Reason:", reason) in the position of fields you want it to be.
Your code should look something like this:
if (command === "blacklist") {
if (!config["allowed-users"].includes(message.member.id)) return;
const user = client.users.cache.get(args[0]);
const reason = args[1];
if (!user) {
return message.channel.send("This user does not exist")
}
if (blacklist.has(user.id)) {
return message.channel.send("This user is already on the blacklist")
}
if (!reason) {
reason = "No reason";
}
blacklist.set(user.id, 'blacklisted');
let set = db.fetch(`g_${message.guild.id}`);
var embed = new Discord.MessageEmbed()
.setTitle(":warning: Blacklisted :warning:")
.setColor('#fc5a03')
.addField("👮 Moderator:", message.author.tag)
.addField("👤 User:", user.username)
.addField("🆔 User ID:", user.id)
.addField("🕒 Blacklisted on:", message.createdAt)
.addField(("💬 Reason:", reason)
.setFooter("© 2020 - 2021 GlobalChat", "https://cdn.discordapp.com/avatars/759021875962576916/cc32b2b08fdd52ae86294516d34532c5.png?size=128")
.setThumbnail(user.avatarURL({
dynamic: true
}))
.addField("Unblacklist?", "Please contact <#267818548431290369> or <#331736522782932993>");
client.guilds.cache.forEach(g => {
try {
client.channels.cache.get(db.fetch(`g_${g.id}`)).send(embed);
} catch (e) {
return;
}
});
}

How can you cancel your whole Discord Application

So I'm creating a Discord Application bot, Ban appeal Application that works within DM's only. I type the command p!apply and start the application, however whenever I try to cancel the application by typing cancel it only replies and does not actually cancel the whole form.
Here's my code:
let userApplications = {}
client.on("message", function(message) {
if (message.author.equals(client.user)) return;
let authorId = message.author.id;
if (message.content === prefix + "apply") {
if (!(authorId in userApplications)) {
userApplications[authorId] = { "step" : 1}
message.author.send("**__Team PhyZics Discord Ban Appeal Form__** \n If you're applying to get unbanned from our server, please fill this application out. We do not accept all applications, so take this application seriously and take your time when filling this out. \n \n - If you want to cancel this application please type `cancel`");
message.author.send("**Question 1: Which server did you get banned from?**");
}
} else {
if (message.channel.type === "dm" && authorId in userApplications) {
if (message.content.toLowerCase() === 'cancel') {
return message.author.send('Application Cancelled');
}
let authorApplication = userApplications[authorId];
if (authorApplication.step == 1 ) {
authorApplication.answer1 = message.content;
message.author.send("**Question 2: Why did you get banned/What reason did you get banned for?**");
authorApplication.step ++;
}
else if (authorApplication.step == 2) {
authorApplication.answer2 = message.content;
message.author.send("**Question 3: Why do you want to get unbanned?**");
authorApplication.step ++;
}
else if (authorApplication.step == 3) {
authorApplication.answer3 = message.content;
message.author.send("**Question 4: Any questions or concerns? If not, please type `no`.**");
authorApplication.step ++;
}
else if (authorApplication.step == 4) {
authorApplication.answer4 = message.content;
message.author.send("Your application has been submitted, please be patient and do not ask any staff member regarding to your ban appeal.");
client.channels.cache.get("790376360848785419")
.send(`**${message.author.tag}'s Application** \n **Q1**: ${authorApplication.answer1} \n **Q2:** ${authorApplication.answer2} \n **Q3:** ${authorApplication.answer3} \n **Q4:** ${authorApplication.answer4} `);
delete userApplications[authorId];
}
}
}
});
enter image description here
You're getting this problem because you're only returning a message Application cancelled without actually removing the user from your userApplications object.
To fix this, all you have to do is delete the entry from your object when the user cancels, like so:
if (message.content.toLowerCase() === 'cancel') {
delete userApplications[authorId];
return message.author.send('Application Cancelled');
}

In discord.js, how could i create a command that displays the avatar of a user tagged, or if not tagged - my avatar?

client.on("message", msg => {
if (msg.content === `${prefix}pfp`) {
var users = msg.mentions.users.first() || msg.author;
msg.channel.send(users.displayAvatarURL());
}
})
Usually, this code only sends the display of the message author's avatar, but not the person who was tagged in the command.
client.on("message", msg => {
if (msg.content === `${prefix}pfp`) {
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
var users = msg.mentions.users.first() || msg.author;
msg.channel.send(users.displayAvatarURL());
}
})
You're using msg.content which is the overall content of the message. If you mention someone, the content will be ${prefix}pfp <#a_user's_id> instead of ${prefix}pfp which will then not call the command.
Try instead to use msg.startsWith() like shown below:
client.on("message", msg => {
if (msg.content.startsWith(`${prefix}pfp`)) {
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
var users = msg.mentions.users.first() || msg.author;
msg.channel.send(users.displayAvatarURL());
}
})
This will call the function if it starts with ${prefix}pfp rather than it containing such. Which will allow them to mention someone.

Categories

Resources