Leave Command Discord JS - javascript

Leave command not working on my Discord bot which is written in JS.
This is the snippet of code I'm using.
if(command == 'leave') {
client.leaveVoiceChannel;
However the command which should make the bot leave the voice channel does not seem to work. Here is how I'm using the code.
const Eris = require('eris');
const client = new Eris(require('./config.json').token, { maxShards: 1 });
fs = require('fs')
var stations = fs.readFileSync("./stations.txt", {"encoding": "utf-8"}).toString()
client.connect();
client.on('ready', () => {
console.log('Ready to go!')
})
client.on('messageCreate', message => {
if(message.author.bot) return;
if(message.content.startsWith('!')) {
let command = message.content.substring(1).split(" ")[0];
let args = message.content.substring(2 + command.length);
if(command == 'leave') {
client.leaveVoiceChannel;
} else if(command == 'streams') {
message.channel.createMessage(stations);
} else if(command == 'radio') {
if(args == '') return message.channel.createMessage(`:exclamation: Please specify the radio stream example: **!radio <stream> or use command **!streams** to see list.`);
if(require('./stations.json')[args]) {
if(!message.member.voiceState.channelID) return message.channel.createMessage(`:exclamation: You need to be in a voice channel to play that stream.`);
client.joinVoiceChannel(message.member.voiceState.channelID).then(vc => {
if(vc.playing) vc.stopPlaying();
message.channel.createMessage(`:radio: You are listening to Streaming station **${args}**. To change the stream use **!radio <stream>**`);
vc.play(require('./stations.json')[args]);
})
} else {
return message.channel.createMessage(`:frowning2: I cannot find a radio stream with that name. Make sure it has capitals and the correct spelling. Type **!streams** to see stream list.`);
}
}
}
})
I'm not sure where I'm going wrong here.

if(command == 'stopstream') {
client.leaveVoiceChannel(message.member.voiceState.channelID);
message.channel.createMessage(`Thanks for tuning in!`); }

Related

Why are these lines of my javascript code unreachable according to VSCode?

I'd like to ask why lines 46 - 49 are unreachable in my discord.js script. I really don't know why it happened.
const TOKEN = "hidden"
const client = new Discord.Client({
intents: [
"GUILDS",
"GUILD_MESSAGES"
]
})
client.on("ready", () => {
console.log(`Logged in as ${client.user.tag}`)
})
client.on("messageCreate", (message) => {
const prefix = "!";
let msg = message.content;
let channel = message.channelId;
const cmd = messageArray[0];
const messageArray = message.content.split(" ");
const args = messageArray.slice(1);
console.log(message)
console.warn(msg)
console.log(channel)
if(msg == "!sayhi"){
message.channel.send("Hi!")
console.log(`Hi command initiated by someone!`)
}
if (cmd == '${prefix}kick'){
if (!args[0]){
return message.reply("Prosze kogos dac do tej komendy!")
** const member = message.mentions.members.first() || message.guild.members.cache.find(x => x.user.username.toLowerCase() === args.slice(0).join(" ") || x.user.username === args[0]);
if (!message.member.permissions.has("KICK_MEMBERS")){
return message.reply("Potrzebujesz moderatora!")
if (message.member.id === member.id){
return message.reply("Nie wywalaj siebie, lol!")
}
if (!message.guild.me.permissions.has('KICK_MEMBERS')){
return message.reply("Nie mam do tego permisji, wezwij admina!")
}
member.kick();
message.channel.send(`${member} zostal wywalony z serwera!`)
}
}**
}
}
)
client.login(TOKEN)
I tried to make it more indented, change brackets, add semicolons but nothing worked. It just stayed "unreachable" for VSCode and node.js, I believe discord too.
Anything after a return statement is unreachable code. If you are baffled by the fact, it may be because you did not close the brackets of the IF. Your mind is thinking this is inside an IF by itself but the code is telling you otherwise.
if (!args[0]) {
return message.reply(...);
} // <---------- HERE. You don't have this. Perhaps this is what you think you have?

Discord.js v14 - db.get is not a function when getting guild prefix

I created an event for messageCreate for my discord bot, it looked entirely fine but then I started getting this:
TypeError: db.get is not a function
I thought quick.db might have updated it but it is still the same in the latest version so I couldnt figure out what the issue was.
Here is my code:
module.exports = {
name: "messageCreate",
async execute(message) {
//get prefix//
PREFIX = require('../config.json')
let prefix = await db.get(`prefix_${message.guild.id}`); //<<< Error//
if (prefix === null) prefix = PREFIX;
//if bot or not a command return//
if (message.author.bot || !message.content.startWith(prefix)) return
const args = message.content.slice(prefix.lenght).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (!client.commands.has(command) && !client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(command))) return
var inputcommand = client.commands.get(command) || client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(command))
//if onlyAdmin = true
if(inputcommand.onlyAdmin){
if(message.member.hasPermission("ADMINISTRATOR")) {
message.channel.send("Only Administrators can run this command")
return
}
}
//run the given command//
inputcommand.execute(message, args, client);
}
}
Am I missing something or should I change something else?
Also im using Replit for this.

