I'm trying to make a discord slash commands filter using distube but when I use the slash command it didn't apply the filter that I picked but it sent the embed when filter is applied
Node: v17.7.2
Discord: ^13.2.0
can someone help me or tell me why the filter is not applying to the current music in vc?
thank you
const { MessageEmbed } = require('discord.js');
const ee = require('../../config.json');
module.exports = {
name: 'filter',
description: 'Add filter.',
usage: 'filter',
options: [
{
name: 'preset',
description: 'Filters to add.',
type: 'STRING',
required: true,
choices: [
{
name: 'BassBoost',
value: 'bassboost'
},
{
name: 'Nightcore',
value: 'nightcore'
},
{
name: 'Vaporwave',
value: 'vaporwave'
}
]
}
],
run: async(client, interaction, args) => {
const filterss = interaction.options.getString('preset');
const queue = client.distube.getQueue(interaction);
let player = client.distube.filters;
if(!queue) {
return interaction.followUp({embeds: [
new MessageEmbed()
.setColor(ee.color)
.setAuthor({name: 'Error', iconURL: 'https://i.imgur.com/81ig9jl.jpg'})
.setDescription('No songs are playing!')
]})
}
let thing = new MessageEmbed().setColor(ee.color);
if (filterss == "nightcore") {
thing.setDescription("✅ | Nightcore filter is now active!");
player.nightcore = true;
} else if (filterss == "bassboost") {
thing.setDescription("✅ | BassBoost filter is now on!");
player.bassboost = true;
} else if (filterss == "vaporwave") {
thing.setDescription("✅ | Vaporwave filter is now on!");
player.vaporwave = true;
}
return interaction.followUp({ embeds: [thing] });
}
}
From what I can find in the docs, it is recommended to use .setFilter() instead of calling client.distube.filters.<filter> = true.
I'd try changing your run code to use this instead and see if that works:
run: async(client, interaction, args) => {
// Your queue check code here
let thing = new MessageEmbed().setColor(ee.color);
if (filterss == 'nightcore') {
thing.setDescription('✅ | Nightcore filter is now active!');
client.distube.setFilter(interaction, filterss);
} else if (filterss == 'bassboost') {
thing.setDescription('✅ | BassBoost filter is now on!');
client.distube.setFilter(interaction, filterss);
} else if (filterss == 'vaporwave') {
thing.setDescription('✅ | Vaporwave filter is now on!');
client.distube.setFilter(interaction, filterss);
}
return interaction.followUp({
embeds: [thing],
});
}
Related
I'm trying to create a simple add slash command with discord.js, but it seems that interaction.options.getNumber just doesn't exists (look at https://github.com/discordjs/discord.js/blob/main/packages/discord.js/src/structures/CommandInteractionOptionResolver.js#L181)
This is a piece of my code:
...
commands?.create({
name: 'add',
description: 'add two numbers',
options: [
{
name: 'num1',
description: 'The first num',
required: true,
type: DiscordJS.ApplicationCommandOptionType.Number
},
{
name: 'num2',
description: 'The second num',
required: true,
type: DiscordJS.ApplicationCommandOptionType.Number
} ]
})
})
...
client.on('interactionCreate', async (interaction) => {
if (!interaction.isCommand()) {
return
}
const { commandName, options } = interaction
if (commandName === 'add') {
console.log(options)
const num1 = options.getNumber('num1')!
const num2 = options.get('num2')!
// idk why but "get" method exists. So I was trying to use it,
// but js says that you couldn't add a string | number | boolean value to an another one
console.log(num1.value + num2.value)
console.log(typeof(num2.value)) // this print "number" btw
interaction.reply({
content: `The sum is ${num1.value}`
})
}
}
There is a solution, but it's intricated:
...
} else if (commandName === 'add') {
console.log(options)
const raw_num1 = options.get('num1')!
const raw_num2 = options.get('num2')!
const num1 = raw_num1.value!
const num2 = raw_num2.value!
interaction.reply({
content: `The sum is ${+(num1) + +(num2)}`
})
}
})
I am making a CLI using inquirer in nodejs.
So in Every choice list I have to give Exit choice so if user want to exit he/she can easily Exit.
So I have to write Exit again and again to avoid that problem I made a Exit.js file and move Exit code there so I can use code again and again.
Exit.js
const executeQuery = require("../executeQuery");
function WantToExit() {
inquirer
.prompt([
{
name: "moreQuery",
type: "confirm",
message: "Want to do anything else?",
},
])
.then((answer) => {
if (answer.moreQuery) return executeQuery();
});
}
module.exports = WantToExit;
and My executeQuery Code look like this
ExecuteQuery.js
const wantToExit = require("../Exit");
const Science = require("../Science");
function executetQuery() {
inquirer
.prompt([
{
type: "list",
name: "cmsType",
message: " Select Subject Options ",
default: false,
choices: ["Science", "Maths", "English", "Exit"],
},
])
.then((answers) => {
if (answers.cmsType === "Science") {
Science();
} else if (answers.cmsType === "Exit") {
wantToExit();
}
});
}
module.exports = executetQuery;
when I select Exit from executeQuery option and press Y option I am getting this error from Exit.js file
if (answer.moreQuery) return executeQuery();
^
TypeError: executeQuery is not a function
at /home/admin/SchoolProject/src/Exit/index.js:13:36
Your approach has issues because it has produced a cyclic dependency of modules. You have "required" wantToExit in ExecuteQuery.js and also "required" executetQuery() in Exit.js
What I believe you want to achieve is to keep asking user his preferred subject and then do something based on his/her choice until a user selects Exit.
I would suggest to use a while loop in ExecuteQuery.js for the main prompt and use a boolean flag to check if user wants to exit.
const wantToExit = require("../Exit");
const Science = require("../Science");
function executetQuery() {
let toStop = false;
// use a while loop
while(!toStop) {
inquirer
.prompt([
{
type: "list",
name: "cmsType",
message: " Select Subject Options ",
default: false,
choices: ["Science", "Maths", "English", "Exit"],
},
])
.then(async (answers) => {
if (answers.cmsType === "Science") {
// you can also set toStop = true here if you want to
// stop after first iteration
Science();
} else if (answers.cmsType === "Exit") {
// wantToExit() now returns a boolean flag
toStop = await wantToExit();
}
});
}
}
module.exports = executetQuery;
and your Exit.js should be like
function WantToExit() {
inquirer
.prompt([
{
name: "moreQuery",
type: "confirm",
message: "Want to do anything else?",
},
])
.then((answer) => {
return !answer.moreQuery;
});
}
module.exports = WantToExit;
This is a scenario of circular dependency. A requires B, B requires A and so on. To get it working, you'll have to modify the module.exports.
In Exit.js file, change module.exports=WantToExit to module.exports.WantToExit = WantToExit and require it as const {WantToExit} =require('./Exit.js') in ExecuteQuery.js file.
Similiary, module.exports.ExecuteQuery=ExecuteQuery and require as const {ExecuteQuery} =require('./ExecuteQuery.js')
My guidance would be to learn RXJS and observables into this somehow.
Also i think (yield* ) might work in strict mode not sure, i wanted to not it because this is more a suggestion to play with and look into
Generator Functions* Exploring ES6 © 2015 - 2018 Axel Rauschmayer (cover by Fran Caye)
RXJS Guide Observable
const { Observable } = require("rxjs");
async function* wantToExit() {
(yield* await inquirer
.prompt([
{
name: "moreQuery",
type: "confirm",
message: "Want to do anything else?",
},
])
.then(answer => answer.moreQuery)
);
}
const executeQuery = new Observable(subscriber => {
inquirer.prompt([
{
type: "list",
name: "cmsType",
message: " Select Subject Options ",
default: false,
choices: ["Science", "Maths", "English", "Exit"],
},
]).then((answers) => {
if (answers.cmsType === "Science") {
subscriber.next(answers.cmsType);
} else if (answers.cmsType === "Exit") {
let doWeExit = await wantToExit().next();
if (doWeExit === ADD_SOMETHING_NO) {
executeQuery.subscribe(userResponse => userResponse);
} else {
console.log('Adios!');
return false;
}
}
});
});
module.exports = { executeQuery };
On a new page you could than do. Or you could just use it right under the function declaration. Hope this vaguely helps to the next step.
const {executeQuery} = require('{INCLUDE YOUR FILEPATH}');
executeQuery.subscribe(userResponse => {
if(userResponse === 'Science') science();
console.log(userResponse);
});
I'm attempting to check if a user's ID is in this array and if they are, also get the "text" from it.
Array:
const staff = [
{
user: '245569534218469376',
text: 'dev'
},
{
user: '294597887919128576',
text: 'loner'
}
];
I've tried if (staff.user.includes(msg.member.id)) (Which I didn't think was going to work, and didn't.)
const findUser = (users, id) => users.find(user => user.id === id)
const usersExample = [
{
id: '123456765',
text: 'sdfsdfsdsd'
},
{
id: '654345676',
text: 'fdgdgdg'
}
]
//////////////////
const user = findUser(usersExample, '123456765')
console.log(user && user.text)
The some method on an array is used to tell if an item meets a condition, it is similar to the find method but the find method returns the item where the some method return true or false.
const staff = [
{
user: '245569534218469376',
text: 'dev'
},
{
user: '294597887919128576',
text: 'loner'
}
];
const isStaff = (staff, id) => staff.some(s => s.user === id);
console.log(isStaff(staff, '123'));
console.log(isStaff(staff, '245569534218469376'));
You may try something like this:
const staff = [
{
user: '245569534218469376',
text: 'dev'
},
{
user: '294597887919128576',
text: 'loner'
}
];
let item = staff.find(item => item.user == '294597887919128576'); // msg.member.id
if (item) {
console.log(item.text);
}
One another way to do that is:
const inArray = (array, id) => array.filter(item => item.user === id).length >= 1;
const users = [
{
user: '245569534218469356',
text: 'foo'
}, {
user: '245564734218469376',
text: 'bar'
}, {
user: '246869534218469376',
text: 'baz'
}
];
console.log(inArray(users, '246869534218469376')); // true
console.log(inArray(users, '222479534218469376')); // false
I want to create an app that has an alert for check connection with two button one is exit for the exit app and two is try again for check connection again,
I searched about it and I tried about it, but I can n't solved this problem please help me.
import { Injectable } from '#angular/core';
import { Network } from '#ionic-native/network/ngx';
import { AlertController } from '#ionic/angular';
#Injectable({
providedIn: 'root'
})
export class CheckInternetService {
public base: string; // this will be set in the constructor based on if we're in dev or prod
timer: any;
constructor(private network: Network, private alertCtrl: AlertController) {}
async presentAlert() {
const alert = await this.alertCtrl.create({
header: 'خطا',
backdropDismiss: false,
subHeader: 'قطعی انترنت',
message: 'لطفا انترنت خودرا چک کنید',
buttons: [{
text: 'خروج',
handler: () => {
navigator['app'].exitApp();
}
},
{
text: 'تلاش مجدد',
handler: () => {
this.doSomething().then(res => {
this.checkConnection();
});
}
}
],
});
await alert.present();
}
doSomething() {
return new Promise((resolve, reject) => {
// pretend a long-running task
this.timer = setTimeout(() => { resolve(true); }, 3000);
});
}
checkConnection(): boolean {
if (document.URL.includes('https://') || document.URL.includes('http://')) {
this.base = 'http://127.0.0.1:3001/';
} else {
this.base = 'https://url.to_actual_URL.com/';
}
const type = this.network.type;
let online;
if (type === 'unknown' || type === 'none' || type === undefined) {
online = false;
this.presentAlert();
} else {
online = true;
clearTimeout(this.timer);
}
this.network.onDisconnect().subscribe( () => {
online = false;
this.presentAlert();
});
this.network.onConnect().subscribe( () => {
online = true;
clearTimeout(this.timer);
});
return online;
}
}
This is my code that I was trying on, I work on this code but I do n't any answer, please help me.
You can make try again button with out any timer, you can use this code for your problem:
async presentAlert() {
this.alertCtrl.dismiss();
const alert = await this.alertCtrl.create({
header: 'خطا',
backdropDismiss: false,
subHeader: 'قطعی انترنت',
message: 'لطفا انترنت خودرا چک کنید',
buttons: [{
text: 'خروج',
handler: () => {
navigator['app'].exitApp();
}
},
{
text: 'تلاش مجدد',
// role: 'cancel',
handler: () => {
// this.doSomething().then(res => {
// this.checkConnection();
// });
const type = this.network.type;
if (type === 'unknown' || type === 'none' || type === undefined) {
this.presentAlert();
}
},
}
],
});
await alert.present();
}
I don't think you can have a alert box with two buttons because Alert box gives only one button "OK" to select and proceed. . You can show a modal instead of a alert box with as much button as you want.
I am working with React, I have got a variable named newtreeData, which looks like:
var newTreeData = {
name: submitted_title,
resource_link: submitted_resource_link,
details: submitted_details,
uuid: submitted_uuid,
website_image: submitted_website_img,
children: [
{
name: "Edit and save",
resource_link: "uh",
uuid: uuid.v4(),
details: "hi",
website_image:
"https://cdn3.iconfinder.com/data/icons/harmonicons-06/64/plus-circle-512.png",
children: [{...}, {}, ...]
},
{
name: "Edit and save",
resource_link: "uh",
uuid: uuid.v4(),
details: "hi",
website_image:
"https://cdn3.iconfinder.com/data/icons/harmonicons-06/64/plus-circle-512.png"
}
]
};
The line children: [{...}, {}] is just representing that newTreeData's children can have children which can have children...
Anyways, I wrote a method name findUUIDthenDelete which should do in pseudocode: if(object.uuid == toFindUUID) then delete object, and here's the full code for findUUIDthenDelete:
findUUIDthenDelete = (orig_data, to_delete_uuid) => {
var targetIsFound = false;
if (orig_data.uuid == to_delete_uuid) {
targetIsFound = true;
}
if (targetIsFound == false) {
if (orig_data.children === undefined) {
} else {
//if target not found, run recursion
orig_data.children.map(eachChildren =>
this.findUUIDthenDelete(eachChildren, to_delete_uuid)
);
}
} else {
console.log(orig_data, "this is the child ");
console.log(orig_data.parent, "is found, deleting its parent");
delete orig_data
}
};
As you can see this method is two parts: first I locate the object which has the uuid that we are trying to seek (potentially with some recursions), then delete the object. However, right now I am getting the "delete in local variable strict mode blah blah" error because of doing delete orig_data. Any insights to any workarounds to that error or some totally new way of tackling this? Also sincere apologies if there is an obvious solution I am out of mental energy and unable to think of anything algorithmic at the moment.
This should do it:
function findUUIDthenDelete(tree, uuid) {
if (!tree.children) return;
tree.children = tree.children.filter(c => c.uuid !== uuid);
tree.children.forEach(c => findUUIDthenDelete(c, uuid));
}
Should be pretty self-explanatory.
First, if the current node has no children, exit right away.
Next, potentially remove a child from the children array if the uuid matches using filter().
Finally, recursion.
Ok I'll admit this turned out to be more complicated than I thought, but the solution below will work if you can use Immutable. Essentially it walks your objects and collects the path to find the object that has the uuid and then once it has done that, it removes it.
const testMap = Immutable.fromJS({
uuid: 1,
children: [{
uuid: 2,
children: [{
uuid: 3,
children:[{
uuid: 8
}]
},
{
uuid: 4
},
{
uuid: 5
},
]
},
{
uuid: 7
}]
});
function findPath(checkMap, uuid, pathMap, currentIndex) {
if (checkMap.has('uuid') && checkMap.get('uuid') === uuid) {
const updatePathMap = pathMap.get('path').push(currentIndex);
return new Immutable.Map({
found: true,
path: pathMap.get('path').push(currentIndex)
});
} else {
if (checkMap.has('children') && checkMap.get('children').size > 0) {
for (let i = 0; i < checkMap.get('children').size; i++) {
const child = checkMap.get('children').get(i);
const checkChildPath = findPath(child, uuid, pathMap, i);
if (checkChildPath.get('found') === true) {
let updatePath = checkChildPath.get('path').push('children');
updatePath = updatePath.push(currentIndex);
return new Immutable.Map({
found: true,
path: updatePath
});
}
}
}
return pathMap;
}
}
const testPath = findPath(testMap, 7, new Immutable.Map({
found: false,
path: new Immutable.List()
}), 0);
console.info(testPath);
const testPath2 = findPath(testMap, 8, new Immutable.Map({
found: false,
path: new Immutable.List()
}), 0);
console.info(testPath2);
if (testPath2.get('found') === true) {
const path = testPath2.get('path');
if (path.size === 1 && path.get(0) === 0) {
// Your highlest level map has the uuid
} else {
const truePath = path.shift();
const cleanedUpMap = testMap.removeIn(truePath);
console.info(cleanedUpMap);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/immutable/3.8.2/immutable.js"></script>