Discord.js, detect if there's a message sent by a certain user? - javascript

So I'm messing around with creating a discord bot that repeatedly pings a user until they respond/say anything in the chat (annoying, right?). The amount of times to ping the user and the time between each ping can also be adjusted if necessary. However, I can't seem to find a way to detect if the pinged user actually says something in the chat, and a way to stop the loop.
The actual pinging part of the code is in this for loop:
const ping = async () => {
for(var i = 1; i <= pingAmount; i++){
//the wait() command
await new Promise(r => setTimeout(r, pingTime * 1000));
//the actual ping
message.channel.send(`hey <#${userID}> let\'s play minecraft`);
}
//sends a message once pinging is finished
message.channel.send("Pinging Complete.");
};
I've tried nesting the following code inside that loop, but I get no results.
client.on('message', message =>{
if(message.author == taggedUser) {
message.channel.send('User has replied. Stopping pings.')
return;
}
});
Any help is appreciated!
full code below:
module.exports = {
name: 'Ping',
description: "Pings specified user until they appear",
execute(message, args, Discord){
//initialize variables
const client = new Discord.Client();
const taggedUser = message.mentions.users.first();
const userID = message.mentions.users.first().id;
//splits the command
const slicedString = message.content.split(' ');
//grabs specific numbers from command as input
const pingAmount = slicedString.slice(4,5);
const pingTime = slicedString.slice(5);
//display confirmation info in chat
message.channel.send(`So, ${message.author.username}, you want to annoy ${taggedUser.username}? Alright then lol`);
message.channel.send(`btw ${taggedUser.username}\'s user ID is ${userID} lmao`);
message.channel.send(`amount of times to ping: ${pingAmount}`);
message.channel.send(`time between pings: ${pingTime} seconds`);
//checks to make sure pingTime isnt too short
if(pingTime < 5){
if(pingTime == 1){
message.channel.send(`1 second is too short!`);
return;
} else {
message.channel.send(`${pingTime} seconds is too short!`);
return;
}
}
//timer and loop using pingAmount and pingTime as inputs
const ping = async () => {
for(var i = 1; i <= pingAmount; i++){
//the wait() command
await new Promise(r => setTimeout(r, pingTime * 1000));
//the actual ping
message.channel.send(`hey <#${userID}> let\'s play minecraft`);
const pingedUsers = [taggedUser];
// doodle message
const msg = {author: {id:1}};
// message event
const onMessage = (message) => {
if (pingedUsers.indexOf(message.author.id) != -1) {
console.log("user replied");
}
}
onMessage(msg); // nothing
pingedUsers.push(msg.author.id); // push the author id
onMessage(msg); // he replied!
}
//sends a message once pinging is finished
message.channel.send("Pinging Complete.");
};
//runs the ping function
ping();
}
}

You should be comparing the author's snowflake (id) in this case.
You can put the pinged users in a list and see if the message author is in that list.
const pingedUsers = [];
// doodle message
const msg = {author: {id:1}};
// message event
const onMessage = (message) => {
if (pingedUsers.indexOf(message.author.id) != -1) {
console.log("user replied");
}
}
onMessage(msg); // nothing
pingedUsers.push(msg.author.id); // push the author id
onMessage(msg); // he replied!

Related

Discord.js v12.5.3 Anyone know why this doesn't work?

