discord.js v13 bot uptime - discord.js

I made some bot uptime code but got an error showing 52 years ago The code is below.
const style = 'R'
const starttime = `<t:${Math.floor(client.readyAt / 1000)}` + (style ? `:${style}` : '') + '>'
client.on('messageCreate' , message=>{
if(message.content == "!uptime"){
message.reply(`uptime!\n uptime : ${starttime}`)
}
})

You are setting that outside of the event, where client.readyAt is null. When you divide null by anything except for 0, you get 0. The result would then be <t:0:R>. You could either make this a function, or set it in the event
function generateReadyTimestamp() {
return `<t:${Math.floor(client.readyAt / 1000)}` + (style ? `:${style}` : '') + '>'
}
// ...
message.reply(`uptime!\n uptime : ${generateReadyTimestamp()}`)
Or, setting it inside the callback:
client.on('messageCreate', message => {
if(message.content == "!uptime"){
const starttime = `<t:${Math.floor(client.readyAt / 1000)}` + (style ? `:${style}` : '') + '>'
message.reply(`uptime!\n uptime : ${starttime}`)
}
})

Related

DiscordJS V12 client.guilds.cache.get(...).emojis.forEach is not a function

let static = [], animated = [];
client.guilds.cache.get('911491194654175242').emojis.forEach(emoji => emoji.animated ? animated.push([emoji.id, emoji.name]) : static.push([emoji.id, emoji.name]));
console.log('Static Emojis\n');
static.forEach(emoji => console.log('<:' + emoji[1] + ':' + emoji[0] + '>'));
console.log('\nAnimated Emojis\n');
animated.forEach(emoji => console.log('<a:' + emoji[1] + ':' + emoji[0] + '>'));
This is my code for my ready event, I am trying to log all the emojis in my guild to the console to make my life easier but returns an error client.guilds.cache.get(...).emojis.forEach is not a function

Discord bot not responding to command

