What i am trying to do is :
When a guy leave a specific voicechannel, and this channel is now empty, the bot :
delete all the messages but 1 in a specific textchannel
delete the voicechannel he just left
The problem :
the voicechannel is successfully delete, but the messages in the textchannel are not delete by the bot
The code :
#Override
public void onGuildVoiceUpdate(GuildVoiceUpdateEvent event) {
VoiceChannel channelLeft = event.getChannelLeft();
if (channelLeft.getName().startsWith("🎒 Coaching de")) {
if (channelLeft.getMembers().isEmpty()) {
channelLeft.delete().queue(); //The bot delete de channel successfully
List<Message> messagesCoaching = event.getChannelLeft().getGuild().getTextChannelById("489420943991635988").getHistory().retrievePast(20).complete(); // Using a list to store the retrieved messages
messagesCoaching.removeIf(m -> m.getId().equals("490567304971812885")); // Removing from the list the message i want to keep
event.getChannelLeft().getGuild().getTextChannelById("489420943991635988").deleteMessages(messagesCoaching).complete(); // Deleting all the messages (not working)
}
}
I'm not 100% sure what your error is, but I'll assure you're trying to delete all messages sent in the text channel.
Currently, your code gets the last 20 messages from the text channel that you got by an ID. If you have more then 20 messages, the bot won't delete those. And if the messages are older then 2 weeks, it won't delete them either. Furthermore do not use complete() as this will stop the main thread of the bot. I'd suggest using code like this:
#Override
public void onGuildVoiceUpdate(GuildVoiceUpdateEvent event) {
VoiceChannel channelLeft = event.getChannelLeft();
if (channelLeft.getName().startsWith("🎒 Coaching de")) {
if (channelLeft.getMembers().isEmpty()) {
channelLeft.delete().queue(); // Telling the bot to delete the channel.
MessageHistory history = event.getGuild().getTextChannelById("489420943991635988").getHistory(); // Pulling up the history from a text channel
history.retrievePast(100).queue(messages -> { // Putting the past 100 messages in a queue, and using a lamba to do something with the returned messages
messages.removeIf(m -> m.getId().equals("490567304971812885")); // If a message contains the same ID as told here, it removes it.
event.getGuild().getTextChannelById("489420943991635988").deleteMessages(messages).queue(); // And now, delete all messages.
});
}
}
}
Related
It's not sending a message, there are no errors I tried modifying the code nothing is working the bot welcome message still works I think that it's not updating with replit.
I tried modifying the code switching some stuff around basically doing stuff if I see any flaws I made.
client.on('message', message => {
// We'll want to check if the message is a command, and if it is, we'll want to handle it
if (!message.content.startsWith(prefix) || message.author.bot) return;
// Split the message into an array of arguments, with the command being the first element
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
// Check if the command is "privatevc"
if (command === 'Privatevc') {
// Check if the member is in a voice channel
if (!message.member.voice.channel) {
// If the member is not in a voice channel, send a message letting them know they need to be in one to use the command
return message.channel.send('You need to be in a voice channel to use this command.');
}
// If the member is in a voice channel, create a private voice channel for them
message.member.voice.createChannel({type: 'Voice'}).then(channel => {
// Send a message to the member letting them know the private voice channel has been created
message.channel.send(`Private voice channel created for you: ${channel}`);
}).catch(console.error); // If there was an error creating the private voice channel, log it to the console
}
});
This code is for Discord.js v12. If using the newest (v14) you need to use the messageCreate event instead of message. So the code would be:
client.on('messageCreate', message => {
You might also enable the MessageContent and GuildMessages intents.
IntentsBitField.Flags.GuildMessages,
IntentsBitField.Flags.MessageContent
To make it all work you need to enable at least the third option, as you might see in the screenshot.
So im making a discord bot, i made a system so if the bot joins a server it sends a message with the server name in the developer server. but i want it to delete the message when it leaves the server. idk how to do that.
You can create a listener that is triggered whenever a user sends a message. In that listener you would check the message.content against your prohibited word(s) and delete it. You can do that like so:
client.on('messageCreate', () => {
if(message.content.includes("Your prohibited word(s)") {
message.delete()
}
}
I'm trying to get the message sent RIGHT BEFORE each time I call the bot.
Right now I'm using:
client.on('message', message => {
if (message.content === '$test')) {
message.channel.messages.fetch({ limit: 2 }).then(messages => {
lastMessage = messages.last().content
message.channel.send(lastMessage)
})
}
The bot correctly sends the message sent before the trigger phrase if I send:
hello
$test
hello
However, if I send four messages quickly:
Welcome!
$test
hello
$test
it sends:
hello
hello
when it should reply with Welcome and then hello.
How do I get the content of the message sent right before each time the bot is triggered, rather than of the second-to-last message in the channel?
You should not try and grab the previous message, rather store the messages in order.
var messages = [];
client.on('message', message => {
if (message.content === '$test') {
message.channel.send(messages[messages.length - 1]);
}
messages.push(message.content);
})
You are grabbing the most recent message from the channel, and that can provide unpredictable results when multiple messages are sent.
This instead logs every message in order. This will make sure that all messages will be added along with the processing to prevent discord messages loading faster than your discord bot application processing them.
There is a similar answered question to this one
DiscordJS Bot - How to get the message immediately before another message in a channel?
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;
I’m trying to make my bot send a message to a channel whenever a user deletes his/her message, sorta like the bot Dyno, but I do not know how to do this. I think the method is .deleted() but I can’t seem to make it work. Can anyone tell me how? Sorry for lack of detail, there’s nothing else to add. Thank you in advance.
The Client (or Bot) has an event called messageDelete which is fired everytime a message is deleted. The given parameter with this event is the message that has been deleted. Take a look at the sample code below for an example.
// Create an event listener for deleted messages
client.on('messageDelete', message => {
// Fetch the designated channel on a server
const channel = message.guild.channels.cache.find(ch => ch.name === 'deleted-messages-log');
// Do nothing if the channel wasn't found on this server
if (!channel) return;
// Send a message in the log channel
channel.send(`A message has been deleted. The message was: ${message.content}`);
});