EDIT: ColinD solved my problem but now the message doesn't delete and I have no idea why the message wont delete because its worked for me before with bots
Code:
const discord = require('discord.js')
const newEmbed = require('embedcord')
const randomHex = require('random-hex')
module.exports = (client, message, options) => {
let links = require('./links.json')
let foundLink = false
let banReason = (options && options.banReason) || 'Sent a phishing link.'
let logs = (options && options.logs)
let member = message.mentions.members.first()
for(var i in links) {
if(message.content.toLowerCase().includes(links[i])) foundLink = true
}
if(foundLink) {
if(message.author.hasPermission('ADMINISTRATOR'))
return
message.delete()
member.ban({reason: banReason})
const embed = newEmbed(
'**Member Banned**',
`${randomHex.generate()}`,
`Member was banend for ${options.banReason}`
)
logs.send(embed)
}
}
Your return position might be preventing anything below if from running try changing this
if (foundLink) {
if (message.author.hasPermission('ADMINISTRATOR')) return;
const embed = newEmbed(
'**Member Banned**',
`${randomHex.generate()}`,
`Member was banend for ${options.banReason}`
);
message.delete();
member.ban({
reason: banReason
});
logs.send(embed);
}
Or this if you want if/else
if (foundLink) {
if (message.author.hasPermission('ADMINISTRATOR')) {
return;
} else {
const embed = newEmbed(
'**Member Banned**',
`${randomHex.generate()}`,
`Member was banend for ${options.banReason}`
);
message.delete();
member.ban({
reason: banReason
});
logs.send(embed);
}
}
EDIT: ColinD solved my problem but now the message doesn't delete and I have no idea why the message wont delete because its worked for me before with bots
foundLink variable is unnecessary, you can move your code inside the loop.
Use message.member.hasPermission() instead of message.author.hasPermission().
Example code for v12.5.3(Message Event):
client.on('message', (message) => {
if (message.author.bot) return; // Ignore bot messages
const { member, channel, guild } = message; // Get the message author, channel, and guild
if (!member || !channel || !guild) return; // Ignore messages without a member, channel or guild
const { links } = require('./links.json'); // Get links from json file
for (let i = 0; i < links.length; i++) { // Check if the message contains a link in the links.json file
if (message.content.toLowerCase().includes(links[i])) { // If the message contains a link
if (member.hasPermission('ADMINISTRATOR')) return; // If the member has the administrator permission, don't ban them
const banReason = 'Sent a phishing link'; // Reason for the ban
message.delete(); // Delete the message
guild.member(member).ban({ reason: banReason }); // Ban the member
channel.send(`${member.displayName} has been banned for sending a phishing link.`) // Send a message to the channel
break;
}
}
})

Enabling and disabling command in JavaScript discord.js

I'm trying to make an automemes command, I can get it to send memes automatically, but when I try to disable it, it sends the Automemes disabled! command, but it still sends them. Here's the code:
const { SlashCommandBuilder } = require("#discordjs/builders");
const fetch = (...args) => import("node-fetch").then(({default: fetch}) => fetch(...args));
module.exports = {
data: new SlashCommandBuilder()
.setName("automemes")
.setDescription("Sends random memes every 5 minutes (from r/memes)")
.addBooleanOption(option =>
option.setName("enabled")
.setDescription("Set the automemes to on/off")
.setRequired(true)),
async execute(client, interaction, Discord) {
let isEnabled = interaction.options.get("enabled").value;
switch (isEnabled) {
case true: interaction.reply("Automemes enabled! " + ENV.CATKISS)
break;
case false: isEnabled = false;
break;
}
async function sendMemes() {
fetch("https://meme-api.herokuapp.com/gimme/memes")
.then(res => res.json())
.then(async json => {
const Embed = new Discord.MessageEmbed()
.setTitle(json.title)
.setImage(json.url)
if (Embed.title.length > 256) return;
await interaction.channel.send({embeds: [Embed]});
});
}
isEnabled? setInterval(() => sendMemes(), 10000) : interaction.reply("Automemes disabled! " + ENV.CATKISS);
}
}
I see what you're trying to accomplish but, as stated above by #Zsolt Meszaros, your interval is never getting cleared. That means that if that interval gets activated once, it will continue perpetually until your bot shuts down. Try declaring your interval as a constant so you can enable and disable it however you choose.
const myInterval = setInterval(sendMemes, 10000) //declaring interval
async fucntion startInterval() {
myInterval; //function to start interval
}
async function disableInterval() {
clearInterval(myInterval); //function to clear interval
interaction.reply(interaction.reply("Automemes disabled! " + ENV.CATKISS));
}
isEnabled? startInterval() : disableInterval(); //added starter and stopper functions
}
}

Antispam for telegram bot

I am working on creating a telegram bot, I want to make an anti-spam system, that is, when a person presses a button too many times, the bot will freeze for him for a certain number of seconds, it is possible to write a message about blocking. I just started learning JavaScript.
I use node-telegram-bot-api.
import {
bot
} from '../token.js';
import {
keyboardMain
} from '../keyboards/keyboardsMain.js';
export function commands() {
bot.on('message', msg => {
const text = msg.text;
const chatId = msg.chat.id;
if (text === '/start') {
return bot.sendMessage(chatId, 'hello', keyboardMain);
}
return bot.sendMessage(chatId, 'error');
});
}
You can create a user throttler using Javascript Map
/*
* #param {number} waitTime Seconds to wait
*/
function throttler(waitTime) {
const users = new Map()
return (chatId) => {
const now = parseInt(Date.now()/1000)
const hitTime = users.get(chatId)
if (hitTime) {
const diff = now - hitTime
if (diff < waitTime) {
return false
}
users.set(chatId, now)
return true
}
users.set(chatId, now)
return true
}
}
How to use: You'll get the user's chatId from telegram api. You can use that id as an identifier and stop the user for given specific time.
For instance I'm gonna stop the user for 10seconds once the user requests.
// global 10 second throttler
const throttle = throttler(10) // 10 seconds
// in your code
const allowReply = throttle(chatId) // chatId obtained from telegram
if (allowReply) {
// reply to user
} else {
// dont reply
}