I'm trying to code the bot to generate a random percentage when the command !percent is used while also mentioning the user. When I use the command it doesn't seem to work but no errors pop up in the console.
if (message.content == ("!Percent" || message.content == "!percent")) {
if (message.isMemberMentioned()) {
message.isMemberMentioned.users.forEach((k, v) => {
message.channel.send( v + ' is ' + ( Math.floor(Math.random() * 100) + 1 ) + "% ! " );
})
}
}
})
I think you want
if(message.content.toLowerCase() === '!percent'){...
or..
if(['!Percent', '!percent'].includes(message.content)){...
Not
if (message.content == ("!Percent" || message.content == "!percent")) {...
Is wrong as its comparing message content, a string, to a boolean as "!Percent" will always be true.
The Message class doesn't have a #isMemberMentioned method documented (never existed??) if you want support for that edit your post with the function code. Same goes for the isMemberMentioned property on the Message class variable.

Make a command that maps arguments in a message after certain words

I want to make it so that it would grab out certain information after certain words, and stop at certain words, for example
ss!submit | WIYISD: _____ | SHIWW: _____ | WDYWTA: _____ | SPN: _____
Collect arguements after the WIYISD:, SHIWW:, WDYWTA:, and SPN: and stop at the |'s after collecting each arguement.
I just don't know where to start.
I looked at what other people did, and I tried to pull it off myself but can't figure out how.
Edit: I'd like it based off of user input, and posts it in a channel, kind of similar to the bug-bot in discord testers.
Start by splitting at the vertical bars to get each portion of the string (String.split()). Then, iterate through the substrings ("Loops and iteration") and check the start of each (String.startsWith()), dealing with the resulting arguments however you want.
const str = 'ss!submit | WIYISD: hopefully | SHIWW: this code | WDYWTA: will | SPN: help you!';
const split = str.split(' | ').slice(1); // Also removing the command portion.
const args = {};
for (let i = 0; i < split.length; i++) {
const arg = split[i];
if (arg.startsWith('WIYISD: ')) args.WIYISD = arg.replace('WIYISD: ', '');
else if (arg.startsWith('SHIWW: ')) args.SHIWW = arg.replace('SHIWW: ', '');
else if (arg.startsWith('WDYWTA: ')) args.WDYWTA = arg.replace('WDYWTA: ', '');
else if (arg.startsWith('SPN: ')) args.SPN = arg.replace('SPN: ', '');
else {
console.error('Check your syntax.'); // Send an error message instead...
break; // ...and return (illegal in this context).
}
}
console.log(args); // The result in this example is an object, not an array.
Incorporating this into your message event...
// const bot = new Discord.Client();
const prefix = 'ss!';
bot.on('message', message => {
// Stop if the author is a bot or the message doesn't start with the prefix.
if (message.author.bot || !message.content.startsWith(prefix)) return;
// This is a very crude setup. Consider a command handler to keep the code organized.
if (message.content.startsWith(`${prefix}submit `)) {
const split = message.content.split(' | ').slice(1);
const args = {};
for (let i = 0; i < split.length; i++) {
const arg = split[i];
if (arg.startsWith('WIYISD: ')) args.WIYISD = arg.replace('WIYISD: ', '');
else if (arg.startsWith('SHIWW: ')) args.SHIWW = arg.replace('SHIWW: ', '');
else if (arg.startsWith('WDYWTA: ')) args.WDYWTA = arg.replace('WDYWTA: ', '');
else if (arg.startsWith('SPN: ')) args.SPN = arg.replace('SPN: ', '');
else {
return message.channel.send(':x: Invalid syntax.')
.catch(console.error); // Make sure the catch rejected promises.
}
}
// Use 'args' as you wish.
}
});

How to add an audit log for role added, removed, and username changed in Discord.js?

For my Discord.js bot, I am attempting to create an audit log that sends messages to a specific log channel within every server it is in for user changes. I have a working 'message deleted' audit log function, but when I attempt to carry it over to role adding and deletion, usernames, nicknames, and avatar changes, the bot fails to log this and crashes. How do I fix this issue within my code?
I have included both the message delete audit log message send, and the role add/remove/username change
client.on('messageDelete', function (message) {
if (message.channel.type === 'text') {
// post in the server's log channel, by finding the accuratebotlog channel (SERVER ADMINS **MUST** CREATE THIS CHANNEL ON THEIR OWN, IF THEY WANT A LOG)
var log = message.guild.channels.find('name', CHANNEL)
if (log != null) {
log.sendMessage('**Message Deleted** ' + message.author + '\'s message: ' + message.cleanContent + ' has been deleted.')
}
}
})
// sends message when important (externally editable) user statuses change (for example nickname)
// user in a guild has been updated
client.on('guildMemberUpdate', function (guild, oldMember, newMember) {
// declare changes
var Changes = {
unknown: 0,
addedRole: 1,
removedRole: 2,
username: 3,
nickname: 4,
avatar: 5
}
var change = Changes.unknown
// check if roles were removed
var removedRole = ''
oldMember.roles.every(function (value) {
if (newMember.roles.find('id', value.id) == null) {
change = Changes.removedRole
removedRole = value.name
}
})
// check if roles were added
var addedRole = ''
newMember.roles.every(function (value) {
if (oldMember.roles.find('id', value.id) == null) {
change = Changes.addedRole
addedRole = value.name
}
})
// check if username changed
if (newMember.user.username != oldMember.user.username) {
change = Changes.username
}
// check if nickname changed
if (newMember.nickname != oldMember.nickname) {
change = Changes.nickname
}
// check if avatar changed
if (newMember.user.avatarURL != oldMember.user.avatarURL) {
change = Changes.avatar
}
// post in the guild's log channel
var log = guild.channels.find('name', CHANNEL)
if (log != null) {
switch (change) {
case Changes.unknown:
log.sendMessage('**[User Update]** ' + newMember)
break
case Changes.addedRole:
log.sendMessage('**[User Role Added]** ' + newMember + ': ' + addedRole)
break
case Changes.removedRole:
log.sendMessage('**[User Role Removed]** ' + newMember + ': ' + removedRole)
break
case Changes.username:
log.sendMessage('**[User Username Changed]** ' + newMember + ': Username changed from ' +
oldMember.user.username + '#' + oldMember.user.discriminator + ' to ' +
newMember.user.username + '#' + newMember.user.discriminator)
break
case Changes.nickname:
log.sendMessage('**[User Nickname Changed]** ' + newMember + ': ' +
(oldMember.nickname != null ? 'Changed nickname from ' + oldMember.nickname +
+newMember.nickname : 'Set nickname') + ' to ' +
(newMember.nickname != null ? newMember.nickname + '.' : 'original username.'))
break
case Changes.avatar:
log.sendMessage('**[User Avatar Changed]** ' + newMember)
break
}
}
})
I expected the bot to send a message to my channel saying 'User Role Removed: memberName + their old role', and vise versa for role adding, but my bot fails to send these messages to the bot log channel I had set up.
There is no guild parameter in a GuildMemberUpdate event. Therefore, newMember is undefined because only two parameters are passed.
client.on('guildMemberUpdate', (oldMember, newMember) => {
const guild = newMember.guild;
// continue with code
});

How do I make a command call a different command along with itself?

I don't know how to do this and I have been looking for answer but am unable to find it.
if message.content.startswith('^trivia autostart'):
await client.send_message(message.channel, "Game is starting!\n" +
str(player1) + "\n" + str(player2) + "\n" + str(player3) + "\n" +
str(player4) + "\n" + str(player5) + "\n" + str(player6) )
--
I have this code and i'm trying to make it so it when that code gets run that it calls my ^trivia play command without typing it in chat.
Is this possible?
The solution to that would be defining functions for each command you need to be called globally by your bot. Take the following example:
const Discord = require('discord.js');
const bot = new Discord.Client();
bot.on('error' => console.log);
bot.on('message', message => {
let prefix = '!';
let sender = message.author;
let msg = message.content;
let cont = msg.split(' ');
let args = cont.slice(1);
let cmd = msg.startsWith(prefix) ? cont[0].slice(prefix.length).toUpperCase() : undefined;
// Ping function
// can be: function pingCommand () {...}
let pingCommand = () => {
message.channel.send(`Pong!\nTime: ${bot.ping} ms`);
}
// Main command
if (cmd === 'PING') {
pingCommand();
}
// Calling command in another command
if (cmd === 'TEST') {
message.channel.send('Running a ping test on the bot');
pingCommand();
}
});
bot.login(token);
Hope you understand how it would work

Resources