I'd like to create a command, that moves all users in my Discord voice channel.
Here is what i tried.
...
client.on('message', async message =>{
//Check message is not Bot
if(message.author.bot) return;
if(message.content=="!movetome"){
if(message.member.voice.channel) {//Is user in voicechannel
message.guild.members.cache.forEach(member => { //Loop every user
if(member.id!=message.member.id&&member.voice.channel){//Is user in voicechannel and is user the command executer
member.setVoiceChannel(message.member.voice.channel)//Sets user to channel
}
});
}
}
});
...
After I tried to run the command "!movetome" in discord chat I got the following error message:
(node:12268) UnhandledPromiseRejectionWarning: TypeError: member.setVoiceChannel is not a function
Thanks for your help :)
Firstly this seems like a bad idea if any user can do it but regardless, .setVoiceChannel is v11, they moved it to <GuildMember>.voice.setChannel()
Change the contents inside of if(message.content=="!movetome") to this
const channel = message.member.voice.channel;
message.guild.members.cache.forEach(member => {
//guard clause, early return
if(member.id === message.member.id || !member.voice.channel) return;
member.voice.setChannel(channel);
});
Related
My bot is not reading the Discord chat. I want it to read the chat and if it finds certain words it will give a certain response. This is my current message event code. This is my first JavaScript project and I have just started learning it so please rip it apart so I can learn quicker :)
At the moment I can get the bot to load into discord. I can turn it on with .node but I can not get it to read a message using message.content.
const Discord = require("discord.js");
const client = new Discord.Client({ intents: ["GUILD_MESSAGES", "DIRECT_MESSAGES"] });
var name = "Poker Bot";
var usersHand
let firstCardValue
let secondCardValue
let firstCardSuit
let secondCardSuit
//starts the bot and sets activity to a funny quote. it also will give a command prompt notification that the
// bot is online
client.on("ready", () => {
console.log(`Bot is online: ${name} !`);
client.user.setActivity('Burning The Fucking Casino Down');
});
//check discord chat to see if a user has posted.
client.on("messageCreate", message => {
//console.log is there to test user input. If it works the message in the discord channel will appear in console
console.log(`The user has said: ${message} `);
//look for poker hand ~~~ position ~~~~ event (ex: AA CO PF ) (PF= PreFlop)
if (message.content.toLowerCase == 'AK' || message.content.toLowerCase == 'AA' || message.content.toLowerCase == 'KK'){
message.reply("RECOMMENDED PLAY SHOVE: ALL IN")
}
.content is not a method, it's a property, you must now also enable the Message Content intent on your bot page as well as in your code.
const Discord = require("discord.js");
const client = new Discord.Client({ intents: ["GUILD_MESSAGES", "DIRECT_MESSAGES"] });
client.on("messageCreate", message => {
// || "String" like you did before would return "true" in every single instance,
// this is case sensitive, if you wanna make it case insensitive
// use `message.content.toLowerCase() == "lowercasestring"`
if (message.content == "AK" || message.content = "AA" || message.content == "KK") {
message.channel.send("Recommend Play is to shove all in" + message.author);
}
})
client.login(token);
Judging by your information, you dont just want to send a response if the message contains only those strings, but may just contain then.
To check for that, I would suggest to use regex#test
Still as #iiRealistic_Dev rightfully mentioned: message.content is not a function, so removing the brackets is the way to go.
client.on("messageCreate", (message) => {
if (/AK|AA|KK/.test(message.content)) {
message.channel.send("Recommend Play is to shove all in" + message.author);
console.log('it got to here');
}
});
So its hard to explain my situation because i am new to discord.js and i have been trying to figure this out for hours
What i need is my bot to look at a certain channel and see that a staff member (or anyone because normal users cannot add reactions) reacted with "👍" and logs it.
Later my end goal is it sees this and replys and sends a command to a minecraft server. but ill figure all that out later. i just need the bot to see that there is that certain reaction on a message
Like i said i am new, and the docs to discord.js are not helping, all i could find/do is this:
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
const filter = (reaction, user) => {
return reaction.emoji.name === '👍' && user.id === Discord.Message.author.id;
};
const collector = Discord.Message.createReactionCollector(filter, { time: 15000 });
collector.on('collect', (reaction, user) => {
console.log(`Collected ${reaction.emoji.name} from ${user.tag}`);
});
And it throws errors about the Message.createReactionCollector
To use the ReactionCollector you will need an instance of Message to create the collector on.
If you don't have a specific message and want to collect the reactions globally, you could listen for an event messageReactionAdd.
client.on("messageReactionAdd", (reaction, user) => {
// Ignore the bot's reactions
if (client.user.id == user.id) return;
// Look only for thumbs up reaction
if (reaction.emoji.name != "👍") return;
// Accept reactions only from specific channel
if (reaction.message.channel.id != "870115890367176724") return;
console.log(`${user.tag} reacted with 👍.`);
});
Note that this won't work for reactions cast on messages sent before the bot was started. The solution is to enable Partial Structures. (If you are dealing with partial data, don't forget to fetch)
I'm attempting to make a discord bot that checks messages sent in channels for a prefix and argument (!send #Usermention "message"), but despite running, the program closes out as soon as a message is typed in my discord server, not outputting any error messages, so I'm not really sure what to do...
const Discord = require('discord.js');
const client = new Discord.Client();
const auth = require('./auth.json');
const prefix = "!";
client.on("message", (message) =>
{
msg = message.content.toLowerCase();
if (message.author.bot) { return; }
mention = message.mention.users.first(); //gets the first mention of the user's message
if (msg.startsWith (prefix + "send")) //!send #name [message]
{
if (mention == null) { return; } //prevents an error sending a message to nothing
message.delete();
mentionMessage = message.content.slice (6); //removes the command from the message to be sent
mention.sendMessage (mentionMessage); //sends message to mentioned user
message.channel.send ("message sent :)");
}
});
client.login(auth.token);
mention = message.mention.users.first();
It is message.mention**s**. You were missing an s.
Also, you might want to use send, rather than sendMessage, since sendMessage is deprecated.
I am making an RP profile creation setup for a discord bot using javascript. I have the conversation starting in a channel and moving to private messaging with the bot. The first question gets asked and the reply from the user is stored in a database. That is working fine.
What seems to be the problem comes when I try to use another command inside a private message with the bot to move to the next step of the RP profile creation. It doesn't seem to register the command is being used. Can commands even be used in private messaging with a bot?
I used the same code as the first question that worked, changed what needed to be, but nothing that should have broken the code. It just looks to not even see the second command, which is stored in a separate command file. How would I do this?
module.exports.run = async (bot, message, args) => {
message.author.send(` SECOND QUESTION, **What is the age of your Brawler or Character?**`)
.then((newmsg) => { //Now newmsg is the message you send to the bot
newmsg.channel.awaitMessages(response => response.content, {
max: 1,
time: 300000,
errors: ['time'],
}).then((collected) => {
newmsg.channel.send(`Your brawler's age is: **${collected.first().content}**
If you are okay with this age, type !profilegender to continue the profile creation process!
If you would like to edit your age, please type !profileage`)
con.query(`UPDATE profile SET age = '${collected.first().content}' WHERE id = ${message.author.id}`);
console.log("1 record updated!")
}).catch(() => {
newmsg.channel.send('Please submit an age for your character. To restart Profile creation, please type "!profilecreate" command in Profile Creation channel on the server.');
});
});
}
Thanks in advance for your time!
EDIT: This is part of the code that is the bot/client is listening for on message.
bot.on(`message`, async message => {
if(message.author.bot) return;
if(message.channel.type === "dm") return;
con.query(`SELECT * FROM profile WHERE id = '${message.author.id}'`, (err, rows) => {
if(err) throw err;
var sql;
if(rows.length < 1) {
var sql = (`INSERT INTO profile (id, username) VALUES (${message.author.id}, '${message.author.tag}')`);
} else {
var sql = (`UPDATE profile SET username = '${message.author.tag}' WHERE id = ${message.author.id}`);
};
//con.query(sql, console.log);
//if (err) throw err;
//console.log("1 record inserted!");
});
Answer from comments
Inside of your client.on("message") there's an if check that exits the function if the channel is a DMChannel
if(message.channel.type === "dm") return;
To avoid that, simply remove this line: in this way, the bot will execute the command regardless of the channel type. If you want to allow some commands only in certain channels, you can do that either in the client.on("message") or in the function of the command itself.
I am trying to make a discord bot, but I can't quite understand Discord.js.
My code looks like this:
client.on('message', function(message) {
if (message.content === 'ping') {
client.message.send(author, 'pong');
}
});
And the problem is that I can't quite understand how to send a message.
Can anybody help me ?
The send code has been changed again. Both the items in the question as well as in the answers are all outdated. For version 12, below will be the right code. The details about this code are available in this link.
To send a message to specific channel
const channel = <client>.channels.cache.get('<id>');
channel.send('<content>');
To send a message to a specific user in DM
const user = <client>.users.cache.get('<id>');
user.send('<content>');
If you want to DM a user, please note that the bot and the user should have at least one server in common.
Hope this answer helps people who come here after version 12.
You have an error in your .send() line. The current code that you have was used in an earlier version of the discord.js library, and the method to achieve this has been changed.
If you have a message object, such as in a message event handler, you can send a message to the channel of the message object like so:
message.channel.send("My Message");
An example of that from a message event handler:
client.on("message", function(message) {
message.channel.send("My Message");
});
You can also send a message to a specific channel, which you can do by first getting the channel using its ID, then sending a message to it:
(using async/await)
const channel = await client.channels.fetch(channelID);
channel.send("My Message");
(using Promise callbacks)
client.channels.fetch(channelID).then(channel => {
channel.send("My Message");
});
Works as of Discord.js version 12
The top answer is outdated
New way is:
const channel = await client.channels.fetch(<id>);
await channel.send('hi')
To add a little context on getting the channel Id;
The list of all the channels is stored in the client.channels property.
A simple console.log(client.channels) will reveal an array of all the channels on that server.
There are four ways you could approach what you are trying to achieve, you can use message.reply("Pong") which mentions the user or use message.channel.send("Pong") which will not mention the user, additionally in discord.js you have the option to send embeds which you do through:
client.on("message", () => {
var message = new Discord.MessageEmbed()
.setDescription("Pong") // sets the body of it
.setColor("somecolor")
.setThumbnail("./image");
.setAuthor("Random Person")
.setTitle("This is an embed")
msg.channel.send(message) // without mention
msg.reply(message) // with mention
})
There is also the option to dm the user which can be achieved by:
client.on("message", (msg) => {
msg.author.send("This is a dm")
})
See the official documentation.
Below is the code to dm the user:
(In this case our message is not a response but a new message sent directly to the selected user.)
require('dotenv').config({ path: __dirname + '/.env.local' });
const Discord = require("discord.js");
const client = new Discord.Client();
client.on("ready", () => {
console.log(client.users.get('ID_OF_USER').send("hello"));
});
client.login(process.env.DISCORD_BOT_TOKEN);
Further documentation:
https://github.com/AnIdiotsGuide/discordjs-bot-guide/blob/master/frequently-asked-questions.md#users-and-members
You can only send a message to a channel
client.on('message', function(message) {
if (message.content === 'ping') {
message.channel.send('pong');
}
});
If you want to DM the user, then you can use the User.send() function
client.on('message', function(message) {
if (message.content === 'ping') {
message.author.send('pong');
}
});
Types of ways to send a message:
DM'ing whoever ran the command:
client.on('message', function(message) {
if (message.content === 'ping') {
message.author.send('pong');
}
});
Sends the message in the channel that the command was used in:
client.on('message', function(message) {
if (message.content === 'ping') {
message.channel.send('pong');
}
});
Sends the message in a specific channel:
client.on('message', function(message) {
const channel = client.channels.get("<channel id>")
if (message.content === 'ping') {
channel.send("pong")
}
});
It's message.channel.send("content"); since you're sending a message to the current channel.