Avoid message repeating? - discord.js

I need some help here I have a code that shows a message being updated per 2 seconds but I want a single message that replaces itself.
let channel = guild.channels.find(channel => channel.name === guilds[guild.id].digitchan);
let channel2 = guild.channels.find(channel => channel.name === guilds[guild.id].countdownchan);
if (channel && channel2) {
channel.send(embed);
scrims[guild.id] = {
timer: setTimeout(function() {
channel2.join().then(connection => {
const dispatcher = connection.playFile('./Audio/test.mp3');
console.log('dispatcher');
console.log(dispatcher == null);
dispatcher.on('end', () => {
channel2.leave();
const embed2 = new RichEmbed()
.setColor(0xc1d9ff)
.addField("message x", false);
channel.send(embed2);
scrims[guild.id].codes = true;
scrims[guild.id].codedata = {};
scrims[guild.id].playerinterval = setInterval(function() {
const embed4 = new RichEmbed()
.setColor(0xc1d9ff)
.setTitle("codes:");
Object.keys(scrims[guild.id].codedata).forEach(function(key) {
let codeobj = scrims[guild.id].codedata[key];
let user_str = "";
Object.keys(scrims[guild.id].codedata[key]).every(function(key2, count) {
let user = scrims[guild.id].codedata[key][key2];
user_str = user_str + user + "\n"
if (count >= 15) {
if (count > 15) user_str = user_str + "and more";
return false;
};
})
embed4.addField(key + " (" + Object.keys(codeobj).length + " codes)", user_str, true);
})
channel.send(embed4);
}, 2000);
scrims[guild.id].timer2 = setTimeout(function() {
scrims[guild.id].codes = false;
clearInterval(scrims[guild.id].playerinterval);
const embed3 = new RichEmbed()
.setColor(0xc1d9ff)
.setTitle("codes:");
Object.keys(scrims[guild.id].codedata).forEach(function(key) {
let codeobj = scrims[guild.id].codedata[key];
let user_str = "";
Object.keys(scrims[guild.id].codedata[key]).every(function(key2, count) {
let user = scrims[guild.id].codedata[key][key2];
user_str = user_str + user + "\n"
if (count >= 15) {
if (count > 15) user_str = user_str + "y mas..";
return false;
};
})
embed3.addField(key + " (" + Object.keys(codeobj).length + " codes)", user_str, true);
})
channel.send(embed3);
}, 1 * 60000);
});
});
}, time * 60000);
};
};
This is the discord action:
Codes:
Codes:
Codes:
Codes:
Codes:
Codes:
Codes:
Codes: 3c5
Codes: 3c5
So could be some kind of message deleting before sending the same message updated again, please let me know how to do it or some kind of code changing.

Just use message.edit() to edit the message.
message.edit() on discord.js docs

Related

discordjs Embed won't show up

