Reputation: 11
I'm currently trying to create a Discord bot that sends a message when a user with a specified role sends the command %sticky This is a test
I want it to always be the first message in the channel and every time another user types in the channel the bot deletes its last message and posts again. I haven't had any luck online yet even finding a bot that already does this functionality, or where to even start. Here's what I kind of have so far
var lastStickyMessage;
client.on('message', message => {
if (lastStickyMessage != null) {
message.channel.fetchMessage(lastStickyMessage)
.then(retrievedMessage => retrievedMessage.delete());
}
message.reply("This is a Sticky Message").then(sent => {
let lastStickyMessage = sent.id;
}
});
Upvotes: 0
Views: 1920
Reputation: 1690
There are several errors with your variable management: One one hand you create a new let with the same name. Since a let is a scoped variable, the lastStickyMessage
will have a different value inside the sent callback than it has outside of it, since those are two different variables (read more on this here).
Apart from that you should save the last sent ID in a file or somewhere since the var will be reset once you restart your bot (the built in fs
module could help you with that, you can find the documentation here).
One last thing: If you initialize a variable without a value it is not null
but undefined
. If you only check using ==
it will still evaluate to true
(means null == undefined
) but if you compare using ===
, it will evaluate to false (null !== undefined
). In your case this is not really a problem but this might be good to know for other cases.
Upvotes: 1