Discord JS V.14 Custom Status Emoji - javascript

//VANITY - ServerID - ROLE ID - CUSTOMSTATUS(STRING)
client.on(Events.PresenceUpdate, async function (oldPresence, newPresence) {
//Obter o Server ID
const guild = newPresence.guild;
const serverID = guild.id;
if (newPresence.activities.length > 0) {
if (oldPresence.activities.length > 0) {
Vanity(oldPresence, serverID);
}
const customStatus = newPresence.activities[0].state
if (customStatus !== "null") {
const QueryVanityServerCount = await VanityRoles.count({ where: { ServerID: serverID, CustomStatus: customStatus } });
if (QueryVanityServerCount > 0) {
//Query
const Query = await VanityRoles.findAll({ where: { ServerID: serverID, CustomStatus: customStatus } });
//Adicionar a Role
for (let i = 0; i < Query.length; i++) {
const role = newPresence.member.guild.roles.cache.find(role => role.id === Query[i].RoleID);
await newPresence.member.roles.add(role);
}
}
}
}
else {
Vanity(oldPresence, serverID);
}
});
async function Vanity(oldPresence, serverID) {
const customStatus = oldPresence.activities[0].state
if (customStatus !== "null") {
const QueryVanityServerCount = await VanityRoles.count({ where: { ServerID: serverID, CustomStatus: customStatus } });
if (QueryVanityServerCount > 0) {
//Query
const Query = await VanityRoles.findAll({ where: { ServerID: serverID, CustomStatus: customStatus } });
//Adicionar a Role
for (let i = 0; i < Query.length; i++) {
const role = oldPresence.member.guild.roles.cache.find(role => role.id === Query[i].RoleID);
await oldPresence.member.roles.remove(role);
}
}
}
}
I've this code to add roles based on the user custom status. The code is working however, when I select an emoji for my custom status with no text at all, my bot doesn't do anything. How can I make the bot to recognize the emoji?
Can someone help me? Thanks.

Related

how to put data in mongodb

