can someone explain the change to bulkDelete (discord.js) - discord

Here is the code I have right now
module.exports ={
name:'purge',
description:'Clears the number of messages you set in a seccond ARG.',
aliases:['clear','nuke'],
execute(msg, args)
{
if(!msg.member.hasPermission("MANAGE_MESSAGES")) {
return msg.reply("You do not have permission to run this command").then(msg => msg.delete(5000));
}
if (!isNaN(args[0]) || parseInt(args[0]) <= 0) {
return msg.reply("That is not a number").then(msg => msg.delete(5000));
}
if(!msg.guild.me.hasPermission("MANAGE_MESSAGES")) {
return msg.reply("Sorry I can't messages please make sure i have the correct permissions").then(msg => msg.delete());
}
let deleteAmount;
if(parseInt(args[0]) > 100) {
deleteAmount = 100;
} else {
deleteAmount = parseInt(args[0]);
}
msg.channel.bulkDelete(deleteAmount, true);
}
}
Error:
(node:25048) UnhandledPromiseRejectionWarning: TypeError [MESSAGE_BULK_DELETE_TYPE]: The messages must be an Array, Collection, or number.
at TextChannel.bulkDelete (C:\StrangeOccBot\node_modules\discord.js\src\structures\interfaces\TextBasedChannel.js:364:11)
at Object.execute (C:\StrangeOccBot\commands\purge.js:27:21)
at Client.<anonymous> (C:\StrangeOccBot\index.js:46:39)
at Client.emit (events.js:315:20)
at WebSocketShard.onPacket (C:\StrangeOccBot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:436:22)
at WebSocketShard.onMessage (C:\StrangeOccBot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:293:10)
at WebSocket.onMessage (C:\StrangeOccBot\node_modules\ws\lib\event-target.js:120:16)

So I'm not sure if an int is still the way to do it with bulkDelete()
but as far as I know, you can fetch messages in a channel and pass those to the method!
msg.channel.messages.fetch({ limit: deleteAmount }).then(messages => {
msg.channel.bulkDelete(messages).then(deleted => {
msg.channel.send(`${deleted.size} messages pruged!`).then(msg => msg.delete(5000));
})
})
This is the way how I have done it for the last few times I created functions like what you try to archive.
Also you can add .catch() methods to the .then() methods so you can check if something went wrong or not!
Edit: I changed your code a little bit especially at the end so you have an idea how I would have done it to archive what you wanna archive
module.exports ={
name:'purge',
description:'Clears the number of messages you set in a seccond ARG.',
aliases:['clear','nuke'],
execute(msg, args) {
if (!msg.member.hasPermission("MANAGE_MESSAGES")) {
return msg.reply("You do not have permission to run this command").then(msg => msg.delete(5000));
}
if (!msg.guild.me.hasPermission("MANAGE_MESSAGES")) {
return msg.reply("Sorry I can't messages please make sure i have the correct permissions").then(msg => msg.delete());
}
if (!isNaN(args[0]) || parseInt(args[0]) <= 0) {
return msg.reply("That is not a number").then(msg => msg.delete(5000));
}
// I changed this slightly to how I would do it!
let deleteAmount = 100;
if (parseInt(args[0]) < 100) {
deleteAmount = parseInt(args[0])
}
// If I'm not mistaken, the bulkDelete() method also works with fetched messages in an variable.
// To archive this, you can use `msg.channel.messages.fetch()` as I will show below!
// Ofcourse I did not use the .catch() method, so if something isn't correctly done it can cause issues!
msg.channel.messages.fetch({ limit: deleteAmount }).then(messages => {
msg.channel.bulkDelete(messages).then(deleted => {
msg.reply(`${deleted.size} messages pruged!`).then(msg => msg.delete(5000));
})
})
}
}

Related

Discord await messages timing out | Discord V12