Issue with Java Discord.js Modmail System

I have been trying to make a discord ModMail system on my bot and there is an error that I can't understand my code is below:
client.on('message', message => {
if (message.author.bot || !message.content.startsWith(prefix)) return;
const args = message.content.slice(prefix.length).split(/+ /)
if (!message.channel.name.includes('modmail')) {
return;
} else {
if (isNaN(args[0])) {
return message.channel.send('Sorry but that is not a valid user')
}
let storage = message.guild.members.cache;
let memberId = storage.find(member => member.id.toLowerCase() === args[0]);
if (memberId) {
const msg = message.content.slice(args[0].length + prefix.length).split(" ").join(" ");
let embed = new Discord.MessageEmbed()
.setThumnail(message.author.displayAvatarURL())
.setDescription(`<#${message.author.id}>\n------------\n${msg}`)
.setColor('#599cff')
.setFooter('ModMail System')
.setTimestamp();
client.users.fetch(args[0]).then(user => user.send(embed).catch(err => console.log(err)));
message.channel.send('Your message was sent to the staff team! Please be patient for your reply.')
} else {
return message.channel.send('Could not find the user sorry.');
}
}
});
client.on('message', message => {
var msg = message.content;
var n = message.author.username;
if (message.channel.type === 'dm') {
if (message.author.bot) return;
let blacklisted = ['word1', 'word2']
let foundInText = false;
for (var i in blacklisted) {
if (message.content.toLowerCase().includes(blacklisted[i].toLowerCase())) foundInText = true;
}
if (foundInText) {
return message.channel.send('Please do not use foul language in the message. (if you must please cover it with symbols *not letters*)');
}
message.channel.send('Your message was sent to the staff team! Please be patient for your reply.');
const mailMessage = `${message.author.id} ${msg}`
client.channels.fetch('795031406442315816').then(user => user.send(mailMessage).catch(err => console.log(err)));
}
});
The error that is shown is:
SyntaxError: Invalid regular expression: /+ /: Nothing to repeat
This has been confusing me for a while (I am new to code) please if you know how to fix this it would help a lot thank you.
I think the error is because there is a problem here:
const args = message.content.slice(prefix.length).split(/+ /)
If you change .split(/+ /) to .split(' ') or .split(/ /) it would work.

How to allow the bot to create a file / append a file on my dropbox

Since my discord group often have quite a bit of dispute , I made a bot to record chat messages on demand to keep evidence of what people have said. However, since the bot is running on heroku, i could not let the bot dump the log into the github thing. I would need it to append to the file in the dropbox. And if a file didnt exsist, create a file for me.
I am not familliar with the dropbox api and thus wanting you guyz to help me complete the code.
p.s. if there is any problem/ bad parts of the code, feel free to help me improve it , its my first time creating a bot.
Thanks in advance
code :
https://pastebin.com/asftq3zJ
const Discord = require('discord.js');
const client = new Discord.Client();
const fs = require("fs");
//Options
const prefix = "!";
const documentation = "https://docs.google.com/spreadsheets/d/1dlUBQur9d8ANC-JJH6HA4gn4zxbFyz2xwQnTiPYZQi4/edit?usp=sharing"
//On Ready
client.on("ready",() => {
console.log("JojoTheOtokonko is ready")
client.user.setActivity("AV",{type: "WATCHING"});
});
//Login
client.login(process.env.token);
//Command Handler
client.on("message", async msg => {
let message = msg.toString();
let args = "";
if(message[0] === prefix){
args = message.substring(1).split(" ");
}
//Useful Commands
//!a
if(args[0] === "a"){
let mentioned = msg.mentions.users.first();
let server = args[1];
await mentioned.send("Hello, Would you mind joining " + server + "?\nLove you :)");
}
//!record
if(args[0] === "record" || args[0] === "rec"){
recording = true;
await msg.channel.send("#here Recoding message in " + msg.channel +" ,MIND YOUR LANGUAGE");
await client.user.setActivity("to messages in " + msg.channel, {type: "LISTENING"});
}
if(args[0] === "record-stop" || args[0] === "rec-stop"){
recording = false;
await msg.channel.send("#here stopped recoding message in " + msg.channel);
client.user.setActivity("AV",{type: "WATCHING"});
}
//help
if(args[0] === "help"){
await msg.reply("Full list of commands can be found at : \n" + documentation);
}
//Troll Commands
//!ftl
if(args[0] === "fti" || args[0] === "ftl"){
let channel = msg.member.voice.channel
if(!channel){
return msg.channel.send("You need to be in a voice channel to use this command");
}
try {
var connection = await channel.join();
} catch (e) {
console.log("Error connecting to voice channel");
}
connection.play('fti.mp3', { volume: 0.5 })
.on("finish", () => channel.leave())
.on("error", (error) => console.log(error));
}
if(args[0] === "fti-stop" || args[0] === "ftl-stop"){
if(msg.member.voice.channel){
msg.member.voice.channel.leave();
await msg.channel.send("Successfully disconnected from voice , why dont you like Fire Three Island? TAT");
}
}
//!elevator
if(args[0] === "elevator"){
await msg.channel.send("5_AvenueLocal");
}
//!innocity
if(args[0] === "inno" || args[0] === "innocity"){
await msg.channel.send("Is InnoCity Watersuno?");
}
});
//Recorder
var recording = false;
client.on("message", msg =>{
if(recording){
let server = msg.guild.name;
let appendata = "[" +Date.now()+"]" + "<" + msg.author.username + "> " + msg.toString() + "\n";
fs.appendFile(server + ".txt", appendata, (err) => {
if (err) throw err
});
}
});

