Discord.js fired several times - javascript

The code that I made is fired several times, I have tried to add returns but it doesn't matter. I'm running the code with a raspberry pi 3.
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!')
})
client.on('error', console.error);
client.on('message', message =>{
if (message.channel.id == '...........') {
console.log(message.content);
}
if (message.content.startsWith(`${prefix}ping`)) {
if (message.member.roles.some(role => role.name === '⚙️ | Manager'))
{message.channel.send('Pong!');} else {
message.channel.send('Not enough rights! :no_entry:');
}}
if (message.content.startsWith(`${prefix}test`)) {
if (message.author.id == '.........') {
const role = message.guild.roles.find('name', 'test');
message.member.addRole(role);
message.channel.send('test');
}}});
client.login(token);
I expect it to output it onces, but I don't get it to work.
This is the output:
I want him to do it only once.

Yeah I've had that problem before, simply turn off the bot from everything you're hosting it on, you were probably logged in on it multiple times, that might be because you're running it on a raspberry pi and did not properly shut it.

Related

im making a discord bot for the first time in discord js and my test command wont work

This is "my code" and the command doesn't work. tried following a YouTube tutorial. this is my first time trying to do something like this. all my code experience comes from simple python code. so if you have any vids that explains this pls send
const { Client, GatewayIntentBits, EmbedBuilder, PermissionsBitField, Permissions, Message } = require(`discord.js`);
const prefix = '>';
const client = new Client({
intents: [
32767
]
});
client.on("ready", () => {
console.log("botong is online!")
client.user.setPresence({
status: 'online',
activity: {
name: 'status',
type: 'ActivityType.Playing'
}
});
});
client.on("messageCreate", (message) => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
//message array
const messageArray = message.content.split(" ");
const argument = messageArray.slice(1);
const cmd = messageArray[0];
//commands
//test commands
if (commands === 'test') {
message.channel.send("Bot is working!")
}
})
client.login("MY TOKEN");
tried to run this and nothing happened, it should send a message in my discord server saying "Bot is Working"
so if you have any vids that explains this pls send
Here's an article from Codeacademy which explains how to create a simple Discord bot. https://www.codecademy.com/article/christine_yang/build-a-discord-bot-with-node-js
Reason why your test message doesn't appear: the message never gets sent because you haven't defined commands so it can obviously never be 'test'.
if (commands === 'test') {
message.channel.send("Bot is working!")
}
Edit: Here's a code sample from the article which sends message to the channel each time someone sends "Hello" there.
client.on('messageCreate', msg => {
// You can view the msg object here with console.log(msg)
if (msg.content === 'Hello') {
msg.reply(`Hello ${msg.author.username}`);
}
});

Discord.js Replit, cannot get my bot to respond to commands

