Bot welcome message embed - bots

I'm trying to make the bot display an embed, when a user joins with some user information.
I was able to get the username, avatar and the total guild members.
Problem is when I use .addField('Date Joined', member.user.createdAt, true) it indeed shows the date, but it is formatted like this:
Date Joined Mon Nov 26 2018 19:11:11 GMT-0500 (Eastern Standard Time)
How could I only show the date and simplified time e.g.
mm: dd: yyyy HH: MM
const Discord = require('discord.js');
const client = new Discord.Client();
const auth = require('./auth.json');
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
// Create an event listener for new guild members
client.on('guildMemberAdd', member => {
// Send the message to a designated channel on a server:
const channel = member.guild.channels.find(ch => ch.name === 'join-leaves');
// Do nothing if the channel wasn't found on this server
if (!channel) return;
// Send the message, mentioning the member
let embed = new Discord.RichEmbed()
.setTitle("Welcome")
.setAuthor(`${member.user.tag} Has Joined.`, member.user.displayAvatarURL,)
.setThumbnail(member.user.displayAvatarURL)
.addField('Date Joined', member.user.createdAt, true)
.addField('Total Members', member.guild.memberCount, true)
channel.send(embed);
});
client.login(auth.token);

You could try with the npm package dateformat and add this to your code :
var dateFormat = require('dateformat');
.addField('Date Joined', dateFormat(member.user.createdAt, "mm:dd:yyyy h:MM"), true)
Or try with toLocaleDateString

Related

How do I forward messages posted on different server to mine using discord.js?

I'm creating a bot on my server, I just need some kind of direction on how to do it or if its even possible.
The bot function is to copy the message that's being posted in different server and post it into my own server. Bare in mind that the bot is only on my server.
The code below forwards the message from text channel to another text channel in my own server. The main objective is to forward a message from different server into mine.
const Discord = require('discord.js');
const client = new Discord.Client();
const token = 'ODA3MjAyOD456ODE3NzU2Njcz.4GFDFHA.8MHQ9ZaGSFFFEDSJZQSgv-wB84'; //fake token
client.once('ready', () => {
console.log('The bot is online!');
});
client.on('message', message => {
if (message.channel.type != 'text' || message.author.bot || !message.content.startsWith('*'))
return;
if (message.content === '*pp') {
let channel = client.channels.cache.get('80565937858574763'); // gets the message from this channel
channel.messages.fetch({ limit: 1 }).then(messages => {
let lastMessage = channel.lastMessage.content;
const marketnews = client.channels.cache.get('807577438839489436096'); //sends it to this text channel
marketnews.send(lastMessage);
})
}
});
client.login(token);
Disclaimer: Channel ID and Token are examples and not real.
its pretty easy, if message guild id is not your server id then it will send that message with information to your server text channel.
client.on("message", async (message) => { //Message Event
if (message.guild.id != "YOUR GUILD ID") { //If Guild ID Is Not Your Guild ID
const Channel = client.channels.cache.get("GUILD LOG MESSAGE CHANNEL ID"); //Finding Log Channel With ID
if (!Channel) return console.log("No Channel Found To Log!"); //If No Channel
const Embed = new Discord.MessageEmbed() //New Embed
.setColor("RANDOM") //Setting Color
.setTitle("New Message") //Setting Title
.setDescription(`Author - ${message.author.username} (${message.author.id})\nGuild - ${message.guild.name} (${message.guild.id})\nMessage -\n${message.content}`) //Description
.setTimestamp(); //Timestamp
return Channel.send(Embed); //Sending Embed To Channel
};
});
Links:
Guild#id
MessageEmbed

How to code a bot to send a message if they ping the owner

I am trying to make a bot say a message when the owner is pinged, a bit like this.
User: #JetSamsterGaming please respond.
Bot: (deletes message) #User You cannot ping JetSamsterGaming!
Thanks!
The Message has a property called mentions (MessageMentions) which contains all the mentions (roles, channels, members, users).
You can use MessageMentions.has() to check if the owner was mentioned in the message.
const Discord = require("discord.js");
const client = new Discord.Client();
const ownerId = "ID";
client.on("message", async message => {
if (message.author.bot) return false;
if (message.mentions.has(ownerId)) {
await message.delete();
message.reply(`You cannot ping my owner!`);
};
});
client.login(process.env.DISCORD_AUTH_TOKEN);
//setup stuff
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
//real code
client.on('message', msg => { //when a message is sent
if(msg.content.includes("<#!id>")){//checks if they pinged the owner.
// you can get the id by right-clicking the profile and copy id. you will need to turn on developer mode
msg.channel.send('You cannot ping that user');
msg.delete() //deletes the message
}
});
client.login('id');