I'm calling for your help today because I can't put the data in mongo db, indeed, I managed to connect, but impossible to add the data.
I'm going to explain you a little bit my code, in a first time, I'm going to search the pages according to a start number and an end number, the first function is going to search if the page exists or not, in my 2nd function search, then I'm going to search the category I'm interested in, then I'm going to get the information of this page, that is to say what you can see in the "const contact", then I'm going to add all this in a db file.
So what I want is instead of putting it in the db file it automatically adds me to mongodb.
// import
const Datastore = require('nedb')
// const fs = require('fs')
const puppeteer = require('puppeteer');
const fs = require('fs');
const { resolve } = require('path');
// global variables
var totalFound = 0
var headless = true
const DB_PATH = './huarenjietest2.db' //addition in the db file
const START_LINK = 'https://www.huarenjiewang.com/info-[pageIndex].html'
const LOCATION_SeleCTOR = 'body > div.body1000 > div.location'
const COOKIE_SELECTOR = 'body > div.fc-consent-root > div.fc-dialog-container > div.fc-dialog.fc-choice-dialog > div.fc-dialog-content > div > div.fc-header.fc-dialog-restricted-content > h1'
const NotFoundSelector = 'body > div > div.tip-bgC > div'
const phoneSelector = '#show-phone'
const workTypeSelector = 'body > div.body1000 > div.wrapper > div.information_bd > div.bd_left > div.extra_contact > div > ul > li:nth-child(4)'
const zoneSelector = 'body > div.body1000 > div.wrapper > div.information_bd > div.bd_left > div.extra_contact > div > ul > li:nth-child(1)'
const whoSelector = 'body > div.body1000 > div.wrapper > div.information_bd > div.bd_left > div.extra_contact > div > ul > li:nth-child(6) > span.faburen > a:nth-child(1)'
const infoSelector = 'body > div.body1000 > div.wrapper > div.information_bd > div.bd_left > div.view_bd > p'
const dateSeloctor = 'body > div.body1000 > div.wrapper > div.information_bd > div.bd_left > div.information_hd > div.my_yp_view_title2 > div.my_yp_view_title2_l'
const COOKIE_BUTTON = 'body > div.fc-consent-root > div.fc-dialog-container > div.fc-dialog.fc-choice-dialog > div.fc-footer-buttons-container > div.fc-footer-buttons > button.fc-button.fc-cta-consent.fc-primary-button'
//mongodb
var express = require("express")
const database = require('./config/database')
var router = express.Router();
const Huarenjiemongo = require("./model/huarenjiemodel")
database.connection()
// command line options
const optionDefinitions = [
{ name: 'headless', type: Boolean },
{ name: 'start', type: Number },
{ name: 'end', type: Number },
{ name: 'export', type: String },
]
const commandLineArgs = require('command-line-args');
const { exit } = require('process');
const { mongo } = require('mongoose');
const options = commandLineArgs(optionDefinitions)
const startIndex = options.start
const endIndex = options.end
const outputPath = options.export
if(!startIndex || !endIndex){
console.log('use command like : node huarenjie.js --start 12321323 --end 13321323 --export output.csv')
exit()
}
const dbPath = DB_PATH
const db = new Datastore({ filename: dbPath, autoload: true })
db.ensureIndex({ fieldName: 'infoIndex', unique: true }, function (err) {
if (err) {
console.log('ensureIndex error :', err)
}
})
function dateyyyyMMdd(d, separate = '') {
let date = d
var mm = date.getMonth() + 1 // getMonth() is zero-based
var dd = date.getDate()
return [date.getFullYear(), (mm > 9 ? '' : '0') + mm, (dd > 9 ? '' : '0') + dd].join(separate)
}
database.connection();
function delay(time) {
return new Promise(function(resolve) {
setTimeout(resolve, time)
});
}
async function checkPageExite(page){
return new Promise((resolve, reject) => {
page.waitForSelector(LOCATION_SeleCTOR).then(() => {
resolve(true)
}).catch(()=> { resolve(false)})
page.waitForSelector(NotFoundSelector).then(() => {
console.info('page not exist')
resolve(false)
}).catch(()=> { resolve(false)})
page.waitForSelector(COOKIE_BUTTON).then(() => {
return Promise.resolve()
}).then(() => {
return page.$eval( COOKIE_BUTTON, form => form.click() )
}).then(() => {
if(page.url() === 'https://www.huarenjiewang.com/changecity.php'){
resolve(false)
} else {
resolve(true)
}
}).catch(()=> { resolve(false)})
})
}
async function search() {
const browser = await puppeteer.launch({ headless: headless })
console.log('====> Puppeteer started')
const page = await browser.newPage();
await page.setViewport({ width: 1280, height: 800 })
for(var i=startIndex;i<=endIndex;i++){
try {
console.info(`====== index : ${i} ========`)
await page.goto(START_LINK.replace('[pageIndex]',i))
// await page.waitForSelector(LOCATION_SeleCTOR)
const exist = await checkPageExite(page)
if(exist === 'skip'){
continue
}
if(exist === true){
let element = await page.$(LOCATION_SeleCTOR)
let categoryValue = await page.evaluate(el => el.textContent, element)
if(categoryValue.includes('appartement/louer')){
let phone = await page.$(phoneSelector)
let phoneValue = await page.evaluate(el => el.getAttribute("data-phone"), phone)
if(phoneValue){
let workElement = await page.$(workTypeSelector)
let workValue = await page.evaluate(el => el.textContent, workElement)
let zoneElement = await page.$(zoneSelector)
let zoneValue = await page.evaluate(el => el.textContent, zoneElement)
let whoElement = await page.$(whoSelector)
let whoValue = await page.evaluate(el => el.textContent, whoElement)
let infoElement = await page.$(infoSelector)
let infoValue = await page.evaluate(el => el.textContent, infoElement)
let dateElement = await page.$(dateSeloctor)
var dateValue = await page.evaluate(el => el.textContent, dateElement)
var date
var dateStr
var reg1 = /(\d{4}-\d{2}-\d{2})/
const found1 = dateValue.match(reg1)
if(found1 && found1.length > 1){
dateStr = found1[1]
}
if(dateValue.includes('昨天')){
var date = new Date()
date.setDate(date.getDate() -1)
dateStr = dateyyyyMMdd(date,'-')
}
if(dateValue.includes('前天')){
var date = new Date()
date.setDate(date.getDate() -2)
dateStr = dateyyyyMMdd(date,'-')
}
const contact = {
phone : phoneValue,
zone: zoneValue,
workType: workValue,
who: whoValue,
info: infoValue,
date: dateStr || '',
infoIndex: i
}
db.update({ infoIndex: i }, { $set: contact }, { upsert: true }, function () {});
console.info(`${i}#############>saved`)
} else {
console.info(`${i}=>skip==>phone number missing`)
}
} else {
console.info(`${i}=>skip==>category not correct`)
}
if(categoryValue.includes('maison/louer')){
let phone = await page.$(phoneSelector)
let phoneValue = await page.evaluate(el => el.getAttribute("data-phone"), phone)
if(phoneValue){
let workElement = await page.$(workTypeSelector)
let workValue = await page.evaluate(el => el.textContent, workElement)
let zoneElement = await page.$(zoneSelector)
let zoneValue = await page.evaluate(el => el.textContent, zoneElement)
let whoElement = await page.$(whoSelector)
let whoValue = await page.evaluate(el => el.textContent, whoElement)
let infoElement = await page.$(infoSelector)
let infoValue = await page.evaluate(el => el.textContent, infoElement)
let dateElement = await page.$(dateSeloctor)
var dateValue = await page.evaluate(el => el.textContent, dateElement)
var date
var dateStr
var reg1 = /(\d{4}-\d{2}-\d{2})/
const found1 = dateValue.match(reg1)
if(found1 && found1.length > 1){
dateStr = found1[1]
}
if(dateValue.includes('昨天')){
var date = new Date()
date.setDate(date.getDate() -1)
dateStr = dateyyyyMMdd(date,'-')
}
if(dateValue.includes('前天')){
var date = new Date()
date.setDate(date.getDate() -2)
dateStr = dateyyyyMMdd(date,'-')
}
const contact = {
phone : phoneValue,
zone: zoneValue,
workType: workValue,
who: whoValue,
info: infoValue,
date: dateStr || '',
infoIndex: i
}
db.update({ infoIndex: i }, { $set: contact }, { upsert: true }, function () {})
console.info(`${i}#############>saved-tech`)
} else {
console.info(`${i}=>skip==>phone number missing`)
}
} else {
console.info(`${i}=>skip==>category not correct`)
}
}
// await delay(5000)
} catch (error) {
console.info(`${i}=>error read page:`, error)
}
}
}
const connectToMongoDB = async() => {
await database().then(async (mongoose) => {
try {
console.log('Connecto to mongodb')
db.collection({ infoIndex: i }, { $set: contact }, { upsert: true }, function () {})
await new huarenjieShema(contact).save()
} finally {
mongoose.connection.close()
}
})
}
connectToMongoDB()
async function main() {
if(outputPath){
db.find({ "infoIndex": { $gte: startIndex , $lte: endIndex} }, function (err, docs) {
if(err){
console.error(err)
} else {
var body = `infoIndex;who;phone;zone;workType;comment\n`
for(var doc of docs){
body += `${doc.infoIndex};${(doc.who || '').trim()};${doc.phone};${(doc.zone || '').trim()};${(doc.workType || '').trim()};${(doc.info || '').trim()}\n`
}
fs.writeFileSync(options.export, body)
}
exit()
});
} else {
await search()
}
console.info('>>>>> Finished')
console.info('>>>>> totalFound:', totalFound)
}
main()
here is the model
const mongoose = require('mongoose')
const huarenjieShenma = mongoose.Schema({
infoIndex: {
type: Number,
unique: true,
},
who: {
type: String,
},
phone: {
type: Number,
},
zone: {
type: String,
},
workType: {
type: String,
},
comment: {
type: String,
},
})
module.exports = mongoose.model('Huarenjie', huarenjieShenma)
I will not check your whole code. Just a small hint how to insert data to your collection using your schema.
const huarenjieShenma = mongoose.Schema({
infoIndex: {
type: Number,
unique: true,
},
who: {
type: String,
},
phone: {
type: Number,
},
zone: {
type: String,
},
workType: {
type: String,
},
comment: {
type: String,
},
})
const Huarenjie = mongoose.model('Huarenjie', huarenjieShenma);
const testObject = {
infoIndex: 1,
who: "Me",
phone: 555666777, //im my opinion phone is not a number
zone: "Area 51",
workType: "WorkType",
comment: "Just a comment"
};
(async () => {
const newObject = await Huarenjie.create(testObject);
console.log(newObject);
})();