Ok, so i'm trying to make a push notification for my discord.
i found this script online.
but it will not post the embed....
This is my monitor code:
TwitchMonitor.onChannelLiveUpdate((streamData) => {
const isLive = streamData.type === "live";
// Refresh channel list
try {
syncServerList(false);
} catch (e) { }
// Update activity
StreamActivity.setChannelOnline(streamData);
// Generate message
const msgFormatted = `${streamData.user_name} is nu live op twitch <:bday:967848861613826108> kom je ook?`;
const msgEmbed = LiveEmbed.createForStream(streamData);
// Broadcast to all target channels
let anySent = false;
for (let i = 0; i < targetChannels.length; i++) {
const discordChannel = targetChannels[i];
const liveMsgDiscrim = `${discordChannel.guild.id}_${discordChannel.name}_${streamData.id}`;
if (discordChannel) {
try {
// Either send a new message, or update an old one
let existingMsgId = messageHistory[liveMsgDiscrim] || null;
if (existingMsgId) {
// Fetch existing message
discordChannel.messages.fetch(existingMsgId)
.then((existingMsg) => {
existingMsg.edit(msgFormatted, {
embed: msgEmbed
}).then((message) => {
// Clean up entry if no longer live
if (!isLive) {
delete messageHistory[liveMsgDiscrim];
liveMessageDb.put('history', messageHistory);
}
});
})
.catch((e) => {
// Unable to retrieve message object for editing
if (e.message === "Unknown Message") {
// Specific error: the message does not exist, most likely deleted.
delete messageHistory[liveMsgDiscrim];
liveMessageDb.put('history', messageHistory);
// This will cause the message to be posted as new in the next update if needed.
}
});
} else {
// Sending a new message
if (!isLive) {
// We do not post "new" notifications for channels going/being offline
continue;
}
// Expand the message with a #mention for "here" or "everyone"
// We don't do this in updates because it causes some people to get spammed
let mentionMode = (config.discord_mentions && config.discord_mentions[streamData.user_name.toLowerCase()]) || null;
if (mentionMode) {
mentionMode = mentionMode.toLowerCase();
if (mentionMode === "Nu-Live") {
// Reserved # keywords for discord that can be mentioned directly as text
mentionMode = `#${mentionMode}`;
} else {
// Most likely a role that needs to be translated to <#&id> format
let roleData = discordChannel.guild.roles.cache.find((role) => {
return (role.name.toLowerCase() === mentionMode);
});
if (roleData) {
mentionMode = `<#&${roleData.id}>`;
} else {
console.log('[Discord]', `Cannot mention role: ${mentionMode}`,
`(does not exist on server ${discordChannel.guild.name})`);
mentionMode = null;
}
}
}
let msgToSend = msgFormatted;
if (mentionMode) {
msgToSend = msgFormatted + ` ${mentionMode}`
}
let msgOptions = {
embed: msgEmbed
};
discordChannel.send(msgToSend, msgOptions)
.then((message) => {
console.log('[Discord]', `Sent announce msg to #${discordChannel.name} on ${discordChannel.guild.name}`)
messageHistory[liveMsgDiscrim] = message.id;
liveMessageDb.put('history', messageHistory);
})
.catch((err) => {
console.log('[Discord]', `Could not send announce msg to #${discordChannel.name} on ${discordChannel.guild.name}:`, err.message);
});
}
anySent = true;
} catch (e) {
console.warn('[Discord]', 'Message send problem:', e);
}
}
}
liveMessageDb.put('history', messageHistory);
return anySent;
});
This is the embed code:
const Discord = require('discord.js');
const moment = require('moment');
const humanizeDuration = require("humanize-duration");
const config = require('../data/config.json');
class LiveEmbed {
static createForStream(streamData) {
const isLive = streamData.type === "live";
const allowBoxArt = config.twitch_use_boxart;
let msgEmbed = new Discord.MessageEmbed();
msgEmbed.setColor(isLive ? "RED" : "BLACK");
msgEmbed.setURL(`https://twitch.tv/${(streamData.login || streamData.user_name).toLowerCase()}`);
// Thumbnail
let thumbUrl = streamData.profile_image_url;
if (allowBoxArt && streamData.game && streamData.game.box_art_url) {
thumbUrl = streamData.game.box_art_url;
thumbUrl = thumbUrl.replace("{width}", "288");
thumbUrl = thumbUrl.replace("{height}", "384");
}
msgEmbed.setThumbnail(thumbUrl);
if (isLive) {
// Title
msgEmbed.setTitle(`:red_circle: **${streamData.user_name} is live op Twitch!**`);
msgEmbed.addField("Title", streamData.title, false);
} else {
msgEmbed.setTitle(`:white_circle: ${streamData.user_name} was live op Twitch.`);
msgEmbed.setDescription('The stream has now ended.');
msgEmbed.addField("Title", streamData.title, true);
}
// Add game
if (streamData.game) {
msgEmbed.addField("Game", streamData.game.name, false);
}
if (isLive) {
// Add status
msgEmbed.addField("Status", isLive ? `Live with ${streamData.viewer_count} viewers` : 'Stream has ended', true);
// Set main image (stream preview)
let imageUrl = streamData.thumbnail_url;
imageUrl = imageUrl.replace("{width}", "1280");
imageUrl = imageUrl.replace("{height}", "720");
let thumbnailBuster = (Date.now() / 1000).toFixed(0);
imageUrl += `?t=${thumbnailBuster}`;
msgEmbed.setImage(imageUrl);
// Add uptime
let now = moment();
let startedAt = moment(streamData.started_at);
msgEmbed.addField("Uptime", humanizeDuration(now - startedAt, {
delimiter: ", ",
largest: 2,
round: true,
units: ["y", "mo", "w", "d", "h", "m"]
}), true);
}
return msgEmbed;
}
}
module.exports = LiveEmbed;
But it won't post the embed, only the msg. as you can see it updates teh msg aswell.
enter image description here
i'm stuck on this for four days now, can someone help?

Command deprecated [duplicate]

