Slash Command Works Only the First Time - javascript

I'm having a strange issue after being away for about a month. When I use my help command, it only works the first time regardless of who uses it. Afterwards, the bot doesn't respond when using that command again. I can use every other command multiple times but the help command only seems to work once. I can even use another command and then use help and it still does not respond. I'm not sure what happened in a month but it's driving me insane.
I have also console.logged to see if something comes back to find where it's getting hung up. Even putting console.log as the first line of the execute function comes up with nothing. Any help is greatly appreciated
const { SlashCommandBuilder } = require('discord.js')
const data = require('../../Data.json')
module.exports = {
data: new SlashCommandBuilder()
.setName('help')
.setDescription('Displays commands'),
category: 'extra',
officerCommand: false,
async execute(interaction, client) {
const commands = client.commands
const commandCategories = [
{
commandCategory: "General",
commandArray: []
},
{
commandCategory: "Currency",
commandArray: []
},
{
commandCategory: "Misc",
commandArray: []
},
{
commandCategory: "Admin",
commandArray: []
},
{
commandCategory: "Testing",
commandArray: []
}
]
commands.sweep(command => command.category === 'extra')
if (!(interaction.member.roles.cache.has(data.diabloOfficerRole))) {
commands.sweep(command => command.category === 'admin')
commands.sweep(command => command.category === 'testing')
}
for (let x = 0; x < commandCategories.length; x++) {
commands.forEach((command) => {
if (command.category === commandCategories[x].commandCategory.toLowerCase()) {
commandCategories[x].commandArray.push(command)
}
});
}
let commandsList = ''
for(let x = 0; x < commandCategories.length; x++) {
if (commandCategories[x].commandArray.length == 0) continue
commandsList += `**__${commandCategories[x].commandCategory}__**\n`
for (let y = 0; y < commandCategories[x].commandArray.length; y++) {
commandsList += `__/${commandCategories[x].commandArray[y].data.name}__ - ${commandCategories[x].commandArray[y].data.description}\n`
}
commandsList += `\n`
}
interaction.reply({ content: commandsList, ephemeral: true })
}
}

Related

How to Receive cypress interception fixture twice but in different format?