Discord bot send birthday message

I have made a Discord bot and I want it to be able to check the current date, and if current date is any of the users birthday, then it'll tag them and say happy birthday. I have tried using Node.js' Date, like
if(Date === "this or that")
but that didn't seem to work. So what I need help with is:
Checking the current date (like run a check each day or something)
send a message at that current date
I'll probably just hardcode all the birthdays in since we're not that many (I know that's not good practice, but I just want it working for now, I can polish it later)
If anyone could help me with that, that'd be great.
This is what my index.js file looks like (if that is relevant):
const discord = require("discord.js");
const config = require("./config.json");
const client = new discord.Client();
const prefix = '>';
const fs = require('fs');
const { time, debug } = require("console");
client.commands = new discord.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for(const file of commandFiles)
{
const command = require(`./commands/${file}`)
client.commands.set(command.name, command);
}
client.once('ready', () =>
{
console.log(`${client.user.username} is online`);
})
client.on('message', message =>
{
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ + /);
const command = args.shift().toLowerCase();
if(command === 'ping')
{
client.commands.get('ping').execute(message, args);
}else if(command === 'wololo')
{
client.commands.get('wololo').execute(message, args);
}
})
client.login('TOKEN')
Edit:
I realise I wrote the "if(date)" statement in "client.on('message',message =>{})", so that obviously wouldn't check unless you wrote a command at that specific time. What function would I use?
You can check the full list of Discord.js events here.
There are no built in events in Discord.js that are fired based on scheduled time.
In order to do that, you could build a time system that fires events every single day based on a timeout out or interval. Or... you could use a library, like node-cron that do this for you.
I'll try to exemplify a way you could do this using the just said node-cron.
First, you'll have to require the node-cron package, thus you can use npm just as you did with discord.js itself. So paste and execute this command on your terminal:
npm install node-cron
Unfortunately, Discord.js doesn't offer a way for you to get the birthday date of the user. So, hard coding the birthdays (as you stated that it's okay) and also, for this example, the general channel Id that you'll send the message of the congratulations, you could something like this:
const Discord = require('discord.js');
const cron = require('node-cron');
const client = new Discord.Client();
// Hard Coded Storing Birthdays in a Map
// With the key beeing the user ID
// And the value a simplified date object
const birthdays = new Map();
birthdays.set('User 1 Birthday Id', { month: 'Jan', day: 26 });
birthdays.set('User 2 Birthday Id', { month: 'Jun', day: 13 });
birthdays.set('User 3 Birthday Id', { month: 'Aug', day: 17 });
const setSchedules = () => {
// Fetch the general channel that you'll send the birthday message
const general = client.channels.cache.get('Your General Channels Id Go Here');
// For every birthday
birthdays.forEach((birthday, userId) => {
// Define the user object of the user Id
const user = client.users.cache.get(userId);
// Create a cron schedule
cron.schedule(`* * ${birthday.day} ${birthday.month} *`, () => {
general.send(`Today's ${user.toString()} birthday, congratulations!`);
});
});
};
client.on('ready', setSchedules);
client.login('Your Token Goes Here');
This is not optimized an intends to just give a general idea of how you can do it. Notice though that the client should be instantiated before you set the tasks, so I'd recommend doing it like this example and setting the schedule on ready.
Anyway, you could always use an already created and tested bot such as Birthday Bot.

How to get all the mentions from an user in a channel discord.js

