Hi im new with this type of programming so im triying to do a bot, that allows me to create something like a poll but before that, i wanna know some information from the user (which I'll use later), so i triying to use forceReplay for that, but i dont know how to start to interacting with the user after that
bot.start((ctx) => {
const opts = {
reply_markup: JSON.stringify(
{
force_reply: true,
}
)};
bot.telegram.sendMessage(ctx.chat.id, 'Hi what is your name?', opts);
});
this is my initial code, so, what i need to do from this is wait for the user to write his name and then start a new question...
Note: im using telegraf to create my bot
This is the code I referenced from: Link
bot.onText(/\/start/, async(msg) => {
let listenerReply;
let contentMessage = await bot.sendMessage(msg.chat.id, "Type your name: ", {
"reply_markup": {
"force_reply": true
}
});
listenerReply = (async (replyHandler) => {
bot.removeReplyListener(listenerReply);
await bot.sendMessage(replyHandler.chat.id, `Ohh your name is ${replyHandler.text}`, {"reply_markup": {"force_reply": false}})
});
bot.onReplyToMessage(contentMessage.chat.id, contentMessage.message_id, listenerReply);
});
Hope it helps you
Related
I am currently working on a command right now that I would like the server owner to use. When done it sends the embed and will wait for the server owner to paste we will say the channel id. I want to label this to call in another command but at the moment it sends the embed but when I send a channel ID nothing happens. No message is sent but it also does not break the bot. I am still able to send the command again and again.
Please do not mind the slop, I am new to all this and trying to learn as I go any tips would be appreciated!
EDIT: I am using version 12 (12.5.3)
const { prefix } = require('../config.json');
const Discord = require('discord.js');
const client = new Discord.Client();
module.exports = {
name: 'setchannel',
description: 'command to assign bot to channel',
execute(message, args) {
if(message.channel.type == "dm") {
const keepinservercommandembed = new Discord.MessageEmbed()
.setColor('#FF0000')
.setTitle('**Im Sorry!**')
.addFields(
{ name: `**Can` + `'t accept: ${prefix}setchannel**`, value: 'Please keep this command to the server!' },
)
message.channel.send(keepinservercommandembed);
}
else {
const messagesender = message.member.id;
const serverowner = message.guild.owner.id;
const setchannelembed = new Discord.MessageEmbed()
.setColor('#FF0000')
.addFields(
{ name: `**Let's get searching!**`, value: `Hello ${message.guild.owner}, what channel would you like me to post group finding results?` },
)
const notownerembed = new Discord.MessageEmbed()
.setColor('#FF0000')
.addFields(
{ name: `**Whoops!**`, value: `Sorry only ${message.guild.owner} can use this command.` },
)
if(messagesender == serverowner) {
message.delete ();
const filter = m => m.content.message;
const collector = message.channel.createMessageCollector(filter, { time: 15000 });
message.channel.send(setchannelembed).then(() => {
collector.on('collect', m => {
message.channel.send(`${m.content}`)
});
});
}
else {
message.delete ();
message.channel.send(notownerembed);
}
}
}
}
After comparing your code to my similiar discord.js v13 code and checking out the v12 docs, I think I found the problem.
I don't think m.content.message is a function. If your aim is for someone to paste the channel ID, the filter code would be:
const filter = m => m.author.id === message.guild.owner.id;
To filter out other people who may be entering an ID (assuming the input is valid).
Use the filter as follows:
message.channel.createMessageCollector({filter: filter, time: 15000 });
To filter out invalid inputs:
collector.on('collect', m => {
if (isNaN(m)) return; //all channel id's in discord are integers (numbers)
else message.channel.send(`${m.content}`);
});
First things first, I'm a beginner in node.js and discord.js.
I'm currently working on my own discord bot for fun and I was wondering if it was possible to "store" the data of a slash command. Here is an example of what I mean :
const response = new Discord.MessageEmbed()
.properties()
.properties()
etc...
module.exports = () {
const data = {
data: {
type: 4, // I don't know what type to use for embed message so please correct me if I'm wrong
data: {
content: response
}
}
}
}
Could this be possible to "store" the embed message data in rules.js and use it in main.js like so :
const rules = require('rules.js') //the file would be in a "commands" folder but I'm keeping this simple
client.ws.on('INTERACTION_CREATE', async (interaction) => {
const command = interaction.data.name.toLowerCase()
if (command === 'rules') {
client.api.interactions(interaction.id, interaction.token).callback.post(data) // or post(rules.data) ??? again, I'm a beginner
}
})
You should try to create a function instead of save and export module because is dangerous to use instance class like a module because it's causing a memory issue, so write a factory for this
Here is something you can try:
//file name: slashCmd.js
const Discord = require('discord.js')
module.exports = async function(client, cmdObj) {
client.api.applications(client.user.id).commands.post(cmdObj)
}
You can customize the function as much as you want but you can do this in your index.js
const slashCmd = require('./slashCmd.js');
const client = new Discord.Client()
client.on('ready', () => {
slashCmd(client, {
name: 'cmdName',
description: 'cmdDesc'
})
})
so I made an event handler for my discord bot so that the index.js file would be neat. But for some reason the welcome message that I made whenever someone joins the server doesn't work.
Here's my event handler code:
const eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args, Discord, client));
} else {
client.on(event.name, (...args) => event.execute(...args, Discord, client));
}
}
And Here's my welcome message code:
module.exports = {
name: 'welcome',
once: false,
execute(Discord, client) {
const welcomechannelId = '753484351882133507' //Channel You Want to Send The Welcome Message
const targetChannelId = `846341557992292362` //Channel For Rules
client.on('guildMemberAdd', (member) => {
let welcomeRole = member.guild.roles.cache.find(role => role.name === 'Umay');
member.roles.add(welcomeRole);
const channel = member.guild.channels.cache.get(welcomechannelId)
const WelcomeEmbed = new Discord.MessageEmbed()
.setTitle(`Welcome To ${member.guild.name}`)
.setThumbnail(member.user.displayAvatarURL({dynamic: true, size: 512}))
.setDescription(`Hello <#${member.user.id}>, Welcome to **${member.guild.name}**. Thanks For Joining Our Server.
Please Read ${member.guild.channels.cache.get(targetChannelId).toString()}, and assign yourself some roles at <#846341532520153088>. You can chat in <#753484351882133507> and talk with other people.`)
// You Can Add More Fields If You Want
.setFooter(`Welcome ${member.user.username}#${member.user.discriminator}`,member.user.displayAvatarURL({dynamic: true, size: 512}))
.setColor('RANDOM')
member.guild.channels.cache.get(welcomechannelId).send(WelcomeEmbed)
})
}
}
I get no error, but whenever someone joins the server, he/she won't be given the role and the welcome message doesn't appear. I put the welcome message code on an events folder that the event handler is handling. Can anyone help?
The issue lies within the welcome code.
In the handler code you have the following line:
client.on(event.name, (...args) => event.execute(...args, Discord, client));
This triggers the client on the name property set in the welcome code.
You currently have it set to welcome, which is not a valid event.
The bot is now listening for a welcome event, which will never happen.
First course of action is setting the name property to guildMemberAdd like this:
module.exports = {
name: 'guildMemberAdd',
//the rest of the code
Then you have another issue.
Within the welcome code you have client.on() again.
This will never work, unless by some incredibly lucky chance 2 people join within a millisecond of each other, but even then you'll only have 1 welcome message.
Removing the following:
client.on('guildMemberAdd', (member) => {
//code
})
will fix that issue.
Then the last thing to do is having the member value being imported correctly.
We do this by changing the following line:
execute(Discord, client) {
to:
execute(member, Discord, client) {
//code
The resulting code will look like this:
module.exports = {
name: 'guildMemberAdd',
once: false,
execute(member, Discord, client) {
const welcomechannelId = '753484351882133507' //Channel You Want to Send The Welcome Message
const targetChannelId = `846341557992292362` //Channel For Rules
let welcomeRole = member.guild.roles.cache.find(role => role.name === 'Umay');
member.roles.add(welcomeRole);
const channel = member.guild.channels.cache.get(welcomechannelId)
const WelcomeEmbed = new Discord.MessageEmbed()
.setTitle(`Welcome To ${member.guild.name}`)
.setThumbnail(member.user.displayAvatarURL({dynamic: true, size: 512}))
.setDescription(`Hello <#${member.user.id}>, Welcome to **${member.guild.name}**. Thanks For Joining Our Server.
Please Read ${member.guild.channels.cache.get(targetChannelId).toString()}, and assign yourself some roles at <#846341532520153088>. You can chat in <#753484351882133507> and talk with other people.`)
// You Can Add More Fields If You Want
.setFooter(`Welcome ${member.user.username}#${member.user.discriminator}`,member.user.displayAvatarURL({dynamic: true, size: 512}))
.setColor('RANDOM')
member.guild.channels.cache.get(welcomechannelId).send(WelcomeEmbed)
}
}
Happy coding!
My code is:
client.ws.on('INTERACTION_CREATE', async interaction => {
const command = interaction.data.name.toLowerCase();
const args = interaction.data.options;
if (command === 'test'){
console.log("Test executed")
client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 4,
data: {
content: "Check"
}
}
})
}
});
I want to delete the answer but I don't really understand how (Very new to this discord.js thing xd)
I saw this post but can't make the answer work
Can anybody please help :(
EDIT: Is it also possible to have a cooldown for a slash command?
To delete a reply to an interaction (according to Discord Developer Portal) with discord.js v12 use the following:
client.api.webhooks(client.user.id, interaction.token)
.messages("#original").delete();
Is it also possible to have a cooldown for a slash command?
Yes, it is definitely possible. It should be very similar to cooldowns for non-slash commands. Here you can take a look at this post, very simple cooldown system. Or here you have something more complex.
Here you can have a look at my simple and far from perfect example concerning cooldown system for slash commands:
const cooldowns = new Set();
client.ws.on("INTERACTION_CREATE", (interaction) => {
const userId = interaction.member.user.id;
const commandName = interaction.data.name.toLowerCase();
const cooldownId = `${commandName}_${userId}`;
const cooldownDuration = 60000; // 60 000 ms = 1 minute
if (cooldowns.has(cooldownId)) {
// There is a cooldown, notify user and return
client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 4,
data: {
content: "Wait 1 minute before typing this again!",
flags: 64, // make reply ephemeral
}
}
});
return;
}
// Create cooldown for next use
cooldowns.add(cooldownId);
setTimeout(() => { // Schedule cooldown deletion
cooldowns.delete(cooldownId);
}, cooldownDuration);
// ... Execute the command ...
});
i have been trying to make a afk and endafk command for my bot using mongodb.My command work fine but i would like so when you ping someone who is afk it send a message like this: This user is currently AFK!\n**${afkReason}**,but this isnt working.I have been trying to fix it but it still doesn't work so if someone could help me that would be nice thanks you.
Here is my afk command:
const mongoose = require('mongoose')
const db = process.env.DB
mongoose.connect(db)
const Afk = require(process.env.ROOTDIR + '/models/afk.js')
const Discord = require('discord.js')
module.exports.help = {
name: "afk",
aliases: ['afk', 'setafk', 'afkset'],
category: 'misc',
description: "Set your activity to afk",
usage: " ",
cooldown: 0,
args: false
};
module.exports.run = async (client, message, args) => {
await message.delete()
let afkReason = args.slice(0).join(" ")
if(!afkReason) return(afkReason = "No reason provided")
const nAfk = new Afk({
username: message.author.tag,
userID: message.author.id,
afkReason: afkReason,
guildID: message.guild.id,
time: message.createdAt.toUTCString()
})
nAfk.save()
.then(result => console.log(result))
.catch(err => console.log(err));
message.reply(`is now afk: **${afkReason}.**`)
message.member.setNickname("[AFK] " + message.author.username);
// this is the part where it isnt working
if (message.mentions.member) {
message.reply(`This user is currently AFK!\n**${afkReason}**`);
}
}
Have a good day.
:)
You actually check message in your afk command 😃
You need to put this code :
if (message.mentions.member) {
message.reply(`This user is currently AFK!\n**${afkReason}**`);
}
inside message event, and check if member mentionned is afk 😉
I hope my answer helps you :)
Just a simple Problem
When you do
if(!afkReason) return(afkReason = "No reason provided")
The return actually ends the function (the run function)there and no code after that will be executed.
So try doing it without the return
if(!afkReason){ afkReason = "No reason provided" }
Now where you said the actual error was.
As you can see message.mentions.member dosen't exist. It should be message.mentions.members.first()
Then run a find
Example:
if(message.mentions.members.first(){
let member = message.mentions.members.first();
Afk.find({
userID: member.user.id
}).then( afkstat => {
message.channel.send(`The user is afk.\nReason: ${afkstat.afkReason}`);
}).catch(console.log)
}
You might wanna put this in the chient.on("message", message=> {}); function