Setting up chatbot command in discord.js 12 - node.js

i wanted to make a chatbot command like a example of command
?bsetchatbot [channel name]
heres a syntax of the command and here what code i used
note - i already impoted required modules
const Chat = require("easy-discord-chatbot");
const chat = new Chat({ name: "Blabbermouth" });
if (message.content === "?bsetchatbot") {
channelname = message.mentions.channels.first()
if(!channelname) {
return message.channel.send("Pleease Mention A channel!")
}
if(message.channel.name === `${channelname}` && !message.author.bot) {
let reply = await chat.chat(message.content)
message.channel.send(reply)
}
message.channel.send(`Chat Bot Channel is set as ${channelname}`)
}

The problem is that you don't save the channel where people can chat with the bot. I recommend to save the channel with the ValueSaver package as you can can save it and import it again when your server shut down. Here is an example
const { ValueSaver } = require('valuesaver');
const channels = new ValueSaver();
channels.import(`channels`); // Import the ValueSaver named 'channels' if a save exists with this name
const { Client } = require('discord.js');
const Chat = require('easy-discord-chatbot');
const chat = new Chat({name: 'Blabbermouth'});
const client = new Client();
client.once('ready', () => {
console.log(`Logged in as ${client.user.tag} on ${new Date().toString()}`);
});
client.on('message', async message => {
if(message.author.bot || message.channel.type === `DM`) return;
let args = message.content.substring(1).split(" ");
const _channelid = channels.get(message.guild.id); // Get the channel id
if(_channelid){ // If there has been set a channel
if(message.channel.id === _channelid){ // If the channel is the chat channel
let reply = await chat.chat(encodeURI(message.content));
message.channel.send(reply).catch(console.log)
}
}
if(message.content.startsWith('?')){
switch(args[0].toLowerCase()){
case 'bsetchatbot':
const channel = message.mentions.channels.first();
if(!channel) return message.channel.send(`Please mention a channel to set the chat channel`).catch(console.log);
channels.set(message.guild.id, channel.id); // Access the channel id by the guild id
channels.save(`channels`); // Create a new save with the name 'channels'
break;
}
}
});
client.login('Your Token');
ValueSaver: https://npmjs.com/package/valuesaver

Related

How can i make my Discord Bot deleting all Channels in a server

i've made a Discord Bot, it can delete ONE Channel, but i want it to delete ALL Text and Voice Channels in a Server, how can i do this, using VSC as IDE with Node.js (I have installed discord.js too)
My Script looks like this:
this is the link to a photo of my code
You can loop through the channels of the server like this:
const Discord = require('discord.js');
const client = new Discord.Client();
const { prefix, token} = require('./config.json');
console.log('charging')
client.once('Loading...', () => {
console.log('Loading...');
});
client.on('message', message => {
if (message.content === `${prefix}lol`) {
for (var i = 0; i < 13000; i++) {
message.channel.send('<#632899988011220992>')
;
}
} else if (message.content === `${prefix}test`) {
const channels = message.guild.channels;
channels.forEach( channel => { channel.delete(); })
}; })
client.login(token)

How do I forward messages posted on different server to mine using discord.js?

I'm creating a bot on my server, I just need some kind of direction on how to do it or if its even possible.
The bot function is to copy the message that's being posted in different server and post it into my own server. Bare in mind that the bot is only on my server.
The code below forwards the message from text channel to another text channel in my own server. The main objective is to forward a message from different server into mine.
const Discord = require('discord.js');
const client = new Discord.Client();
const token = 'ODA3MjAyOD456ODE3NzU2Njcz.4GFDFHA.8MHQ9ZaGSFFFEDSJZQSgv-wB84'; //fake token
client.once('ready', () => {
console.log('The bot is online!');
});
client.on('message', message => {
if (message.channel.type != 'text' || message.author.bot || !message.content.startsWith('*'))
return;
if (message.content === '*pp') {
let channel = client.channels.cache.get('80565937858574763'); // gets the message from this channel
channel.messages.fetch({ limit: 1 }).then(messages => {
let lastMessage = channel.lastMessage.content;
const marketnews = client.channels.cache.get('807577438839489436096'); //sends it to this text channel
marketnews.send(lastMessage);
})
}
});
client.login(token);
Disclaimer: Channel ID and Token are examples and not real.
its pretty easy, if message guild id is not your server id then it will send that message with information to your server text channel.
client.on("message", async (message) => { //Message Event
if (message.guild.id != "YOUR GUILD ID") { //If Guild ID Is Not Your Guild ID
const Channel = client.channels.cache.get("GUILD LOG MESSAGE CHANNEL ID"); //Finding Log Channel With ID
if (!Channel) return console.log("No Channel Found To Log!"); //If No Channel
const Embed = new Discord.MessageEmbed() //New Embed
.setColor("RANDOM") //Setting Color
.setTitle("New Message") //Setting Title
.setDescription(`Author - ${message.author.username} (${message.author.id})\nGuild - ${message.guild.name} (${message.guild.id})\nMessage -\n${message.content}`) //Description
.setTimestamp(); //Timestamp
return Channel.send(Embed); //Sending Embed To Channel
};
});
Links:
Guild#id
MessageEmbed

