I have a discord bot, and I was using v12. When the new v13 version came out, I tried to update my bot but it was too much for me. Now, I tried again and it went a little better. Now at least it gets on, but doesn´t reply! When I execute the help command, it returns me this error:
TypeError: message.channel.startTyping is not a function
at Client.module.exports (/app/events/messageCreate.js:172:21)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
This is my bot.js file:
const { Client, Intents } = require('discord.js');
const Discord = require("discord.js");
const { I18n } = require("locale-parser");
const Mongoose = require("mongoose");
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
//client.errors = require("./modules/errors");
client.config = require("./config.json");
client.i18n = new I18n({ defaultLocale: "en" });
Mongoose.connect(client.config.mongo_uri, {
useNewUrlParser: true,
useUnifiedTopology: true
});
client.database = Mongoose.connection;
client.database.on("error", err => {
throw err;
});
client.database.once("open", async () => {
require("./models");
require("./handlers/eventHandler")(client);
require("./handlers/moduleHandler")(client);
client.login(process.env.BOT_TOKEN);
});
And this one, is app/events/messageCreate.js:
const Discord = require("discord.js");
const embeds = require("../modules/embeds.js");
const cooldown = {};
const Uses = require("../models/uses.js");
const Enmap = require("enmap");
const db = require("megadb"); //aca definimos db para lo que necesitemos mas adelante
let desactivadodb = new db.crearDB("ComandosDesactivados");
const fs = require("fs");
const guildModel = require("../models/guildModel");
var language = "";
module.exports = async message => {
try {
const bot = message.client;
const funcs = require("../modules/functions.js");
bot.color = funcs.color(message);
bot.lang = funcs.lang(message) || "en";
bot.langs = message.guild.language || language;
const msg = message;
if (msg.author.bot || !msg.guild) return;
let prefix = bot.config.prefixes[0];
let argsSlice = prefix.length;
if (!msg.content.toLowerCase().startsWith(prefix.toLowerCase())) {
let content = msg.content.trim();
let mention1 = "<#!" + bot.user.id + ">";
let mention2 = "<#" + bot.user.id + ">";
if (content == mention1 || content == mention2)
return embeds.mention(msg, prefix, bot);
if (content.startsWith(mention1)) argsSlice = mention1.length;
else if (content.startsWith(mention2)) argsSlice = mention2.length;
else return;
}
let args = msg.content
.slice(argsSlice)
.trim()
.split(/ +/g);
let command = args.shift().toLowerCase();
let cmdFile =
bot.commands.get(command) ||
bot.commands.find(
cmdFile => cmdFile.aliases && cmdFile.aliases.includes(command)
);
if (!cmdFile) return;
if (message.guild && !message.guild.language) {
let language = "en";
let guildDocument = await guildModel.findOne({
guildID: message.guild.id
});
if (guildDocument && guildDocument.language)
message.guild.language = guildDocument.language;
}
if (!message.guild) {
let language = "en"
};
if (cmdFile.guildOnly && !message.guild)
return await message.channel.send(
message.client.i18n.get(language, "errors", "command_guild_only")
);
if (
!cmdFile.enabled ||
desactivadodb.tiene(
`ComandosDesactivados_${command}_${message.guild.id}`,
`g${message.guild.id}`
)
)
return await message.channel.send(
message.client.i18n.get(
message.guild.language,
"errors",
"command_disabled"
)
);
if (
cmdFile.ownerOnly &&
!message.client.config.owners.includes(message.author.id)
)
return await message.channel.send(
message.client.i18n.get(
language,
"errors",
"command_owner_only",
{ command: cmdFile.name }
)
);
if (cmdFile.nsfwOnly && !message.channel.nsfw)
return await message.channel.send(
message.client.i18n.get(language, "errors", "nsfw_only", {
command: cmdFile.name
})
);
if (
cmdFile.permissions &&
!// message.client.config.owners.includes(message.author.id) ||
message.member.permissions.has(cmdFile.permissions || "ADMINISTRATOR")
)
return await message.channel.send(
message.client.i18n.get(
language,
"errors",
"not_enough_permission",
{ permissions: cmdFile.permissions.join(", ") }
)
);
if (
cmdFile.botpermissions &&
!message.guild.me.permissions.has(
cmdFile.botpermissions || "ADMINISTRATOR"
)
)
return await message.channel.send(
message.client.i18n.get(
language,
"errors",
"not_bot_enough_permission",
{ permissions: cmdFile.botpermissions.join(", ") }
)
);
let numuses = 1;
Uses.findOne(
{
command: cmdFile.name
},
(err, res) => {
if (err) console.log(err);
if (!res) {
const newDoc = new Uses({
command: cmdFile.name,
uses: 0
});
newDoc.save().catch(err => console.log(err));
} else {
res.uses = res.uses + numuses;
res.save().catch(err => console.log(err));
}
}
);
if (cmdFile.cooldown) {
if (!cooldown[msg.author.id]) cooldown[msg.author.id] = {};
let time = cooldown[msg.author.id][cmdFile.name] || 0;
if (time && time > Date.now()) {
let wait = ((time - Date.now()) / 1000).toFixed(2);
return message.channel.send(
message.client.i18n.get(
language,
"errors",
"wait_cooldown",
{ cooldown: wait, command: cmdFile.name }
)
);
}
cooldown[msg.author.id][cmdFile.name] =
Date.now() + cmdFile.cooldown * 1000;
}
message.channel.startTyping();
cmdFile.exec(bot, msg, args).then(message.channel.stopTyping());
} catch (err) {
console.error(err);
}
};
I just changed the Client thing of the bot.js, but I think I don´t understand the actual module.exports and I am very sure that there is where the error is.
In discord.js v13 TextChannel.startTyping() method was replaced by TextChannel.sendTyping() which you have to use now! As moving to v13 guide says: "This method automatically stops typing after 10 seconds, or when a message is sent"!
Related
I have a simple reaction roles bot with a nice anticrash coded with Chalk Package. It was originally made in replit and worked just fine, but I wanted better uptime so I made a repository, loaded it into vscode and compiled it into an executable but I get this error
I tried changing my intents and even going into the discord.js discord server and no one answered me
const express = require('express')
const app = express()
const chalk = require("chalk")
app.get('/', (req, res) => {
res.send('Bot Loaded! Changes Saved!');
});
app.listen(3000, () => {
console.log(
chalk.white('['),
chalk.cyan('Express'),
chalk.white(']'),
chalk.gray(':'),
chalk.white('Connected')
);
});
const {
Client,
Collection,
GatewayIntentBits,
Partials,
} = require("discord.js");
const Discord = require('discord.js')
const client = new Client({
intents: [
"Guilds",
"GuildMessages",
"DirectMessages",
GatewayIntentBits.DirectMessages,
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildBans,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
const db = require("quick.db")
let pagination = require('./function/pagination')
// ———————————————[Global Variables]———————————————
client.commands = new Collection();
client.aliases = new Collection();
client.cooldowns = new Collection();
client.slashCommands = new Collection();
const Timeout = new Collection();
client.snipes = new Collection()
client.config = require("./botconfig/main.json");
require("./handler")(client);
// Initializing the project.
// ———————————————[Logging Into Client]———————————————
client.login('');
// ———————————————[Error Handling]———————————————
process.on("unhandledRejection", (reason, p) => {
console.log(chalk.gray("—————————————————————————————————"));
console.log(
chalk.white("["),
chalk.red.bold("AntiCrash"),
chalk.white("]"),
chalk.gray(" : "),
chalk.white.bold("Unhandled Rejection/Catch")
);
console.log(chalk.gray("—————————————————————————————————"));
console.log(reason, p);
});
process.on("uncaughtException", (err, origin) => {
console.log(chalk.gray("—————————————————————————————————"));
console.log(
chalk.white("["),
chalk.red.bold("AntiCrash"),
chalk.white("]"),
chalk.gray(" : "),
chalk.white.bold("Uncaught Exception/Catch")
);
console.log(chalk.gray("—————————————————————————————————"));
console.log(err, origin);
});
process.on("multipleResolves", (type, promise, reason) => {
console.log(chalk.gray("—————————————————————————————————"));
console.log(
chalk.white("["),
chalk.red.bold("AntiCrash"),
chalk.white("]"),
chalk.gray(" : "),
chalk.white.bold("Multiple Resolves")
);
console.log(chalk.gray("—————————————————————————————————"));
console.log(type, promise, reason);
});
const Levels = require("discord-xp");
const { mongooseConnectionString } = require("./botconfig/main.json");
Levels.setURL(mongooseConnectionString);
// ———————————————[Anti Ghost ping]———————————————
let { MessageEmbed } = require("discord.js")
client.on('messageCreate', message => {
if(message.author.bot) return;
if(!message.guild) return;
const args = message.content.split(" ").slice(1)
if(message.content.toLowerCase().startsWith("+ghostpingdetector")) {
//=====
let embedon = new MessageEmbed()
.setDescription(":green_square: | Turned On GhostPingDetector")
.setTimestamp()
//===
let embedoff = new MessageEmbed()
.setDescription(":red_square: | Turned Off GhostPingDetector")
.setTimestamp()
//====
if(!args[0]) return message.reply('Do You Want To Turn On or Off ghostpingdetector? Please Type \`w?ghostpingdetector true/false\` or \`on/off\`');
if(args[0] === "on" || args[0] === "true") {
message.reply({embeds: [embedon]})
db.set(`gp_${message.author.id}`, true)
} else if(args[0] === "off" || args[0] === "false") {
db.delete(`gp_${message.author.id}`)
message.reply({embeds: [embedoff]})
}
}[![enter image description here](https://i.stack.imgur.com/4SanR.png)](https://i.stack.imgur.com/4SanR.png)
})
client.on('messageDelete', message => {
message.mentions.users.forEach(m => {
if(db.has(`gp_${m.id}`) && m.id !== message.author.id && !message.author.bot){
let emb = new MessageEmbed()
emb.setTitle('GhostPingDetector')
emb.setDescription(`<#${m.id}>, You've Been Ghost Pinged.\nUserName: \`${message.author.username}\`\nUserID: \`${message.author.id}\`\nServerName: ${message.guild.name}\nChannel: <#${message.channel.id}>\nContent: ${message.content}`)
emb.setColor("GREEN")
emb.setFooter(`Anti-Ghost Ping! woop woop`)
m.send({embeds: [emb]})
message.channel.send({embeds: [emb]})
}
})
})
client.on('message', message => {
if (message.channel.id === '1029286082879180832') {
message.react('✅');
}
});
I'm still trying to place an order for the voice bot to enter. I want to make a music system using youtube-dl and I always get this error saying that it doesn't know what "Voice" means in the line "message.member.voiceChannel"
I'm already getting nervous about this problem, I tried to add permissions, but it doesn't work, I want to specify that it uses Discord.js#v12
below you have all the files that I use for the command, such as message event and command class.
Error Code:
2022-06-02 05:39:42 [info] [Command] "n!join" (join) ran by "GhostStru#1982" (780808189226123294) on guild "GhostStru🌿's server" (939865905708552242) channel "#cmmds" (980923745768181831)
TypeError: Cannot read properties of undefined (reading 'voice')
at module.exports.run (C:\Users\Ghost\Desktop\NucleusNEW\commands\music\join.js:23:36)
at module.exports.runCommand (C:\Users\Ghost\Desktop\NucleusNEW\events\message\message.js:417:23)
at module.exports.run (C:\Users\Ghost\Desktop\NucleusNEW\events\message\message.js:391:20)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
This is my Join command
const { joinVoiceChannel } = require('#discordjs/voice');
const { MessageEmbed, Util } = require('discord.js');
const discord = require("discord.js")
const Command = require('../../structures/Command');
module.exports = class extends Command {
constructor(...args) {
super(...args, {
name: 'join',
aliases: ['add'],
usage: "",
category: "Music",
examples: ["join"],
description: "Join into you'r voice channel.",
cooldown: 5,
})
}
async run(client, message, args) {
const voiceChannel = message.member.voice.channel;
if (!message.member.voiceChannel) return message.channel.send({embeds: [new MessageEmbed().setColor(client.color.error).setDescription(`You must be a voice channel before using this command.`)]});
if (message.guild.me.voiceChannel && message.member.voiceChannel.id !== message.guild.me.voiceChannel.id) return message.channel.send({embeds: [new MessageEmbed().setColor(client.color.error).setDescription(`You are not in same voice channel.`)]});
try {
joinVoiceChannel({
channelId: message.member.voiceChannel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator,
});
await message.react('👍').catch(() => { });
} catch {
return message.channel.send({embeds: [new MessageEmbed().setColor(client.color.error).setDescription(`An error occurred while joining the voice channel.`)]});
}
}
}
This is my message event
const Event = require('../../structures/Event');
const { Permissions, Collection } = require("discord.js");
const afk = require("../../models/afk");
const Statcord = require("statcord.js");
const moment = require('moment');
const discord = require("discord.js");
const config = require('./../../config.json');
const { MessageEmbed } = require('discord.js');
const logger = require('../../utils/logger');
const nsfwplease = require('../../assets/json/nfsw.json');
const mongoose = require('mongoose');
const Guild = require('../../database/schemas/Guild');
const User = require('../../database/schemas/User');
const Moderation = require('../../database/schemas/logging');
const Blacklist = require('../../database/schemas/blacklist');
const customCommand = require('../../database/schemas/customCommand');
const autoResponse = require('../../database/schemas/autoResponse');
const autoResponseCooldown = new Set();
const inviteFilter = require('../../filters/inviteFilter');
const linkFilter = require('../../filters/linkFilter');
const maintenanceCooldown = new Set();
const metrics = require('datadog-metrics');
const permissions = require('../../assets/json/permissions.json')
const Maintenance = require('../../database/schemas/maintenance')
require("moment-duration-format");
module.exports = class extends Event {
constructor(...args) {
super(...args);
this.impliedPermissions = new Permissions([
"VIEW_CHANNEL",
"SEND_MESSAGES",
"SEND_TTS_MESSAGES",
"EMBED_LINKS",
"ATTACH_FILES",
"READ_MESSAGE_HISTORY",
"MENTION_EVERYONE",
"USE_EXTERNAL_EMOJIS",
"ADD_REACTIONS"
]);
this.ratelimits = new Collection();
}
async run(message) {
try {
if (!message.guild) return;
if(config.datadogApiKey){
metrics.init({ apiKey: this.client.config.datadogApiKey, host: 'nucleus', prefix: 'nucleus.' });
}
const mentionRegex = RegExp(`^<#!?${this.client.user.id}>$`);
const mentionRegexPrefix = RegExp(`^<#!?${this.client.user.id}>`);
if (!message.guild || message.author.bot) return;
const settings = await Guild.findOne({
guildId: message.guild.id,
}, async (err, guild) => {
if (err) console.log(err)
if (!guild) {
const newGuild = await Guild.create({
guildId: message.guild.id,
prefix: config.prefix || 'p!',
language: "english"
});
}
});
//if (!settings) return message.channel.send('Oops, this server was not found in the database. Please try to run the command again now!');
if (message.content.match(mentionRegex)) {
const proofita = `\`\`\`css\n[ Prefix: ${settings.prefix || '!'} ]\`\`\``;
const proofitaa = `\`\`\`css\n[ Help: ${settings.prefix || '!'}help ]\`\`\``;
const embed = new MessageEmbed()
.setTitle('Hello, I\'m Nucleus. What\'s Up?')
.addField(`Prefix`,proofita, true)
.addField(`Usage`,proofitaa, true)
.setDescription(`\nIf you like Nucleus, Consider [voting](https://top.gg/bot/980373513691090974), or [inviting](https://discord.com/oauth2/authorize?client_id=980373513691090974&scope=bot&permissions=470150262) it to your server! Thank you for using Nucleus, we hope you enjoy it, as we always look forward to improve the bot`)
.setFooter('Thank you for using Nucleus!!')
.setColor('#FF2C98')
message.channel.send(embed);
}
if(config.datadogApiKey){
// Add increment after every darn message lmfao!
metrics.increment('messages_seen');
}
// Filters
if (settings && await inviteFilter(message)) return;
if (settings && await linkFilter(message)) return;
let mainPrefix = settings ? settings.prefix : '!';
const prefix = message.content.match(mentionRegexPrefix) ?
message.content.match(mentionRegexPrefix)[0] : mainPrefix
const guildDB = await Guild.findOne({
guildId: message.guild.id
});
const moderation = await Moderation.findOne({
guildId: message.guild.id
});
if(!moderation){
Moderation.create({
guildId: message.guild.id
})
}
// maintenance mode
const maintenance = await Maintenance.findOne({
maintenance: "maintenance"
})
const userBlacklistSettings = await Blacklist.findOne({ discordId: message.author.id,});
const guildBlacklistSettings = await Blacklist.findOne({ guildId: message.guild.id });
//autoResponse
const autoResponseSettings = await autoResponse.findOne({ guildId: message.guild.id, name: message.content.toLowerCase() });
if (autoResponseSettings && autoResponseSettings.name) {
if (userBlacklistSettings && userBlacklistSettings.isBlacklisted) return;
if(maintenance && maintenance.toggle == "true") return;
if(autoResponseCooldown.has(message.author.id)) return message.channel.send(`${message.client.emoji.fail} Slow Down - ${message.author}`)
message.channel.send(autoResponseSettings.content
.replace(/{user}/g, `${message.author}`)
.replace(/{user_tag}/g, `${message.author.tag}`)
.replace(/{user_name}/g, `${message.author.username}`)
.replace(/{user_ID}/g, `${message.author.id}`)
.replace(/{guild_name}/g, `${message.guild.name}`)
.replace(/{guild_ID}/g, `${message.guild.id}`)
.replace(/{memberCount}/g, `${message.guild.memberCount}`)
.replace(/{size}/g, `${message.guild.memberCount}`)
.replace(/{guild}/g, `${message.guild.name}`)
.replace(/{member_createdAtAgo}/g, `${moment(message.author.createdTimestamp).fromNow()}`)
.replace(/{member_createdAt}/g, `${moment(message.author.createdAt).format('MMMM Do YYYY, h:mm:ss a')}`))
autoResponseCooldown.add(message.author.id)
setTimeout(()=>{
autoResponseCooldown.delete(message.author.id)
}, 2000)
return;
}
//afk
let language = require(`../../data/language/english.json`)
if(guildDB) language = require(`../../data/language/${guildDB.language}.json`)
moment.suppressDeprecationWarnings = true;
if(message.mentions.members.first()){
if(maintenance && maintenance.toggle == "true") return;
const afklist = await afk.findOne({ userID: message.mentions.members.first().id, serverID: message.guild.id});
if(afklist){
await message.guild.members.fetch(afklist.userID).then(member => {
let user_tag = member.user.tag;
return message.channel.send(`**${afklist.oldNickname || user_tag || member.user.username}** ${language.afk6} ${afklist.reason} **- ${moment(afklist.time).fromNow()}**`).catch(() => {});
});
}
}
const afklis = await afk.findOne({ userID: message.author.id, serverID: message.guild.id});
if(afklis) {
if(maintenance && maintenance.toggle == "true") return;
let nickname = `${afklis.oldNickname}`;
message.member.setNickname(nickname).catch(() => {});
await afk.deleteOne({ userID: message.author.id });
return message.channel.send(new discord.MessageEmbed().setColor('GREEN').setDescription(`${language.afk7} ${afklis.reason}`)).then(m => {
setTimeout(() => {
m.delete().catch(() => {});
}, 10000);
});
};
if (!message.content.startsWith(prefix)) return;
// eslint-disable-next-line no-unused-vars
const [cmd, ...args] = message.content.slice(prefix.length).trim().split(/ +/g);
const command = this.client.commands.get(cmd.toLowerCase()) || this.client.commands.get(this.client.aliases.get(cmd.toLowerCase()));
// maintenance mode
if(!this.client.config.developers.includes(message.author.id)){
if(maintenance && maintenance.toggle == "true") {
if(maintenanceCooldown.has(message.author.id)) return;
message.channel.send(`Nucleus is currently undergoing maintenance which won't allow anyone to access Nucleus Commands. Feel free to try again later. For updates: https://discord.gg/FqdH4sfKBg`)
maintenanceCooldown.add(message.author.id);
setTimeout(() => {
maintenanceCooldown.delete(message.author.id)
}, 10000);
return;
}
}
// Custom Commands
const customCommandSettings = await customCommand.findOne({ guildId: message.guild.id, name: cmd.toLowerCase() });
const customCommandEmbed = await customCommand.findOne({ guildId: message.guild.id, name: cmd.toLowerCase() });
if (customCommandSettings && customCommandSettings.name && customCommandSettings.description) {
if (userBlacklistSettings && userBlacklistSettings.isBlacklisted) return;
let embed = new MessageEmbed()
.setTitle(customCommandEmbed.title)
.setDescription(customCommandEmbed.description)
.setFooter(``)
if( customCommandEmbed.image !== "none") embed.setImage(customCommandEmbed.image)
if( customCommandEmbed.thumbnail !== "none") embed.setThumbnail(customCommandEmbed.thumbnail)
if( customCommandEmbed.footer !== "none") embed.setFooter(customCommandEmbed.footer)
if( customCommandEmbed.timestamp !== "no") embed.setTimestamp()
if( customCommandEmbed.color == 'default') {
embed.setColor(message.guild.me.displayHexColor)
} else embed.setColor(`${customCommandEmbed.color}`)
return message.channel.send(embed)
}
if (customCommandSettings && customCommandSettings.name && !customCommandSettings.description && customCommandSettings.json == "false") {
if (userBlacklistSettings && userBlacklistSettings.isBlacklisted) return;
return message.channel.send(customCommandSettings.content
.replace(/{user}/g, `${message.author}`)
.replace(/{user_tag}/g, `${message.author.tag}`)
.replace(/{user_name}/g, `${message.author.username}`)
.replace(/{user_ID}/g, `${message.author.id}`)
.replace(/{guild_name}/g, `${message.guild.name}`)
.replace(/{guild_ID}/g, `${message.guild.id}`)
.replace(/{memberCount}/g, `${message.guild.memberCount}`)
.replace(/{size}/g, `${message.guild.memberCount}`)
.replace(/{guild}/g, `${message.guild.name}`)
.replace(/{member_createdAtAgo}/g, `${moment(message.author.createdTimestamp).fromNow()}`)
.replace(/{member_createdAt}/g, `${moment(message.author.createdAt).format('MMMM Do YYYY, h:mm:ss a')}`)
)
}
if (customCommandSettings && customCommandSettings.name && !customCommandSettings.description && customCommandSettings.json == "true") {
if (userBlacklistSettings && userBlacklistSettings.isBlacklisted) return;
const command = JSON.parse(customCommandSettings.content)
return message.channel.send(command).catch((e)=>{message.channel.send(`There was a problem sending your embed, which is probably a JSON error.\nRead more here --> https://nucleus.xyz/embeds\n\n__Error:__\n\`${e}\``)})
}
if (command) {
await User.findOne({
discordId: message.author.id
}, (err, user) => {
if (err) console.log(err)
if (!user) {
const newUser = new User({
discordId: message.author.id
})
newUser.save()
}
});
const disabledCommands = guildDB.disabledCommands;
if (typeof(disabledCommands) === 'string') disabledCommands = disabledCommands.split(' ');
const rateLimit = this.ratelimit(message, cmd);
if (!message.channel.permissionsFor(message.guild.me).has('SEND_MESSAGES')) return;
// Check if user is Blacklisted
if (userBlacklistSettings && userBlacklistSettings.isBlacklisted) {
logger.warn(`${message.author.tag} tried to use "${cmd}" command but the user is blacklisted`, { label: 'Commands' })
return message.channel.send(`${message.client.emoji.fail} You are blacklisted from the bot :(`);
}
// Check if server is Blacklisted
if (guildBlacklistSettings && guildBlacklistSettings.isBlacklisted) {
logger.warn(`${message.author.tag} tried to use "${cmd}" command but the guild is blacklisted`, { label: 'Commands' })
return message.channel.send(`${message.client.emoji.fail} This guild is Blacklisted :(`);
}
let number = Math.floor((Math.random() * 10) + 1);
if (typeof rateLimit === "string") return message.channel.send(` ${message.client.emoji.fail} Please wait **${rateLimit}** before running the **${cmd}** command again - ${message.author}\n\n${number === 1 ? "*Did You know that Nucleus has its own dashboard? `https://nucleus.xyz/dashboard`*" : ""}${number === 2 ? "*You can check our top.gg page at `https://vote.nucleus.xyz`*" : ""}`).then((s)=>{
message.delete().catch(()=>{});
s.delete({timeout: 4000}).catch(()=>{})
}).catch(()=>{})
if (command.botPermission) {
const missingPermissions =
message.channel.permissionsFor(message.guild.me).missing(command.botPermission).map(p => permissions[p]);
if (missingPermissions.length !== 0) {
const embed = new MessageEmbed()
.setAuthor(`${this.client.user.tag}`, message.client.user.displayAvatarURL({ dynamic: true }))
.setTitle(`<:wrong:822376943763980348> Missing Bot Permissions`)
.setDescription(`Command Name: **${command.name}**\nRequired Permission: **${missingPermissions.map(p => `${p}`).join(' - ')}**`)
.setTimestamp()
.setFooter('https://nucleus.xyz')
.setColor(message.guild.me.displayHexColor);
return message.channel.send(embed).catch(()=>{})
}
}
if (command.userPermission) {
const missingPermissions =
message.channel.permissionsFor(message.author).missing(command.userPermission).map(p => permissions[p]);
if (missingPermissions.length !== 0) {
const embed = new MessageEmbed()
.setAuthor(`${message.author.tag}`, message.author.displayAvatarURL({ dynamic: true }))
.setTitle(`<:wrong:822376943763980348> Missing User Permissions`)
.setDescription(`Command Name: **${command.name}**\nRequired Permission: **${missingPermissions.map(p => `${p}`).join('\n')}**`)
.setTimestamp()
.setFooter('https://nucleus.xyz')
.setColor(message.guild.me.displayHexColor);
return message.channel.send(embed).catch(()=>{})
}
}
if(disabledCommands.includes(command.name || command)) return;
if (command.ownerOnly) {
if (!this.client.config.developers.includes(message.author.id)) return
}
if(config.datadogApiKey){
metrics.increment('commands_served');
}
if (command.disabled) return message.channel.send(`The owner has disabled the following command for now. Try again Later!\n\nFor Updates: https://discord.gg/duBwdCvCwW`)
if (command.nsfwOnly && !message.channel.nsfw && message.guild) return message.channel.send(`${nsfwplease[Math.round(Math.random() * (nsfwplease.length - 1))]}`)
Statcord.ShardingClient.postCommand(cmd, message.author.id, this.client);
await this.runCommand(message, cmd, args)
.catch(error => {
if(config.datadogApiKey){
metrics.increment('command_error');
}
return this.client.emit("commandError", error, message, cmd);
})
}
} catch(error) {
if(config.datadogApiKey){
metrics.increment('command_error');
}
return this.client.emit("fatalError", error, message);
}
}
async runCommand(message, cmd, args) {
if (!message.channel.permissionsFor(message.guild.me) || !message.channel.permissionsFor(message.guild.me).has('EMBED_LINKS'))
return message.channel.send(`${message.client.emoji.fail} Missing bot Permissions - **Embeds Links**`)
const command = this.client.commands.get(cmd.toLowerCase()) || this.client.commands.get(this.client.aliases.get(cmd.toLowerCase()));
logger.info(`"${message.content}" (${command.name}) ran by "${message.author.tag}" (${message.author.id}) on guild "${message.guild.name}" (${message.guild.id}) channel "#${message.channel.name}" (${message.channel.id})`, { label: 'Command' })
await command.run(message, args)
}
ratelimit(message, cmd) {
try {
const command = this.client.commands.get(cmd.toLowerCase()) || this.client.commands.get(this.client.aliases.get(cmd.toLowerCase()));
if (message.author.permLevel > 4) return false;
const cooldown = command.cooldown * 1000
const ratelimits = this.ratelimits.get(message.author.id) || {}; // get the ENMAP first.
if (!ratelimits[command.name]) ratelimits[command.name] = Date.now() - cooldown; // see if the command has been run before if not, add the ratelimit
const difference = Date.now() - ratelimits[command.name]; // easier to see the difference
if (difference < cooldown) { // check the if the duration the command was run, is more than the cooldown
return moment.duration(cooldown - difference).format("D [days], H [hours], m [minutes], s [seconds]", 1); // returns a string to send to a channel
} else {
ratelimits[command.name] = Date.now(); // set the key to now, to mark the start of the cooldown
this.ratelimits.set(message.author.id, ratelimits); // set it
return true;
}
} catch(e) {
this.client.emit("fatalError", error, message);
}
}
}
And this is my Command class
module.exports = class Command {
constructor(client, name, options = {}) {
this.client = client;
this.name = options.name || name;
this.aliases = options.aliases || [];
this.description = options.description || "No description provided.";
this.category = options.category || "General";
this.usage = `${this.name} ${options.usage || ''}` || "No usage provided.";
this.examples = options.examples || [];
this.disabled = options.disabled || false;
this.cooldown = "cooldown" in options ? options.cooldown : 5 || 5;
this.ownerOnly = options.ownerOnly || false;
this.guildOnly = options.guildOnly || false;
this.nsfwOnly = options.nsfwOnly || false;
this.botPermission = options.botPermission || ['SEND_MESSAGES', 'EMBED_LINKS'];
this.userPermission = options.userPermission || null;
}
// eslint-disable-next-line no-unused-vars
async run(message, args) {
throw new Error(`The run method has not been implemented in ${this.name}`);
}
reload() {
return this.store.load(this.file.path);
}
}
In this "code cases" i put my personal codes, and i dont know where can i find the problem, or what can i modifiy in my code, thats all i can say..
Can someone tell me what can i do?...
Its a simple join command, and he cannot read voice.channel...
this is my second question today. I'm using discord.js v13. Earlier I looked into finding out how to make audio play from the bot, and now I am attempting to make a queue work for my discord.js bot. My problem is getting the queue defined from index.js correctly. I will provide the error log along with my code.
error logs: https://i.imgur.com/ScDcJHK.jpg
index.js
const fs = require('fs');
const { Collection, Client, Intents } = require('discord.js');
const Levels = require('discord-xp');
require('dotenv').config();
const client = new Client({
presence: {
status: 'idle',
afk: false,
activities: [{
name: 'The Official Xontavs',
type: 'WATCHING'
}],
},
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_VOICE_STATES, Intents.FLAGS.GUILD_PRESENCES, Intents.FLAGS.GUILD_MEMBERS]
});
client.queue = new Map();
const mongoose = require('./database/mongoose.js');
Levels.setURL(`mongodb+srv://discordbot:${process.env.PASS}#bot.z8ki0.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`);
['aliases', 'commands'].forEach(x => client[x] = new Collection());
['command', 'event'].forEach(x => require(`./handlers/${x}`)(client));
mongoose.init();
client.login(process.env.CLIENT_TOKEN); // SECRET TOKEN
play.js
const ytdl = require('ytdl-core');
const ytSearch = require('yt-search');
const { getVoiceConnection, joinVoiceChannel, AudioPlayerStatus, createAudioResource, getNextResource, createAudioPlayer, NoSubscriberBehavior } = require('#discordjs/voice');
const { createReadStream} = require('fs');
module.exports = {
name: "play",
category: "music",
description: "plays a song",
usage: "<id | mention>",
run: async (client, message, args, queue) => {
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send('You are not in a voice channel.');
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT', 'SPEAK')) return message.channel.send('You do not have the correct permissions');
if(!args.length) return message.channel.send('You need to send the second argument');
const server_queue = queue.get(message.guild.id);
let song = {};
if (ytdl.validateURL(args[0])) {
const song_info = await ytdl.getInfo(args[0]);
song = { title: song_info.videoDetails.title, url: song_info.videoDetails.video_url }
} else {
const video_finder = async (query) =>{
const videoResult = await ytSearch(query);
return (videoResult.videos.length > 1) ? videoResult.videos[0] : null;
}
const video = await video_finder(args.join(' '));
if (video){
song = { title: video.title, url: video.url }
} else {
message.channel.send('Error finding video.');
}
}
if (!server_queue){
const queue_constructor = {
voice_channel: voiceChannel,
text_channel: message.channel,
connection: null,
songs: []
}
queue.set(message.guild.id, queue_constructor);
queue_constructor.songs.push(song);
try {
const connection = joinVoiceChannel({
channelId: voiceChannel.id,
guildId: message.guild.id,
adapterCreator: message.guild.voiceAdapterCreator
});
queue_constructor.connection = connection;
video_player(message.guild, queue_constructor.songs[0]);
} catch (err) {
queue.delete(message.guild.id);
message.channel.send('Error connecting');
throw err;
}
} else {
server_queue.songs.push(song);
return message.channel.send(`**${song.title}** added to queue.`);
}
//audioPlayer.play(createAudioResource(stream, {seek: 0, volume: 1}))
//audioPlayer.on(AudioPlayerStatus.Idle, () => {
//audioPlayer.stop();
//connection.destroy();
//message.channel.send('Leaving VC');
//});
}
}
const video_player = async (guild, song, queue) => {
const song_queue = queue.get(guild.id);
if(!song) {
connection.destroy();
queue.delete(guild.id);
return;
}
const audioPlayer = createAudioPlayer();
song_queue.connection.subscribe(audioPlayer);
const stream = ytdl(song.url, { filter: 'audioonly' });
audioPlayer.play(createAudioResource(stream, {seek: 0, volume: 1}))
audioPlayer.on(AudioPlayerStatus.Idle, () => {
song_queue.songs.shift();
video_player(guild, song_queue.songs[0]);
});
song_queue.text_channel.send(`Now playing **${song.title}**`)
}
messageCreate.js (if needed)
const del = require('../../functions.js');
const Levels = require('discord-xp');
require('dotenv').config();
const prefix = process.env.PREFIX;
const queue = new Map();
module.exports = async (Discord, client, message) => {
if (message.author.bot || !message.guild) return;
const randomXP = Math.floor(Math.random() * 14) + 1; //1-15
const hasLeveledUP = await Levels.appendXp(message.author.id, message.guild.id, randomXP);
if (hasLeveledUP) {
const user = await Levels.fetch(message.author.id, message.guild.id);
message.channel.send(`${message.member} is now level ${user.level}.`);
}
//const args = message.content.startsWith(prefix) ? message.content.slice(prefix.length).trim().split(/ +/g) : message.content.replace(/[^\s]*/, '').trim().split(/ +/g);
const args = message.content.slice(prefix.length).trim().split(" ");
const cmd = args.shift().toLowerCase();
if (cmd.length === 0) return;
let command = client.commands.get(cmd) || client.commands.find(c => c.aliases?.includes(cmd));
if (command) {
command.run(client, message, args, queue);
}
}
Any help is appreciated because I'm really not smart and I'm still trying to learn how all this stuff works, especially with discord.js v13
In
video_player(message.guild, queue_constructor.songs[0]);
You only put two parameters and as you said in the comments, you only had to change it to this to fix your problem
video_player(message.guild, queue_constructor.songs[0], queue, audioPlayer)
So I've had multiple problems one after another. The first being;
TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client
Which I solved by changing up my code from:
const Discord = require("discord.js");
const bot = new Discord.Client();
To:
const { Client, Intents, Discord } = require("discord.js");
const bot = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
But now I am running into a seperate issue. Where I keep getting this error;
Startup TypeError: Cannot read property 'Collection' of undefined
This is really frustrated because I've been at this problem for a couple of hours. Any help would be massively appreciated!
All essential code:
const { Client, Intents } = require("discord.js");
const bot = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const { prefix, token, mongoPath } = require("./jsonFiles/config.json");
const mongoose = require("mongoose");
const mongo = require("./utility/mongo.js");
const fs = require("fs");
const Levels = require("discord-xp");
bot.login(token);
bot.commands = new Discord.Collection();
bot.cooldowns = new Discord.Collection();
const commandFolders = fs.readdirSync("./commands");
for (const folder of commandFolders) {
//Finds the name of the command
const commandFiles = fs
.readdirSync(`./commands/${folder}`)
.filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require(`./commands/${folder}/${file}`);
bot.commands.set(command.name, command);
}
}
bot.on("ready", async () => {
console.log("Connect as " + bot.user.tag);
//levels(bot);
await mongo().then(() => {
try {
console.log("Connected to mongo!");
} finally {
mongoose.connection.close();
}
});
bot.user.setActivity(".help", {
type: "WATCHING",
});
});
bot.on("message", async (message) => {
try {
await mongo().then(async (mongoose) => {
Levels.setURL(mongoPath);
if (!message.guild) return;
if (message.author.bot) return;
const randomAmountOfXp = Math.floor(Math.random() * 20) + 1; // Min 1, Max 30
const hasLeveledUp = await Levels.appendXp(
message.author.id,
message.guild.id,
randomAmountOfXp
);
if (hasLeveledUp) {
const user = await Levels.fetch(message.author.id, message.guild.id);
message.channel.send(
`${message.author}, congratulations! You have leveled up to **${user.level}** in \`${message.guild.name}\` :sunglasses:`
);
}
});
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command =
bot.commands.get(commandName) ||
bot.commands.find((cmd) => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
if (command.guildOnly && message.channel.type === "dm")
return message.reply("I can't execute that command inside DMs!");
if (command.permissions) {
const authorPerms = message.channel.permissionsFor(message.author);
if (!authorPerms || !authorPerms.has(command.permissions)) {
if (message.author.id !== "344834268742156298") {
return message.reply("YOU DO NOT HAVE PERMISSION (git gud scrub)");
}
}
}
if (command.creator === true && message.author.id !== "344834268742156298")
return message.reply("Wait what, you are not creator man, you cannot use the command!!!!!");
if (command.args === true && !args.length) {
let reply = `You didn't provide a valid arguments, ${message.author}!`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
}
message.delete({
timeout: 25 * 1000,
});
return message.channel.send(reply).then((message) => {
message.delete({
timeout: 25 * 1000,
});
});
}
const { cooldowns } = bot;
if (!cooldowns.has(command.name)) {
cooldowns.set(command.name, new Discord.Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.name);
const cooldownAmount = (command.cooldown ?? 1.5) * 1000;
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return message.reply(
`please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${
command.name
}\` command.`
);
}
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
const maxArguments = command.maxArgs || null;
if (
args.length < command.minArgs ||
(maxArguments !== null && command.args === "true" && args.length > command.maxArgs)
) {
let reply = `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
return message.channel.send(reply);
}
try {
command.execute(message, args, message.guild);
} catch (err) {
console.log(err);
}
} catch (err) {
console.log(err);
}
});
At the top you never defined Discord properly. You are trying to access the non-existant Discord property of the discord.js module with object destructuring. There are 2 quick fixes for this, the first one will be faster however.
//at the top change the declaration of Client
const Discord = {
Client,
Intents
} = require('discord.js')
//Discord is module discord.js
Or you can do
const {
Collection,
Client,
Intents
} = require('discord.js')
//use new Collection() instead of new Discord.Collection()
Try instead of:
const { Client, Intents } = require("discord.js");
Try:
const Discord = require("discord.js"), { Client, Intents } = Discord;
Or you can also import Collection from discord:
const { Client, Intents, Collection } = require("discord.js");
and replace:
new Discord.Collection() with new Collection()
ok so this is a discord bot to record voice chat
https://hatebin.com/hgjlazacri
Now the bot works perfectly fine but the issue is that the audio sounds a bit deeper and slower than normal.. Why does it happen? how can I make the audio sound 1:1..
const Discord = require('discord.js');
const client = new Discord.Client();
const ffmpegInstaller = require('#ffmpeg-installer/ffmpeg');
const ffmpeg = require('fluent-ffmpeg');
ffmpeg.setFfmpegPath(ffmpegInstaller.path);
const fs = require('fs-extra')
const mergeStream = require('merge-stream');
const config = require('./config.json');
const { getAudioDurationInSeconds } = require('get-audio-duration');
const cp = require('child_process');
const path1 = require('path');
const Enmap = require('enmap');
const UserRecords = require("./models/userrecords.js")
const ServerRecords = require("./models/serverrecords.js")
let prefix = `$`
class Readable extends require('stream').Readable { _read() {} }
let recording = false;
let currently_recording = {};
let mp3Paths = [];
const silence_buffer = new Uint8Array(3840);
const express = require('express')
const app = express()
const port = 3000
const publicIP = require('public-ip')
const { program } = require('commander');
const { path } = require('#ffmpeg-installer/ffmpeg');
const version = '0.0.1'
program.version(version);
let debug = false
let runProd = false
let fqdn = "";
const mongoose = require("mongoose");
const MongoClient = require('mongodb').MongoClient;
mongoose.connect('SECRRET',{
useNewUrlParser: true
}, function(err){
if(err){
console.log(err);
}else{
console.log("Database connection initiated");
}
});
require("dotenv").config()
function bufferToStream(buffer) {
let stream = new Readable();
stream.push(buffer);
return stream;
}
client.commands = new Enmap();
client.on('ready', async () => {
console.log(`Logged in as ${client.user.tag}`);
let host = "localhost"
let ip = await publicIP.v4();
let protocol = "http";
if (!runProd) {
host = "localhost"
} else {
host = `35.226.244.186`;
}
fqdn = `${protocol}://${host}:${port}`
app.listen(port, `0.0.0.0`, () => {
console.log(`Listening on port ${port} for ${host} at fqdn ${fqdn}`)
})
});
let randomArr = []
let finalArrWithIds = []
let variable = 0
client.on('message', async message => {
console.log(`fuck`);
if(message.content === `$record`){
mp3Paths = []
finalArrWithIds = []
let membersToScrape = Array.from(message.member.voice.channel.members.values());
membersToScrape.forEach((member) => {
if(member.id === `749250882830598235`) {
console.log(`botid`);
}
else {
finalArrWithIds.push(member.id)
}
})
const randomNumber = Math.floor(Math.random() * 100)
randomArr = []
randomArr.push(randomNumber)
}
const generateSilentData = async (silentStream, memberID) => {
console.log(`recordingnow`)
while(recording) {
if (!currently_recording[memberID]) {
silentStream.push(silence_buffer);
}
await new Promise(r => setTimeout(r, 20));
}
return "done";
}
console.log(generateSilentData, `status`)
function generateOutputFile(channelID, memberID) {
const dir = `./recordings/${channelID}/${memberID}`;
fs.ensureDirSync(dir);
const fileName = `${dir}/${randomArr[0]}.aac`;
console.log(`${fileName} ---------------------------`);
return fs.createWriteStream(fileName);
}
if (!fs.existsSync("public")) {
fs.mkdirSync("public");
}
app.use("/public", express.static("./public"));
if (!message.guild) return;
if (message.content === config.prefix + config.record_command) {
if (recording) {
message.reply("bot is already recording");
return
}
if (message.member.voice.channel) {
recording = true;
const connection = await message.member.voice.channel.join();
const dispatcher = connection.play('./audio.mp3');
connection.on('speaking', (user, speaking) => {
if (speaking.has('SPEAKING')) {
currently_recording[user.id] = true;
} else {
currently_recording[user.id] = false;
}
})
let members = Array.from(message.member.voice.channel.members.values());
members.forEach((member) => {
if (member.id != client.user.id) {
let memberStream = connection.receiver.createStream(member, {mode : 'pcm', end : 'manual'})
let outputFile = generateOutputFile(message.member.voice.channel.id, member.id);
console.log(outputFile, `outputfile here`);
mp3Paths.push(outputFile.path);
silence_stream = bufferToStream(new Uint8Array(0));
generateSilentData(silence_stream, member.id).then(data => console.log(data));
let combinedStream = mergeStream(silence_stream, memberStream);
ffmpeg(combinedStream)
.inputFormat('s32le')
.audioFrequency(44100)
.audioChannels(2)
.on('error', (error) => {console.log(error)})
.audioCodec('aac')
.format('adts')
.pipe(outputFile)
}
})
} else {
message.reply('You need to join a voice channel first!');
}
}
if (message.content === config.prefix + config.stop_command) {
let date = new Date();
let dd = String(date.getDate()).padStart(2, '0');
let mm = String(date.getMonth() + 1).padStart(2, '0');
let yyyy = date.getFullYear();
date = mm + '/' + dd + '/' + yyyy;
let currentVoiceChannel = message.member.voice.channel;
if (currentVoiceChannel) {
recording = false;
await currentVoiceChannel.leave();
let mergedOutputFolder = './recordings/' + message.member.voice.channel.id + `/${randomArr[0]}/`;
fs.ensureDirSync(mergedOutputFolder);
let file_name = `${randomArr[0]}` + '.aac';
let mergedOutputFile = mergedOutputFolder + file_name;
let download_path = message.member.voice.channel.id + `/${randomArr[0]}/` + file_name;
let mixedOutput = new ffmpeg();
console.log(mp3Paths, `mp3pathshere`);
mp3Paths.forEach((mp3Path) => {
mixedOutput.addInput(mp3Path);
})
console.log(mp3Paths);
//mixedOutput.complexFilter('amix=inputs=2:duration=longest');
mixedOutput.complexFilter('amix=inputs=' + mp3Paths.length + ':duration=longest');
let processEmbed = new Discord.MessageEmbed().setTitle(`Audio Processing.`)
processEmbed.addField(`Audio processing starting now..`, `Processing Audio`)
processEmbed.setThumbnail(`https://media.discordapp.net/attachments/730811581046325348/748610998985818202/speaker.png`)
processEmbed.setColor(` #00FFFF`)
const processEmbedMsg = await message.channel.send(processEmbed)
async function saveMp3(mixedData, outputMixed) {
console.log(`${mixedData} MIXED `)
return new Promise((resolve, reject) => {
mixedData.on('error', reject).on('progress',
async (progress) => {
let processEmbedEdit = new Discord.MessageEmbed().setTitle(`Audio Processing.`)
processEmbedEdit.addField(`Processing: ${progress.targetSize} KB converted`, `Processing Audio`)
processEmbedEdit.setThumbnail(`https://media.discordapp.net/attachments/730811581046325348/748610998985818202/speaker.png`)
processEmbedEdit.setColor(` #00FFFF`)
processEmbedMsg.edit(processEmbedEdit)
console.log('Processing: ' + progress.targetSize + ' KB converted');
}).on('end', () => {
console.log('Processing finished !');
resolve()
}).saveToFile(outputMixed);
console.log(`${outputMixed} IT IS HERE`);
})
}
// mixedOutput.saveToFile(mergedOutputFile);
await saveMp3(mixedOutput, mergedOutputFile);
console.log(`${mixedOutput} IN HEREEEEEEE`);
// We saved the recording, now copy the recording
if (!fs.existsSync(`./public`)) {
fs.mkdirSync(`./public`);
}
let sourceFile = `${__dirname}/recordings/${download_path}`
console.log(`DOWNLOAD PATH HERE ${download_path}`)
const guildName = message.guild.id;
const serveExist = `/public/${guildName}`
if (!fs.existsSync(`.${serveExist}`)) {
fs.mkdirSync(`.${serveExist}`)
}
let destionationFile = `${__dirname}${serveExist}/${file_name}`
let errorThrown = false
try {
fs.copySync(sourceFile, destionationFile);
} catch (err) {
errorThrown = true
await message.channel.send(`Error: ${err.message}`)
}
const usersWithTag = finalArrWithIds.map(user => `\n <#${user}>`);
let timeSpent = await getAudioDurationInSeconds(`public/${guildName}/${file_name}`)
let timesSpentRound = Math.floor(timeSpent)
let finalTimeSpent = timesSpentRound / 60
let finalTimeForReal = Math.floor(finalTimeSpent)
if(!errorThrown){
//--------------------- server recording save START
class GeneralRecords {
constructor(generalLink, date, voice, time) {
this.generalLink = generalLink;
this.date = date;
this.note = `no note`;
this.voice = voice;
this.time = time
}
}
let newGeneralRecordClassObject = new GeneralRecords(`${fqdn}/public/${guildName}/${file_name}`, date, usersWithTag, finalTimeForReal)
let checkingServerRecord = await ServerRecords.exists({userid: `server`})
if(checkingServerRecord === true){
existingServerRecord = await ServerRecords.findOne({userid: `server`})
existingServerRecord.content.push(newGeneralRecordClassObject)
await existingServerRecord.save()
}
if(checkingServerRecord === false){
let serverRecord = new ServerRecords()
serverRecord.userid = `server`
serverRecord.content.push(newGeneralRecordClassObject)
await serverRecord.save()
}
//--------------------- server recording save STOP
}
//--------------------- personal recording section START
for( member of finalArrWithIds) {
let personal_download_path = message.member.voice.channel.id + `/${member}/` + file_name;
let sourceFilePersonal = `${__dirname}/recordings/${personal_download_path}`
let destionationFilePersonal = `${__dirname}${serveExist}/${member}/${file_name}`
await fs.copySync(sourceFilePersonal, destionationFilePersonal);
const user = client.users.cache.get(member);
console.log(user, `user here`);
try {
ffmpeg.setFfmpegPath(ffmpegInstaller.path);
ffmpeg(`public/${guildName}/${member}/${file_name}`)
.audioFilters('silenceremove=stop_periods=-1:stop_duration=1:stop_threshold=-90dB')
.output(`public/${guildName}/${member}/personal-${file_name}`)
.on(`end`, function () {
console.log(`DONE`);
})
.on(`error`, function (error) {
console.log(`An error occured` + error.message)
})
.run();
}
catch (error) {
console.log(error)
}
// ----------------- SAVING PERSONAL RECORDING TO DATABASE START
class PersonalRecords {
constructor(generalLink, personalLink, date, time) {
this.generalLink = generalLink;
this.personalLink = personalLink;
this.date = date;
this.note = `no note`;
this.time = time;
}
}
let timeSpentPersonal = await getAudioDurationInSeconds(`public/${guildName}/${file_name}`)
let timesSpentRoundPersonal = Math.floor(timeSpentPersonal)
let finalTimeSpentPersonal = timesSpentRoundPersonal / 60
let finalTimeForRealPersonal = Math.floor(finalTimeSpentPersonal)
let newPersonalRecordClassObject = new PersonalRecords(`${fqdn}/public/${guildName}/${file_name}`, `${fqdn}/public/${guildName}/${member}/personal-${file_name}`, date, finalTimeForRealPersonal)
let checkingUserRecord = await UserRecords.exists({userid: member})
if(checkingUserRecord === true){
existingUserRecord = await UserRecords.findOne({userid: member})
existingUserRecord.content.push(newPersonalRecordClassObject)
await existingUserRecord.save()
}
if(checkingUserRecord === false){
let newRecord = new UserRecords()
newRecord.userid = member
newRecord.content.push(newPersonalRecordClassObject)
await newRecord.save()
}
// ----------------- SAVING PERSONAL RECORDING TO DATABASE END
const endPersonalEmbed = new Discord.MessageEmbed().setTitle(`Your performance was amazing ! Review it here :D`)
endPersonalEmbed.setColor('#9400D3')
endPersonalEmbed.setThumbnail(`https://media.discordapp.net/attachments/730811581046325348/745381641324724294/vinyl.png`)
endPersonalEmbed.addField(`📅 Date`, `${date}`)
endPersonalEmbed.addField(`⏰ Time spent by you`, `${finalTimeForRealPersonal} minute(s)`)
endPersonalEmbed.addField(`🔻 Download`, `${fqdn}/public/${guildName}/${member}/personal-${file_name}`)
endPersonalEmbed.setFooter(`Use \`$myrecordings\` to get a list of all your recordings !`)
user.send(endPersonalEmbed)
}
// ----------------- personal recording section OVER
const endEmbed = new Discord.MessageEmbed().setTitle(`I will be honest, that recording session was sick !`)
endEmbed.setColor('#9400D3')
endEmbed.addField(`🎙️ Voices`, usersWithTag)
endEmbed.addField(`⏰ Time spent`, `${finalTimeForReal} minute(s)`)
endEmbed.addField(`🔻 Download`, `${fqdn}/public/${guildName}/${file_name}`)
endEmbed.setThumbnail(`https://media.discordapp.net/attachments/730811581046325348/745370416352067704/microphone.png`)
endEmbed.setFooter(`Check your DMs for a recording of your personal voice during this session.`)
message.channel.send(endEmbed)
} else {
message.reply('You need to join a voice channel first!');
}
}
if (message.content.indexOf(prefix) !== 0) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
const cmd = client.commands.get(command);
if (!cmd) return;
cmd.run(client, message, args);
});
fs.readdir('./commands/', async (err, files) => {
if (err) return console.error;
files.forEach(file => {
if (!file.endsWith('.js')) return;
let props = require(`./commands/${file}`);
let cmdName = file.split('.')[0];
console.log(`Loaded command '${cmdName}'`);
// Register extra Listeners
client.commands.set(cmdName, props);
});
});
async function main() {
program.option('-debug')
program.option('-prod')
program.parse(process.argv)
console.log(program.opts())
if (program.Debug != undefined) {
debug = !debug
}
if (program.Prod != undefined) {
runProd = !runProd
}
if (runProd) {
client.login(process.env.DISCORD_TOKEN_PROD).catch(e => {
console.log("ERROR")
console.log(e)
})
} else {
client.login(process.env.DISCORD_TOKEN_TEST).catch(e => {
console.log("ERROR")
console.log(e)
})
}
}
main()
Now the bot works perfectly fine but the issue is that the audio sounds a bit deeper and slower than normal.. Why does it happen? how can I make the audio sound 1:1..
How do i fix the sample rate mismatch
Note; I have already tried to set Audio freq as 48000 but it has made no difference.