My bot keeps spamming the same message. What is wrong? - javascript

const Discord = require("discord.js");
const client = new Discord.Client();
const ayarlar = require("./ayalar.json");
let takipedilen = "648424230081265664";
let onlinetakipedilen = 648424230081265664;
let hesap = "648424230081265664";
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on("presenceUpdate", (oldMember, newMember) => {
if (!oldMember.id == onlinetakipedilen) return;
if (oldMember.id == onlinetakipedilen) {
if (oldMember.presence.status != newMember.presence.status) {
var interval = setInterval(function () {
// use the message's channel (TextChannel) to send a new message
client.guilds
.get("812505935280472084")
.channels.get("812506306321580062")
.send("**" + `${newMember.user.username}` + "**" + " " + "şuanda" + " " + `${newMember.presence.status}`)
.catch(console.error); // add error handling here
}, 1000);
}
}
});
This my code and it's spamming the same thing to my text channel.
This is the result;

You're doing the first evaluation kind of wrong.
Instead of doing this:
if(!oldMember.id == onlinetakipedilen) return;
try:
if(oldMember.id !== onlinetakipedilen) return;

The issue is because onlinetakipedilen is an Integer, not a String.
Replace 5th line with:
let onlinetakipedilen = "648424230081265664";
If you are wondering why this is happening please read What is JavaScript's highest integer value that a number can go to without losing precision?.
You're also comparing a Boolean to an Integer.
if (oldMember.id !== onlinetakipedilen)
Equality comparisons and sameness

Related

Having an issue with randomization in Discord JS

so i've been trying to make it so that every time the user sends a message there's a 50/50 chance that the bot reacts with an emoji, however the number is only picked every time i restart the bot. any ideas on how i can make it pick the number every time the command is triggered?
i tried to use setInterval but that didn't work so idk
here code;
const userID = "user id"
let random = Math.floor(Math.random()*2)
client.on('messageCreate', (message) => {
if(random === 1) {
if(message.author.id === userID) {
message.react('emoji');
}
}
});
Simply, define the random variable inside the messageCreate event.
Example:
const userID = "user id";
client.on('messageCreate', (message) => {
let random = Math.floor(Math.random() * 2);
if (random === 1) {
if (message.author.id === userID) {
message.react('emoji');
}
}
});
If you define random inside of the messageCreate event it means that a new random number is generated each time the even is called.
const userID = "user id"
client.on('messageCreate', (message) => {
let random = Math.floor(Math.random()*2)
if(random === 1) {
if(message.author.id === userID) {
message.react('emoji');
}
}
});
As Tyler2P has already shown an example, just wanted to explain why this works.
Thanks

Not finding an easy solution to unban command for Discord Bot

