Discord.js - Delete all channel by running Discord-Bot without a command - discord.js

Hey i need for a project a tool to delete all channsl on a Discordserver via a Discord.js Bot.
i got one with handlers and this is my "event code" but dosent work.
Discord.js v14
const client = require("../../index");
module.exports = {
name: "blacksheep"
};
client.on("ready", () => {
var server = Client.guilds.get('1045245227264397382');
for (var i = 0; i < server.channels.array().length; i++) {
server.channels.array()[i].delete();
}})
i dont find the right way to get it worked. thx <3
Then i start the bot all Channels should be deletet without any command.

You need to include error messages or what the results of running this code was for us to actually help you, but for now I'm going to assume that everything in your bot and bot event handlers is working except for the last three lines that loop through the channels and delete them. If that's the case, then you just need to change those lines to something like this (replace your for-loop block with this):
server.channels.cache.forEach((channel) => {
channel.delete();
});
This accesses the server's channel cache, which is a collection, and so it uses the collection's forEach function to loop through all the channels, and then calls each of the channels' delete() functions to delete them.
Note that you may experience severe ratelimiting when doing this, because Discord has heavy ratelimits on requests to server channels.

Related

How to (and is it possible to) make link markup work in a discord bot message?

What I'm trying to achieve is simple:
send a message like links: [link1](https://example.com/1), [link1](https://example.com/2) via a bot
get it displayed as "links: link1, link1"
In a ephemeral follow up, it works as expected:
const content = "links: [link1](https://example.com/1), [link1](https://example.com/2)"
await interaction.followUp({
ephemeral: true,
content,
})
But when I send this to a public channel like this:
await channel.send(content)
I'm getting it as plain text (links: [link1](https://example.com/1), [link1](https://example.com/2)) except the links are clickable.
Is it possible to get the same result as in an ephemeral message?
I've checked the permissions, there's only "embed" links (which sounds like "allow links in embeds", and not "allow links in messages) and it is enabled anyway on server for everyone, for the bot and in the channel. So what am I missing here?
PS Here they say that "it's only possible if the message was sent with webhook though", but I'm not quite sure what does this mean (can this be different for a public and an ephemeral message?)
You cannot use hyper links in normal messages sent by a bot. You need to use a Webhook. Considering you're using discord.js, see this guide on their documentation. When using something like that it will work as expected
const { WebhookClient } = require('discord.js');
const webhookClient = new WebhookClient({ url: "WEBHOOK_URL" });
webhookClient.send({
content: "[Hello world](https://github.com)",
username: "Webhook Username",
});
Otherwise you may use embeds and send one of these with your bot and the content you wish to have.
Right, so I've found a solution based on suggestion by Krypton. As an embed doesn't look nice and manual creation of a webhook is not an option for me, I've found that I can create a webhook on the go and use it.
After some testing, I've figured that such webhooks are also permanent (although they can be found in another part of settings than the manually created ones); they should be deleted as there's a limit of 15 webhooks – an attempt to create more fails (with DiscordAPIError[30007]: Maximum number of webhooks reached (15)).
Instead of doing
await channel.send(content)
I've put
// a guard, TypeScript requires us to be sure
if(channel instanceof TextChannel) {
const webhook = await channel.createWebhook({
// a message from a webhook has a different sender, here we set its name,
// for instance the same as the name of our bot (likewise, we can set an avatar)
name: "MyBot",
})
await webhook.send(content)
await webhook.delete()
}
This seems to be a minimal code change to get the links working.

How can I change the volume of my discord bot in discord.js V13?

I am creating a Discord Bot and I am getting along quite good, however, I am now trying to implement a command for changing the volume of the bot and I can't figure out how to do it. All I am finding on the Internet is for V12 or below, but I am using the new version of discord.js - V13. Here is what I have for playing the music:
const connection = await connect(channel);
const audioPlayer = createAudioPlayer();
const stream = createStream(song.url);
const resource = createAudioResource(stream, {
inputType: StreamType.Arbitrary,
});
stream.on('error', () => playQueue(guild, channel));
connection.subscribe(audioPlayer);
audioPlayer.play(resource);
This all works but does one of you know how to change the volume?
Side question:
I am also trying to make a /seek <time> to jump to any place in the video and neither am I making any progress with that.
I fixed it now, thanks to Leau:
The problem I had was that I was trying to set resource.volume to the value, whereas I actually would have had to do it via resource.volume.setVolume() with the #discordjs/opus package installed and the option on resource for inlineVolume set to true

Avoid rate limit for changing voice channel name discord js 13

I'm trying to create a slash command using discord.js v13 to change the names of voice channels. I am using this code to do this :
module.exports = {
data: new SlashCommandBuilder()
.setName('name')
.setDescription('Set name for your voice channel')
.addStringOption(option => option.setName('name').setDescription('Enter your name').setRequired(true)),
async execute(interaction) {
const name = interaction.options.getString('name');
if (!interaction.member.voice.channel) await interaction.reply('Error not in a voice channel!');
else {
await interaction.member.voice.channel.setName(name);
await interaction.reply('Done!');
}
},
};
This code is fine and makes the job done. But as you know I can change the voice channel's name only 2 times per 10 minutes because of the limit rate. So if a user tries to change the voice channel's name for the third time, I won't get any error on the console, and discord js will queue this request for later and will do it after 10 minutes. But the user gets this error on discord: This interaction failed.
I want to check if there was a rate limit for my request, and if is, don't send the request and just reply to the user. Is this possible?
There is no inherent functionality that is able to handle the situation in the way you want it to, but the problem is soluble using regular old JavaScript. For example, you could use an integer to indicate how many times the command has been used and use setTimeout() to decrement it 10 minutes after the command was called. That way you can check if the int is equal to 2 in which case you skip the .setName().
There are undoubtedly other ways to implement the same or similar behavior, but, to answer your question, unfortunately the discordjs/voice library does not provide any simple way to do it.

How to not send bots message edit discord.js

I have a message edit log but I want to stop sending the log if a mobs message was updated, I tried a few codes like
if(bot.oldMessage.content.edit()){
return;
}
It showed and error
cannot read property 'edit' of undefined
I then removed edit then content was undefined. The code for the message update is below.
The Code
module.exports = async (bot, oldMessage, newMessage) => {
let channels = JSON.parse(
fs.readFileSync('././database/messageChannel.json', 'utf8')
);
let channelId = channels[oldMessage.guild.id].channel;
let msgChannel = bot.channels.cache.get(channelId);
if (!msgChannel) {
return console.log(`No message channel found with ID ${channelId}`);
}
if (oldMessage.content === newMessage.content){
return;
}
let mEmbed = new MessageEmbed()
.setAuthor(oldMessage.author.tag, oldMessage.author.displayAvatarURL({dynamic: true}))
.setColor(cyan)
.setDescription(`**Message Editied in <#${oldMessage.channel.id}>**`)
.addField(`Before`, `${oldMessage.content}`)
.addField(`After`, `${newMessage.content}`)
.setFooter(`UserID: ${oldMessage.author.id}`)
.setTimestamp()
msgChannel.send(mEmbed)
}
How would I stop it from sending the embed if a bots message was updated.
Making a really simple check will resolve this issue. In Discord.js there is a user field that tells you if the user is a bot or not.
In fact, it is really recommended you add this in the "onMessage" part of your code as it stops other bots from using your bot, this is to make sure things are safe and no loopbacks/feedbacks happen, either way, you don't want a malicious bot taking advantage of your bot, which can get your bot in trouble too.
Here is what you want to do;
if (message.author.bot) return;
What this code specifically does is check if the message's author is a bot, if it returns true, it will break the code from running, if it returns a false, the code continues running.
You can do the same if you want to listen to bots ONLY by simply adding a exclamation mark before the message.author.bot like this;
if (!message.author.bot) return;
It is also possible to see what other kinds of information something holds, you can print anything to your console. For example, if you want to view what a message object contains, you can print it into your console with;
console.log(message) // This will show everything within that object.
console.log(message.author) // This will show everything within the author object (like ID's, name, discriminators, avatars, etc.)
Go ahead and explore what you can do!
Happy developing! ^ -^
That is really easy to do. All you need to do is check if the author of the message ist a bot and then return if true. You do that like this
if (oldMessage.author.bot) return;

Creating a Discord bot to notify people when to certain text on a website has changed

const Discord = require('discord.js');
const bot = new Discord.Client();
const token = '';
bot.on('ready', () =>{
console.log('This bot is online');
})
bot.on('message', msg=>{
if(msg.content === "?rates"){
msg.reply('.')
}
})
bot.login(token);
This is what I have so far it is very basic, I understand, I'm just trying to get some sort of idea how to process. What I want is as soon as a website gets updated or changed. I would like it to tag everyone and in a certain channel and specifies what has changed. I know this will be a long process but I'm in for the ride :) would appreciate any help.
You need a webhook on the website and listen to it with your bot, if you have control over the site, this may help you, otherwise you could look if the site has one or perhaps ask an owner.
A probably working but not very nice (and not very clean) solution would be to save the text of the website every 5 seconds or so and compare it to the previous save. If it changed, you notify the members through sending a message.

Resources