How would I make the bot react to it's own message? I know it's probably a simple enough thing but I can't find an answer. Thanks in advance.
module.exports = {
name: "ping",
description: "Basic ping command",
execute(message) {
message.channel.send("Pong.");
message.react("🏓");
},
};
Edit: I forgot to say in here that this is Discord.JS, not python
You have the right idea but you add the reaction to the wrong message. To react to the message the bot has send, you can use the Promise returned by TextChannel.send(). Take a look at the example code below and give it a try:
module.exports = {
name: "ping",
description: "Basic ping command",
execute(message) {
message.channel.send("Pong.").then((botMessage) => {
botMessage.react("🏓");
});
},
};
see this article
the code should be
bot.add_reaction(msg, "🏓")
Related
I've been working on a Discord bot. I needed a solution for questions like this: Who are you or who are you.
The above sentences may seem similar but are case sensitive, and I want my bot to reply the same answer to a few similar questions like I showed above. This is What I tried:
import Discord from 'discord.js'
import { Client, Intents } from 'discord.js'
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
client.on("ready", () => {
console.log("Log In Successful!!")
})
client.on("message", msg => {
if (msg.content === 'hello', 'hey') {
msg.reply("hi");
}
})
client.login(process.env.TOKEN)
But when I run it and write the command, it repeats the reply several times.
Any ideas to fix this?
The line that is causing the multiple replies is this one:
if (msg.content === 'hello', 'hey'){
Your syntax is slightly off and the 'hey' is not part of the statement like you want it to be. The 'hey' evaluates to true which triggers the if statement's code a second time.
To fix it, you may want to have an array of responses, and check if the user's message is in the array
(note the .toLowerCase() means you don't have to worry about capital letters):
greetings = ['hello', 'hey', 'hi']
if (greentings.indexOf(msg.content.toLowerCase()) > -1) {
// the message is in the array - run your code here
}
You can group similar questions in an array and use Array#includes to check if the question is in that array. You can also make it case-insensitive by using toLowerCase. Something like this:
client.on("message", (msg) => {
const group = [
'how are you',
'how you doin',
'you alright',
]
if (group.includes(msg.content.toLowerCase())) {
msg.reply('hi');
}
})
Whenever I ping my discord.js bot it shows the API latency as NaNms
This is the output
This is the code
module.exports = {
name: 'ping',
description: 'Pings the bot!',
usage: '',
execute(message) {
const pingEmbed = new Discord.MessageEmbed()
.setColor('RANDOM')
.setTitle('Pong!')
.setThumbnail('https://i.gifer.com/fyMe.gif')
.addFields(
{ name: 'Latency - ', value: `${Date.now() - message.createdTimestamp}ms`, inline: true },
{ name: 'API Latency', value: `${Math.round(client.ws.ping)}ms`, inline: true },
)
.setTimestamp();
message.channel.send(pingEmbed);
},
};
You didnt pass the client as here it's undefined
Either pass the client or use message.client.ws.ping
That's the solution unless the code sample you gave is no full one.
i had this issue too, the problem is that you're adding the client.ws.ping part in the embed instead of the command.
The embed wont have:
client.on('messageCreate', (message) => {}
which is why it gives out "NaNms"
so instead of a separate embed i just made the embed within the command and it works fine, here (but depending on how different the way you set your bot up, it might not work) :
message.channel.send({embeds:[{
title:'Pong!',
description:`API Latency: ${client.ws.ping}`
}]
});
Problem
I am trying to create a [message object][1] in [discordjs][1] in order to send a message from my account. When I do this, I always get this error:
Cannot read property 'slice' of undefined
Code
Here is my code:
client.on("message", async message => {
if (message.author && message.author.bot) {
return;
}
try {
const myMessage = new Discord.Message(
client,
{ author: { id: "myID" }, content: "My new Message" },
message.channel
);
console.log(myMessage);
Additional Information
I have logged Discord, client and message, all exist and are valid objects. I also replaced the data part of the constructor with this:
{ author: message.author, content: message.content },
but to no avail. The error was the same. So what am I doing wrong here?
Solution
After hacking the source code of discord.js I discovered the culprit in the Message.js file. It is this line:
this.createdTimestamp = SnowflakeUtil.deconstruct(this.id).timestamp;
The problem is that I never passed any id to the constructor function in my data object. Just passing a fake id (a string of random numbers) did the trick.
So I have this command that sets the bot's "Playing" status:
const commando = require('discord.js-commando');
const { RichEmbed } = require('discord.js');
class sets extends commando.Command {
constructor(client) {
super(client, {
name: 'setgame',
group: 'owner',
memberName: 'setgame',
description: 'Sets the Bots\' activity',
examples: ['Playing __on many servers!__'],
args: [
{
key: "game",
prompt: "What do you want to set my game as?",
type: "string"
}
]
});
}
async run(message, { game } ) {
if (message.author.id !== "442918106378010635"){
message.channel.send("That's for TheRSC only!");
}
else {
this.client.bot.setActivity(game)
const embed = new RichEmbed()
.setColor(0x00AE86)
.setDescription("Game set!");
message.channel.send({embed});;
}
}
}
module.exports = sets;;
I ran into a few bugs before and managed to fix them, but this one stumps me. No matter how I code it, I keep getting: TypeError: Cannot read property 'setActivity' of undefined
I've tried a few things, having text be defined in run, putting args.game into .setActivity() and it keeps spitting out that error. I tried the splitting the args method but that didn't work either. Any ideas? (As a side note, I'd also like to turn this into a .setPresence command if possible.)
Note: I am a beginner at coding, so I may be doing something that the average coder wouldn't.
Try changing
client.bot.setActivity(game)
to
client.user.setActivity(game)
You can take a look at this example provided by the official documentation on setActivity() if you need more help, or if my solution doesn't work.
client.user.setActivity('YouTube', { type: 'WATCHING' })
.then(presence => console.log(`Activity set to ${presence.game ? presence.game.name : 'none'}`))
.catch(console.error);
EDIT: I still think it has something to do with the .bot part because the only reference on the documentation of .bot was a boolean of whether or not a user was a bot.
I might just be missing something simple, but I've never had this error before and I don't think I edited it enough to cause this problem since it was last functional. The code block below keeps giving me this error at the top of the file:
(node:17592) UnhandledPromiseRejectionWarning: TypeError: client.catch is not a function
I have specified client = new Discord.Client();
The other issue I am having is that I am trying to get the role that is being made by the bot to be the name of the two players/users (challenger vs target format) after the target has accepted the challenge posed by the challenger. It just makes a role named "new role" instead. Any help with either of these problems?
if (message.channel.id === '541736552582086656') return challenged.send("Do you accept the challenge? Please reply with 'accept' or 'deny'.")
.then((newmsg) => {
newmsg.channel.awaitMessages(response => response.content, {
max: 1,
time: 150000,
errors: ['time'],
}).then((collected) => {
// Grabs the first (and only) message from the collection.
const reply = collected.first();
if (reply.content === 'accept'){
reply.channel.send(`You have ***accepted *** the challenge from ${challenger}. Please wait while your battlefield is made...`);
message.author.send(`${target} has accepted your challenge! Please wait while the channel is made for your brawl...`)
var server = message.guild;
var permsName = `${target} vs ${challenger}`;
var name = `${target} vs ${challenger}`;
message.guild.createRole({
data: {
name: permsName,
hoist: true,
color: "#00fffa",
permissions: [] }
}).then(role => {
target.addRole(data, permsName)
challenger.addRole(role, permsName)
// client.catch error occurring below
.catch(error => client.catch(error))
}).catch(error => client.catch(error)).then(
server.createChannel(name, "text")).then(
(channel) => {
channel.setParent("542070913177485323")
})
} else if (reply.content === 'deny') {
reply.channel.send("You have ***denied *** the challenge.")
} else {
reply.channel.send("Your response wasn't valid.");
}
})
})
}
module.exports.help = {
name: "challenge"
}
I have tried looking up the problem and I don't see anything that has helped so far with either issue. They might be related since the catch is after the add role part? Thanks in advance for the help!
Curious if there's a template you copied for this bot? The Discord.Client object does not have any catch method, so calling client.catch() is not going to work.
To clarify, this is fine:
challenger.addRole(role, permsName)
.catch(error => /* do something with this error */);
What can you do with the error? You could print it to console, I suppose:
challenger.addRole(role, permsName)
.catch(error => console.error(error));
But you can't call client.catch(error), because that's not a real method - you can check out the docs for the Client object here.
Regarding the role name, you just have a small error: you don't want to wrap your options object in { data: }, your options object is the data. Just pass them in directly, like so:
message.guild.createRole({
name: permsName,
hoist: true,
color: "#00fffa",
permissions: []
}).then(role => {
Hope that helps!