JoinCommand discord.js issue, Cannot read property 'voice' of undefined

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...

API getting multiple Calls

My program in a nutshell. If the trigger word is detected in the message, my application creates invoices.
The issue: Multiple calls to the trigger function. All of the requests to the API are simultaneous. This causes my data to have problems.
I have added the async and await to wait for the trigger function to complete. But it seems my calls are still being called all together.
// Links to a Facebook Live.
export const fblive = async (liveid) => {
if (liveid != null) {
try {
const reg = new RegExp("\\d{5,}");
const found = liveid.match(reg);
if (found > 0) {
console.log(found, " || ", found[0]);
let activate = false;
var userid = "";
//var accesstoken = ''
var accesstoken =''
var videoID = found;
var live_url =
"https://streaming-graph.facebook.com/" +
videoID +
"/live_comments?access_token=" +
accesstoken +
"&comment_rate=one_hundred_per_second&fields=from{name,id},message";
var source = new EventSource(live_url);
source.onmessage = function (event) {
var result = JSON.parse(event["data"]);
let trigger_word = result["message"].search("#");
// looking at comments
readcomment(result["message"]);
if (result["from"] != null) {
console.log("FROM ! !:", result["from"]);
}
};
} else {
console.log("ZERO FOUND");
}
} catch (error) {
console.log("FB LIVE COMMENT IS NOT RUNNING");
}
} else {
console.log("Live ID not valid");
}
};
// Looking at every comment in a facebook live
export const readcomment = async (the_comment) => {
try {
console.log(" CALLING LIVE READ COMMENT ", the_comment);
let re = await new Promise((resolve) =>
setTimeout(
setTimeout(async function () {
console.log(the_comment);
if (the_comment.includes("#")) {
populatelist();
console.log(the_comment);
let new_string = the_comment.trim().split(" ");
console.log(new_string, " STRING SPLIT");
let customer_found = await findcust(new_string);
let item_found = await finditem(new_string);
console.log(customer_found, item_found, "WE FOUND ");
if (customer_found != false && item_found != false) {
console.log("THERE'S A TRIGGER SALE HERE");
let remove = await find_remov(new_string);
console.log(remove, "WE ARE LOOKING AT RMOVE ");
await comment_trigger(customer_found,item_found,remove)
console.log(the_comment)
console.log("promise for " , the_comment, " has been fullfilled")
}
}
}, 2000)
)
);
} catch (error) {
console.log(error.response)
}
};
// This is when a comment was found to be the triggers words (customer id and a item name)
export const comment_trigger = async (customer, item, rmv) => {
// FIND THE ITEM IN INVOICE.
const client = find(customer, customer_list1);
const real_item = find(item, item_list1);
try {
console.log(client, real_item);
if (client != false && real_item != false) {
let inv = await invoicesbycustomer(client.id);
console.log(inv);
if (inv == undefined || inv.length ==0) {
console.log(customer, item);
console.log(real_item.id);
let new_Invoice = new Invoice("", client);
let new_item = new Product(real_item.id, real_item.name, 1);
await new_Invoice.addItem(new_item);
console.log(new_Invoice);
await createInvoice(new_Invoice);
console.log("NO INVOICE WAS FOUND FOR THIS CLIENT");
} else {
console.log(inv);
// making sure there's a real invoice.
console.log("DATA TYPE IS ", typeof inv);
if (typeof inv !== "undefined") {
console.log(inv, "THIS IS INVOICE WITH CLIENT");
console.log(inv[0].node.items.length);
let oldItems = inv[0].node.items;
let NewInvoice = new Invoice(
inv[0].node.id,
inv[0].node.customer.id
);
let Itemsize = oldItems.length;
let found = false;
if (Itemsize > 0) {
//IF ITEMS EXIST ADD QTY.
// ELSE ADD THIS NEW ITEM.
for (let x in oldItems) {
if (real_item.id == oldItems[x].product.id) {
found = true;
}
}
if (found && rmv == "removeqty") {
await removeqtyitem(customer, item);
} else if (found && rmv == "removeAll") {
await removeitem(customer, item);
} else if (found) {
let aqi = await addqtyitem(customer, item);
} else {
// add item
await additems(customer, item);
}
} else {
await additems(customer, item);
}
}
}
} else {
let errmssg = "";
if (!client) {
errmssg = errmssg.concat(" ", " Client is not valid ");
console.log("client not found", errmssg);
}
if (!real_item) {
errmssg = errmssg.concat("", " Item not found");
}
console.log(errmssg);
console.error(errmssg);
}
} catch (error) {
console.error(error.response.data)
}
};
Here's an example of the api being called. this is using graphql
//DELETING INVOICE API CALL
export const deleteInvoice = async(id) => {
const invoiceId = id;
console.log(invoiceId, "THIS I S INVOICE DELET EDELETE DELETE DELTE ")
try {
const token = "zCtQa00zlorbFFum6I7Rlzc0QwMDoS";
const shema = `
mutation ($input: InvoiceDeleteInput !) {
invoiceDelete(input: $input) {
didSucceed
inputErrors {
path
code
message
}
}
}`;
//About to submit my shema to waveapps
const API_URL="https://gql.waveapps.com/graphql/public"
const bussID = "QnVzaW5lc3M6ZTIyZmVhODEtNjg5OC00N2ZiLTgzOGItYWMyYzllNDZiM2Jk";
let watch = await axios(API_URL, {
method: "POST",
headers: {
Authorization: token ? `Bearer ${token}` : "",
"Content-Type": "application/json",
},
data:{
query: shema,
variables: {
input:{
invoiceId: invoiceId,
}
},
},
})
console.log(watch.data)
} catch (error) {
console.log(error.response)
}
//console.log("return delete invoice complete")
};
I have used async/await and promises.
When multiple calls are made. The await and promises are still being called at the same time. Not sure what else to look at? any suggestions please. I have spent a week on this.