I have been trying to get the unban command to work for the past 2 days, but I haven't found an easy solution for it, I keep getting errors like ".find()" isn't a function, or can't define "id". And I just don't get what I need to do. PS.: I am a noobie when it comes to code.
It's also worth mentioning that I have gone through many variations of this code and I have ended at this, probably previous iterations of the code were closer to the actual solution.
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = "+";
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', msg => {
const { content } = msg;
if (!content.startsWith(prefix)) return;
const args = content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
switch(command) {
case "ping" : {
let latency = Date.now() - msg.createdTimestamp;
let latencyOfAPI = Math.round(client.ws.ping);
msg.reply("This is the latency between the message and the response: " + latency + "." + "\nThis is the API latency: " + latencyOfAPI + ".");
break;
}
case "pong" : {
msg.reply("ping");
break
}
case "ban" : {
const user = msg.mentions.members.first();
if (user) {
msg.guild.members.ban(user);
msg.reply("The user " + user + " has been banned.")
} else {
return msg.reply("There is no one to ban.").catch(console.error);
}
break
}
case "unban" : {
const user = client.users.cache.find(user => user.username == "").id;
let banList = msg.guild.fetchBans();
if(banList = 0) {
return msg.reply("This user isn't in the community, or he is not banned.");
} else {
banList.find(user)
msg.guild.members.unban(user);
msg.reply("User " + user + " has been unbanned.")
}
break
}
}
});
client.login('.....');
Try this:
case "unban" : {
const user = client.users.fetch(args[1]).catch((err) => console.log(err));
user.then((u) => {
if (!args[1]) {
return msg.reply("Enter ID to unban")
} else {
if (u) {
msg.guild.members.unban(u).then(() => {
msg.reply("The user " + u.username + " has been unbanned.")
}).catch((err) => console.log(err))
} else {
return msg.reply("Cannot Find User")
}
}
})
break
Usage: [prefix]unban [ID] e.g [prefix]unban 3426743678738 (type in text channel)
Tip #1: Try to use .then() & .catch() on function which return a promise. You can use .then() to confirm that you've successfully unbanned a user and .catch() to see why there was a issue with unbanning a user.
Tip #2: Make an if statement which checks if the user running this command has the right permissions before trying the code i.e BAN_MEMBERS & ADMINISTRATOR
Also Note: .fetchBans() returns a collection and Promise

Issue with Java Discord.js Modmail System

I have been trying to make a discord ModMail system on my bot and there is an error that I can't understand my code is below:
client.on('message', message => {
if (message.author.bot || !message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).split(/+ /)
if (!message.channel.name.includes('modmail')) {
return;
} else {
if (isNaN(args[0])) {
return message.channel.send('Sorry but that is not a valid user')
}
let storage = message.guild.members.cache;
let memberId = storage.find(member => member.id.toLowerCase() === args[0]);
if (memberId) {
const msg = message.content.slice(args[0].length + prefix.length).split(" ").join(" ");
let embed = new Discord.MessageEmbed()
.setThumnail(message.author.displayAvatarURL())
.setDescription(`<#${message.author.id}>\n------------\n${msg}`)
.setColor('#599cff')
.setFooter('ModMail System')
.setTimestamp();
client.users.fetch(args[0]).then(user => user.send(embed).catch(err => console.log(err)));
message.channel.send('Your message was sent to the staff team! Please be patient for your reply.')
} else {
return message.channel.send('Could not find the user sorry.');
}
}
});
client.on('message', message => {
var msg = message.content;
var n = message.author.username;
if (message.channel.type === 'dm') {
if (message.author.bot) return;
let blacklisted = ['word1', 'word2']
let foundInText = false;
for (var i in blacklisted) {
if (message.content.toLowerCase().includes(blacklisted[i].toLowerCase())) foundInText = true;
}
if (foundInText) {
return message.channel.send('Please do not use foul language in the message. (if you must please cover it with symbols *not letters*)');
}
message.channel.send('Your message was sent to the staff team! Please be patient for your reply.');
const mailMessage = `${message.author.id} ${msg}`
client.channels.fetch('795031406442315816').then(user => user.send(mailMessage).catch(err => console.log(err)));
}
});
The error that is shown is:
SyntaxError: Invalid regular expression: /+ /: Nothing to repeat
This has been confusing me for a while (I am new to code) please if you know how to fix this it would help a lot thank you.
I think the error is because there is a problem here:
const args = message.content.slice(prefix.length).split(/+ /)
If you change .split(/+ /) to .split(' ') or .split(/ /) it would work.

How to allow the bot to create a file / append a file on my dropbox

Since my discord group often have quite a bit of dispute , I made a bot to record chat messages on demand to keep evidence of what people have said. However, since the bot is running on heroku, i could not let the bot dump the log into the github thing. I would need it to append to the file in the dropbox. And if a file didnt exsist, create a file for me.
I am not familliar with the dropbox api and thus wanting you guyz to help me complete the code.
p.s. if there is any problem/ bad parts of the code, feel free to help me improve it , its my first time creating a bot.
Thanks in advance
code :
https://pastebin.com/asftq3zJ
const Discord = require('discord.js');
const client = new Discord.Client();
const fs = require("fs");
//Options
const prefix = "!";
const documentation = "https://docs.google.com/spreadsheets/d/1dlUBQur9d8ANC-JJH6HA4gn4zxbFyz2xwQnTiPYZQi4/edit?usp=sharing"
//On Ready
client.on("ready",() => {
console.log("JojoTheOtokonko is ready")
client.user.setActivity("AV",{type: "WATCHING"});
});
//Login
client.login(process.env.token);
//Command Handler
client.on("message", async msg => {
let message = msg.toString();
let args = "";
if(message[0] === prefix){
args = message.substring(1).split(" ");
}
//Useful Commands
//!a
if(args[0] === "a"){
let mentioned = msg.mentions.users.first();
let server = args[1];
await mentioned.send("Hello, Would you mind joining " + server + "?\nLove you :)");
}
//!record
if(args[0] === "record" || args[0] === "rec"){
recording = true;
await msg.channel.send("#here Recoding message in " + msg.channel +" ,MIND YOUR LANGUAGE");
await client.user.setActivity("to messages in " + msg.channel, {type: "LISTENING"});
}
if(args[0] === "record-stop" || args[0] === "rec-stop"){
recording = false;
await msg.channel.send("#here stopped recoding message in " + msg.channel);
client.user.setActivity("AV",{type: "WATCHING"});
}
//help
if(args[0] === "help"){
await msg.reply("Full list of commands can be found at : \n" + documentation);
}
//Troll Commands
//!ftl
if(args[0] === "fti" || args[0] === "ftl"){
let channel = msg.member.voice.channel
if(!channel){
return msg.channel.send("You need to be in a voice channel to use this command");
}
try {
var connection = await channel.join();
} catch (e) {
console.log("Error connecting to voice channel");
}
connection.play('fti.mp3', { volume: 0.5 })
.on("finish", () => channel.leave())
.on("error", (error) => console.log(error));
}
if(args[0] === "fti-stop" || args[0] === "ftl-stop"){
if(msg.member.voice.channel){
msg.member.voice.channel.leave();
await msg.channel.send("Successfully disconnected from voice , why dont you like Fire Three Island? TAT");
}
}
//!elevator
if(args[0] === "elevator"){
await msg.channel.send("5_AvenueLocal");
}
//!innocity
if(args[0] === "inno" || args[0] === "innocity"){
await msg.channel.send("Is InnoCity Watersuno?");
}
});
//Recorder
var recording = false;
client.on("message", msg =>{
if(recording){
let server = msg.guild.name;
let appendata = "[" +Date.now()+"]" + "<" + msg.author.username + "> " + msg.toString() + "\n";
fs.appendFile(server + ".txt", appendata, (err) => {
if (err) throw err
});
}
});

Javascript: Anti-spam Automoderator (Discord.js)

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.
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
});
}
})

Categories

Resources