how to implement my unban code into a working code - discord.js

how can I implement my code to an actual code?
I wanted to unban a user
the code that I used for the unbanning is:
const id = interaction.options.get('target')?.value;
guild.members.unban(id);
how can I implement this to a code that executes this command when a user says something like:
":unban #user"

You should just put it in an message event (messageCreate in v13). You can then put your code in there. You can't however use the interaction if you want it to start with .unban.
client.on("message", async msg => {
if(msg.content.startsWith(".unban")) {
const [, ...args] = msg.content.split(/ +/g)
const user = msg.mentions.users.first() || await client.users.fetch(args[0])
if(!user) return msg.channel.send("No user found")
msg.guild.members.unban(user.id || user)
}
})
Warning: This is incomplete, untested code. It may have some problems. If you have any, just comment below.

Related

Bot - DisTubeError [INVALID_TYPE]: Expected 'Discord.Message'

I made a music bot, but I'm looking to turn this into interactions, but I'm having a problem calling the play function.
With "message" it works, but with "interaction" it doesn't. I tried to pass on some information, I searched but I couldn't.
I even found a different way, but it didn't work.
The error returned is this:
DisTubeError [INVALID_TYPE]: Expected 'Discord.Message' for 'message', but got undefined (undefined)
Play.js
const { SlashCommandBuilder } = require('#discordjs/builders');
module.exports = {
data: new SlashCommandBuilder()
.setName('play')
.setDescription('Play a song!')
.addStringOption(option => option.setName('song').setDescription('Enter name of the music.')),
async execute (interaction, client){
// if(!interaction.member.voice.channel) return interaction.reply("Please, join a voice channel!");
const music = interaction.options.getString('song');
if(!music) return interaction.reply("Please, provide a song!");
await client.distube.play(interaction, music);
// await client.distube.playVoiceChannel(
// interaction.member.voice.channel,
// music,
// {
// textChannel: interaction.channel,
// member: interaction.member
// }
// );
}
}
DisTube, at the time of this question being posted, doesn't support slash commands, and it looks like the creator doesn't have any plans on supporting it officially. As a workaround, you can use the Distube#playVoiceChannel method instead of the Distube#play method, like so:
await client.distube.playVoiceChannel(interaction.member.voice.channel, music);
But before you do any of that, it looks like interaction is undefined - that's probably a problem with your command handler, so look there.
Edit: Also docs for Distube#playVoiceChannel if you're interested

Discord.js slash commands type 5

