Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
112
rated 0 times [  114] [ 2]  / answers: 1 / hits: 16990  / 7 Years ago, tue, july 11, 2017, 12:00:00

I am coding a multipurpose Discord bot to replace some of the more minor ones, and I am looking for a piece of code for a feature that recognizes repeated messages or messages sent in a very short time period (let's say 5000ms).



Here is what could be used to implement this idea.



client.on(message, (message) => {
//let's use something like a spam variable for 10 or more messages sent within 5000ms
if(message.content === spam) {
message.reply(Warning: Spamming in this channel is forbidden.);
console.log(message.author.username + ( + message.author.id + ) has sent 10 messages or more in 5 seconds in + message.channel.name + .);
}
});


For reference, I also made a feature that deletes messages, using a ~delete [n] command. It looks like this:



//this will only delete one message in the channel, the most recent one.
message.delete(1000);
//1000 represents the timeout duration. it will only delete one message, regardless of the value.

//we can delete multiple messages with this, but note it has to come before the reply message.
message.channel.bulkDelete(11);


I was thinking of somehow combining the delete command with recognizing spam messages. If you have any ideas, that would be perfect.


More From » command

 Answers
14

Try This:


const usersMap = new Map();
const LIMIT = 7;
const DIFF = 5000;

client.on('message', async(message) => {
if(message.author.bot) return;

if(usersMap.has(message.author.id)) {
const userData = usersMap.get(message.author.id);
const { lastMessage, timer } = userData;
const difference = message.createdTimestamp - lastMessage.createdTimestamp;
let msgCount = userData.msgCount;
console.log(difference);

if(difference > DIFF) {
clearTimeout(timer);
console.log('Cleared Timeout');
userData.msgCount = 1;
userData.lastMessage = message;
userData.timer = setTimeout(() => {
usersMap.delete(message.author.id);
console.log('Removed from map.')
}, TIME);
usersMap.set(message.author.id, userData)
}
else {
++msgCount;
if(parseInt(msgCount) === LIMIT) {

message.reply("Warning: Spamming in this channel is forbidden.");
message.channel.bulkDelete(LIMIT);

} else {
userData.msgCount = msgCount;
usersMap.set(message.author.id, userData);
}
}
}
else {
let fn = setTimeout(() => {
usersMap.delete(message.author.id);
console.log('Removed from map.')
}, TIME);
usersMap.set(message.author.id, {
msgCount: 1,
lastMessage : message,
timer : fn
});
}
})

[#57119] Sunday, July 9, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
karivictoriab

Total Points: 530
Total Questions: 90
Total Answers: 95

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
;