Start bot with one message and end with other command

I'm basically creating a bot that does a loop, and I want it to end when you say *parar but i don't know how to make it.
Here is a bit of code to explain my problem
module.exports = {
name: 'epico',
execute(message, args, Discord, client){
//this is the loop
var interval = setInterval(function(){...}, 1000)
}
The loop starts when I put *epico and I want it to stop when user sends *parar
I was trying something like this:
client.on('message', message =>{
if(message.content.startsWith('parar')){clearInterval(interval)}
}
But this keeps working until I shut down the bot (I want it to just work 1 time)
Try something like the following: Basically what you want to do is save your interval to a variable that is accessible later on in order to stop your interval again.
const Discord = require("discord.js");
const client = new Discord.Client();
let interval;
client.on("message", async (message) => {
if (message.content.startsWith("*epico")) {
return (interval = setInterval(() => {
console.log("do something");
}, 1000));
}
if (message.content.startsWith("*parar")) {
clearInterval(interval);
return console.log("stopped interval");
}
});
client.login("your-token");
I assume your are using multiple commands in several different files. If that is the case I would simply save the interval to the client object in your *epico command file since you pass the client to your execute function anyways.
module.exports = {
name: "epico",
execute(message, args, Discord, client) {
return (client.interval = setInterval(() => {
console.log("do something");
}, 1000));
},
};
And then just clear the interval in your *parar command. Also don't forget to check if client.interval is even set ;)
module.exports = {
name: "parar",
execute(message, args, Discord, client) {
client.interval && clearInterval(client.interval);
return console.log("stopped interval");
},
};
maybe you have a typo???
client.on('message', message => {
if (message.content.startsWith('parar')){
clearInterval(interval)
}
});

Discord js check reaction user role

I am trying to close a ticket by reacting to a button. But reaction must be given by "support" role. I couldnt do it. reaction.message.member.roles.has is not helping me at this point. Here is my code ;
client.on("messageReactionAdd", (reaction, user) => {
if(reaction.message.member.roles.has('ROLE')) {
let id = user.id.toString().substr(0, 4) + user.discriminator;
let chan = `ticket-${id}`;
const supchan = reaction.message.guild.channels.find(
(channel) => channel.name === chan
);
const chan_id = supchan ? supchan.id : null;
if (
reaction.emoji.name === "🔒" &&
!user.bot &&
user.id != "ID"
) {
reaction.removeAll();
const channel = client.channels.find("name", chan);
const delMsg = new Discord.RichEmbed()
.setColor("#E74C3C")
.setDescription(`:boom: Ticket will be deleted in 5 seconds.`);
channel.send(delMsg).then(() => {
var counter = 0;
const intervalObj = setInterval(() => {
counter++;
if (counter == 5) {
const message = reaction.message;
message.delete();
Thanks for helps !
All of this wrapped inside the messageReactionAdd event
// Replace "message_id" with the proper message id
// Checks if it's the correct message
if (reaction.message.id == "message_id") {
// Check if author of ticket message is from the same user who reacted
if (reaction.message.author == user) {
// Check correct emoji
if (reaction.emoji.name == "🔒") {
// Code to close ticket
}
}
}
EDIT:
Again, this would be wrapped inside the messageReactionAdd event:
// Try to get the ticket message
// If there's none then the user was never opened a ticket so we simply return the code
const ticketMessage = client.tickets.get(user);
if (!ticketMessage) return;
// Checks if it's the correct message
if (reaction.message.id == ticketMessage.id) {
// Check correct emoji
if (reaction.emoji.name == "🔒") {
// Code to close ticket
}
}
I removed the code that check for the reaction message author because getting ticketMessage already handles that. Do note that this means you can make sure a user can only open one ticket.

Categories