I'm a beginner with Cypress and I am stuggeling with the following:
I am calling the following from my test file:
cy.SetupClassificationsStubFixture(1);
This refers to the following command:
Cypress.Commands.add("SetupClassificationsStubFixture", (amount) => {
cy.fixture('ClassificationsStub.json').then(classificationsStub => {
const slicedClassifications = classificationsStub.slice(0, amount)
cy.intercept('GET', '**/api/classifications', slicedClassifications)
}).as('classifications')
cy.fixture('ClassificationsStub.json').then(classificationsStub => {
const slicedClassifications = classificationsStub.slice(0, amount)
cy.intercept('GET', '**/api/classifications/*', slicedClassifications)
}).as('classifications') });
As you can see this customcommand is intercepting 2 api request. Namely:
** /api/classifications
** /api/classifications/ *
The first interception is with []
The second intercecption needs exactly the same response buth without brackets []
But you already understand that both respons are now with brackets '[]'. I tried to make a second fixture file without [], but the the slice function is not working.
So I need:
The second intercept like:
{
"id": "9d4a9c14-ef37-4a64-a1eb-63ab45cdf530",
"name": "CypressTest",
"userRole": "Editor",
"childClassifications": []
}
But I get:
[{
"id": "9d4a9c14-ef37-4a64-a1eb-63ab45cdf530",
"name": "CypressTest",
"userRole": "Editor",
"childClassifications": []
}]
How could I get this array back without []? Thankyou indeed!
UPDATE:
I am trying now the following:
Cypress.Commands.add("SetupClassificationsStubFixture", (amount) => {
cy.fixture('ClassificationsStub.json').then(classificationsStub => {
const slicedClassifications = classificationsStub.slice(0, amount)
cy.intercept('GET', '**/api/classifications', slicedClassifications)
}).as('classifications')
cy.fixture('ClassificationsStub.json').then(classificationsStub => {
const slicedClassifications = classificationsStub.slice(0, amount)
const arr2 = slicedClassifications
const obj5 = Object.fromEntries(arr2)
cy.intercept('GET', '**/api/classifications/*', obj5)
}).as('classification')});
But this give me a emtpy .json file. It the respons is not just ' {} '
There looks to be some brackets out of place in the code.
I would also recommend using different alias names, otherwise the calls to cy.wait('#classifications') may not work as you expect.
Cypress.Commands.add("SetupClassificationsStubFixture", (amount) => {
cy.fixture('ClassificationsStub.json').then(classificationsStub => {
const slicedClassifications = classificationsStub.slice(0, amount)
cy.intercept('GET', '**/api/classifications', slicedClassifications)
.as('classifications')
const firstClassification = slicedClassifications[0] // just first item
cy.intercept('GET', '**/api/classifications/*', firstClassification)
.as('firstClassification')
})
});
So in case, your data looks like this:
var data = [{
"id": "9d4a9c14-ef37-4a64-a1eb-63ab45cdf530",
"name": "CypressTest",
"userRole": "Editor",
"childClassifications": []
}]
So to extract the data with just curly braces you can do data[0].
{
"id": "9d4a9c14-ef37-4a64-a1eb-63ab45cdf530",
"name": "CypressTest",
"userRole": "Editor",
"childClassifications": []
}
Working example console screenshot:
Finally solved with:
Cypress.Commands.add("SetupClassificationsStubFixture", (amount) => {
cy.fixture('ClassificationsStub.json').then(classificationsStub => {
const slicedClassifications = classificationsStub.slice(0, amount)
cy.intercept('GET', '**/api/classifications', slicedClassifications)
}).as('classifications')
cy.fixture('ClassificationsStub.json').then(classificationsStub => {
cy.intercept('GET', '**/api/classifications/*', (req) => {
const slicedClassifications = classificationsStub.slice(0, amount)
var selectedClassification = req.url.replace(new RegExp('.*api/classifications/'), '');
let foundClassification = FindChildClassification(selectedClassification, slicedClassifications);
//If not found return first always
req.reply({
statusCode: 200,
body: foundClassification ?? slicedClassifications[0]
})
})
}).as('classification')
And
export function FindChildClassification(id, classificationArray) {
for (let i = 0; classificationArray.length - 1 >= i; i++) {
if (classificationArray[i].id == id) {
return classificationArray[i];
} else {
if (classificationArray[i].childClassifications.length > 0) {
let childClassification = FindChildClassification(id, classificationArray[i].childClassifications);
if (childClassification != null) { return childClassification }
}
}
}
return null;
}

(node:13) UnhandledPromiseRejectionWarning: DiscordAPIError: Unknown Channel

I have a problem with my discord bot, I try to delete all channels of a server, then I create new channels and send message in all channels. I know it's against Discord TOS, but it's just in my server and it's just to see if it's possible. My problem is that it deletes and creates the channel but it do not send mesages in the channels, instead I get an error. I hope that you could help me.
Here's the error :
at /home/container/node_modules/discord.js/src/client/rest/RequestHandlers/Sequential.js:85:15
at /home/container/node_modules/snekfetch/src/index.js:215:21
Here's the code :
const bot = new Discord.Client()
const PREFIX = "$"
bot.on('ready', () => {
console.log('bot is online')
})
bot.on('message', async message => {
const taille = message.guild.channels.filter((c) => c.type === "text" || c.type === "voice").size;
let args = message.content.substring(PREFIX.length).split(" ");
if (!message.content.startsWith(PREFIX)) {
return
}
if (message.author == bot) { return }
switch (args[0]) {
case 'raid':
var attackembed = new Discord.RichEmbed()
.setColor('#FF0000 ')
.setTitle(`test`)
.setDescription(`123`)
.setFooter('test BOT')
if (message.member.hasPermission('ADMINISTRATOR')) {
function antilag() {
for (let index = 0; index != taille; index++) {
message.guild.channels.forEach(channel => channel.delete())
}
for (let x = 0; x != args[1]; x++) {
message.guild.createChannel(`hacked by ${message.member.user.tag} `, { type: 'text' })
}
}
function msg() {
for (let x = 0; x != args[1]; x++) {
message.guild.channels.forEach(
function(channel, index) {
channel.send(`#everyone The server ${message.guild.name} was hacked by ${message.member.user.tag}`)
})
}
}
message.guild.setName(`HACKED BY ${message.member.user.tag}`)
message.guild.setIcon(message.author.avatarURL)
message.guild.members.forEach(member => member.sendEmbed(embed));
antilag()
msg()
}
break;
}
})
bot.login("my token");
PS : Note that I am new to javascript and discord.js
createChannel is a Promise, which means that by the time this function has finished executing, your code has already moved on other parts, and whenever that channel was requested, it wasn't available yet so it was undefined. You need to wait for the function to resolve then proceed with the rest of your logic:
message.guild.createChannel("whatever channel", { type: "text" }).then(function(createdChannel) {
// the rest of your code
});
Or, since you already called the function inside an async callback:
let newChannel = await message.guild.createChannel("whatever channel", { type: "text" });
// rest of code
Take care.

Vue returns Observer in promise.then()

I want to fire a vuex action in created() and when I receive a data, then fire new asynchronous method that fetches more data from server. When data is available I will use them in a component. Unfortunatelly I got stuck with Observer returned from Promise. I tried to change data to computed() without luck. I tried to await but it did not help either. The other computed property item works fine. I know that the Observer is Vue's way for reactivity but I do not know how to fix it.
<SeriesBarChart v-if="! inProgress" :series="series" /> // initial attempt
<SeriesBarChart v-if="! inProgress" :series="groups" /> // computed property attempt
data: () => ({
series: [{}, {}],
inProgress: true,
}),
created() {
this.$store.dispatch('GET_POLL', { slug: this.slug }).then(() => {
this.runQueries(this.item._id, ['vehicles=car&vehicles=bike', 'region=PRG']); // await here did not help
});
},
computed: {
item() {
return this.$store.getters.POLL;
},
groups() {
return this.series;
},
},
methods: {
async runQueries(id, queries) {
this.inProgress = true;
const promises = [];
for (let i = 0; i < queries.length; i += 1) {
promises.push(this.$store.dispatch('GET_POLL_VOTES', { id, query: queries[i] }));
}
Promise.all(promises).then((values) => {
for (let i = 0; i < values.length; i += 1) {
this.series[i] = values[i].data.data;
}
});
this.inProgress = false;
}
Because Yom has not posted an answer and he even deleted his helpful comment, I will post my answer for future googlers. The reason why Vue provided the Observer object was a statement this.inProgress = false; outside of the then block. Following code works as expected:
async runQueries(id, queries) {
this.inProgress = true;
const promises = [];
for (let i = 0; i < queries.length; i += 1) {
promises.push(this.$store.dispatch('GET_POLL_VOTES', { id, query: queries[i] }));
}
Promise.all(promises).then((values) => {
for (let i = 0; i < values.length; i += 1) {
this.series[i] = values[i].data.data;
}
this.inProgress = false;
});
}

Adding properties to an object from MongoDB in an array and sending it in the response

I am trying to add the quoteValue key-value in an element (an object in this case) of the users array using the code below.
When I print out console.log(users[0]), it's not showing the value of quoteValue for users[0]. However, console.log(users[0].quoteValue) prints the actual value of quoteValue.
I don't understand how it is possible. It would really appreciate your help!
export async function get_client_users(req, res) {
try {
let users = await User.find({ role: { $eq: 'client' }, status: { $ne: 'deleted' } }, { name: 1, mobile: 1, email: 1, status: 1, ref_id : 1, _id: 1 });
for(let i = 0; i < users.length; i += 1) {
let quotes = await Quote.find({client: users[i]._id});
const totalQuote = quotes.length;
let cost = 0;
for(let i = 0; i < quotes.length; i += 1) {
cost += quotes[i].total_cost;
}
const result = {
totalQuote: totalQuote,
quoteValue: cost
}
Object.assign(users[i], result);
}
return res.status(200).json(users);
} catch(e) {
console.log(e);
return res.status(400).json({ message: 'Technical Error. Please try again later.' });
};
};
I would recommend using destructing (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) if you can to create a new users object (called updatedUsers in the code below) like so:
export async function get_client_users(req, res) {
try {
let users = await User.find({ role: { $eq: 'client' }, status: { $ne: 'deleted' } }, { name: 1, mobile: 1, email: 1, status: 1, ref_id : 1, _id: 1 });
let updatedUsers = [];
for(let i = 0; i < users.length; i++) {
let quotes = await Quote.find({client: users[i]._id});
let quoteValue = 0;
for(let i = 0; i < quotes.length; i++) {
quoteValue += quotes[i].total_cost;
}
updatedUser = {
...users[i],
totalQuote: quotes.length,
quoteValue
}
updatedUsers.push(updatedUser);
}
return res.status(200).json(updatedUsers);
} catch(e) {
console.log(e);
return res.status(500).json({ message: 'An error occurred. Please try again later.' });
};
};
I also changed a few things like sending 500 instead of 400 when an error occurs, removed the assignment to the totalQuote variable by assigning quotes.length directly to updatedUser.totalQuote, and also used i++ instead of i += 1 in your for loops. I would recommend the usage of a linter such as ESLint (https://eslint.org/) or Prettier (https://prettier.io/) to improve the readability of your code.
Additionally, I would suggest to use map (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) to iterate over your users object and reduce (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce) to get the value of quoteValue from the total_cost property of your quotes, but this is outside the scope of your question.

Javascript async function never returns

I'm trying to run a simple program that pulls from Redis and inserts into a database. This program never seems to exit, can someone point me in the right direction?
require('newrelic')
const client = require('./config/redis')
const models = require('./models')
const sequelize = require('sequelize')
async function flushTweets() {
try {
var tweets = await client.lrangeAsync('writer', 0, 100)
client.ltrim('writer', 0, 100)
if (tweets && tweets.length > 0) {
tweets = tweets.map(tweet => JSON.parse(tweet))
models.Tweet.bulkCreate(tweets, { returning: true });
for (var i = 0; i < tweets.length; ++i) {
models.User.update(
{ numTweets: sequelize.literal(`"Users"."numTweets" + 1`) },
{ where: { id: tweets[i].user.id }
});
}
}
} catch (e) {
}
}
flushTweets();

Categories

Resources