I am trying to make a system that makes a user enter a code(like a verification code sent to the dms) before doing the action. I am trying to understand how my code can wait for the code to be entered, and I came across the awaitMessages tag. I am trying to understand how I can use it properly in my code. Here is my code.
const Discord = require("discord.js");
const config = require("./config.json");
const { MessageAttachment, MessageEmbed } = require('discord.js');
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES", "DIRECT_MESSAGES", "DIRECT_MESSAGE_REACTIONS", "DIRECT_MESSAGE_TYPING"], partials: ['CHANNEL',] })
const RichEmbed = require("discord.js");
const prefix = "!";
client.on("messageCreate", function(message) {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const commandBody = message.content.slice(prefix.length);
const args = commandBody.split(' ');
const command = args.shift().toLowerCase();
if (command === "news") {
if (message.channel.type == "DM") {
message.author.send(" ");
}
}
if (command === "help") {
message.author.send("The help desk is avaliable at this website: https://example.com/");
}
});
client.on("messageCreate", function(message) {
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const commandBody = message.content.slice(prefix.length);
const args = commandBody.split(' ');
const command = args.shift().toLowerCase();
if (command === "ping") {
const timeTaken = Date.now() - message.createdTimestamp;
message.channel.send(`Pong! This message had a latency of ${timeTaken}ms.`);
}
if (command === "delete all messages") {
const timeTaken = Date.now() - message.createdTimestamp;
const code = Math.random(1,1000)
message.channel.send(`Executing command. Verification Required.`);
message.author.send(`Your code is the number ${code}.`)
message.channel.send(`Please confirm your code. The code has been sent to your dms. Confirm it in here.`)
message.channel.awaitMessage(code) {
message.channel.send('confirmed. Doing the action.')
}
}
});
client.login(config.BOT_TOKEN)
To wait for a response from the user, you can use a collector.
You can create a filter to see if the user sending the code is the same as the one who executed the command and if the code sent is correct
const filter = (msg) => msg.author.id === message.author.id && msg.content === code;
const collector = message.channel.createMessageCollector({
filter,
time: 60000,
});
collector.on('collect', (collectedMessage) => {
collector.stop('success');
message.channel.send('confirmed. Doing the action.')
});
collector.on('end', (collected, reason) => {
if (reason === 'success') return;
else message.channel.send('Timeout or error');
});
Related
How assign role to user in discord by slash command?
This is my discord code by node.js using discord.js module.
After finish this code, I want add role on ready event.
Please fixt:
This small code doesn't working.
else if (command === "red") {
// Create a new text channel
let role = guild.roles.find((r) => r.id === "948192740632588329");
// Or add it to yourself
message.member.roles.add(role);
}
in below.
const Discord = require("discord.js");
const config = require("./config.json");
const {
Client,
Intents,
MessageEmbed,
MessageAttachment,
} = require("discord.js");
const { MessageActionRow, MessageButton } = require("discord.js");
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
});
client.on("messageCreate", function (message) {
let guild = message.guild;
if (message.author.bot) return;
if (!message.content.startsWith(prefix)) return;
const commandBody = message.content.slice(prefix.length);
const args = commandBody.split(" ");
const command = args.shift().toLowerCase();
if (command === "ping") {
const timeTaken = Date.now() - message.createdTimestamp;
message.reply(`Pong! This message had a latency of ${timeTaken}ms.`);
} else if (command === "sum") {
const numArgs = args.map((x) => parseFloat(x));
const sum = numArgs.reduce((counter, x) => (counter += x));
message.reply(`The sum of all the arguments you provided is ${sum}!`);
} else if (command === "channel") {
// Create a new text channel
guild.channels
.create("nft-checking", { reason: "Needed a cool new channel" })
.then(console.log)
.catch(console.error);
} else if (command === "red") {
// Create a new text channel
let role = guild.roles.find((r) => r.id === "948192740632588329");
// Or add it to yourself
message.member.roles.add(role);
}
});
if (command === "ping") {
const timeTaken = Date.now() - message.createdTimestamp;
message.reply(ping! This message had a latency of ${timeTaken}ms.);
Replace these line with this
Or
Just correct the spelling of from pong to ping.
I started making a music bot for my discord server when i input command for playing song it returns that execute is not defined i tried to fix but i had no success. That's why I am asking here.
Note: I made event and command handler but that is not the problem since it was also not working before implementing it.
Here is my code from event that happens on message aka starting command:
module.exports = (client, Discord, message)=>{
const prefix = '-';
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split('/ +/');
const cmd = args.shift().toLowerCase();
const command = client.commands.get(cmd) || client.commands.find(a => a.aliases && a.aliases.includes(cmd));
//const ChannelName = message.channel.name;
try{
command.execute(args, cmd, client, Discord, message);
} catch(err){
message.reply("There was an error trying to execute this command!");
console.log(err);
}
}
And here is my code for play command:
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
const queue = new Map();
module.exports = {
name: 'play',
aliases: ['skip', 'stop'],
cooldown: 0,
description: 'Advanced music bot',
async execute(args, cmd, client, Discord, message){
const voice_channel = message.member.voice.channel;
if (!voice_channel) return message.channel.send('You need to be in a channel to execute this command!');
const permissions = voice_channel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) return message.channel.send('You dont have the correct permissins');
if (!permissions.has('SPEAK')) return message.channel.send('You dont have the correct permissins');
const server_queue = queue.get(message.guild.id);
if (cmd === 'play'){
if (!args.length) return message.channel.send('You need to send the second argument!');
let song = {};
if (ytdl.validateURL(args[0])) {
const song_info = await ytdl.getInfo(args[0]);
song = { title: song_info.videoDetails.title, url: song_info.videoDetails.video_url }
} else {
const video_finder = async (query) =>{
const video_result = await ytSearch(query);
return (video_result.videos.length > 1) ? video_result.videos[0] : null;
}
const video = await video_finder(args.join(' '));
if (video){
song = { title: video.title, url: video.url }
} else {
message.channel.send('Error finding video.');
}
}
if (!server_queue){
const queue_constructor = {
voice_channel: voice_channel,
text_channel: message.channel,
connection: null,
songs: []
}
queue.set(message.guild.id, queue_constructor);
queue_constructor.songs.push(song);
try {
const connection = await voice_channel.join();
queue_constructor.connection = connection;
video_player(message.guild, queue_constructor.songs[0]);
} catch (err) {
queue.delete(message.guild.id);
message.channel.send('There was an error connecting!');
throw err;
}
} else{
server_queue.songs.push(song);
return message.channel.send(`👍 **${song.title}** added to queue!`);
}
}
else if(cmd === 'skip') skip_song(message, server_queue);
else if(cmd === 'stop') stop_song(message, server_queue);
}
}
const video_player = async (guild, song) => {
const song_queue = queue.get(guild.id);
if (!song) {
song_queue.voice_channel.leave();
queue.delete(guild.id);
return;
}
const stream = ytdl(song.url, { filter: 'audioonly' });
song_queue.connection.play(stream, { seek: 0, volume: 0.5 })
.on('finish', () => {
song_queue.songs.shift();
video_player(guild, song_queue.songs[0]);
});
await song_queue.text_channel.send(`🎶 Now playing **${song.title}**`)
}
const skip_song = (message, server_queue) => {
if (!message.member.voice.channel) return message.channel.send('You need to be in a channel to execute this command!');
if(!server_queue){
return message.channel.send(`There are no songs in queue 😔`);
}
server_queue.connection.dispatcher.end();
}
const stop_song = (message, server_queue) => {
if (!message.member.voice.channel) return message.channel.send('You need to be in a channel to execute this command!');
server_queue.songs = [];
server_queue.connection.dispatcher.end();
}
I think that problem is in main part of code but I cant seem to find problem.
Here is code for command handling
const fs = require('fs');
module.exports = (client, Discord) =>{
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for (const file of commandFiles){
const command = require(`../commands/${file}`);
if(command.name){
client.commands.set(command.name, command);
} else{
continue;
}
}
}
And here is my main file of the bot with commands collection
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
client.user.setStatus('online')
console.log('Bot is online!');
client.user.setActivity('Youtube',{
type:"LISTENING"
})
console.log('Servers:')
client.guilds.cache.forEach((guild) => {
console.log('-' + guild.name)
})
});
const fs = require('fs');
const message = require('./events/guild/message');
client.commands = new Discord.Collection();
client.events = new Discord.Collection();
['command_handler', 'event_handler'].forEach(handler =>{
require(`./handlers/${handler}`)(client, Discord);
})
Im trying to do a set presence command to being able to change presence without restarting my bot and changing my code but im not able to do it, here's my code:
const Discord = require("discord.js")
const bot = new Discord.Client()
const fetch = require('node-fetch')
const config = require("./config.json")
bot.login(config.token)
bot.on("ready", () => {console.log("Loaded up!")});
bot.on("message", message => {
if (message.author.bot) return;
if (message.content.indexOf(config.prefix) !== 0) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase()
if (command === "set") {
bot.user.setPresence({
status: "online",
game: {
name: "a",
type: "WATCHING" }})}});
Having a look at the documentation for discordjs. I can see an example for setting your clientUsers presence while the bot is running.
working code:
const Discord = require("discord.js");
const config = require("./config.json")
const bot = new Discord.Client();
bot.on("ready", () => {
console.log("Initialized bot, listening...")
});
bot.on("message", message => {
if (message.author.bot || !message.content.startsWith(config.prefix)) return;
let [command, ...args] = message.content.slice(config.prefix.length).split(/ +/g);
if (command === "set") {
bot.user.setPresence({ activity: { name: 'with discord.js' }, status: 'idle' });
return;
}
if (command === "ping") {
message.channel.send("Pong")
return;
}
})
bot.login(config.token)
Documentation Link:
https://discord.js.org/#/docs/main/stable/class/ClientUser?scrollTo=setPresence
Want a bot to play a predetermined audio file when a word is written in a text channel of my personal server. Having trouble, as it is reading the message, running the code, but not finding that im in a voice channel when I really am. has permissions to join, have no idea why its not working.
Edit: New Code
var Discord = require('discord.js');
const { waitForDebugger } = require('inspector');
var bot = new Discord.Client();
var isReady = true;
const path = require('path');
const ytdl = require('ytdl-core');
bot.on('guildMemberAdd', guildMember =>{
let welcomeRole = guildMember.guild.roles.cache.find(role => role.name === 'Average Bread');
guildMember.roles.add(welcomeRole);
console.log('Role Assigned');
});
bot.once('ready', () => {
console.log('Bot is Online');
});
bot.on('message', message => {
const args = message.content.split(/ +/);
const command = args.shift().toLowerCase();
var VC = message.member.voice.channel;
if (command === "join") {
if (!VC) return message.reply("You are not in a voice channel.")
VC.join()
.then(connection => {
message.channel.send('Joining Channel');
var stream = ytdl('https://www.youtube.com/watch?v=U06jlgpMtQs')
connection.play(stream, {seek: 0, volume: 1});
console.log('Joining')
})
.catch(console.error);
}
else if (command === "leave") {
VC.leave()
message.channel.send('Leaving channel');
console.log('Leaving');
}});
bot.login('token');
I tried to many things the thing. But I m not able to change the config file by using the command. I want to add channel id in that config
const fs = require('fs');
const config = require('../config.json')
const Discord = require('discord.js');
const client = new Discord.Client();
module.exports.run = async (client, message, args) => {
let owner = process.env.OWNER.split(',')
if(!owner.includes(message.author.id)) {
return message.reply("This command is not made for everyone")
}
if (message.channel.type === "dm" || message.author.bot || message.author === client.user) return; // Checks if we're on DMs, or the Author is a Bot, or the Author is our Bot, stop.
fs.writeFile('./config.json', args[0], (err) => {
if (err) console.log(err)
})
message.channel.send("Done")
}
exports.help = {
name: "wtp",
category: "General",
description: "Add this channel into WTP",
usage: "wtp <channel_id>"
};```
Also you can do it like this, add/change variable of config and then save it.
const fs = require('fs');
const config = require('../config.json')
const Discord = require('discord.js');
const client = new Discord.Client();
module.exports.run = async (client, message, args) => {
let owner = process.env.OWNER.split(',')
if(!owner.includes(message.author.id)) return message.reply("This command is not made for everyone")
if (message.channel.type === "dm" || message.author.bot || message.author === client.user) return; // Checks if we're on DMs, or the Author is a Bot, or the Author is our Bot, stop.
if (args.length === 0) return message.reply('Pls mention a channell')
let targetChannel = message.mentions.channels.first() || message.guild.channels.get(args[0])
if (!targetChannel) return message.reply('Cant fin`d channel')
config.channed_id = targetChannel.id
fs.writeFile('./config.json',JSON.stringify(config) , (err) => {
if (err) console.log(err);
message.channel.send("Done")
})
}
exports.help = {
name: "wtp",
category: "General",
description: "Add this channel into WTP",
usage: "wtp <channel_id>"
};