I am currently developing a Discord bot for replit, and I am able to get it to post and even get it to send an intro message when joining a server, however whenever I try to get it to respond to a command I type it won't respond. The message for the first one client.on guild create works. However the client.on for async message will not work.
This is what I have so far.
const { Client } = require('discord.js');
const client = new Client({ intents: 32767 });
//const Discord = require('discord.js');
const keepAlive = require('./server');
require("dotenv").config();
//const client = new Discord.Client();
//const fetch = require('node-fetch');
const config = require('./package.json');
const prefix = '!';
const guild = "";
client.once('ready', () => {
console.log('Jp Learn Online');
});
// let defaultChannel = "";
// guild.channels.cache.forEach((channel) => {
// if(channel.type == "text" && defaultChannel == "") {
// if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
// defaultChannel = channel;
// }
// }
// })
//defaultChannel.send("This is a test message I should say this message when I join");
//if(guild.systemChannelId != null) return guild.systemChannel.send("This is a test message I should say this message when I join"), console.log('Bot entered new Server.')
// client.on('guildCreate', (g) => {
// const channel = g.channels.cache.find(channel => channel.type === 'GUILD_TEXT' && channel.permissionsFor(g.me).has('SEND_MESSAGES'))
// channel.send("This is a test message I should say this message when I join");
// });
client.on('guildCreate', guild => {
guild.systemChannel.send('this message wil print')
});
client.on('message', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/); // This splits our code into to allow multiple commands.
const command = args.shift().toLowerCase();
if (command === 'jhelp') {
message.channel.send('こんにちは、私はDiscordロボットです。始めたいなら、!jhelp タイプしてください。 \n\n Hello I am a discord bot built to help learn the Japanese language! \n\n If you want to access a japanese dictionary type !dictionary \n\n If you would like to learn a random Japanese Phrase type !teachme \n\n If you would like to answer a challenge question type !challenge1 through 5 each different numbered challnege will ask a different question \n (ie. !challenge1) this will ask the first question.')
}
please note. the lower parts of the code are simply commands. That expand further from jhelp I want to know mainly why my second client.on with messages wont work specifically in the context of working with replit.
Thanks for the help in advance.
I expected that maybe changing intents might work, I even went into the discord developer portal, and enabled options, and am still not able to get it working.
After Discord separated out the message intent as a privileged one, the bit field you need to use for all intents has changed. You need to use 131071.
I.e.
const { Client } = require('discord.js');
const client = new Client({ intents: 131071 });
//const Discord = require('discord.js');
const keepAlive = require('./server');
require("dotenv").config();
//const client = new Discord.Client();
//const fetch = require('node-fetch');
const config = require('./package.json');
const prefix = '!';
const guild = "";
client.once('ready', () => {
console.log('Jp Learn Online');
});
// let defaultChannel = "";
// guild.channels.cache.forEach((channel) => {
// if(channel.type == "text" && defaultChannel == "") {
// if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
// defaultChannel = channel;
// }
// }
// })
//defaultChannel.send("This is a test message I should say this message when I join");
//if(guild.systemChannelId != null) return guild.systemChannel.send("This is a test message I should say this message when I join"), console.log('Bot entered new Server.')
// client.on('guildCreate', (g) => {
// const channel = g.channels.cache.find(channel => channel.type === 'GUILD_TEXT' && channel.permissionsFor(g.me).has('SEND_MESSAGES'))
// channel.send("This is a test message I should say this message when I join");
// });
client.on('guildCreate', guild => {
guild.systemChannel.send('this message wil print')
});
client.on('messageCreate', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/); // This splits our code into to allow multiple commands.
const command = args.shift().toLowerCase();
if (command === 'jhelp') {
message.channel.send('こんにちは、私はDiscordロボットです。始めたいなら、!jhelp タイプしてください。 \n\n Hello I am a discord bot built to help learn the Japanese language! \n\n If you want to access a japanese dictionary type !dictionary \n\n If you would like to learn a random Japanese Phrase type !teachme \n\n If you would like to answer a challenge question type !challenge1 through 5 each different numbered challnege will ask a different question \n (ie. !challenge1) this will ask the first question.')
}
Yes! its the problem with your intents, for guildMemberAdd/Remove you require GuildMembers intents

Discord.js 12.0.0 msg.content returning blank

I'm making a stats checker bot in discord.js v12.0.0 because I don't want to deal with slash commands and intents, just wanted this to be a quick little project that I throw together. But, after coding for a while a command I made didn't work, and I decided to console log msg.content to see if that was the issue. It shows as completely blank when I log msg.content, as well as logging msg itself. NO, I am not running a self bot, I read that doing that can also give this issue.
Images:
Code:
import Discord from 'discord.js';
const client = new Discord.Client();
import fetch from 'node-fetch';
client.on('ready', () => {
console.log(`online`);
});
let lb;
async function fet() {
await fetch("https://login.deadshot.io/leaderboards").then((res) => {
return res.json();
}).then((res) => {
lb = res;
})
}
client.on('message', async msg => {
console.log(msg)
let channel = msg.channel.id;
if (msg.author.id == client.user.id) return;
if (channel != 1015992080897679370) return;
await fet();
let r;
for (var x in lb.all.kills) {
if (msg.content.toLowerCase() == lb.all.kills[x].name.toLowerCase()) {
r = lb.all.kills[x].name;
}
}
if (!r) return msg.channel.send('Error: user not found')
})
client.login(token)
Discord enforced the Message Content privileged intent, since September 1st.
Here's the announcement from Discord Developers server (invite)
Source message: Discord Developers #api-announcements
You can fix this, but you do need to use intents...
const client = new Discord.Client({
ws: {
intents: [Discord.Intents.ALL, 1 << 15]
}
})
You also need to flip the Message Content intent switch in developer portal
It's much better to update to version 13+, v12 is deprecated and is easily broken.