So, I'm trying to create a simple bot that when the user writes:
!howmanypoints {user}
It should just go to a specific channel, and search how many times it was mentioned in the specific channel.
As of now, I encountered the function fetchMentions() but it seems deprecated and the API doesn't like it when a bot tries to do this..
Any input or at least a better approach for this. Maybe I'm fixated with making it work.
const Discord = require('discord.js')
const client = new Discord.Client()
client.on('message', msg => {
if (msg.content.includes('!howmanypoints') || msg.content.includes('!cuantospuntos')) {
const canal_de_share = client.channels.find('name', 'dev')
const id_user = client.user.id
client.user.fetchMentions({guild: id_user })
.then(console.log)
.catch(console.error);
}
})
ClientUser.fetchMentions() is deprecated, and only available for user accounts.
As an alternative, you could fetch all the messages of the channel and iterate over each, checking for mentions.
Example:
let mentions = 0;
const channel = client.channels.find(c => c.name === 'dev');
const userID = client.user.id;
channel.fetchMessages()
.then(messages => {
for (let message of messages) {
if (message.mentions.users.get(userID)) mentions++;
}
console.log(mentions);
})
.catch(console.error);

Values get overwritten by latest person to request the bot?

I have made a raffle ballot discord bot that allows a user to DM the bot their name and raffle entry amount. Once they have set the values they can start the entry of the raffle by DMing !enter. Once this has happend a function is called which then starts a for-loop the for loop will run based on the specified entry amount. I have also added in a delay within the for-loop due to the service to get the raffle tickets takes some time (Code is edited for SO Post due to sensitive API info)
Once this is complete it then sends a DM back to the user that had DMed the bot originally. The problem I am facing is that if multiple users DM at the same time or while it is running from the first DM the variables get overwritten by the latest person requesting the bot.
I assumed that by using a Discord.js bot each time a user DMs it creates a new instance of the script or node process?
Is it possible for the function that the bot calls once DMed to create a new process within the main node process so it doesn't get overwritten?
const Discord = require('discord.js');
const botconfig = require('./discordBotConfig.json');
const bot = new Discord.Client({disableEveryone: true});
const c = require('chalk');
// Chalk Theme
const ctx = new c.constructor({level: 2});
const error = c.red;
const waiting = c.magenta;
const success = c.green;
const discordBot = c.yellow;
// Current Raffles (API Link Later)
let activeRaffles = 'Raffle 1';
// User Parmas
let usrName = '';
let entryAmount = 0;
// Ticket
let raffleTicket = [];
let retryDelay = 3000;
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Enter
const enterIn = async () => {
console.log('User name', usrName);
raffleTicket.push(Math.random(0, 50));
}
// Init Raffle Entry
const raffleInit = async (entryAmount) => {
for (let i = 0; i < entryAmount; i++) {
enterIn();
await sleep(retryDelay);
}
dmUser();
}
const dmUser = () => {
// Discord Message Complete
let botCompleteMsg = new Discord.RichEmbed()
.setTitle('Finished!')
.setColor('#25E37A')
.addField('Name: ', usrName)
.addField('Tickets: ', raffleTicket)
.addField('Last Update: ', bot.user.createdAt);
bot.fetchUser(userID).then((user) => {
user.send(botCompleteMsg);
});
return; // End the application
}
// Discord Bot Setup
bot.on('ready', async () => {
console.log(discordBot(`${bot.user.username} is Online!`));
bot.user.setActivity('Entering Raffle');
});
bot.on('message', async message => {
if (message.channel.type === 'dm') {
let prefix = botconfig.prefix;
let messageArray = message.content.split(' ');
let cmd = messageArray[0];
if (cmd === `${prefix}name`) {
if (messageArray.length === 3) {
userID = message.author.id;
usrName = messageArray[1];
entryAmount = messageArray[2];
// Raffle summary
let raffleSummary = new Discord.RichEmbed()
.setTitle('Entry Summary')
.setColor('#8D06FF')
.addField('Name: ', usrName)
.addField('Entry Amount: ', entryAmount)
return message.author.send(raffleSummary), message.author.send('Type **!start** to begin entry or type **!set** again to set the entry details again.');
}
}
if (cmd === `${prefix}enter`) {
// Raffle summary
let startMessage = new Discord.RichEmbed()
.setTitle('Entering raffle!')
.setDescription('Thanks for entering! :)')
.setColor('#8D06FF')
return message.author.send(startMessage), raffleInit(entryAmount);
}
}
});
bot.login(botconfig.token);
You can store your user data in a list with classes.
var userData = [
{name: "sample#0000", entryNum: 0}
];

Resources