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');
Related
I'm trying to create a modmail system and whenever I try to make it, it says "channel.send is not a function, here is my code."
const Discord = require("discord.js")
const client = new Discord.Client()
const db = require('quick.db')
// ...
client.on('message', message => {
if(db.fetch(`ticket-${message.author.id}`)){
if(message.channel.type == "dm"){
const channel = client.channels.cache.get(id => id.name == `ticket-${message.author.id}`)
channel.send(message.content)
}
}
})
// ...
client.login("MYTOKEN")
I'm trying this with version 12.0.0
EDIT:
I found my issue, for some reason the saved ID is the bots ID, not my ID
As MrMythical said, you should use the find function instead of get. I believe the issue is that you're grabbing a non-text channel, since channel is defined, you just can't send anything to it.
You could fix this by adding an additional catch to ensure you are getting a text channel, and not a category or voice channel. I would also return (or do an error message of sorts) if channel is undefined.
Discord.js v12:
const channel = client.channels.cache.find(c => c.name === `ticket-${message.author.id}` && c.type === 'text');
Discord.js v13:
const channel = client.channels.cache.find(c => c.name === `ticket-${message.author.id}` && c.type === 'GUILD_TEXT');
Edit:
You can tell channel is defined because if it weren't it would say something along the lines of: Cannot read property 'send' of undefined.
You are trying to find it with a function. Use .find for that instead:
const channel = client.channels.cache.find(id => id.name == `ticket-${message.author.id}`)
I have a code where if someone joins the bot gives a Privat message and a Role but when a user joins, the bot does not give the message and the Role.
TypeError: memb.guild.roles.find
const AUTOROLEID = "689098211536666624"
client.on('guildMemberAdd', (memb) => {
var role = memb.guild.roles.find(r => r.id == "689098211536666624")
if (role) {
memb.addRole(role).then(() => {
memb.send('', new Discord.MessageEmbed().setColor(0x18FFFF).setDescription(`Willkommen aufm Discord deine aktuelle rolle ist ${role.name}!`))
})
}
})
As Discord.js v12 docs you need to access the property cache after <GuildMember>.guild.roles which is a collection of all roles in the guild so you can try this:
var role = memb.guild.roles.cache.find(r => r.id == "689098211536666624")
From the given code, I assume you are using discord.js v11 which got deprecated. So update to v12. v12 introduced the concept of managers/cache. In v11 you were able to use collection methods like get() and find()on collection structures, but now you need to ask for cache on a manager before trying to use collection methods.
Eg:
var role = memb.guild.roles.cache.find(r => r.id == "689098211536666624") //find requires a function
var var role = memb.guild.roles.cache.get("689098211536666624"); //get requires an ID as string.
and <GuildMember>.addRole() method got deprecated. You need to pass through the managers(GuildMemberRoleManager) and then call then .add() method.
Eg:
var role = memb.guild.roles.cache.find(r => r.id == "689098211536666624")
if(role){
memb.roles.add(role).then(()=>{
//do things.
}
}
I am trying to build a bot with the discord.js library in node.js that will create a new voice channel in a certain category when a user joins a certain channel. After the creation of the channel, I want the bot to then move the user to the new channel!
I am trying the following code:
var temporary = [];
client.on('voiceStateUpdate', async (oldMember, newMember) => {
const mainCatagory = '815281015207624704';
const mainChannel = '814938402137833484';
if (newMember.voiceChannelID == mainChannel) {
await newMember.guild
.createChannel(`📞 ┋ Support Room`, { type: 'voice', parent: mainCatagory })
.then(async (channel) => {
temporary.push({ newID: channel.id, guild: newMember.guild.id });
await newMember.setVoiceChannel(channel.id);
});
}
if (temporary.length >= 0)
for (let i = 0; i < temporary.length; i++) {
let ch = client.guilds
.find((x) => x.id === temporary[i].guild)
.channels.find((x) => x.id === temporary[i].newID);
if (ch.members.size <= 0) {
await ch.delete();
return temporary.splice(i, 1);
}
}
});
The code comes with no error but doesn't create the voice channel!
The problem is that you are using discord.js v12, but your code is made for v11.
Client#voiceStateUpdate now passes VoiceStates as parameters, not GuildMembers. You should rename newMember and oldMember to newState and oldState respectively.
GuildMember#voiceChannelID is a deprecated property, which is why you don't get any errors. Your code never actually gets past the if statement. It has turned into GuildMember#voice#channelID (newState.channelID).
Guild#createChannel is also deprecated, being replaced with Guild#channels#create. The function still looks and acts the same, so you only need to change the name (newState.guild.channels.create).
GuildMember#setVoiceChannel has turned into GuildMember#voice#setChannel (newState.setChannel)
Client#guilds#find has turned into Client#guilds#cache#find (client.guilds.cache.find)
Guild#channels#find has turned into Guild#channels#cache#find (client.cache.find(...).channels.cache.find)
(As a side note, always use Collection#get instead of Collection#find when searching by IDs. .find((value) => value.id === '...') should always be converted to simply .get('...'). This also applies to switching Collection#some with Collection#has)
Guild#members#size has turned into Guild#members#cache#size (ch.members.cache.size)
Every single one of these deprecations occurred as a result of discord.js switching to a Manager/caching system. For example, Client#guilds now returns a GuildManager instead of a collection.
More information about switching from v11 to v12 (including Managers)
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().
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();
}
});
})