Discord bot node.js extrenal folder with commands - javascript

can someone help me how to make my main.js file read another .js file only with one command?
Here is that command:
client.on('voiceStateUpdate', (prevMember, newMember) => {
console.log('old: ', prevMember)
console.log('new: ', newMember)
//let channel = newMember.channel
let channel = "800656175297200149"
const generalChannel = client.channels.cache.get(channel)
// if it's the first person joining voice, notify everyone
if (!prevMember.channelID) {
generalChannel.send(`#everyone ${newMember} just hopped on voice. WARWEEK Tribe go see what's up!`)
}

Related

Rasa to dialogflow connection in javascript

I need a solution for the Rasa nlu to dialogflow connection. I tried different ways in the code from adding the yml file, tar.gz file and Rasa provided webhooks and API. None of these methods are working and it is not responsing the answers from the domain.yml file but getting the response "Sorry. Something went wrong. Can you say that again?" in the dialogflow and getting different errors in the vs code terminal when I try to enter the inputs from the nlu.yml file for Rasa nlu in the dialogflow.
async function defaultFallback(agent) {
const yaml = require('js-yaml');
const fs = require('fs');
const defaultFallback = yaml.load(fs.readFileSync('nlu.yml'));
const dialog = [
`The following is a conversation with an AI assistant that can have meaningful conversations with users. The assistant is helpful, empathic, and friendly. Its objective is to make the user feel better by feeling heard. With each response, the AI assisstant prompts the user to continue the conversation in a natural way.
AI: Hello, my name is Debra. I am your personal AI assistant from Orient Telecoms. How are you doing today?`,
];
let query = agent.query;
console.log('querytext ', query)
dialog.push(`User: ${query}`);
dialog.push('AI:');
try{
var targz = require('targz');
var tar = require('tar-stream');
var extract = tar.extract();
// targz.decompress({src: '20221206-172837-simple-assistant.tar.gz',
// dest: '\dialogflow'})
// const response = yaml.load(fs.readFileSync('domain.yml'));
// const response = await fetch (extract.on('20221206-172837-simple-assistant.tar.gz'));
const response = await fetch ('http://0.0.0.0:5005',
{
method: "POST",
body: JSON.stringify(query),
});
const botResponse = await response.json();
console.log('botResponse: ', botResponse)
agent.add(botResponse[0].generated_text.substring(botResponse[0].generated_text.indexOf('?') + 1).trim());
}catch(err){
console.log('This is error:', err);
agent.add('Sorry. Something went wrong. Can you say that again?');
}
}
I was able to run with rasa shell, node and ngrok command together but there is no response from the yml file when I'm working on the dialogflow. Is there a solution for these problems?

How to open a file in folders with discord.js

I am now coding a Discord bot in a folder named "bot", and I am making it play audio file. But I face a problem. If every files I want to make it play are stored in "bot", the folder will look mess. So I want to create a new folder named "music" in "bot". But I don't know to open the file in this way. Here is a part of my original code:
if (cmd === "play" && message.member.voice.channel) {
const connection = await message.member.voice.channel.join();
const dispatcher = connection.play('01. Snow halation.flac');
dispatcher.on('start', () => {
console.log('Now playing!');
});
dispatcher.on('finish', () => {
console.log('Finished playing!');
connection.disconnect();
});
dispatcher.on('error', console.error);
I want let file "01. Snow halation.flac" be in "music", and how can I make it play?
const dispatcher = connection.play('./music/01. Snow halation.flac');

how do I make a discord bot I made configurable per server?

I recently made a discord word filter bot and I was wondering how I could make it configurable per server? I want to be able to make a command that adds words to be filtered to the code and I want people to be able to add a custom prefix per server. I also want people to be able to set their log channel per server. Can someone help me with this please? I spent a lot of time on this bot and I dont want to just keep making more of the same bot for different servers. I'm using discord.js 12.5.3. I'll attach my code below.
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', async () => {
console.log('yay, the bot is online')
client.user.setActivity('im real', {type: 'PLAYING'})
})
client.on('message', async message => {
if(message.channel.type === 'dm' || message.author.bot) return;
const logChannel = client.channels.cache.find(channel => channel.id === '921730444498726924')
let words = [“bad”, “words”, “here”]
let foundInText = false;
for (var i in words) {
if (message.content.toLowerCase().includes(words[i].toLowerCase())) foundInText = true;
}
if (foundInText) {
let logEmbed = new Discord.MessageEmbed()
.setDescription(<#${message.author.id}> Said a bad word)
.addField('The Message', message.content)
.setColor('RANDOM')
.setTimestamp()
logChannel.send(logEmbed)
let embed = new Discord.MessageEmbed()
.setDescription('That word is not allowed here')
.setColor('RANDOM')
.setTimestamp()
let msg = await message.channel.send(embed);
message.delete()
msg.delete({timeout: '3500'})
}
})
I've tried following a tutorial but it didn't help because I need one specifically for my case. If anyone could help, that would be great.

Importing variables from other files

I am trying to import a variable from one of my files (File 1) and use it in File 2. I have imported File 2 into File 1 but I am receiving error. My channel ID is correct, in this case you would have to choose the channel so the channel ID is not the issue here.
TypeError: setr.send is not a function
File 1
const Discord = require("discord.js");
const axios = require("axios");
let config = require("../config.json");
module.exports = {
name: "setrestart",
description: "sets the restart channel",
async execute(message, args) {
const perm = new Discord.MessageEmbed()
.setDescription(":x: You do not have permission to use this command.")
.setColor("#E74C3C");
if (!message.guild.me.hasPermission("ADMINISTRATOR"))
return message.channel.send(perm);
if (message.author.id !== "ID")
return message.channel.send(perm);
const channelx =
message.mentions.channels.first() ||
message.guild.channels.cache.find((c) => c.id === args[0]);
if (!channelx)
return message.channel.send(
`:x: Please specify the channel where server restarts will go!`
);
message.reply(`All server restart logs will now go to ${channelx}.`)
},
};
File 2
const Discord = require("discord.js");
const axios = require("axios");
let config = require("../config.json");
let setr = require("./setrestart"); // This is importing file 1
module.exports = {
name: "restart",
description: "send a restart message in status channel",
async execute(message, args) {
const perm = new Discord.MessageEmbed()
.setDescription(":x: You do not have permission to use this command.")
.setColor("#E74C3C");
if (!message.guild.me.hasPermission("ADMINISTRATOR"))
return message.channel.send(perm);
if (message.author.id !== "ID")
return message.channel.send(perm);
const restart = new Discord.MessageEmbed()
.setTitle(" Server Restarted! ")
.setDescription(`F8 connect to ${config.SERVER_URL} `)
.setColor("RANDOM")
.setTimestamp()
.setFooter(`${config.SERVER_LOGO}`);
setr.channelx.send(restart) // This does not work.
},
};
Help is much appreciated.
Edit: I left out the most crucial thing about what I am trying to import.
I am trying to import channelx which is in File 1 and I am trying to use the variable in File 2.
Output
User: /setrestart #channel
Bot: All server restart logs will now go to ${channelx}.
User: /restart
Bot: Embed sent in channelx
The variable channelx is accessible only in the function scope of execute(), you can't import it. Basically after the function goes out of scope the variable is lost. Use a global object, note that the object is destroyed when the program exits. So if you are trying to make some kind of bot's configuration, you want to save the object to a file.
Here is an example of how to properly implement what you are trying to do.
File 1 (file1.js):
// ... Load storage from a JSON file ...
const storage = {};
module.exports = {
name: "setrestart",
description: "sets the restart channel",
async execute(message, args) {
// ... Permission checking ...
const channelx = message.mentions.channels.first() ||
message.guild.channels.cache.find((c) => c.id === args[0]);
if (!channelx) {
return message.channel.send(
`:x: Please specify the channel where server restarts will go!`
);
}
// Store restart channel id per guild
storage[message.guild.id] = channelx.id;
message.reply(`All server restart logs will now go to ${channelx}.`);
// ... Write to the storage JSON file and update it with new data ...
},
};
module.exports.storage = storage;
File 2 (file2.js):
const Discord = require("discord.js");
const file1 = require("./file1.js");
module.exports = {
name: "restart",
description: "send a restart message in status channel",
async execute(message, args) {
// ... Permission checking ...
const restart = new Discord.MessageEmbed()
.setTitle(" Server Restarted! ")
.setColor("RANDOM")
.setTimestamp();
const channelId = file1.storage[message.guild.id];
// If there is no restart channel set, default to the system channel
if (!channelId) channelId = message.guild.systemChannelID;
const channel = await message.client.channels.fetch(channelId);
channel.send(restart);
},
};
Note that I have remove some parts of your code, to make it work on my machine.
Using discord.js ^12.5.3.
I am pretty sure you can't use the module.exports in that way. You should just add the channelx to the exports instead.
using this.channelx = channelx.
This is not how importing and exporting works. Your channelx variable is defined within the execution of a function, and you are not returning it.
I am not sure how the whole Discord API works and what are the shapes that get returned, but you should be able to do something like this:
File 1
module.exports = {
name: "setrestart",
description: "sets the restart channel",
async execute(message, args) {
// ... everything as per your file
message.reply(`All server restart logs will now go to ${channelx}.`);
return channelx;
},
};
File 2
module.exports = {
name: "restart",
description: "send a restart message in status channel",
async execute(message, args) {
// ... everything the same as per your file
const channelx = await setr.execute(message, args);
channelx.send(restart);
},
};
Basically, what is happening here is that the first module exposes a function that figures out your target channel and then returns it.
Once you return it, you can do whatever you want with that.
Please be aware that your first function might not need to be async as you don't have any await instruction.
Read more about scope: https://developer.mozilla.org/en-US/docs/Glossary/Scope

Discord.js bot sending two memes from different reddits

So basically, I'm trying to get my discord bot to send a meme from r/marvelmemes, as the bot is for a MCU themed server. I followed a tutorial to create my code, and in the tutorial, the coder used r/memes. I only changed one thing. I changed this line:
got('https://www.reddit.com/r/memes/random/.json').then(response => {
Into this:
got('https://www.reddit.com/r/marvelmemes/random/.json').then(response => {
That's all I changed from the original tutorial. When I try to run the bot, it does in fact send a meme from r/marvelmemes. However, it also sends a meme from r/memes. It sends two memes. How do I make it so that it only sends one meme from r/marvelmemes? Here's the full code.
const got = require ('got');
module.exports = {
name: 'meme',
description: "send a meme",
execute(message, args, Discord) {
const embed = new Discord.MessageEmbed()
got('https://www.reddit.com/r/marvelmemes/random/.json').then(response => {
let content = JSON.parse(response.body);
let permalink = content[0].data.children[0].data.permalink;
let memeUrl = `https://reddit.com${permalink}`;
let memeImage = content[0].data.children[0].data.url;
let memeTitle = content[0].data.children[0].data.title;
let memeUpvotes = content[0].data.children[0].data.ups;
let memeDownvotes = content[0].data.children[0].data.downs;
let memeNumComments = content[0].data.children[0].data.num_comments;
embed.setTitle(`${memeTitle}`)
embed.setURL(`${memeUrl}`)
embed.setImage(memeImage)
embed.setColor('RANDOM')
embed.setFooter(`👍 ${memeUpvotes} 👎 ${memeDownvotes} 💬 ${memeNumComments}`)
message.channel.send(embed);
})
}
}
I use a basic command handler, and here's what it looks like if it helps:
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 == 'meme') {
client.commands.get('meme').execute(message, args, Discord);
}
Any help would be appreciated!
I'm pretty sure you have a second bot running because of multiple terminals.
If you have Visual Studio Code, you can see them here:
Here you are able to delete terminals (red box)

Categories

Resources