Discord.js how to make suggest command?

What can I do in Discord.js to make suggest command? My actual code doesn't work, i have 2 types of suggestions: support server and bot.
Here's my code:
if (command === "suggest"){
const type = args.join(" ")
const thing = args.join(" ").slice(6)
const thing2 = args.join(" ").slice(3)
const suggestion = new Discord.RichEmbed()
.setTitle("New suggestion!")
.setAuthor(`${message.author.tag}`, `${message.author.avatarURL}`)
.addField(`${message.author.tag}`, `suggested: ${thing}`)
const suggestion2 = new Discord.RichEmbed()
.setTitle("New suggestion!")
.setAuthor(`${message.author.tag}`, `${message.author.avatarURL}`)
.addField(`${message.author.tag}`, `suggested: ${thing2}`)
if (!typ){
message.reply("enter suggestion type, which you want to suggest!");
return;
}
if (type === "server"){
if (!thing){
message.reply("enter thing you want to suggest!");
return;
}
client.channels.get("channel_id").send(suggestion);
return;
}
if (type === "bot"){
if (!suggestion2){
message.reply("enter thing you want to suggest!");
return;
}
client.channels.get("another_channel_id").send(suggestion2);
return;
}
else if (type !== "bot" || type !== "server"){
message.reply("invalid suggestion type!");
return;
}
}
and it outputs "invalid suggestion type!" when I type !suggestion
I'm not an expert with discord.js but this should work! (It does on my server!)
client.on('message', msg => { //This runs when a message is sent.
const args = msg.content.slice(prefix.length).split(' '); //Get the arguments
const command = args.shift().toLowerCase(); //Making the command non case-sensitive
if (command === 'suggest'){ //if command is suggest
const channel = msg.guild.channels.find(ch => ch.name === 'suggestions'); //finds the channel named suggestions
channel.send('Suggestion:\n ' + args.join(' ')) //Sends the arguments
} //Closes the if (command === 'suggest'){
}); //Closes the client.on('message',msg => {
Great if i can help!
Also you used !== so if user is not a bot it doesn't send message. Try using === instead!
I dont know if you use a command handler or not but if you do, this should work:
if (command === 'suggest'){
const Discord = require('discord.js'); // this should be on top of ur js file, NOT HERE
const { Client, MessageEmbed } = require('discord.js'); // this should be on top of ur js file, NOT HERE
if(!args[0]) return message.reply('You need to type a suggestion..') // bot reply if user only typed !suggest n didnt include any text..
const user_avatar = message.author.avatarURL({ format: 'png', dynamic: true, size: 2048 }); // gets discord user avatar
const user_suggestion = args.slice(0).join(" ") // gets discord user args
let suggestion_channel = message.guild.channels.cache.find(
(cache) => cache.name === "suggestions" // the channel name u want the embed to be sent to..
);
if (!suggestion_channel) return;
const suggestion_emb = new MessageEmbed() // The suggestion embed that will be sent to the "suggestions" channel
.setAuthor(`Suggestion:`, `${user_avatar + "?size=2048"}`)
.setDescription(`${user_suggestion}`)
.setColor("RANDOM") // randomizes the color of the embed, can also be hex n rgb so ".setColor("#3d71e7")" for example.
.setFooter(`Suggested by: ${message.author.tag}`);
const suggestion_reply_emb = new MessageEmbed() // the reply embed so when someone does !suggest suggestion here, it will reply with the embed below
.setAuthor(`${message.author.tag}`, `${user_avatar + "?size=2048"}`)
.setDescription(`:white_check_mark: Your suggestion has been sent to <#CHANNEL_ID_HERE>.`)
.setColor("RANDOM");
message.reply(suggestion_reply_emb) && suggestion_channel.send(suggestion_emb)
};
if u use a command handler just remove the first & last line

Categories

Resources