I am now trying in vain to remove buttons from a bot message. I have created a command for this purpose. When executing it, it should at best remove a specific, the last or at least all buttons that are on a specific message.
I have tried various things, but in all attempts the buttons are not removed.
module.exports = {
category: 'Utilities',
description: 'Delete Buttons',
permissions: ['ADMINISTRATOR'],
callback: async ({ client, message }) => {
const channel = client.channels.cache.get('the channel id')
channel.messages.fetch('the message id').then(msg => msg.edit({components: []}));
console.log(msg)
}
}
When I try to do this, I get the following console error:
TypeError: Cannot read properties of undefined (reading 'messages')
When I try this, I neither get a console log, nor does the bot do anything ...
const { Client, Message } = require("discord.js");
module.exports = {
category: 'Utilities',
description: 'Delete Buttons',
permissions: ['ADMINISTRATOR'],
callback: async ({ client, message }) => {
client.on('ready', async () => {
const channel = client.channels.cache.get('the channel id')
channel.messages.fetch('the message id').then(msg => {
msg.edit({ components: [] })
});
},
)}
}
Maybe one of you knows a solution or an idea. :)
Thanks a lot!
When I try this, I neither get a console log, nor does the bot do anything
The second example does not do anything because you are creating a ready event handler on running your command. Meaning, it's waiting for the bot to once again be "ready", i.e. the state of having logged in to the API as it does on startup. But your bot is already ready, and will not become ready again until the next time it restarts, so nothing will happen.
As for the first example, the error you are getting suggests channel is undefined, meaning either:
A) You have the incorrect channel ID
- OR -
B) The specified channel is no longer in the channel cache
If you are 100% sure the ID is correct, we can assume the issue you are having is the latter (the channel not being in the cache). There are many ways to solve this, but one simple way is to simply fetch the channel similar to how you are trying to fetch the message. Here's an example:
const channel = await client.channels.fetch('the channel id');
const msg = await channel.messages.fetch('the message id');
msg.edit({components: []});
That should fix the issue. If it doesn't, then the issue is much more complicated and not enough information has been provided. Also note that in the above example, I swapped Promise syntax for async/await since you are using an async function anyways; I did this just to make this answer more readable, you can choose whichever format you prefer.
Related
It was working fine earlier, but now it's just being weird.
module.exports = {
commands: 'test',
callback: (message, args, client) => {
const guild = client.guilds.cache.get('ID') // 'ID' is a replacement for the actual guild ID I'm using.
console.log(guild) // client returns undefined
}
}
(dumbed down to exclude code that is not relevant.)
It was working before, I changed nothing regarding fetching the guild. It's been the same for weeks now, somehow it just doesn't work.*
UPDATE: Found the issue, originally, callback() accepted three params, I edited it to include text (Everything after the command, e.g. !test test would only pick up test and not !test)
So, in reality, client has been arguments.join() all along.
I figured this out after logging client, something I should have done before I posted it here.
I would suggest changing your code to this.
module.exports = {
name: "test",
description: "test",
execute(message, args, client){
const guild = client.guilds.cache.get('ID') // 'ID' is a replacement for the actual guild ID I'm using.
console.log(guild) // client returns undefined
}
}
Recently, discord added support for slash commands for your own application. I read through the documentation for it, and I've tried to search for some videos (however the feature did JUST come out) but I do not understand what I actually have to do to get it working. I am using WebStorm (js, node.js). Has anyone successfully made a slash command, and if so, how?
Documentation
You can use the regular discord.js, by now its v12.5.1.
This is just a sample, but worked for me.
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
client.api.applications(client.user.id).guilds(YOUR_GUILD_ID_HERE).commands.post({
data: {
name: "hello",
description: "hello world command"
// possible options here e.g. options: [{...}]
}
});
client.ws.on('INTERACTION_CREATE', async interaction => {
const command = interaction.data.name.toLowerCase();
const args = interaction.data.options;
if (command === 'hello'){
// here you could do anything. in this sample
// i reply with an api interaction
client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 4,
data: {
content: "hello world!!!"
}
}
})
}
});
});
client.login(token);
Of course you can have options, see documentation...
IDE won't register the new code...at least my php storm currently does'nt :)
However, its important to give the bot the correct permissions to use this type of command!
So go to Discord.com/developers, select your application, go to OAuth2 and select
application.commands
from the scope section. This should be at the bottom of the middle column. You should select bot as well and under Bot Permissionsyou set some other specific permissions. Then use that new invite link to reinvite the bot.
Without application.commands permission, the command won't work and you will receive some error like Missing Access or some similar.
IMPORTANT THINGS
Use .guilds('11231...').comma to test these commands. When not using this, it takes round about 1h to get active. Using it will activate it immediately.
Give the bot the correct permission. application.commands
Hi I don't usually work with discord.js but I was able to find some good documentation on this. You should be able to do it like this with "client" defined.
const interactions = require("discord-slash-commands-client");
const client = new interactions.Client(
"you unique bot token",
"your bots user id"
);
If the client is defined as shown, then a /command should work if defined like this.
// will create a new command and log its data.
//If a command with this name already exist will that be overwritten.
client.createCommand({
name: "your command name",
description: "description for this command",
})
.catch(console.error)
.then(console.log);
Hello I am a bit stuck here, I am trying to make my bot join VC but it returns:
(node:847) UnhandledPromiseRejectionWarning: TypeError: channel.join is not a function
Help would be appreciated :)
client.on("ready", () => {
const channel = client.channels.cache.get("757004209701912587");
if (!channel) return console.error("The channel does not exist!");
channel.join().then(connection => {
// Yay, it worked!
console.log("Successfully connected.");
}).catch(e => {
// Oh no, it errored! Let's log it to console :)
console.error(e);
});
});
Apparently it's really not a function.
After encountering the same problem and searching to no avail for solution for some time, I've stumbled upon this example code: https://github.com/discordjs/voice/tree/main/examples/radio-bot
It uses completely different principles, but by integrating part of it into my code I've managed to create voice connection successfully.
In order to get a valid channel you will first need get a guild from your client.
const guild = client.guilds.cache.get("YOUR_GUILD_ID");
Then you can change your code to:
const channel = guild.channels.cache.get("757004209701912587");
It should work then.
I’m having trouble getting basic conversation callbacks to be fired. Can anyone point me to a working sample with botkit 4 of getting responses from a conversation in Slack? I set up the SlackAdapter and used the SlackEventMiddleware and SlackMessageTypeMiddleware, but my callbacks aren’t getting called.
I took this basic code from the botkit docs and am calling it after a /slash command. The question is written, but no matter what I write, none of the callbacks are fired. I see the events coming to my server, but not to these call backs.
Here’s the code I’m testing with:
let convo = new BotkitConversation('cheese', controller)
await bot.startPrivateConversation(message.user)
// create a path for when a user says YES
convo.addMessage('You said yes! How wonderful.', 'yes_thread')
// create a path for when a user says NO
convo.addMessage('You said no, that is too bad.', 'no_thread')
// create a path where neither option was matched
// this message has an action field, which directs botkit to go back to the `default` thread after sending this message.
convo.addMessage('Sorry I did not understand.', 'bad_response')
// Create a yes/no question in the default thread...
convo.addQuestion(
'Do you like cheese?',
[
{
pattern: 'yes',
handler: async (response, convo, bot) => {
await convo.gotoThread('yes_thread')
}
},
{
pattern: 'no',
handler: async (response, convo, bot) => {
await convo.gotoThread('no_thread')
}
},
{
default: true,
handler: async (response, convo, bot) => {
await convo.gotoThread('bad_response')
}
}
],
'likes_cheese',
'default'
)
controller.addDialog(convo)
await bot.beginDialog(`cheese`)
Any help much appreciated!
So turns out something in my custom storage provider was interfering. I haven't gotten to the bottom of it yet, but when I commented out my storage provider, I was able to get conversation call backs.
e.g.
const controller: Botkit = new Botkit({
adapter: getSlackAdapter()
// TODO: This is causing conversation call backs to NOT fire, let's revisit this later. We may not actually need this.
//storage: services.storageService
})
So, this works ALMOST as intended. I have the bot private messaging the user who uses the correct command in the correct channel of the server. Instead of clogging up the server with profile creation messages, I have the bot do profile creation privately. I know/think the problem is with the message.channel.awaitMessages, because it only sees the replies in the original channel on the server where the command was put into place.
I am not sure what I should replace the message.channel.awaitMessages with in order for it to pick up on the reply in the private message conversation rather than the original profile creation channel on the server.
I have not tested the sql message yet. I haven't tested what I have but I am pretty sure it won't work. I want the reply that is given by the user in the private message to be inserted (updated maybe?) into a mysql database I have already set up and properly got working. The users ID and username has been put into this table with the rest of the profile related questions being null at this moment. As they reply to these questions, those fields can be filled out/updated. Any ideas/suggestions are welcome!
module.exports.run = async (bot, message, args) => {
if(message.channel.id === '460633878244229120') return message.author.send(`Greetings, ${message.author.username}! FIRST QUESTION, **What is the name of your Brawler or Character?**`)
.then(function(){
message.channel.awaitMessages(response => message.content, {
max: 1,
time: 5000,
errors: ['time'],
})
.then((collected) => {
message.author.send(`Your Name is: ${collected.first().content}`);
var sql = (`UPDATE profile SET name = '${message.content}' WHERE id = ${message.author.id}`);
})
.catch(function(){
message.author.send('Please submit a name for your character. To restart Profile creation, please type "!profilecreate" command in Profile Creation channel on the server.');
});
});
}
Thanks in advance for your time!
I don't use SQL so, since the question is not specifically on that, don't ask me.
When you're using message.channel.awaitMessages, message is still the first one that you passed in the module.exports.run function, not the one that comes from send(). When send is resolved, it passes a new message, that you have to include in the arguments of the function you put inside then: so, instead of .then(function() {}) you'll need something like .then(function(new_message_sent_in_private) {})
This should fix the problem:
module.exports.run = async (bot, message, args) => {
if(message.channel.id === '460633878244229120') return message.author.send(`Greetings, ${message.author.username}! FIRST QUESTION, **What is the name of your Brawler or Character?**`)
.then((newmsg) => { //Now newmsg is the message you sent
newmsg.channel.awaitMessages(response => response.content, {
max: 1,
time: 5000,
errors: ['time'],
}).then((collected) => {
newmsg.channel.send(`Your Name is: ${collected.first().content}`);
var sql = (`UPDATE profile SET name = '${message.content}' WHERE id = ${message.author.id}`);
}).catch(() => {
newmsg.channel.send('Please submit a name for your character. To restart Profile creation, please type "!profilecreate" command in Profile Creation channel on the server.');
});
});
}
Let me now if that worked :)