This question already has an answer here:
Discord.js v12 code breaks when upgrading to v13
(1 answer)
Closed 1 year ago.
So basically I had this blackjack command that worked fine with v12 discord.js but as soon as I updated to discord v13. Bugs starting to appear like:
node:5932) DeprecationWarning: The message event is deprecated. Use messageCreate instead
(Use node --trace-deprecation ... to show where the warning was created)
(Only error showing up)
So I made some research and figured out that what happens to embed, but this command does not content an embed.. I came here to ask help. I would appreciate it :)
Blackjack.js
const { stripIndents } = require('common-tags');
const { shuffle, verify } = require('../../functions');
const db = require('quick.db');
const suits = ['♣', '♥', '♦', '♠'];
const faces = ['Jack', 'Queen', 'King'];
const hitWords = ['hit', 'hit me'];
const standWords = ['stand'];
module.exports = {
config: {
name: 'blackjack',
aliases: ['bj'],
category: 'games',
usage: '[deck] <bet>',
description: 'Play A Game Of Blackjack!',
accessableby: 'everyone'
},
run: async (bot, message, args, ops) => {
if (!args[0]) return message.channel.send('**Please Enter Your Deck Amount!**')
let deckCount = parseInt(args[0])
if (isNaN(args[0])) return message.channel.send('**Please Enter A Number!**')
if (deckCount <= 0 || deckCount >= 9) return message.channel.send("**Please Enter A Number Between 1 - 8!**")
let user = message.author;
let bal = db.fetch(`money_${user.id}`)
if (!bal === null) bal = 0;
if (!args[1]) return message.channel.send("**Please Enter Your Bet!**")
let amount = parseInt(args[1])
if (isNaN(args[1])) return message.channel.send("**Please Enter A Number**")
if (amount > 10000) return message.channel.send("**Cannot Place Bet More Than \`10000\`**")
if (bal < amount) return message.channel.send("**You Are Betting More Than You Have!**")
const current = ops.games.get(message.channel.id);
if (current) return message.channel.send(`**Please Wait Until The Current Game Of \`${current.name}\` Is Finished!**`);
try {
ops.games.set(message.channel.id, { name: 'blackjack', data: generateDeck(deckCount) });
const dealerHand = [];
draw(message.channel, dealerHand);
draw(message.channel, dealerHand);
const playerHand = [];
draw(message.channel, playerHand);
draw(message.channel, playerHand);
const dealerInitialTotal = calculate(dealerHand);
const playerInitialTotal = calculate(playerHand);
if (dealerInitialTotal === 21 && playerInitialTotal === 21) {
ops.games.delete(message.channel.id);
return message.channel.send('**Both Of You Just Hit Blackjack!**');
} else if (dealerInitialTotal === 21) {
ops.games.delete(message.channel.id);
db.subtract(`money_${user.id}`, amount);
return message.channel.send(`**The Dealer Hit Blackjack Right Away!\nNew Balance - **\` ${bal - amount}\``);
} else if (playerInitialTotal === 21) {
ops.games.delete(message.channel.id);
db.add(`money_${user.id}`, amount)
return message.channel.send(`**You Hit Blackjack Right Away!\nNew Balance -**\`${bal + amount}\``);
}
let playerTurn = true;
let win = false;
let reason;
while (!win) {
if (playerTurn) {
await message.channel.send(stripIndents`
**First Dealer Card -** ${dealerHand[0].display}
**You [${calculate(playerHand)}] -**
**${playerHand.map(card => card.display).join('\n')}**
\`[Hit / Stand]\`
`);
const hit = await verify(message.channel, message.author, { extraYes: hitWords, extraNo: standWords });
if (hit) {
const card = draw(message.channel, playerHand);
const total = calculate(playerHand);
if (total > 21) {
reason = `You Drew ${card.display}, Total Of ${total}! Bust`;
break;
} else if (total === 21) {
reason = `You Drew ${card.display} And Hit 21!`;
win = true;
}
} else {
const dealerTotal = calculate(dealerHand);
await message.channel.send(`**Second Dealer Card Is ${dealerHand[1].display}, Total Of ${dealerTotal}!**`);
playerTurn = false;
}
} else {
const inital = calculate(dealerHand);
let card;
if (inital < 17) card = draw(message.channel, dealerHand);
const total = calculate(dealerHand);
if (total > 21) {
reason = `Dealer Drew ${card.display}, Total Of ${total}! Dealer Bust`;
win = true;
} else if (total >= 17) {
const playerTotal = calculate(playerHand);
if (total === playerTotal) {
reason = `${card ? `Dealer Drew ${card.display}, Making It ` : ''}${playerTotal}-${total}`;
break;
} else if (total > playerTotal) {
reason = `${card ? `Dealer Drew ${card.display}, Making It ` : ''}${playerTotal}-\`${total}\``;
break;
} else {
reason = `${card ? `Dealer Drew ${card.display}, Making It ` : ''}\`${playerTotal}\`-${total}`;
win = true;
}
} else {
await message.channel.send(`**Dealer Drew ${card.display}, Total Of ${total}!**`);
}
}
}
db.add(`games_${user.id}`, 1)
ops.games.delete(message.channel.id);
if (win) {
db.add(`money_${user.id}`, amount);
return message.channel.send(`**${reason}, You Won ${amount}!**`);
} else {
db.subtract(`money_${user.id}`, amount);
return message.channel.send(`**${reason}, You Lost ${amount}!**`);
}
} catch (err) {
ops.games.delete(message.channel.id);
throw err;
}
function generateDeck(deckCount) {
const deck = [];
for (let i = 0; i < deckCount; i++) {
for (const suit of suits) {
deck.push({
value: 11,
display: `${suit} Ace!`
});
for (let j = 2; j <= 10; j++) {
deck.push({
value: j,
display: `${suit} ${j}`
});
}
for (const face of faces) {
deck.push({
value: 10,
display: `${suit} ${face}`
});
}
}
}
return shuffle(deck);
}
function draw(channel, hand) {
const deck = ops.games.get(channel.id).data;
const card = deck[0];
deck.shift();
hand.push(card);
return card;
}
function calculate(hand) {
return hand.sort((a, b) => a.value - b.value).reduce((a, b) => {
let { value } = b;
if (value === 11 && a + value > 21) value = 1;
return a + value;
}, 0);
}
}
};
Event Handler:
const { readdirSync } = require("fs")
module.exports = (bot) => {
const load = dirs => {
const events = readdirSync(`./events/${dirs}/`).filter(d => d.endsWith('.js'));
for (let file of events) {
const evt = require(`../events/${dirs}/${file}`);
let eName = file.split('.')[0];
bot.on(eName, evt.bind(null, bot));
};
};
["client", "guild"].forEach(x => load(x));
};
message is an event. you have an event handler, which fires, when a message event is triggered by a user. (they send a message).
What this error is saying is that the message event is deprecated. messageCreate (or messageUpdate) are the new events, and your event handlers need to use that syntax to address the message events (accordingly to creation or update).