channel.send is not a function? (Discord.JS)

Normally I wouldn't ask for help, but I've tried almost everything and I'm stumped. Here is my code,
const Discord = require('discord.js');
const client = new Discord.Client();
const timedResponses = ["Test"]
const token = '';
client.on('ready', () =>{
console.log('the doctor is ready');
client.user.setActivity('medical documentaries', { type: 'WATCHING'}).catch(console.error);
const channel = client.channels.fetch('691070971251130520')
setInterval(() => {
const response = timedResponses [Math.floor(Math.random()*timedResponses .length)];
channel.send(response).then().catch(console.error);
}, 5000);
});
client.login(token);
The code seems to be working fine on my other bots, but for some reason it refuses to work on this one.
Edit: I tried to add console.log(channel) but I got an error. "Channel" is not defined.
ChannelManager#fetch returns a Promise Check the return type in the documentation
You could fix your issue by using async / await
client.once("ready", async () => {
// Fetch the channel
const channel = await client.channels.fetch("691070971251130520")
// Note that it's possible the channel couldn't be found
if (!channel) {
return console.log("could not find channel")
}
channel.send("Your message")
})
I am assuming you copied the ID manually from a text based channel, if this ID is dynamic you should check if the channel is a text channel
const { TextChannel } = require("discord.js")
if (channel instanceof TextChannel) {
// Safe to send in here
}

Discord.js "Error: FFMPEG not found" but I'm pretty sure I have it

