how do i make a setpresence command to trigger it by myself? - node.js

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

Related

message is not defined discord.js slashcommands

I'm getting an error saying that I'm not defining message
content: `🏓Latency is ${Date.now() - message.createdTimestamp}ms.`,
^
ReferenceError: message is not defined
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '.';
const fs = require('fs');
const guildId = ''
const getApp = (guildId) => {
const app = client.api.applications(client.user.id)
if (guildId) {
app.guilds(guildId)
}
return app
}
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once('ready', async () => {
console.log('HenBot Is Online!');
const commands = await getApp(guildId).commands.get()
console.log(commands)
await getApp(guildId).commands.post({
data: {
name: 'ping',
description: 'Bots Latency',
},
})
client.ws.on('INTERACTION_CREATE', async (interaction, message) => {
const slashCommmand = interaction.data.name.toLowerCase()
if(slashCommmand === 'ping') {
client.api.interactions(interaction.id, interaction.token).callback.post({
data: {
type: 4,
data: {
content: `🏓Latency is ${Date.now() - message.createdTimestamp}ms.`,
},
},
})
}
})
})
client.on('message', message =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'ping') {
client.commands.get('ping').execute(message, args);
}
})
It’s because message is not a valid parameter for interactionCreate.
As the discord.js docs implies, you can only pass in interaction in an interactionCreate event.
This should work for your code:
content: `🏓Latency is ${Date.now() - interaction.createdTimestamp}ms.`,
interactionCreate event cannot have message parameter...
client.on('interactionCreate', async interaction => {
// your code here
})

awaitMessages from the user on discord.js

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');
});

How assign role to user in discord by slash command?

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.

Discord Audio Player

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');

How to change files in discord.js by using commands?

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>"
};

Resources