Discord bot not coming online despite no error messages? - discord.js

I have recently spent a long time making a discord ticket bot, and all of a sudden now, it isnt turning on. There are no error messages when I turn the bot on, and the webview says the bot is online. I am hosting on repl.it
Sorry for the long code, but any genius who could work this out would be greatly appreciated. Thanks in advance.
const fs = require('fs');
const client = new Discord.Client();
const prefix = '-'
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);
}
require('./server.js')
client.on("ready", () => {
console.log('Bot ready!');
client.user.setActivity('-help', { type: "LISTENING"} ).catch(console.error)
})
client.on("message", async (message) => {
if (message.author.bot) return;
const filter = (m) => m.author.id === message.author.id;
if (message.content === "-ticket") {
let channel = message.author.dmChannel;
if (!channel) channel = await message.author.createDM();
let embed = new Discord.MessageEmbed();
embed.setTitle('Open a Ticket')
embed.setDescription('Thank you for reaching out to us. If you have a question, please state it below so I can connect you to a member of our support team. If you a reporting a user, please describe your report in detail below.')
embed.setColor('AQUA')
message.author.send(embed);
channel
.awaitMessages(filter, {max: 1, time: 1000 * 300, errors: ['time'] })
.then ( async (collected) => {
const msg = collected.first();
message.author.send(`
>>> ✅ Thank you for reaching out to us! I have created a case for your inquiry with out support team. Expect a reply soon!
❓ Your question: ${msg}
`);
let claimEmbed = new Discord.MessageEmbed();
claimEmbed.setTitle('New Ticket')
claimEmbed.setDescription(`
New ticket created by ${message.author.tag}: ${msg}
React with ✅ to claim!
`)
claimEmbed.setColor('AQUA')
claimEmbed.setTimestamp()
try {
let claimChannel = client.channels.cache.find(
(channel) => channel.name === 'general',
);
let claimMessage = await claimChannel.send(claimEmbed);
claimMessage.react('✅');
const handleReaction = (reaction, user) => {
if (user.id === '923956860682399806') {
return;
}
const name = `ticket-${user.tag}`
claimMessage.guild.channels
.create(name, {
type: 'text',
}).then(channel => {
console.log(channel)
})
claimMessage.delete();
}
client.on('messageReactionAdd', (reaction, user) => {
const channelID = '858428421683675169'
if (reaction.message.channel.id === channelID) {
handleReaction(reaction, user)
}
})
} catch (err) {
throw err;
}
})
.catch((err) => console.log(err));
}
})
client.login(process.env['TOKEN'])

Your problem could possibly be that you have not put any intents. Intents look like this:
const { Client } = require('discord.js');
const client = new Client({
intents: 46687,
});
You can always calculate your intents with this intents calculator: https://ziad87.net/intents/
Side note:
If you are using discord.js v14 you change client.on from message to messageCreate.

Related

Discord js, Bot can only find itself until someone else send a message

I was trying to get all the members of a role but i can only get the bot until someone else send a message then i can see them too
here is my code
const matches = require("../differents-matches")
module.exports = (client) => {
setInterval(async () => {
/*const allmatch = await matches.
where('_notified').exists(false).
where('_startDate').lt(Date.now()).
where('_endDate').gt(Date.now())
allmatch.forEach(element => {
})*/
console.log(client.guilds.cache.get('1050150840813498401').roles.cache.get('1050889003110506516').members.map(m => m.user.id))
//
}, 5000)
}
i tried the solution proposed in this post but the problem is still here
i have all the intents needed :
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMembers], fetchAllMembers: true });
and i did activate the server member intent in the bot options, i can't find any other thing to try. If you have an idea of what is the problem please leave a message.
It is expected, actually the fetchAllMembers client option disappeared with Discord.js v13.
You should now fetch the guild members manually:
const matches = require("../differents-matches")
module.exports = (client) => {
setInterval(async () => {
/*const allmatch = await matches.
where('_notified').exists(false).
where('_startDate').lt(Date.now()).
where('_endDate').gt(Date.now())
allmatch.forEach(element => {
})*/
const guild = client.guilds.cache.get('1050150840813498401');
await guild.members.fetch(); // do what fetchAllMembers previously did
console.log(guild.roles.cache.get('1050889003110506516').members.map(m => m.user.id))
//
}, 5000)
}

Discord.js v13 bot cannot send message