Why does my code run when it is not supposed to?

if (command == "lookup") {
var user = message.content.split(" ").slice(1).join(" ")
Blocked.forEach(bl => {
if (message.author.id == bl) {
message.reply("You have been blocked from using commands.")
IsBlocked = 1
}
if (IsBlocked == 0) {
rblxAPI.getUserIdFromUsername(user).then(found => {
found.getStatus().then(stat => {
found.getFriendsCount().then(count => {
let rblxLookup = new Discord.MessageEmbed()
.setTitle("Lookup of: " + found.name)
.setDescription("User ID: " + found.id + " \n User Description: " + stat + " \n User Friends Count: " + count)
message.channel.send(rblxLookup)
})
})
}).catch(console.error());
}
})
}
So this is my code and when the user is blocked it still continues with the script. I get no errors. Why does this happen?
I think you need to return where you check if they are blocked. Here is my guess on fixing it:
if (command == "lookup") {
var user = message.content.split(" ").slice(1).join(" ")
Blocked.forEach(bl => {
if (message.author.id == bl) {
message.reply("You have been blocked from using commands.")
IsBlocked = 1
// I think you could just return here to end it if the user is blocked
return;
}
if (IsBlocked == 0) {
rblxAPI.getUserIdFromUsername(user).then(found => {
found.getStatus().then(stat => {
found.getFriendsCount().then(count => {
let rblxLookup = new Discord.MessageEmbed()
.setTitle("Lookup of: " + found.name)
.setDescription("User ID: " + found.id + " \n User Description: " + stat + " \n User Friends Count: " + count)
message.channel.send(rblxLookup)
})
})
}).catch(console.error());
}
})
}
But i might just be stupid right now.

code in promise .then firing way before promise finishes