Return empty array in Fastify handler with async/await function

I'm trying to make a web3 wallet with Moralis with Fasitify in back and VueJS in front.
(I would like to say that I already do this in web client (vuejs) and everything works well!)
In my back, I fetch all the asset from user. It works, I get them all well and I can send them back to the front
But I need to process/sort the data to recover only part of it and send it to the front to avoid doing too much treatment at the front and reduce your workload.
I do that :
*handlers/token.js*
const getTokenBalances = async () => {
let userTokens;
const options = {
chain: "bsc",
address: "0x935A438C29bd810c9aBa2F3Df5144d2dF4F3c0A0",
};
userTokens = await Moralis.Web3API.account.getTokenBalances(options);
return userTokens;
};
and if I return userTokens, I had it in Postman. But now, I do something like :
const getTokenBalances = async (tokens) => {
let userTokens;
let userBalances = [];
const options = {
chain: "bsc",
address: "0x935A438C29bd810c9aBa2F3Df5144d2dF4F3c0A0",
};
userTokens = await Moralis.Web3API.account.getTokenBalances(options);
userTokens.forEach((token) => {
if (
!token.name.match(/^.*\.io/) &&
!token.name.match(/^.*\.IO/) &&
!token.name.match(/^.*\.net/) &&
!token.name.match(/^.*\.Net/) &&
!token.name.match(/^.*\.com/) &&
!token.name.match(/^.*\.org/)
) {
getTokenPair(token).then((value) => {
if (value > 2) {
checkTokenPrice(token).then((price) => {
if (price > 0.001) {
userBalances.push(token);
}
});
}
});
}
});
userBalances.sort((a, b) => {
return b.total_value_usd - a.total_value_usd;
});
return userBalances;
};
userBalances its always empty in my response in Postman (And I don't understand why ?)
The getTokenPair function :
const getTokenPair = async (token) => {
const BNBTokenAddress = "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"; //BNB
const options = {
token0_address: token.token_address,
token1_address: BNBTokenAddress,
exchange: "pancakeswapv2",
chain: "bsc",
};
try {
const pairAddress = await Moralis.Web3API.defi.getPairAddress(options);
let amount = 0;
//console.log("token pairAddress : " + pairAddress.pairAddress);
if (pairAddress.token1.symbol === "BUSD") {
try {
let reserve = await getPairReserves(pairAddress.pairAddress);
amount += reserve / 10 ** 18;
} catch (err) {
console.log("error getReservesBUSD : " + err);
}
}
if (pairAddress.token1.symbol === "WBNB") {
try {
let reserve = await getPairReserves(pairAddress.pairAddress);
amount += reserve / 10 ** 18;
} catch (err) {
console.log("error getReservesWBNB : " + err);
}
}
//console.log("amount : " + amount)
return amount;
} catch (err) {
console.log("error getPair : " + err);
}
};
and the checkTokenPrice function :
const checkTokenPrice = async (token) => {
let price;
const options = {
address: token.token_address,
chain: "bsc",
exchange: "PancakeSwapv2",
};
try {
const priceToken = await Moralis.Web3API.token.getTokenPrice(options);
price = priceToken.usdPrice.toFixed(7);
token.price = priceToken.usdPrice.toFixed(7);
token.balance = insertDecimal(token.balance, token.decimals);
token.total_value_usd = (token.balance * token.price).toFixed(2);
return price;
} catch (err) {
console.log("error tokenPrice : " + err);
}
};
They are await method in all the function I use so maybe there is a connection.
Thanks for you help !
**** EDIT *****
I solve my problem like this :
const getTokenBalances = async () => {
let userTokens;
let userBalances = [];
const options = {
chain: "bsc",
address: "0x935A438C29bd810c9aBa2F3Df5144d2dF4F3c0A0",
};
userTokens = await Moralis.Web3API.account.getTokenBalances(options);
for (token of userTokens) {
if (
!token.name.match(/^.*\.io/) &&
!token.name.match(/^.*\.IO/) &&
!token.name.match(/^.*\.net/) &&
!token.name.match(/^.*\.Net/) &&
!token.name.match(/^.*\.com/) &&
!token.name.match(/^.*\.org/)
) {
let value = await getTokenPair(token);
if(value > 2) {
let price = await checkTokenPrice(token);
if (price > 0.001) {
userBalances.push(token);
}
}
}
}
return userBalances;
};
Thanks for the help ! ;)

