I am making a Google Assistant Discord bot, but I want to know how your bot will reply to your second message. For example:
first, you say hey google
, then the bot says I'm listening
, and then you say what time is it
and he says 2.40 pm
.
I did the first part but I don't know how to make it reply to the second argument. Can someone help me with it?
You can use a message collector. You can send an I'm listening
message and in the same channel set up a collector using createMessageCollector
.
For its filter, you can check if the incoming message is coming from the same user who want to ask your assistant.
You can also add some options, like the maximum time the collector is collecting messages. I set it to one minute, and after a minute it sends a message letting the user know that you're no longer listening.
client.on('messageCreate', async (message) => {
if (message.author.bot) return;
if (message.content.toLowerCase().startsWith('hey google')) {
const questions = [
'what do you look like',
'how old are you',
'do you ever get tired',
'thanks',
];
const answers = [
'Imagine the feeling of a friendly hug combined with the sound of laughter. Add a librarian’s love of books, mix in a sunny disposition and a dash of unicorn sparkles, and voila!',
'I was launched in 2021, so I am still fairly young. But I’ve learned so much!',
'It would be impossible to tire of our conversation.',
'You are welcome!',
];
// send the message and wait for it to be sent
const confirmation = await message.channel.send(`I'm listening, ${message.author}`);
// filter checks if the response is from the author who typed the command
const filter = (m) => m.author.id === message.author.id;
// set up a message collector to check if there are any responses
const collector = confirmation.channel.createMessageCollector(filter, {
// set up the max wait time the collector runs (optional)
time: 60000,
});
// fires when a response is collected
collector.on('collect', async (msg) => {
if (msg.content.toLowerCase().startsWith('what time is it')) {
return message.channel.send(`The current time is ${new Date().toLocaleTimeString()}.`);
}
const index = questions.findIndex((q) =>
msg.content.toLowerCase().startsWith(q),
);
if (index >= 0) {
return message.channel.send(answers[index]);
}
return message.channel.send(`I don't have the answer for that...`);
});
// fires when the collector is finished collecting
collector.on('end', (collected, reason) => {
// only send a message when the "end" event fires because of timeout
if (reason === 'time') {
message.channel.send(
`${message.author}, it's been a minute without any question, so I'm no longer interested... 🙄`,
);
}
});
}
});