Bot isn't listening to guildMemberAdd - javascript

I signed up just a few moments ago because something was really bothering me:
I have the following code:
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('guildMemberAdd', (member) => {
console.log('New member.')
const welcomeEmbed = new Discord.MessageEmbed()
.setImage(member.user.avatarURL())
.setColor('#e9fa2a')
.setAuthor("Mangoly Assistant")
.setTitle("New member in server")
.setDescription('Welcome <#${member.id}> to the server! If you are new, please be sure to check out or rules channel and some useful links. We are glad to be having you here, everyone wave hello! :wave:')
.setFooter('Created by kostis;#4464. || Mangoly Assistant')
client.channels.cache.get('825130442197434418').send(welcomeEmbed)
});
client.once('ready', () => {
console.log('Bot is ready')
})
client.login(nice try);
For some reason, when I leave and rejoin the server, the embed isn't sending at all to the channel. I am getting no errors in the console. Any ideas on what may have gone wrong? Thanks. :)

You need 'Server Members Intent' enabled when you invite the bot. Go to Discord Developer Portal > Bot > Scroll to bottom > make sure server members intent is checked
You should also be able to enable it manually in your code, but idrk how to do it. I think it’s like this:
//Client declaration
const client = new Discord.Client({
ws: {
intents: ['GUILD_MEMBERS']
}
})
Also, quick thing: to use ${variableHere} in a string, it must be a string with backticks ( ` ), like this:
var a = 'abc';
var b = '${a}d' //returns ${a}d
var c = `${a}d` //returns abcs

Related

Discord bot not responding to command javascript

I have been trying to make a Discord bot that responds to the user when they ask for help. Sadly I can't seem to get the bot to work. I am using Discord.JS on Node.JS. Any help would be welcome.
const Discord = require('discord.js');
const bot = new Discord.Client();
const token = '[token removed]';
const PREFIX = '!';
bot.on('ready', () => {
console.log('K08 Help Bot is online!');
})
bot.on('message', message=>{
let args = message.content.substring(PREFIX.lenght).split(" ");
switch(args[0]){
case 'help':
message.reply('HELLO');
break;
}
})
bot.login(token);
This might be the issue:
let args = message.content.substring(PREFIX.lenght).split(" "); - length is mistyped as lenght
On a side note: I've submitted an edit to hide your token in this question. For security, you should never share your token; it would allow someone to take over your bot!

displayavatarURL when someone joins the server returns always the same error

im trying to make my discord.js bot send an embed when someone joins, with as thumbnail their pfp, but it always leaves the same error.
code:
bot.on('guildMemberAdd', member => {
// Send the message to a designated channel on a server:
const WelcomeChannel = member.guild.channels.cache.find(ch => ch.name === config.WelcomeChannelVar);
var newMember = member
// Do nothing if the channel wasn't found on this server
if (!WelcomeChannel) return;
const welcomeEmbed = new Discord.MessageEmbed()
.setTitle(newMember + 'joined!')
.addField('username', member)
.setColor(0x348a58)
.setThumbnail(newMember.showAvatarURL())
.setFooter('wow very nice profile bro')
WelcomeChannel.send(welcomeEmbed);
member.send("welcome to frogpond! read the rules :)");
});
error:
TypeError: newMember.showAvatarURL is not a function
I've tried everything. can somebody help plz?
thanks!
I'm pretty sure that showAvatarURL() is not a function and you mean avatarURL() instead, so you should change your code to be like this:
const welcomeEmbed = new Discord.MessageEmbed()
// your stuff before thumbnail
.setThumbnail(newMember.user.avatarURL())
// your stuff after thumbnail
edit: the .user is important, because avatarURL is only a User function
It's because you wrote showAvatarURL() instead of displayAvatarURL().

generalChannel.send is not a function

I'm creating a discord bot, and I am trying to make it so that it would greet everyone when it turns on. I have been using bot.channels.get to find the channel and so far that part of the code works fine. It stops working when it tries to send a message.
I have tried all combinations of bot.channels.get and bot.channels.find, together with generalChannel.send and generalChannel.sendMessage, but to still no avail.
const Discord = require('discord.js');
const fs = require('fs');
const bot = new Discord.Client();
let rawVariables = fs.readFileSync('variables.json');
let variables = JSON.parse(rawVariables);
var generalChannel;
bot.on('ready', () => {
generalChannel = bot.channels.get(variables.Channels.general);
generalChannel.send("Helllo!");
});
bot.login(variables.BotToken);
I just need it to message the channel when it starts up.
variables.Channels.general should be a string of the id of your channel
you can get the id by rightclicking on a channel -> copy id
it should look something like this:
'408632672669273'

How Find Emojis By Name In Discord.js

So I have been utterly frustrated these past few days because I have not been able to find a single resource online which properly documents how to find emojis when writing a discord bot in javascript. I have been referring to this guide whose documentation about emojis seems to be either wrong, or outdated:
https://anidiots.guide/coding-guides/using-emojis
What I need is simple; to just be able to reference an emoji using the .find() function and store it in a variable. Here is my current code:
const Discord = require("discord.js");
const config = require("./config.json");
const fs = require("fs");
const client = new Discord.Client();
const guild = new Discord.Guild();
const bean = client.emojis.find("name", "bean");
client.on("message", (message) => {
if (bean) {
if (!message.content.startsWith("#")){
if (message.channel.name == "bean" || message.channel.id == "478206289961418756") {
if (message.content.startsWith("<:bean:" + bean.id + ">")) {
message.react(bean.id);
}
}
}
}
else {
console.error("Error: Unable to find bean emoji");
}
});
p.s. the whole bean thing is just a test
But every time I run this code it just returns this error and dies:
(node:3084) DeprecationWarning: Collection#find: pass a function instead
Is there anything I missed? I am so stumped...
I never used discord.js so I may be completely wrong
from the warning I'd say you need to do something like
client.emojis.find(emoji => emoji.name === "bean")
Plus after looking at the Discord.js Doc it seems to be the way to go. BUT the docs never say anything about client.emojis.find("name", "bean") being wrong
I've made changes to your code.
I hope it'll help you!
const Discord = require("discord.js");
const client = new Discord.Client();
client.on('ready', () => {
console.log('ready');
});
client.on('message', message => {
var bean = message.guild.emojis.find(emoji => emoji.name == 'bean');
// By guild id
if(message.guild.id == 'your guild id') {
if(bean) {
if(message.content.startsWith("<:bean:" + bean.id + ">")) {
message.react(bean.id);
}
}
}
});
Please check out the switching to v12 discord.js guide
v12 introduces the concept of managers, you will no longer be able to directly use collection methods such as Collection#get on data structures like Client#users. You will now have to directly ask for cache on a manager before trying to use collection methods. Any method that is called directly on a manager will call the API, such as GuildMemberManager#fetch and MessageManager#delete.
In this specific situation, you need to add the cache object to your expression:
var bean = message.guild.emojis.cache?.find(emoji => emoji.name == 'bean');
In case anyone like me finds this while looking for an answer, in v12 you will have to add cache in, making it look like this:
var bean = message.guild.emojis.cache.find(emoji => emoji.name == 'bean');
rather than:
var bean = message.guild.emojis.find(emoji => emoji.name == 'bean');

How to Play Audio File Into Channel?

How do you play an audio file from a Discord bot? Needs to play a local file, be in JS, and upon a certain message being sent it will join the user who typed the message, and will play the file to that channel.
GitHub Project: LINK
In order to do this there are a few things you have to make sure of first.
Have FFMPEG installed & the environment path set for it in Windows [link]
Have Microsoft Visual Studio (VS) installed [link]
Have Node.js installed.[link]
Have Discord.js installed in VS.
From there the steps are quite simple. After making your project index.js you will start typing some code. Here are the steps:
Add the Discord.js dependency to the project;
var Discord = require('discord.js');
Create out client variable called bot;
var bot = new Discord.Client();
3. Create a Boolean variable to make sure that the system doesn't overload of requests;
var isReady = true;
Next make the function to intercept the correct message;
bot.on('message', message =>{ENTER CODE HERE});
Create an if statement to check if the message is correct & if the bot is ready;
if (isReady && message.content === 'MESSAGE'){ENTER CODE HERE}
Set the bot to unready so that it cannot process events until it finishes;
isReady = false;
Create a variable for the channel that the message-sender is currently in;
var voiceChannel = message.member.voice.channel;
Join that channel and keep track of all errors;
voiceChannel.join().then(connection =>{ENTER CODE HERE}).catch(err => console.log(err));
Create a refrence to and play the audio file;
const dispatcher = connection.play('./audiofile.mp3');
Slot to wait until the audio file is done playing;
dispatcher.on("end", end => {ENTER CODE HERE});
Leave channel after audio is done playing;
voiceChannel.leave();
Login to the application;
bot.login('CLIENT TOKEN HERE');
After you are all finished with this, make sure to check for any un-closed brackets or parentheses. i made this because it took my hours until I finally found a good solution so I just wanted to share it with anybody who is out there looking for something like this.
thanks so much!
One thing I will say to help anyone else, is things like where it says ENTER CODE HERE on step 10, you put the code from step 11 IE:
dispatcher.on("end", end => voiceChannel.leave());
As a complete example, this is how I have used it in my message command IF block:
if (command === "COMMAND") {
var VC = message.member.voiceChannel;
if (!VC)
return message.reply("MESSAGE IF NOT IN A VOICE CHANNEL")
VC.join()
.then(connection => {
const dispatcher = connection.playFile('c:/PAtH/TO/MP3/FILE.MP3');
dispatcher.on("end", end => {VC.leave()});
})
.catch(console.error);
};
I went ahead an included Nicholas Johnson's Github bot code here, but I made slight modifications.
He appears to be creating a lock; so I created a LockableClient that extends the Discord Client.
Never include an authorization token in the code
auth.json
{
"token" : "your-token-here"
}
lockable-client.js
const { Client } = require('discord.js')
/**
* A lockable client that can interact with the Discord API.
* #extends {Client}
*/
class LockableClient extends Client {
constructor(options) {
super(options)
this.locked = false
}
lock() {
this.setLocked(true)
}
unlock() {
this.setLocked(false)
}
setLocked(locked) {
return this.locked = locked
}
isLocked {
return this.locked
}
}
module.exports = LockableClient;
index.js
const auth = require('./auth.json')
const { LockableClient } = require('./lockable-client.js')
const bot = new LockableClient()
bot.on('message', message => {
if (!bot.isLocked() && message.content === 'Gotcha Bitch') {
bot.lock()
var voiceChannel = message.member.voiceChannel
voiceChannel.join().then(connection => {
const dispatcher = connection.playFile('./assets/audio/gab.mp3')
dispatcher.on('end', end => voiceChannel.leave());
}).catch(err => console.log(err))
bot.unlock()
}
})
bot.login(auth.token)
This is an semi old thread but I'm going to add code here that will hopefully help someone out and save them time. It took me way too long to figure this out but dispatcher.on('end') didn't work for me. I think in later versions of discord.js they changed it from end to finish
var voiceChannel = msg.member.voice.channel;
voiceChannel.join()
.then(connection => {
const dispatcher = connection.play(fileName);
dispatcher.on("finish", end => {
voiceChannel.leave();
deleteFile(fileName);
});
})
.catch(console.error);
Note that fileName is a string path for example: fileName = "/example.mp3". Hopefully that helps someone out there :)
Update: If you want to detect if the Audio has stopped, you must subscribe to the speaking event.
voiceChannel
.join()
.then((connection) => {
const dispatcher = connection.play("./audio_files/file.mp3");
dispatcher.on("speaking", (speaking) => {
if (!speaking) {
voiceChannel.leave();
}
});
})

Categories

Resources