How to delete a voice channel when everybody disconnects?

I created a join to create system that creates a channel when a user join and delete it when they leave. However, it only deletes if the last person that's leaving is the user who created the room. Any ideas?
const { Collection } = require("discord.js");
const voiceCollection = new Collection();
module.exports = async (Discord, client, oldState, newState) => {
const user = await client.users.fetch(newState.id);
const member = newState.guild.member(user);
// JOIN
if (!voiceName || voiceName === "") {
if (!oldState.channel && newState.channelID === "898245212541976667") {
const channel = await newState.guild.channels.create(user.tag, {
type: "voice",
parent: newState.channel.parent,
});
member.voice.setChannel(channel);
voiceCollection.set(user.id, channel.id);
await channel.overwritePermissions([
{
id: user.id,
allow: ["MANAGE_CHANNELS", "CONNECT"],
},
{
id: member.guild.id,
deny: ["CONNECT"],
},
]);
} else if (!newState.channel) {
if (oldState.channelID === voiceCollection.get(newState.id)) {
if (oldState.channel.members.size < 1) {
return oldState.channel.delete();
}
}
}
var newchannel_id = config.Channel_id;
var category_id = config.category;
var userchannellist = []
client.login(token);
client.on('voiceStateUpdate', async (oldMember, newMember) => {
if (newMember.channel !== null && oldMember.channel === null && newMember.channel.id === newchannel_id || newMember.channel !== null && oldMember.channel !== null && newMember.channel.id === newchannel_id) {
var current_user = newMember.member.user;
console.log(current_user.username + 'creating the channel');
// Start the creation of the new channel
var server = newMember.guild;
let USERA = newMember.member.nickname || newMember.member.user.username;
var channel = {
type: 'voice', bitrate: 384000, parent: category_id, permissionOverwrites: [{
// permissions
id: server.id, allow: ['VIEW_CHANNEL'],
},
{
id: current_user.id, allow: ['MOVE_MEMBERS', 'MANAGE_CHANNELS']
}
]
};
server.channels.create('🔊' + USERA, channel).then(channel => {
newMember.setChannel(channel).catch(console.error)
userchannellist.push(channel)
//channel region
client.api.channels(channel.id).patch({ data: { rtc_region: "rotterdam" } })
}).catch(console.error);
}
// delete Chaneel
if (oldMember.channel) {
let filter = (ch) =>
(ch.parentID == category_id)
&& (ch.id !== newchannel_id)
&& (oldMember.channel == ch.id)
&& (oldMember.channel.members.size == 0);
return oldMember.guild.channels.cache
.filter(filter)
.forEach((ch) => ch.delete()
.catch(console.error));
}
});

Categories

Resources