I created a kick command with reason, but it doesn't kick the member, I don't have any errors...
Also, why when I send the command, it deletes it?
I tried to fix it myself, but still doesn't work. Thanks for your help.
Here my code:
client.on('message', message => {
if(message.content.startsWith(prefix + "kick")) {
if(message.channel.type === 'DM') {
message.channel.send('This command can use only in guide');
return;
};
if(!message.member.hasPermission('KICK_MEMBERS')) {
const KickEmbed = new Discord.MessageEmbed()
.setColor("YELLOW")
.setAuthor(message.author.username)
.setDescription("Sorry, but you don't have the permission to use the kick command.")
message.channel.send(KickEmbed);
return;
};
let mentionMember = message.mentions.members.first();
if(!mentionMember) {
const ErrEmbed = new Discord.MessageEmbed()
.setColor('YELLOW')
.setAuthor(message.author.username)
.setDescription('**Usage:** `y!kick <#user> or ID` You need to mention an user!')
message.channel.send(ErrEmbed);
return;
};
let args = message.content.slice(prefix.length).trim().split(/ +/g);
if(!args.lenght) {
const ReasonError = new Discord.MessageEmbed()
.setColor('YELLOW')
.setAuthor(message.author.username)
.setDescription('Before kicking this member, you need to provide a reason of your kick.')
message.channel.send(ReasonError)
return;
};
let authorHighestRole = message.member.roles.highest.position;
let mentionHighestRole = mentionMember.roles.highest.position;
if(mentionHighestRole >= authorHighestRole) {
message.channel.send('You can`t kick members with equal or higher position');
return;
};
if(!mentionMember.kickable) {
message.channel.send('I have no permissions to kick this user');
return
};
mentionMember.kick()
.then(() => message.channel.send(`Kicked ${mentionMember.tag} with reason: ${args}`))
.catch(console.error);
}
}
);
Should look at docs before posting:
https://discord.js.org/#/docs/main/stable/class/GuildMember?scrollTo=kick
But anyways:
<Member>.kick(Reason), it's just a string you pass in.
Also args looks like an array so you can't just use args inside of a string, try args.join(" "). (Inside of message.channel.send("Kicked..."))
All in all here's the change:
So mentionMember.kick() => mentionMember.kick(args.join(" "))
Related
I am using MongoseDB in order to receive some information about an item. When i try to search for it, it finds it with no trouble, but for some reasons this function is not pushing them into my array. I think this might be because of some async functions and that the console.log() is triggered before any item is being pushed in there.
const getOrders = function(allOrders){
let promise = new Promise((succ, fail)=>{
let ordersTodisplay = []
for (let order of allOrders) {
if (!(order.orderId === null || order.orderItem === null)){
postMong.findById(order.orderItem, function (err, item) {
ordersTodisplay.push(item)
})
}
}
if(ordersTodisplay.length > 0){
succ(ordersTodisplay)
} else{
fail("no items")
}
})
return promise
}
router.get('/accountpage',function(req,res){
const userDB = req.session.username
if (userDB !== undefined && userDB){
userForm.findOne({ username : userDB }, function (err, user) {
const userOrders = user.userOrders;
if (userOrders.length > 1) {
getOrders(userOrders).then((result)=>{console.log(result)}, (fail)=>{console.log(fail)})
res.render('../view/accountpage',{username: userDB,orders: itemsToDisplay});
}
else{
res.render('../view/accountpage',{username: userDB,orders: "There are no orders"});
}
});
} else {
res.redirect("/login")
}
});
The result is : no items
You have to for the database call to complete and then push the data in the array like this, using async-await:
const getOrders = function(allOrders){
let promise = new Promise(async (succ, fail)=>{
let ordersTodisplay = []
for (let order of allOrders) {
if (!(order.orderId === null || order.orderItem === null)){
await postMong.findById(order.orderItem, function (err, item) {
ordersTodisplay.push(item)
})
}
}
if(ordersTodisplay.length > 0){
succ(ordersTodisplay)
} else{
fail("no items")
}
})
return promise
}
Your code is quite nested and that makes it hard to reason about what is happening.
To break down your code, you:
get a single user that has several order IDs referenced
load each order
respond with those orders (although you return itemsToDisplay that doesn't seem to be defined anywhere, so I'm a bit confused)
I'd try to capture that logical pattern in the code. A good trick is returning early to make the code less nested and interdependent:
router.get('/accountpage', function(req,res){
const userDB = req.session.username;
if (!userDB){
res.redirect("/login");
return;
}
loadUserOrders(userDB)
.then(function(orders) {
if(orders.length > 0) {
res.render('../view/accountpage', {username: userDB,orders: orders});
return;
}
// Note: consider returning just the empty array here, that already implies no orders
res.render('../view/accountpage', {username: userDB, orders: "There are no orders"});
})
.catch(function(error) {
//TODO: render error -- case not covered by your code
});
});
// Because this is an async function you can now await inside it, meaning no need for the callback syntax for mongoose
async function loadUserOrders(username) {
const user = await userForm.findOne({ username: username });
// Promise.all runs in parallel several promises and returns an array containing their results
// .map here turns the list of userOrders into a list of promises getting each order
return await Promise.all(user.userOrders.map((userOrder) => postMong.findById(userOrder.orderItem));
}
Notice how this code highlights that you are not explicitly handling the error case from loading orders.
You can further simplify this by using something like express-async-handler which will let your endpoint function be async as well:
const asyncHandler = require('express-async-handler');
router.get('/accountpage', asyncHandler(async function(req,res){
const userDB = req.session.username;
if (!userDB){
res.redirect("/login");
return;
}
// Note: there is no try-catch around loadUserOrders right now, so errors will result in a 500 courtesy of express-async-handler -- better than before
const orders = await loadUserOrders(userDB);
if(orders.length > 0) {
res.render('../view/accountpage', {username: userDB,orders: orders});
return;
}
// Note: consider returning just the empty array here, that already implies no orders
res.render('../view/accountpage', {username: userDB, orders: "There are no orders"});
}));
I think using async/await syntax all the way through leaves the code more consistent and easier to reason about than the mix of callbacks, new Promise and await that was suggested in another answer. In the end, the endpoint is not very complex, and I think the code can reflect that.
at the moment, the issue is that Facebook fbclid queries look atrocious on my otherwise very nice URLs.
I WANT THEM GONE
solution below
the solution that i could find was to use a handle hook to remove it if it's there.
import type { Handle } from '#sveltejs/kit';
export const handle: Handle = ({ event, resolve }) => {
let assign: any = {};
if (event.request.url.match(/\?fbclid=.+/)) {
assign = {
redirected: true,
headers: {
Location: event.request.url.replace(/[\?&]fbclid=[^&]+/, '')
}
};
}
let r = resolve(event);
Object.assign(r, assign);
return r;
};
the key part of this code here is the /[\\?&]fbclid=[^&]+/ which allows other query parameters to exist, this will only remove the fbclid parameter as shown on regexr
I hope this helps :)
I have a browser.wait() in an E2E test which is invoking a function defined in protractor.config.js file. When running the test, I get the following error:
Failed: Wait condition must be a promise-like object, function, or a Condition object
FYI - the function defined in protractor.config.js contains an If-condition which I need for two cases. When I remove the If-condition, the test runs fine. The function returns a: deferred.promise
What does this exactly means and how to fix it? Have been searching, but unfortunately can't anything related to it.
Function in protractor.config.js:
checkMail: function(user, subjectSent) {
const deferred = protractor.promise.defer();
var usermail;
var mailsubject;
var count = 0;
mailListener.on("mail", function(mail, seqno, attributes) {
var mailuid = attributes.uid;
var toMailbox = '[Gmail]/All Mail';
var i = ++count;
user = mail.to[0].address;
mailsubject = mail.subject;
if (i > 2) {
mailListener.stop();
return;
}
deferred.fulfill(mail);
});
if ((user === usermail) && (subjectSent === mailsubject)) {
return deferred.promise;
}
}
E2E it-function:
it("It should do xxxxxxx", (done) => {
browser.wait(browser.params.checkMail('user_email#yyyyy.com', 'Email subject'))
.then((email) => {
expect(email['subject']).toEqual("Email subject");
expect(email['headers'].to).toEqual( 'user_email#yyyyy.com' );
});
done();
});
I am attempting to develop an extension with a language-server for VSCode. I am trying to figure out how to write text to log from language-server part of the extension. console.log produces nothing
Just as an update, you can use vscode.window.createOutputChannel to create the output container and then write to it with the appendLine method.
//Create output channel
let orange = vscode.window.createOutputChannel("Orange");
//Write to output.
orange.appendLine("I am a banana.");
Just open vscode and go to menu "Help"->"Toggle Developer Tools" and the console is displayed on rigth window.
On server side try using connection.console.log.
// Create a connection for the server. The connection uses
// stdin / stdout for message passing
let connection: IConnection = createConnection(process.stdin, process.stdout);
connection.console.log(`Console test.`);
The message with show in Debug console on client side.
For client side simple console.log works well for me.
You have to set an outputChannelName property on the client options inside the client extension code:
let clientOptions: LanguageClientOptions = {
outputChannelName: 'XYZ Language Server',
};
Once you've done that you can use console.log() and it will be shown in the VSCode extension output panel.
The Language Server Protocol supports logging, use the notification window/logMessage to send log messages from the server, VS Code will display the server's log in the output panel, in the channel corresponding to the language client that started the server.
Thanks guys!
export let config: any = {};
export function getConfig() {
//debug
config.debug = workspace.getConfiguration().get('VBI.debug');
config.debugToChannel = workspace.getConfiguration().get('VBI.debugToChannel'); //Instead into dev-tools-console
return config;
}
/**
* #param cat Type String --> define Cathegory [info,warn,error]
* #param o Rest Parameter, Type Any --> Data to Log
*/
export let info = vscode.window.createOutputChannel("VBI-Info");
export function log(cat: string, ...o: any) {
function mapObject(obj: any) {
switch (typeof obj) {
case 'undefined':
return 'undefined';
case 'string':
return obj;
case 'number':
return obj.toString;
case 'object':
let ret: string = '';
for (const [key, value] of Object.entries(obj)) {
ret += (`${key}: ${value}\n`);
}
return ret;
default:
return obj; //function,symbol,boolean
}
}
if (config.debug) {
if (config.debugToChannel) {
switch (cat.toLowerCase()) {
case 'info':
info.appendLine('INFO:');
o.map((args: any) => {
info.appendLine('' + mapObject(args));
});
info.show();
return;
case 'warn':
info.appendLine('WARN:');
o.map((args: any) => {
info.appendLine('' + mapObject(args));
});
info.show();
return;
case 'error':
let err:string='';
info.appendLine('ERROR: ');
//err += mapObject(cat) + ": \r\n";
o.map((args: any) => {
err += mapObject(args);
});
info.appendLine(err);
vscode.window.showErrorMessage(err);//.replace(/(\r\n|\n|\r)/gm,"")
info.show();
return;
default:
info.appendLine('INFO-Other:');
info.appendLine(mapObject(cat));
o.map((args: any) => {
info.appendLine('' + mapObject(args));
});
info.show();
return;
}
}
else {
switch (cat.toLowerCase()) {
case 'info':
console.log('INFO:', o);
return;
case 'warn':
console.log('WARNING:', o);
return;
case 'error':
console.log('ERROR:', o);
return;
default:
console.log('log:',cat, o);
return;
}
}
}
}
tests:
import * as func from './functions';
import { config } from './functions';
func.getConfig();
let text = `debugToChannel:${config.debugToChannel}\n`;
func.log('info','vbi-format',text);
func.log('warn','vbi-format',text);
func.log('error','vbi-format',text);
I've been trying to get the name and only the name.
Like this shows everything:
fb.GetAsync("me", (val) =>
{
if (val.Error == null)
{
var result = (IDictionary<string, object>)val.Result;
Dispatcher.BeginInvoke(() => InfoBox.ItemsSource = result);
}
else
{
// TODO: Need to let the user know there was an error
//failedLogin();
}
});
So how do I just get the name?
regards
Even
I'm JeongSeop Kim. Korean.
You can access infomation by using Dispatcher.BeginInvoke() func.
for example.
Dispatcher.BeginInvoke(() => firstNameTxtBlock.Text = result["first_name"].ToString());
Maybe you can see:)
Good Lock!