I have this code...sorry for the messiness I've been at this a while:
loadAvailabilities() {
let promises = [];
let promises2 = [];
let indexi = 0;
//return new Promise((resolve, reject) => {
this.appointments = this.af.list('/appointments', { query: {
orderByChild: 'selected',
limitToFirst: 10
}});
let mapped;
this.subscription2 = this.appointments.subscribe(items => items.forEach(item => {
//promises.push(new Promise((resolve, reject) => {
console.log(item);
let userName = item.$key;
//this.availabilities = [];
for(let x in item) {
let month = x;
console.log(x + " month");
this.appointmentsMonth = this.af.list('/appointments/' + userName + '/' + month);
this.subscription3 = this.appointmentsMonth.subscribe(items => items.forEach(item => {
this.startAtKeyAvail = item.$key;
//console.log(JSON.stringify(item) + " item");
let date = new Date(item.date.day * 1000);
let today = new Date();
console.log(date.getMonth() + "==" + today.getMonth() + "&&" + date.getDate() + "==" + today.getDate());
console.log("IN LOAD AVAILABILITIES *(*((**(*(*(*(*(*(*&^^^^%^%556565656565");
if(date.getMonth() == today.getMonth() && date.getDate() == today.getDate()) {
console.log(" inside the if that checks if its today");
console.log(item.reserved.appointment + " *************appointment");
//let counter = 0;
//mapped = item.reserved.appointment.map((r) => {
//item.reserved.appointment.forEach((r, index) => {
for(let r of item.reserved.appointment) {
promises.push(new Promise((resolve, reject) => {
if(r.selected == true) {
//this.renderer.setElementStyle(this.noavail.nativeElement, 'display', 'none');
let storageRef = firebase.storage().ref().child('/settings/' + userName + '/profilepicture.png');
let obj = {'pic':"", 'salon': userName, 'time': r.time};
storageRef.getDownloadURL().then(url => {
console.log(url + "in download url !!!!!!!!!!!!!!!!!!!!!!!!");
obj.pic = url;
this.availabilities.push(obj);
console.log(JSON.stringify(this.availabilities));
resolve();
}).catch((e) => {
console.log("in caught url !!!!!!!$$$$$$$!!");
obj.pic = 'assets/blankprof.png';
this.availabilities.push(obj);
console.log(JSON.stringify(this.availabilities));
resolve();
});
}
}))
}
}
}))
}
}))
//}));
Promise.all(promises).then(() => {
console.log("in load availabilities ......... ")
console.log(JSON.stringify(this.availabilities));
this.availabilities.sort(function(a,b) {
return Date.parse('01/01/2013 '+a.time) - Date.parse('01/01/2013 '+b.time);
});
console.log('*****previous******');
console.log(JSON.stringify(this.availabilities));
console.log('*****sorted********');
for(let i of this.availabilities) {
console.log(i.time + " this is itime");
let date = new Date('01/01/2013 ' + i.time);
console.log(date + " this is date in idate");
let str = date.toLocaleTimeString('en-US', { hour: 'numeric', hour12: true, minute: 'numeric' });
console.log(str);
i.time = str;
}
});
//}))
//})
}
I can tell from the log messages that the storageRef.getDownloadURL() function happens close to the end of when my page loads...this is where the objects actually get pushed to this.availabilities (eventually used to populate a list). The code in the Promise.all .then() actually fires before anything gets pushed to this.availabilities so when the sorting happens it is an empty array and nothing gets sorted.
I used a promise inside each forEach loop. I pushed all the promises to the same array and used Promise.all(array).then(...) how it is being used above - and the promises did their job - the array is sorted because everything is happening asynchronously.

Discordie Channel Switching

So I have your average Discordie node.js code, but I have no idea how to make this send messages in other channels.
The idea is, when a user requests something, it will go into a channel called requests.
var Discordie = require("discordie");
var Events = Discordie.Events;
var client = new Discordie();
client.connect({ token: "" });
client.Dispatcher.on(Events.GATEWAY_READY, e => {
console.log("Connected as: " + client.User.username);
});
client.Dispatcher.on(Events.MESSAGE_CREATE, e => {
if (e.message.content == "request")
//make this send in a request channel.
e.message.channel.sendMessage("pong");
});
var Discordie = require("discordie");
var Events = Discordie.Events;
var client = new Discordie();
client.connect({ token: "" });
client.Dispatcher.on(Events.GATEWAY_READY, e => {
console.log("Connected as: " + client.User.username);
});
client.Dispatcher.on(Events.MESSAGE_CREATE, e => {
if (e.message.content == "request")
var channels = e.message.channel.guild.textChannels;
var channel = null;
for(int i = 0; i < channels.length; i++) {
channel = channels[i];
if(channel.name == "YOUR CHANNEL NAME")
break;
}
channel.sendMessage("pong");
});

Resources