I am stuck on a problem. When "Player 2" (player[1]) types !yes in the channel then reason it times out. I'm not sure what I am doing wrong. player[1] is defined as msg.mentions.members.first();
let answer = true;
if (players[1].user.bot) {
return;
} else {
answer = await msg.channel.awaitMessages((msg) => {
console.log(msg.author.id === players[1].id && msg.content === `!yes`) // returns true
if (msg.author.id === players[1].id && msg.content === `!yes`) {
console.log("Player has accepted") // The console does print "Player has accepted"
return true;
}
return false;
}, {maxMatches: 1, time: 30000, errors: ['time']})
.catch(() => {
console.log("Timed out!") // The console does print "Timed Out as well"
return false;
});
}
// if user refuses to play
if (!answer) {
return channel.send(`${players[1]} preferred to run away.`);
}
You have incorrect syntax for awaitMessages() - the first argument should be a CollectorFilter (see here), not a callback.
Consider using createMessageCollector() instead. It reads much more nicely than awaitMessages() and makes more sense than forcing async/await into a collector. Should look something like this:
const filter = m => (m.author.id===players[1].id && m.content==="!yes");
const collector = msg.channel.createMessageCollector(filter, {max: 1, time: 30000});
collector.on("collect", (m) => {
// Player has accepted... do whatever
});
collector.on("end", (reason) => {
if(reason === "time") {
// Ran out of time
}
});

How to make a clearinterval/stop in discord.js?

I cant get it so if I do !stop it stops the interval and it just really annoys me.
client.on('message', msg => {
if (msg.guild && msg.content.startsWith('!messageall')) {
let text = msg.content.slice('!messageall'.length); // cuts off the /private part
setInterval(function(){
msg.guild.members.forEach(member => {
if (member.id != client.user.id && !member.user.bot) member.send("Message Here");
msg.channel.send(`Sent a message to <#${member.id}> `)
});
console.log("Started.")
}, 60000);
}
if (msg.guild && msg.content.startsWith('!stopall')) {
clearInterval()
}
});
I dont know how it will work
You need to have a reference to setInterval(), I also suggest you use client.setInterval() instead, so what you should do is:
const timer = client.setInterval(function(), 60000);
if (msg.guild && msg.content.startsWith('!stopall')) clearInterval(timer)

Unsubscribe from timer in rxjs