Here is my code
I tried to run it and when i run the command nothing shows up
can someone pls help me with this
const Discord = require("discord.js");
const bot = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
const token =
"MTAxNzgyMjQ1MjU1MTc5NDgxOA.GjO8F-.VWCMsDKV5_YdP1w6gnEME6Jucd7BN9OADesM4s";
const prefix = "lb!";
bot.on("ready", () => {
console.log("Your bot is now online");
});
bot.on("messagecreate", (message) => {
if (message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLocaleLowerCase();
if (command === "hello") {
message.reply("Hi ${message.author}");
}
});
bot.login(token);
Message content is now a privileged intent. You may have to enable it for your bot in the Discord Developer Portal. You could (or should) also use interaction commands instead, so that you don't need that intent, as its purpose is to provide user privacy.
Hello Syed Faizan Ali Kazmi, Done Fix Your Code
// © Ahmed1Dev
const Discord = require("discord.js");
const bot = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
const token =
"MTAxNzgyMjQ1MjU1MTc5NDgxOA.GjO8F-.VWCMsDKV5_YdP1w6gnEME6Jucd7BN9OADesM4s";
const prefix = "lb!";
bot.on("ready", () => {
console.log("Your bot is now online");
});
bot.on("messagecreate", (message) => {
if (message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLocaleLowerCase();
if (command === prefix + "hello") {
message.reply("Hi ${message.author}");
}
});
bot.login(token);
// © Ahmed1Dev
With Regards,
Ahmed1Dev
I rewrite the code. Hope this will work
const Discord = require("discord.js");
const bot = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
const token = "never post your bot token online";
const prefix = "lb!";
bot.on("ready", () => {
console.log("Your bot is now online");
});
bot.on("messageCreate", (message) => {
if (message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (command === "hello") {
message.reply(`Hi ${message.author}`);
}
});
bot.login(token);
Also, if you didn't tick Message Content Intent, then go tick it in Discord Developer Portal

Discord.js v13, #discordjs/voice Play Music Command

This is my code,
The command executes perfectly, The bot joins the voice channel and also sends the name of the song its about to play, but it doesnt play the song in the voice channel.
This is my first time ever asking a question on stackoverflow so dont mind the format and stuff. But I really need help here.
Discord v13 and latest node module.
const ytsearch = require('yt-search');
const Discord = require('discord.js')
const {
joinVoiceChannel,
createAudioPlayer,
createAudioResource,
NoSubscriberBehavior
} = require('#discordjs/voice');
module.exports = {
name: "play",
description: "test command",
async run(client, message, args) {
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send('Please connect to a voice channel!');
if (!args.length) return message.channel.send('Please Provide Something To Play!')
const connection = await joinVoiceChannel({
channelId: message.member.voice.channel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
const videoFinder = async (query) => {
const videoResult = await ytsearch(query);
return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
}
const video = await videoFinder(args.join(' '));
if (video) {
const stream = ytdl(video.url, { filter: 'audioonly' });
const player = createAudioPlayer();
const resource = createAudioResource(stream)
await player.play(resource);
connection.subscribe(player);
await message.reply(`:thumbsup: Now Playing ***${video.title}***`)
} else {
message.channel.send('No video results found');
}
}
}```
I would suggest you look at the music bot example at #discordjs/voice.
They do a good job of how to extract the stream from ytdl.
I'm currently still learning how this all works but the part that you will want to look at is in the createAudioResource function.
public createAudioResource(): Promise<AudioResource<Track>> {
return new Promise((resolve, reject) => {
const process = ytdl(
this.url,
{
o: '-',
q: '',
f: 'bestaudio[ext=webm+acodec=opus+asr=48000]/bestaudio',
r: '100K',
},
{ stdio: ['ignore', 'pipe', 'ignore'] },
);
if (!process.stdout) {
reject(new Error('No stdout'));
return;
}
const stream = process.stdout;
const onError = (error: Error) => {
if (!process.killed) process.kill();
stream.resume();
reject(error);
};
process
.once('spawn', () => {
demuxProbe(stream)
.then((probe) => resolve(createAudioResource(probe.stream, { metadata: this, inputType: probe.type })))
.catch(onError);
})
.catch(onError);
});
}

TypeError: Cannot read properties of null (reading 'id')

So I was updating my bot to discord.js v13 and apparently my logging system has now broke, for some reason it can't read the ID of the guild where this log is occurring.
banAdd.js
const { MessageEmbed} = require("discord.js");
const {red_light} = require("../../other/colors.json");
const Channel = require('../../models/ModerationModel.js');
module.exports = async (bot, guild, user) => {
const guildDB = await Channel.findOne({
guildId: guild.id
}, async (err, guild) => {
if(err) console.error(err)
if (!guild) {
const newGuild = new Channel({
guildId: guild.id,
modChannel: null,
msgChannel: null
});
await newGuild.save().then(result => console.log(result)).catch(err => console.error(err));
}
});
const modChannel = guild.channels.cache.get(guildDB.modChannel);
if (!modChannel) {
return console.log(`No message channel found`);
}
let mEmbed = new MessageEmbed()
.setAuthor(`Member Unbanned`, user.displayAvatarURL({dynamic : true}))
.setColor(red_light)
.setDescription(`${user} ${user.tag}`)
.setThumbnail(`${user.displayAvatarURL({dynamic : true})}`)
.setFooter(`ID: ${user.id}`)
.setTimestamp()
modChannel.send({embeds:[mEmbed]});
}
Error
/home/runner/switch-beta-test/events/guild/banRemove.js:13
guildId: guild.id,
^
TypeError: Cannot read properties of null (reading 'id')
at /home/runner/switch-beta-test/events/guild/banRemove.js:13:27
at /home/runner/switch-beta-test/node_modules/mongoose/lib/model.js:5074:18
at processTicksAndRejections (node:internal/process/task_queues:78:11)
I have no idea why this is not working as it works in previous versions but updating to discord.js V13 completely broke this system. I tried looking at any possible solution but I can't find a single solution.
The cause of this error was because guild can no longer be defined during a users ban or unban, guild and user should be replaced with ban in both the unban and ban logs.
CODE
const { MessageEmbed} = require("discord.js");
const {red_light} = require("../../other/colors.json");
const Channel = require('../../models/ModerationModel.js');
module.exports = async (bot, ban) => {
const guildDB = await Channel.findOne({
guildId: ban.guild.id
}, async (err, guild) => {
if(err) console.error(err)
if (!guild) {
const newGuild = new Channel({
guildId: ban.guild.id,
modChannel: null,
msgChannel: null
});
await newGuild.save().then(result => console.log(result)).catch(err => console.error(err));
}
});
const modChannel = ban.guild.channels.cache.get(guildDB.modChannel);
if (!modChannel) {
return console.log(`No message channel found`);
}
let mEmbed = new MessageEmbed()
.setAuthor(`Member Unbanned`, ban.user.displayAvatarURL({dynamic : true}))
.setColor(red_light)
.setDescription(`${ban.user} ${ban.user.tag}`)
.setThumbnail(`${ban.user.displayAvatarURL({dynamic : true})}`)
.setFooter(`ID: ${ban.user.id}`)
.setTimestamp()
modChannel.send({embeds:[mEmbed]});
}
After this the error should no longer show.
The error says that the guild variable is empty doesn't have a value null and when you do guild.id you're trying to access a property that don't exist
Make sure that the guild variable is assigned to a value
Probably they add some changes to the new version of npm package go check the docs

How to transfer reaction to original message, discord.js

I am trying to make a suggestion feature for one of my bots. I have searched online but nothing really helps with it. The suggestion part is working but I want to add a feature where if i react to the message in the log channel it sends the reaction to the original message. Here is my code:
bot.on('message', message => {
if (message.content.startsWith("/suggest")){
message.reply(`Your response has been recorded.`)
var yes = message.content
const channel1 = bot.channels.cache.get('722590953017442335');
channel1.send(`${message.author} suggests: ${yes.slice(9)}`)
if (chanell1.reaction.emoji.name === '✅'){
const channel2 = bot.channels.cache.get('722595812462297139');
channell2.react.author.message('✅')
}
}
})
I am using v12 of node.
You can use the awaitReactions() function:
bot.on("message", (message) => {
if (message.content.startsWith("/suggest")) {
message.reply(`Your response has been recorded.`);
var yes = message.content;
bot.channels.cache
.get("722590953017442335")
.send(`${message.author} suggests: ${yes.slice(9)}`)
.then(async (msg) => {
msg
.awaitReactions((reaction) => reaction.emoji.name === "✅", {
time: 15000,
})
.then((collected) => message.react("✅"))
.catch(console.error);
});
}
});
Please read the official documentation at https://discord.js.org/#/docs/main/v12/general/welcome for v12 help. You ought to use the Client#messageReactionAdd event to track reactions - your code isn't too far off, however it is missing that key event. Please note that to track reactions you'll need persistent storage if you want the reactions to work after restart. Alternatively, you could try awaiting the reactions or using a reaction collector if only short term.
Try this instead:
const { Client } = require('discord.js');
const bot = new Client({ partials: ['REACTION', 'USER'] });
const prefix = '/';
const suggestionsCache = {};
bot.on('message', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.split(' '),
command = args.shift().slice(prefix.length);
if (command == 'suggest') {
const suggestion = args.join(' '),
suggestionMessage = `${message.author} suggests: ${suggestion}`,
suggestionChannel = bot.channels.cache.get('722590953017442335'),
logChannel = bot.channels.cache.get('722595812462297139');
if (!suggestionChannel || !logChannel) return message.reply('Oops! Something went wrong.');
try {
const suggestionMessage = await suggestionChannel.send(suggestionMessage);
const logMessage = await logChannel.send(suggestionMessage);
suggestionsCache[logMessage.id] = suggestionMessage.id; // Save the ID for later.
message.reply('Your response has been recorded.');
} catch {
message.reply('Oops! Something went wrong.');
};
};
});
bot.on('messageReactionAdd', async (reaction, user) => {
if (reaction.partial) {
try {
await reaction.fetch();
} catch {}
}
const messageID = suggestionsCache[reaction.message.id];
if (!messageID || reaction.emoji.name !== '✅') return; // If not found in cache, ignore and if the emoji isn't the check, ignore it.
try {
const channel = await client.channels.fetch('722590953017442335');
if (!channel) return;
const message = channel.messages.fetch(messageID);
if (!message) return; // Message deleted.
message.react('✅');
} catch {
return;
};
});
Please note that I am new to v12 and normally use v11! The code above is not tested and may contain bugs as a result. Please feel free to edit/update the code.

Resources