Discord.js : A part of the code does not work, but there is no error

When I start the bot there comes the Ready message but wehen one of somebody send for example a link into a channel nothing happens. Ther comes no error. I had to reduce the code because of the stackoverflow limit. There were three other parts but they worked. Only these two parts doesnt work.
const Discord = require('discord.js');
const client = new Discord.Client();
const TOKEN = '';
const PREFIX = '!';
//ready
client.once('ready', () => {
console.log('Ready!');
});
//welcome
client.on('guildMemberAdd', member => {
console.log('User joind');
});
//commands
client.on('message', message => {
if (!message.content.startsWith(PREFIX)) return;
if (message.author.bot) return;
if (!message.guild) return;
}
//delete links
else if (message.content.includes('https://')) {
console.log('Link!!!');
}
});
client.login(TOKEN);
Most likely the message does not have the required prefix, thus the the function just returns.

Discord Bot Logging in Over 1000 Times

I suspect this is happening due to the code below. It's the only bot of 3 with this code. The code itself hasn't been working 100% of the time when the bot is logged in. It's supposed to give anyone that is live streaming a "streaming" role. Some people it adds the role onto and for others it doesn't.
I'd like help for both issues if possible. Mostly the logging issue since I can't even keep the bot online anymore
The code below shows the entire index.js file. The code talked about above is the "presenceUpdate" section of code.
const fs = require('fs');
const Discord = require('discord.js');
const {prefix, token} = require('./config.json');
const welcomeGif = require('./welcomeGifs.json');
const client = new Discord.Client();
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once('ready', () => {
console.log(`${client.user.username} is online!`);
});
client.on('guildMemberAdd', gif => {
gif = new Discord.Attachment(welcomeGif[Math.floor(Math.random() * welcomeGif.length)]);
client.channels.get('614134721533968494').send(gif);
});
client.on('presenceUpdate', (oldPresence, newPresence) => {
const guild = newPresence.guild;
const streamingRole = guild.roles.cache.find(role => role.id === '720050658149138444');
if (newPresence.user.bot || newPresence.presence.clientStatus === 'mobile' || oldPresence.presence.status !== newPresence.presence.status) return;
const oldGame = oldPresence.presence.activities ? oldPresence.presence.activities.streaming: false;
const newGame = newPresence.presence.activities ? newPresence.presence.activities.streaming: false;
if (!oldGame && newGame) { // Started playing.
newPresence.roles.add(streamingRole)
.then(() => console.log(`${streamingRole.name} added to ${newPresence.user.tag}.`))
.catch(console.error);
} else if (oldGame && !newGame) { // Stopped playing.
newPresence.roles.remove(streamingRole)
.then(() => console.log(`${streamingRole.name} removed from ${newPresence.user.tag}.`))
.catch(console.error);
}
});
// This is the start of the main function when the bot is turned on
client.on('message', message => {
// The bot will not respond if there is no prefix,
// the user that typed it was a bot,
// or if it was not sent from in the server
if (!message.content.startsWith(prefix) || message.author.bot || !message.guild) return;
// Creates the arguments variable and separates it with a space
// and creates the command variable
const args = message.content.slice(prefix.length).split(' ');
const commandName = args.shift().toLowerCase();
if (!client.commands.has(commandName)) return;
const command = client.commands.get(commandName);
if (command.guildOnly && message.channel.type !== 'text') {
return message.reply('I can\'t execute that command inside DMs!');
}
try {
command.execute(message, args);
}
catch (error) {
console.error(error);
message.channel.send('There was an error trying to execute that command!\nCheck the console for details.');
}
});
// This logs in the bot with the specified token found in config
client.login(token);
Ok I'm getting closer and closer I think. I think the issue is that upon the bot logging in, it crashes from an error I found. When it crashes it is set to automatically restart so when it restarts it crashes again and repeats the cycle. The error I found is "clientStatus" is undefined which is in the presenceUpdate section.

Categories

Resources