Hi I have a timer running which is like it should show a component for 30sec after every 10 seconds. My code is like this`
import { timer } from "rxjs";
componentWillReceiveProps(nextProps, nextState) {
console.log("RECEIVED PROPS");
if (this.props.venuesBonusOfferDuration === 0) {
this.subscribe.unsubscribe();
}
this.firstTimerSubscription;
this.secondTimerSubscription;
// if (this.state.isMounted) {
if (
nextProps.showBonusObj &&
(!nextProps.exitVenue.exitVenueSuccess || nextProps.enterVenues)
) {
// console.log("isMounted" + this.state.isMounted);
//if (this.state.isMounted) {
let milliseconds = nextProps.venuesBonusOfferDuration * 1000;
this.source = timer(milliseconds);
this.firstTimerSubscription = this.source.subscribe(val => {
console.log("hiding bonus offer");
this.firstTimerSubscription.unsubscribe();
this.props.hideBonusOffer();
this.secondTimerSubscription = bonusApiTimer.subscribe(val => {
console.log("caling timer" + val);
this.props.getVenuesBonusOffer(
this.props.venues.venues.id,
this.props.uid,
this.props.accessToken
);
});
});
//}
} else {
try {
if (this.secondTimerSubscription != undefined) {
this.secondTimerSubscription.unsubscribe();
console.log("secondTimer UNSUBSCRIBED");
}
if (this.firstTimerSubscription != undefined) {
this.firstTimerSubscription.unsubscribe();
console.log("firstTimer UNSUBSCRIBED");
}
} catch (error) {
console.log(
"error when removing bonusoffer timer" + JSON.stringify(error)
);
}
//}
}
}
`
Problem is if I try to unsubscribe this * this.firstTimerSubscription* and this.secondTimerSubscription like this
try {
if (this.secondTimerSubscription != undefined) {
this.secondTimerSubscription.unsubscribe();
console.log("secondTimerunmount UNSUBSCRIBED");
}
if (this.firstTimerSubscription != undefined) {
this.firstTimerSubscription.unsubscribe();
console.log("firstTimerunmount UNSUBSCRIBED");
}
} catch (error) {
console.log("error bonusoffer timer" + JSON.stringify(error));
}
its still prints logs within timer like "hiding bonus offer" and "calling timer".
Can someone please point out the issue. It been a day since am into this.
Any help is appreciated.
The problem is that you subscribe multiple times (whenever component receives props) and reassign newest subscription to firstTimerSubscription or secondTimerSubscription references. But doing that, subscriptions does not magically vanish. To see how it works here is a demo:
const source = timer(1000, 1000);
let subscribe;
subscribe = source.subscribe(val => console.log(val));
subscribe = source.subscribe(val => console.log(val));
setTimeout(() => {
subscribe.unsubscribe();
}, 2000)
Even though you unsubscribed, the first subscription keeps emiting. And the problem is that you lost a reference to it, so you can't unsubscribe now.
Easy fix could be to check whether you already subscribed and unsubscribe if so, before subscribing:
this.firstTimerSubscription ? this.firstTimerSubscription.unsubscribe: false;
this.firstTimerSubscription = this.source.subscribe(...
I wouldn't use a second timer. Just do a interval of 10 seconds. The interval emits the iteration number 1, 2, 3..... You can use the modulo operator on that tick. Following example code (for example with 1 second interval) prints true and false in console. After true it needs 3 seconds to show false. After false it needs 1 second to show true.
interval(1000).pipe(
map(tick => tick % 4 !== 0),
distinctUntilChanged(),
).subscribe(x => console.log(x));

TypeError: Cannot read property 'id' of undefined [discord.js]

Im getting this error for writing this "unban" codes to unban.js
Re-installed discord.js library, re-writed the code but did'nt worked.
module.exports.run = async (client, message, args) => {
if (!message.member.roles.find(role => role.name === "🚫| Ban Hammer")) {
return message.channel.send(
"**Kanka `🚫| Ban Hammer` yetkisine sahip değilsin.**"
);
}
let bannedMember = await client.fetchUser(args[0]);
if (!bannedMember) {
return message.channel.send(`**Bir id yazmalısın.**`);
}
let reason = args.slice(1).join(" ");
if (!reason) {
reason = "Bir sebep belirtilmedi.";
}
try {
message.guild.unban(bannedMember, { reason: reason });
message.react(emoji);
} catch (e) {
console.log(e.message);
}
};
module.exports.conf = {
name: "unban"
};
[ Sorry guys, my english is bad. ]
It seems that your code does not reference id in that particular file.
When looking for debugging help, please attach the full, or at least main error message, like Cursed said. my only suggestion would be that id might be misused in a different file, or incorrectly referenced elsewhere.

Angular: What's the correct way to return Observable?

I have the following method which isn't working correct:
getProducts(): Observable<Product[]> {
let PRODUCTS: Product[];
this.http.get(this.base_url + "api/products")
.subscribe(
(data) => {
for(var i in data) {
PRODUCTS.push(new Product(data[i].id, data[i].name, data[i].category, data[i].description, data[i].price, data[i].amount));
}
},
(error) => {
console.log(error);
});
return of(PRODUCTS);
}
The error I'm getting is this:
TypeError: Cannot read property 'push' of undefined
Now, I know that the PRODUCT array is not accessable from within the subscribe function, but I cannot get the correct solution for it.
Can anyone help me with that. I want to return an Observable<Product[]>.
Thank you in advance!
Edit: Updated to account for the fact that the API seems to return an array-like object rather than a true array.
You want to use map:
getProducts(): Observable<Product[]> {
return this.http.get(this.base_url + "api/products")
.map(data => {
let products = [];
for (let i in data) {
products.push(new Product(data[i].id, data[i].name, data[i].category, data[i].description, data[i].price, data[i].amount));
}
return products;
})
.do(null, console.log);
}
Since #pixelbit's comment keeps getting upvotes despite being wrong, here's an example showing why it is wrong:
// Fakes a HTTP call which takes half a second to return
const api$ = Rx.Observable.of([1, 2, 3]).delay(500);
function getProducts() {
let products = [];
api$.subscribe(data => {
for (let i in data) {
products.push(data[i]);
}
});
return Rx.Observable.of(products);
}
// Logs '[]' instead of '[1, 2, 3]'
getProducts().subscribe(console.log);

Resources