Opening file with js - javascript

I'm trying to make a discord.js bot which whenever someone types a certain command on Discord, it opens a program on my PC:
client.on("message", (message) => {
if (message.content == "!ping") {
//here I want to open a program on my pc
}
});

Assuming you are using Node you can include the execFile function from the child_process package and just call it from the command line.
const { execFile } = require("child_process");
client.on("message", (message) => {
if(message.content == "!ping") {
execFile("<path to file>", ["optional arg1", "optional arg2"]);
}
});
Or if you just want to run a command, just exec
const { exec } = require("child_process");
client.on("message", (message) => {
if(message.content == "!ping") {
exec("<shell command>", ["optional arg1", "optional arg2"]);
}
});
Check out https://nodejs.org/api/child_process.html#child_processexeccommand-options-callback for documentation.
You may need to "npm install child_process"

Related

Only reply in dms discord.js

So I was working on this project where people will DM the BOT and run command and it replies test. But it doesn't reply.
client.on("messageCreate", async message => {
if (message.content.startsWith(prefix)) {
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (message.channel.type === 'dm') {
message.reply("test");
}
}
});
That's because you didn't enable the intents for getting a dm message,
try putting those two on your client declarations :
const client = new Discord.Client({
intents : ['DIRECT_MESSAGES','GUILD_MESSAGES'],
partials: ["CHANNEL","MESSAGE"]
})
here is a way:
1.Create a file named ** 'privateMessage.js'** and in the main file add:
const privateMessage = require('./privateMessage')
client.on('ready' ,() =>{
console.log('I am online')
client.user.setActivity('YouTube Music 🎧', {type:'PLAYING'})
privateMessage(client, 'ping', 'pong')
})
and in the file we just created privateMessage.js add:
module.exports=(client, triggerText, replyText)=>{
client.on('message', message =>{
if(message.content.toLowerCase()===triggerText.toLowerCase()){
message.author.send(replyText)
}
})
}

Discord only recognizing "ping" command in discord.js

In my Discord.JS bot, I have multiple commands setup (ping, beep, etc.) but Discord only recognizes "ping". I have tried multiple setups, and all are the same.
Here is my code:
const { Client, Intents } = require('discord.js');
const { token } = require('./config.json');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
client.once('ready', () => {
console.log('Ready!');
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const { commandName: command } = interaction;
if (command === 'ping') {
await interaction.reply('Pong!');
} else if (command === 'beep') {
await interaction.reply('Boop!');
} else if (command === 'server') {
await interaction.reply(`Server name: ${interaction.guild.name}\nTotal members: ${interaction.guild.memberCount}`);
} else if (command === 'user-info') {
await interaction.reply(`Your username: ${interaction.user.username}\nYour ID: ${interaction.user.id}`);
}
});
client.login(token);
And here is Discords command view when "/" is enter
As you can see, ping is the only thing being recognized by discord.
It is also worth noting the ‘ping’ command has a description which the original description I setup, so it seems like issue is that Discord is not updating the commands each time the script changes. But, I don’t know how to resolve that issue.
It seems like you only registered the ping command. You have to register each slash command individually.
I guess you registered the slashcommand some tile earlier, and have not removed it since. You are only responding in your code example to slashcommands, but you have to create them in the first hand.
Check here on how to do that.
it may take up to one hour to register a global command tho, so be patient. If you are fine, with slashcommands for one guild only, you can also only create guildCommands. These are up and running within a view minutes (under 10minutes max)
Here is a simple command, with which you can update the slashcommands (this is staright from the docs)
client.on('messageCreate', async message => {
if (!client.application?.owner) await client.application?.fetch();
if (message.content.toLowerCase() === '!deploy' && message.author.id === client.application?.owner.id) {
const data = [
{
name: 'ping',
description: 'Replies with Pong!',
},
{
name: 'pong',
description: 'Replies with Ping!',
},
];
const commands = await client.application?.commands.set(data);
console.log(commands);
}
});
NOTE: you have to be running the master branch of discord.js (aka Discord.js V13). If you have not installed it yet, you can install it by running: npm install discord.js#latest. Make sure, you have uninstalled the "normal" discord.js dependency beforehand, by running npm uninstall discord.js.
If you are not sure what version you currently have installed, simply run npm list
This worked for me, the idea is to render each command separately.
I also went for some hardcoded configs: guild_id & client_id (to win some time in dev mode)
const { Client, Collection, Intents } = require('discord.js');
const { token, client_id, guild_id } = require('./config.json');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
client.once('ready', () => {
console.log('Ready!');
});
client.on('messageCreate', async message => {
if (!client.application?.owner) await client.application?.fetch();
// => client_id was just a quick fix, the correct value should be the id of the guild owner(s)
if (message.content.toLowerCase() === '!deploy' && message.author.id === client_id) {
const data = [
{
name: 'ping',
description: 'Replies with Pong!',
},
{
name: 'foo',
description: 'Replies with bar!',
},
{
name: 'chicken',
description: 'Replies with sticks!',
},
];
// same here, guild_id should also be replaced by the correct call to the idea number, just as client_id in this code!
for (let i = 0; data.length > i; i++) {
await client.guilds.cache.get(guild_id)?.commands.create(data[i]);
}
}
});
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const command = interaction.commandName;
if (command === 'ping') {
await interaction.reply('pong')
} else if (command === 'foo') {
await interaction.reply('bar')
} else if (command === 'chicken') {
await interaction.reply('nuggets')
}
});
client.login(token);