So I have been developing a bot recently and I have implemented the slash commands into said bot. I have come across the need for a type 5 command "response" but I can't seem to find good documentation on the slash commands. I can't seem to make it "stop thinking". Any help would be appreciated!
EDIT: I found that you need to edit the interaction response (https://discord.com/developers/docs/interactions/slash-commands#interaction-response) but I'm not using webhooks I'm using a bot and I don't want to have to get another npm library if I don't have to. So how do I edit my interaction?
I have solved this, if you want to know how I did here is some code.
if your interaction responder looks like this:
if (interaction.data.name === 'whatever') {
whatever.whatever (interaction)//i am using a command handler to put
//the actual event into a different file
}
and your "interaction message sender" looks like this: (notice it's type 5)
module.exports.whatever = (interaction) => {
client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 5
}
})
};
then it will say "{botname} is thinking" with a little ellipses, and after 15 minutes if nothing happens it will fail the interaction. If you want to make it "stop thinking" you have to edit the message. I am using the axios npm library (https://www.npmjs.com/package/axios) and if you just put in this code it should edit your interaction message. this goes at the top of your file with your requirements:
const axios = require('axios')
const appId = ''//bot id goes here
and somewhere near the bottom of your file maybe put in this:
const editInteraction = async (client, interaction, response) => {
const data = typeof response === 'object' ? { embeds: [ response ] } : { content: response };
const channel = await client.channels.resolve(interaction.channel_id);
return axios
.patch(`https://discord.com/api/v8/webhooks/${appId}/${interaction.token}/messages/#original`, data)
.then((answer) => {
return channel.messages.fetch(answer.data.id)
})
};
then you will have the basic code structure to edit the message, now you just need to edit the message. to do that, in your code, do this:
if (interaction.data.name === 'whatever') {
whatever.whatever (interaction).then(m => {
editInteraction(client, interaction, '>:(')//this will actually edit the message so
//instead of " >:( " put in what you want to edit you message to be
})
}
then you can run that command and it will say the bot is thinking then after whatever event you want to run it will edit it to say whatever!

Discord.js How can I edit previous bot's message?

so I am trying to make a ROSTER command. The command is $roster add/remove #user RANK. This command basically should edit a previous bot's message (roster) and add a user to the roster to the RANK in the command... This is my code so far, but I haven't managed to make the roster message and the editing part of it and the RANK system. If someone could help that would be very amazing!
//ROOSTER COMMAND
client.on('message', async message => {
if (message.content.startsWith(prefix + "roster")) {
if (!message.member.hasPermission('ADMINISTRATOR')) return message.channel.send('You do not have that permission! :x:').then(message.react(':x:'))
const args = message.content.slice(prefix.length + 7).split(/ +/)
let uReply = args[0];
const user = message.mentions.members.first()
if(!uReply) message.channel.send("Please use `add` or `remove`.")
if(uReply === 'add') {
if(!user) return message.channel.send("Please make sure to provide which user you would like to add...")
message.channel.send(`you are adding **${user.displayName}** from the roster.`)
} else if(uReply === 'remove') {
if(!user) return message.channel.send("Please make sure to provide which user you would like to add...")
message.channel.send(`you are removing **${user.displayName}** from the roster.`)
}
}})
Sounds like the .edit() method is what you want.
Example from the docs:
// Update the content of a message
message.edit('This is my new content!')
.then(msg => console.log(`Updated the content of a message to ${msg.content}`))
.catch(console.error);
To edit your bots previous message, you need to have a reference of the message you want to edit. The returned reference is a promise so do not forget to use await keyword. you can then use .edit() function on the reference to update you msg.
const msgRef = await msg.channel.send("Hello");
msgRef.edit("Bye");

SyntaxError: Unexpected Token ':'

So it's my first ever time coding and i'm creating a discord bot. It's all been going fine until I try to run the bot.js file on commmand line (using "node bot.js")
But It just comes up with a bunch of errors.
My Code:
const Discord = require('discord.js');
const client = new Discord.Client();
const auth = require('./auth.json');
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`)
});
client.login(auth.token);
client.on('message', msg => {
if (msg.content === 'ping') {
msg.reply('pong');
}
});
Question: Will you re-post you error picture? When you click on it it says the page doesn't exist.
PLEASE READ ALL BEFORE MAKING CHANGES!
First (Bad) Guess: But without the picture, I would guess (and this is not a good guess) that it's because "client.login(auth.token)" isn't at the bottom. Another guess is that ".content ===" does nothing. You should try and remove ".content" to see if it then works.
Here is your code with just that change:
const Discord = require('discord.js');
const client = new Discord.Client();
const auth = require('./auth.json');
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}`)
});
client.on('message', msg => {
if (msg.content === 'ping') {
msg.reply('pong')
}
});
client.login(auth.token);
Logging bot is ready: The is also some other things I think you should change, this changing "client.user.tag" to "client.user.username" to instead show the bot's username. Another thing is "msg.content" I'm pretty sure this does nothing, and should be changed to just "===", there are some other ones, but that's my favorite one because it's the least amount of characters and easiest to type.
Here is your code with all of these changes:
const Discord = require('discord.js');
const client = new Discord.Client();
const auth = require('./auth.json');
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}`)
});
client.on('message', msg => {
if (msg === "ping") {
msg.reply('pong')
}
});
client.login(auth.token);
Token (& patrik's answer): (No hate to patrik) What patrik says that putting your token in the actual script will help (It won't, and makes it easier to hack), now while I do this, I really don't care if my bot gets hacked, it's in one server. He/She also says that the token error means that discord.js can't get the token, this is a node.js error, not a discord.js error. You probably messed up on writing a piece of code, that is likely in "auth.json". You should probably re-run through your files before doing any of these changes.
A auth/config/token (token file) .json file should look like this:
{
"token":"TOKEN-HERE"
}
And then it should be used by doing
const auth|config|token = require(./auth|config|token.json);
client.login(auth.token);
I hope this helps with coding your bot!
It's because the node.js version is not updated to be compatible with the new discord.js version
First, install old version of discord.js in console type
npm i discord.js.old#11.6.4
In your script change
this:
const Discord = require('discord.js')
To:
const Discord = require('discord.js.old')
Glad to see you are into making bots too!
I would firstly suggest replacing all those "client" words with "bot"
The unexpected token might be because of that above mentioned thing or that your token is not just simply there.
Remove line:
client.login(auth.token);
and replace it with:
bot.login('YOUR-TOKEN-HERE');
You can check what if your token at the Discord Developer page

How to run code with await in filter/collect code

I'm trying to make a confirmation portion of my command where if you activate the command, you need to say "yes" before the code activates. The reoccurring problem is that the code right after the message that says
Confirmed... Please wait.
After this, it completely skips over the code and does nothing. When I was writing the code in VSC, the async portion of the code wasn't highlighted with yellow, but more of a darker yellow.
I've tried removing this portion of the code
const async = async () => {
But the code with await cannot run unless it's connected to async.
I've tried changing how the async is ran.
async () => {
Still the same result.
Removing the beginning async code will also just result in the command breaking.
I've placed the big chunk of code outside of the then(collected code, but after a few seconds of waiting when the command activates, it immediately runs, then brings up a value error. But I want it so that code activates when the author says "Yes"
async run(message, args){
if (message.channel instanceof Discord.DMChannel) return message.channel.send('This command cannot be executed here.')
let replyMessage = message.reply('Please make sure that my integration role "Synthibutworse" is above the default role used for this server. Is this correct? [Reply with "YES"] if so. Will expire in 20 seconds...');
let filter = msg => msg.author.id == message.author.id && msg.content.toLowerCase() == 'yes';
message.channel.awaitMessages(filter, {max: 1, time: 20000}).then(collected => {
message.reply('Confirmed... Please wait.');
const async = async () => {
if(!message.member.guild.me.hasPermission(['MANAGE_WEBHOOKS'])) return message.channel.send('I don\'t have the permissions to make webhooks, please contact an admin or change my permissions!')
if(!message.member.guild.me.hasPermission(['MANAGE_ROLES'])) return message.channel.send('I don\'t have the permissions to make roles, please contact an admin or change my permissions!')
if (!message.member.hasPermission(['MANAGE_WEBHOOKS'])) return message.channel.send('You need to be an admin or webhook manager to use this command.')
if (!message.member.hasPermission(['MANAGE_ROLES'])) return message.channel.send('You need to be an admin or role manager to use this command.')
const avatar = `https://cdn.discordapp.com/attachments/515307677656678420/557050444954992673/Generic5.png`;
const name2 = "SYNTHIBUTWORSE-1.0WOCMD";
let woaID = message.mentions.channels.first();
if(!woaID) return message.channel.send("Channel is nonexistant or command was not formatted properly. Please do s!woa #(channelname)");
let specifiedchannel = message.guild.channels.find(t => t.id == woaID.id);;
const hook = await woaID.createWebhook(name2, avatar).catch(error => console.log(error))
await hook.edit(name2, avatar).catch(error => console.log(error))
message.channel.send("Please do not tamper with the webhook or else the command implied before will no longer function with this channel.")
var role = message.guild.createRole({
name: `Synthibutworse marker v1.0`,
color: 0xcc3b3b,}).catch(console.error);
specifiedchannel.send("Created role...");
if(message.guild.roles.name == "Synthibutworse marker v1.0") {
role.setMentionable(false, 'SBW Ping Set.')
role.setPosition(1)
role.setPermissions(['CREATE_INSTANT_INVITE', 'SEND_MESSAGES'])
.then(role => console.log(`Edited role`))
.catch(console.error)};
message.channel.send("Role set up...");
const sbwrID = message.guild.roles.find(`Synthibutworse marker v1.0`);
let specifiedrole = message.guild.roles.find(r => r.id == sbwrID.id)
message.channel.send('Created Role... Please wait.');
message.guild.specifiedchannel.replacePermissionOverwrites({
overwrites: [
{
id: specifiedrole,
denied: ['SEND_MESSAGES'],
allowed: ['VIEW_CHANNEL'],
},
],
reason: 'Needed to change permissions'
});
var bot = message.client
bot.on('message', function(message) { {
if(webhook.name == `Synthibutworse marker`) return
if(message.channel.id == webhook.channelID) return
{let bannedRole = message.guild.roles.find(role => role.id === specifiedrole);
message.member.addRole(bannedRole)};
}});
}});
}};
module.exports = woa;
I expect the command to run with the async and continue with the code when the message author says "yes", and doesn't stop at the Please wait. message.
What actually happens is the code doesn't run right after the Please wait message.
In your current code, you're declaring an async function but never calling it. That's why the code is never run and why VSC darkens its name.
Solution:
Define your awaitMessages(...)'s .then() callback as async:
.then(async collected => {
// do async stuff
});
For future reference, if you need to use async code somewhere that you can't define a function as async, use the following setup:
(async function() {
// do async stuff
})();

Resources