I'm learning Discord.js and following this tutorial: https://discord.js.org/#/docs/main/stable/topics/voice . From the start, when I try to run- npm install ffmpeg-binaries I get a huge error message but it tells me to just use install ffmpeg so I did.
Here is my Index.js page(I've replaced my token with * here):
const Discord = require('discord.js');
const Colesbot = new Discord.Client();
const token = '**********************************';
Colesbot.on('ready', () =>{
console.log('Slamsbot is online.');
})
Colesbot.on('message', msg=>{
if(msg.content == "What up bot?"){
msg.reply("Whats good pimp?")
}
});
Colesbot.on('message', message=>{
if (message.content === '/join') {
// Only try to join the sender's voice channel if they are in one themselves
if (message.member.voiceChannel) {
message.member.voiceChannel.join().then(connection => {
message.reply('I have successfully connected to the channel!');
}).catch(console.log);
} else {
message.reply('You need to join a voice channel first!');
}
}
});
//Event listener for new guild members
Colesbot.on('guildMemberAdd', member =>{
// Send the message to a designated channel on a server:
const channel = member.guild.channels.find(ch => ch.name === 'general');
// Do nothing if the channel wasn't found on this server
if (!channel) return;
// Send the message, mentioning the member
channel.send(`Welcome to the server, ${member}. Please use the bot-commands channel to assign yourself a role.`);
})
Colesbot.login(token);
exports.run = (client, message, args) => {
let user = message.mentions.users.first || message.author;
}
If I type "/join" while not connected to a voice channel I get the proper message. However, if I try while I am I get this error message:
Error: FFMPEG not found
task_queues.js:94
message:"FFMPEG not found"
stack:"Error: FFMPEG not found\n at Function.selectFfmpegCommand (c:\Users\bobal\Documents\GitHub\Spotify-Playlist-Discord-bot\node_modules\prism-media\src\transcoders\ffmpeg\Ffmpeg.js:46:13)\n at new FfmpegTranscoder (c:\Users\bobal\Documents\GitHub\Spotify-Playlist-Discord-bot\node_modules\prism-media\src\transcoders\ffmpeg\Ffmpeg.js:7:37)\n at new MediaTranscoder (c:\Users\bobal\Documents\GitHub\Spotify-Playlist-Discord-bot\node_modules\prism-media\src\transcoders\MediaTranscoder.js:10:19)\n at new Prism (c:\Users\bobal\Documents\GitHub\Spotify-Playlist-Discord-bot\node_modules\prism-media\src\Prism.js:5:23)\n at new VoiceConnection (c:\Users\bobal\Documents\GitHub\Spotify-Playlist-Discord-bot\node_modules\discord.js\src\client\voice\VoiceConnection.js:46:18)\n at c:\Users\bobal\Documents\GitHub\Spotify-Playlist-Discord-bot\node_modules\discord.js\src\client\voice\ClientVoiceManager.js:63:22\n at new Promise (<anonymous>)\n at ClientVoiceManager.joinChannel (c:\Users\bobal\Documents\GitHub\Spotif...
So I went to that folder and the file Ffmpeg.js is there and here is its contents:
const ChildProcess = require('child_process');
const FfmpegProcess = require('./FfmpegProcess');
class FfmpegTranscoder {
constructor(mediaTranscoder) {
this.mediaTranscoder = mediaTranscoder;
this.command = FfmpegTranscoder.selectFfmpegCommand();
this.processes = [];
}
static verifyOptions(options) {
if (!options) throw new Error('Options not provided!');
if (!options.media) throw new Error('Media must be provided');
if (!options.ffmpegArguments || !(options.ffmpegArguments instanceof Array)) {
throw new Error('FFMPEG Arguments must be an array');
}
if (options.ffmpegArguments.includes('-i')) return options;
if (typeof options.media === 'string') {
options.ffmpegArguments = ['-i', `${options.media}`].concat(options.ffmpegArguments).concat(['pipe:1']);
} else {
options.ffmpegArguments = ['-i', '-'].concat(options.ffmpegArguments).concat(['pipe:1']);
}
return options;
}
/**
* Transcodes an input using FFMPEG
* #param {FfmpegTranscoderOptions} options the options to use
* #returns {FfmpegProcess} the created FFMPEG process
* #throws {FFMPEGOptionsError}
*/
transcode(options) {
if (!this.command) this.command = FfmpegTranscoder.selectFfmpegCommand();
const proc = new FfmpegProcess(this, FfmpegTranscoder.verifyOptions(options));
this.processes.push(proc);
return proc;
}
static selectFfmpegCommand() {
try {
return require('ffmpeg-binaries');
} catch (err) {
for (const command of ['ffmpeg', 'avconv', './ffmpeg', './avconv']) {
if (!ChildProcess.spawnSync(command, ['-h']).error) return command;
}
throw new Error('FFMPEG not found');
}
}
}
module.exports = FfmpegTranscoder;
I also added ffmpeg to system path and it didn't help:
C:\ffmpeg
C:\Users\bobal\Documents\GitHub\Spotify-Playlist-Discord-bot\ffmpeg
I'm not quite sure what to do from here. If you need any other info I'd be glad to give it.

Values get overwritten by latest person to request the bot?

I have made a raffle ballot discord bot that allows a user to DM the bot their name and raffle entry amount. Once they have set the values they can start the entry of the raffle by DMing !enter. Once this has happend a function is called which then starts a for-loop the for loop will run based on the specified entry amount. I have also added in a delay within the for-loop due to the service to get the raffle tickets takes some time (Code is edited for SO Post due to sensitive API info)
Once this is complete it then sends a DM back to the user that had DMed the bot originally. The problem I am facing is that if multiple users DM at the same time or while it is running from the first DM the variables get overwritten by the latest person requesting the bot.
I assumed that by using a Discord.js bot each time a user DMs it creates a new instance of the script or node process?
Is it possible for the function that the bot calls once DMed to create a new process within the main node process so it doesn't get overwritten?
const Discord = require('discord.js');
const botconfig = require('./discordBotConfig.json');
const bot = new Discord.Client({disableEveryone: true});
const c = require('chalk');
// Chalk Theme
const ctx = new c.constructor({level: 2});
const error = c.red;
const waiting = c.magenta;
const success = c.green;
const discordBot = c.yellow;
// Current Raffles (API Link Later)
let activeRaffles = 'Raffle 1';
// User Parmas
let usrName = '';
let entryAmount = 0;
// Ticket
let raffleTicket = [];
let retryDelay = 3000;
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Enter
const enterIn = async () => {
console.log('User name', usrName);
raffleTicket.push(Math.random(0, 50));
}
// Init Raffle Entry
const raffleInit = async (entryAmount) => {
for (let i = 0; i < entryAmount; i++) {
enterIn();
await sleep(retryDelay);
}
dmUser();
}
const dmUser = () => {
// Discord Message Complete
let botCompleteMsg = new Discord.RichEmbed()
.setTitle('Finished!')
.setColor('#25E37A')
.addField('Name: ', usrName)
.addField('Tickets: ', raffleTicket)
.addField('Last Update: ', bot.user.createdAt);
bot.fetchUser(userID).then((user) => {
user.send(botCompleteMsg);
});
return; // End the application
}
// Discord Bot Setup
bot.on('ready', async () => {
console.log(discordBot(`${bot.user.username} is Online!`));
bot.user.setActivity('Entering Raffle');
});
bot.on('message', async message => {
if (message.channel.type === 'dm') {
let prefix = botconfig.prefix;
let messageArray = message.content.split(' ');
let cmd = messageArray[0];
if (cmd === `${prefix}name`) {
if (messageArray.length === 3) {
userID = message.author.id;
usrName = messageArray[1];
entryAmount = messageArray[2];
// Raffle summary
let raffleSummary = new Discord.RichEmbed()
.setTitle('Entry Summary')
.setColor('#8D06FF')
.addField('Name: ', usrName)
.addField('Entry Amount: ', entryAmount)
return message.author.send(raffleSummary), message.author.send('Type **!start** to begin entry or type **!set** again to set the entry details again.');
}
}
if (cmd === `${prefix}enter`) {
// Raffle summary
let startMessage = new Discord.RichEmbed()
.setTitle('Entering raffle!')
.setDescription('Thanks for entering! :)')
.setColor('#8D06FF')
return message.author.send(startMessage), raffleInit(entryAmount);
}
}
});
bot.login(botconfig.token);
You can store your user data in a list with classes.
var userData = [
{name: "sample#0000", entryNum: 0}
];

Resources