Discord.js help command to compile list of commands and embed with thumbnails

I have a very simple Discord bot that posts images/gifs on command by linking Imgur/Tenor htmls.
The commands are stored in individual .js files ./commands/
I would like to create a help command that collects all current commands in the folder, and embeds the command name, with the executed command beneath it so that a thumbnail of the image/gif is created, but I mostly just about managed to follow the Discord.js guide so I'm very very new to this. Can anyone suggest some code to help me get started? How can I populate embed fields based on an array of existing commands?
Example of bot below:
The commands are imported in index.js via:
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);
}
And executed via:
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const commandName = args.shift().toLowerCase();
if (!client.commands.has(commandName)) return;
const command = client.commands.get(commandName);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('Something bad happened!');
}
});
An example of a command ./commands/test.js is:
module.exports = {
name: 'test',
description: 'A test',
execute(message, args) {
message.channel.send('This is a test.');
}
}
You can use a .forEach() loop.
For example:
module.exports = {
name: 'help',
description: 'View a full list of commands',
execute(message, client) {
const Discord = require('discord.js');
const embed = Discord.MessageEmbed();
client.commands.forEach(command => {
embed.addField(`${command.name}`, `${command.description}`, false);
}
message.channel.send(embed);
}
}

Making a Discord Bot execute an Ubuntu command

I want to make a Discord bot execute a command (sudo service terraria start) when it sees a message like "!t start". I've seen this guide https://thomlom.dev/create-a-discord-bot-under-15-minutes/ and I know how to make the bot know when you send a certain message, but I don't know how could I make it do a command. I'll copy my index.js.
Thank you!
const client = new Discord.Client()
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}!`)
})
client.on("message", msg => {
if (msg.content === "Ping") {
msg.reply("Pong!")
}
})
Obviously at the end would be the token.
You can try using child_process
const { exec } = require("child_process");
exec("sudo service terraria start", (error, stdout, stderr) => {
if(error) { console.log(`error: ${error.message}`);
return;}
if(stderr){ console.log(`stderr: ${stderr}`);
return; }
console.log(`stdout: ${stdout}`);
});
See https://nodejs.org/api/child_process.html for more details.

discord.js bot working locally but not on Heroku

I have been attempting to run my discord.js bot on Heroku but I am having trouble getting my bot to join voice channels. Whenever I run my bot locally, everything works well, but when I host it on Heroku, some things don't work.
My bot.js looks like this:
const Discord = require('discord.js');
const client = new Discord.Client();
const ffmpeg = require('ffmpeg');
const opus = require('opusscript');
const token = 'Hidden for obious reasons'
var isReady = true;
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', message => {
if (message.content === 'ping') {
message.reply('Test message');
client.channels.get('Our general chat').send('Test message 2')
}
});
client.on('message', message => {
if (message.content === 'join') {
isReady = false;
const voiceChannel = client.channels.get('ID of our voiceChannel');
if (!voiceChannel) {
client.channels.get('ID of our general chat').send('Can\'t get vc');
}
else {
client.channels.get('ID of our general chat').send('Got here 1');
voiceChannel.join();
client.channels.get('ID of our general chat').send('Got here 2');
isReady = true;
}
}
});
client.on('message', message => {
if (message.content === 'leave') {
isReady = false;
const voiceChannel = client.channels.get('ID of our voiceChannel');
voiceChannel.leave();
isReady = true;
}
});
client.on('voiceStateUpdate', (oldMember, newMember) => {
if (isReady && newMember.id === 'My friends ID' && oldMember.voiceChannel === undefined && newMember.voiceChannel !== undefined)
{
isReady = false;
var voiceChannel = client.channels.get('ID of our voiceChannel');
voiceChannel.join().then(connection =>
{
// Play the file
const dispatcher = connection.playFile('./clip.mp3');
dispatcher.on("end", end => {
voiceChannel.leave();
});
}).catch(err => console.log(err));
isReady = true;
}
});
client.login(token);
While my package.json looks like:
{
"name": "mybot",
"version": "1.0.0",
"description": "Make It Say Dumb Thing",
"main": "bot.js",
"scripts": {
"start": "node bot.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"discord.js": "^11.5.1",
"ffmpeg": "0.0.4",
"opusscript": "0.0.7"
}
}
With my Procfile simply being:
worker: node bot.js
When I run this locally on my machine, everything works perfectly. However, when I host this on Heroku, the .join() function is not working. It prints out 'Got here 1' and 'Got here 2' but the bot never joins the voice chat.
you are using
client.login(token);, Not client.login(process.env.token);.
The problem is you are not asking the code to look into the Vars.
this is also showing up because you may not be setting the .env right.
In heroku the ENV is under
(Your App) > Settings > Config Vars .
if those are not set up, this is also the problem.
I hope this helps.
Add the ffmpeg build to Heroku
Heroku &rightarrow; [Settings] &rightarrow; [Add buildpack]
paste the link
https://github.com/jonathanong/heroku-buildpack-ffmpeg-latest.git
[Save changes]
Someone to follow as guidance:
https://www.youtube.com/watch?v=f3wsxbMbi5M

Categories