Creating a Reminder Discord Bot (Discord.js) - javascript

I am writing my first Discord bot and I am fairly new to JavaScript, especially dealing with libraries such as Discord.JS. My project here is a Reminder Discord bot, which takes a user input by prefix, stores and checks data based on time, then outputs a user inputted message when the user time set is the same as current time (to alert).
My current issue is that I don't know how to send a message to a discord channel using the client outside of the two specificed scopes. Ideally, I'd like to send a message between
if (userTime === machineTime) {
console.log("Reminder!");
clearInterval();
}
Thank you
const { Client, GatewayIntentBits, EmbedBuilder, PermissionsBitField, Permissions } = require(`discord.js`);
const { type } = require("os");
const prefix = '!';
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent] });
var machineTime = null;
var userTime = null;
// Discord Client Ready Check
client.on("ready", () => {
console.log("Bot is online!")
})
// Message Listener
client.on("messageCreate", (message) => {
if (message.author.bot) return;
//Split input into array & get current date
var content = message.content.split(" ");
console.log(content);
// Output
if (content[0] === prefix + 'set-reminder'){
//Start timer
setInterval(checkTime, 1000);
//Convert user time
var inputTime = content[2].split(':');
var inputDate = content[1].split('/');
//Change store metrics and format date
var convertMinutes = parseInt(inputTime[1]);
var convertHours = parseInt(inputTime[0]);
var convertMonth = parseInt(inputDate[0]);
var convertDay = parseInt(inputDate[1]);
var formatDate = convertMonth + "/" + convertDay + "/" + inputDate[2];
//If PM add 12 hours to time input
if (content[3].toLowerCase() === "pm") {
convertHours += 12;
}
userTime = formatDate + " " + convertHours + " " + convertMinutes;
//Send reminder confirmation
message.channel.send("Members will be alerted at " + content[1] + ":white_check_mark:");
}
// Input Array: 0 = prefix, 1 = date, 2 = time, 3 = am/pm, 4 = channel, 5 = message
})
//Current Time Check
const checkTime = () => {
var machineOutput = new Date();
var machineDate = machineOutput.toLocaleDateString();
var machineMinutes = machineOutput.getMinutes();
var machineHours = machineOutput.getHours();
machineTime = machineDate + " " + machineHours + " " + machineMinutes;
if (userTime === machineTime) {
console.log("Reminder!");
clearInterval();
}
console.log(machineTime);
}
client.login("MY_LOGIN_KEY");```

As long as you have access to the client, you can send a message to any channel.
if (userTime === machineTime) {
console.log("Reminder!");
clearInterval();
const channel = await client.channels.fetch('channel id');
channel.send('...');
}

Related

Multi-user login webpage with time recorder using JS

I have been working on a personal project of user check In/Out time recorder. I created the multi user login and time recorder using JS. I faced an issue to record the time of each logged in user. The code I created is only able to record the time of single user. I used localStorage command to store time because it need to be displayed every users time data on admin page. I am using single JS file for login, user page recorder and also for admin page loader. Plz help me out if anyone has any solution. I can't use server based code right now. I only have to write this web-app code in html,css and javascript.
var users= [
{user : 'user1', pass: 'pass1'},
{user : 'user2', pass: 'pass2'},
{user : 'user3', pass: 'pass3'},
{user : 'admin', pass: 'admin'}
];
function login()
{
//login page
var username = document.getElementById('uname').value;
var password = document.getElementById('psw').value;
for (var i = 0; i < users.length; i++)
{
console.log('enter the loop');
console.log("current user: ", i+1);
if (username == users[i].user && password == users[i].pass)
{
window.location.href = 'user.html';
alert("Login Successful");
break;
}
else if (i == (users.length-1))
{
alert('Login failed! Try Again');
console.log(i,'-times wrong');
}
else if (username == users[3].user && password == users[3].pass)
{
console.log('admin login');
window.location.href = 'admin.html';
break;
}
else
{
console.log('else statement');
}
}
var userId = i;
console.log("current user: ", userId);
}
//Date & Time Display
setInterval(myTimer,1000);
function myTimer()
{
const d = new Date();
document.getElementById('date').innerHTML = d.toLocaleDateString();
document.getElementById('time').innerHTML = d.toLocaleTimeString();
}
let date = document.getElementById('date');
let time = document.getElementById('time');
let newDate = new Date();
let year = newDate.getFullYear();
let month = newDate.getMonth();
let todaysDate = newDate.getDate();
let hours = newDate.getHours();
let minutes = newDate.getMinutes();
let seconds = newDate.getSeconds();
var cal = {
data : null,
sMth : 0,
sYear : 0,
init : () => {
let newDate = new Date();
cal.sDay = newDate.getDate();
cal.sMth = newDate.getMonth();
cal.hour = newDate.getHours();
cal.minutes = newDate.getMinutes();
cal.date = document.getElementById('date');
cal.data = localStorage.getItem("cal-" + cal.sDay + "-" + cal.sMth);
if (cal.data == null)
{
localStorage.setItem("cal-" + cal.sDay + "-" + cal.sMth, "{}");
cal.data = {};
console.log("cal.data: null-",cal.data);
}
else
{
cal.data = JSON.parse(cal.data);
console.log("cal.data: JSON-",cal.data);
}
},
checkIn : () => {
cal.data[cal.sDay] = cal.hour + ":" + cal.minutes;
localStorage.setItem('cal-${cal.sDay}-${cal.sMth}',JSON.stringify(cal.data));
console.log('Time:', cal.data);
}
}
window.onload = cal.init;

When I try to execute my script the console on replit just doesnt work

I am very new to Javascript so please bear with me! When I try to execute my script it doesnt respond! It just keeps dropping on to the next line waiting for me to write node index.js AGAIN. I have posted 2 images in the Imgur album, the first one is me writing node index.js and the second is me pressing enter and the response. Literally blank.
I would like some help as I feel like this is the last step to get my bot up and running! :D.
https://imgur.com/a/bRFFKKf
Here is my index.js
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const {token} = require('./token.json');
var jsonconfig = require("./config.json")
var jsonconfig,DISCORD_ID
var CMDS = jsonconfig.CMDS
var prefix = 'p!'
client.on("message", message => {
var args = message.content.split(" ")
args.forEach((a, b) => {
args[b] = a.replace("`", "")
args[b] = args[b].replace(".", "")
args[b] = args[b].replace("`", "")
args[b] = args[b].replace(`"`, "")
args[b] = args[b].replace(`'`, "")
})
var args = message.content.split(" ")
if (message.author.bot == false) {
if (message.content.startsWith("$")) {
if (message.channel.id != CMDS && message.author.id != DISCORD_ID) {
message.reply("stop using cmds here idiot. <#" + CMDS + ">")
return;
}
}
args.forEach((a, b) => {
args[b] = a.replace("`", "")
args[b] = args[b].replace(".", "")
args[b] = args[b].replace("`", "")
args[b] = args[b].replace(`"`, "")
args[b] = args[b].replace(`'`, "")
})
switch (args[0]) {
case prefix + "pois":
var id = parseInt(args[1])
if (id) {
fetch(`https://www.rolimons.com/uaid/` + id).then(res => res.text()).then(res => {
//// clog(res)
if (res != 'Uaid not found, try again later') {
var search = res,
first = 'uaid_details'
var second = `owner_list`;
var itemdat = JSON.parse(search.substring(search.indexOf(first) + first.length, search.indexOf(second)).replace(";", "").replace("=", "").replace("var", ''))
// clog(itemdat)
var search = res,
first = 'item_details'
var second = `uaid_details`;
var itemname = JSON.parse(search.substring(search.indexOf(first) + first.length, search.indexOf(second)).replace(";", "").replace("=", "").replace("var", ''))
var search = res,
first = 'owner_list'
var second = `lucky_cat_uaid`;
var owners = JSON.parse(search.substring(search.indexOf(first) + first.length, search.indexOf(second)).replace(";", "").replace("=", "").replace("var", ''))
message.reply(`Checking be patient bozo...`)
var em = new discord.messageEmbed()
.setFooter("Archs")
.setURL("https://www.rolimons.com/item/" + args[1])
.setColor("#ffc0cb")
.setThumbnail("https://www.roblox.com/thumbs/asset.ashx?width=420&height=420&assetid=" + itemdat["asset_id"])
.setTitle(`UAID ` + args[1])
.setURL(`https://www.rolimons.com/uaid/` + args[1])
.setAuthor(itemname.name, `https://www.roblox.com/thumbs/asset.ashx?width=420&height=420&assetid=` + itemdat["asset_id"])
if (itemdat.serial) {
em.addField('SERIAL', itemdat.serial)
}
em.addField('OWNER', (itemdat.owner_name || `Hidden/Deleted`))
em.addField(`Last Traded`, itemdat["updated_relative_string"])
message.reply(em)
if (itemdat["updated_relative_string"].search(`month`) != -1 || itemdat["updated_relative_string"].search(`year`) != -1) {
message.channel.send(`Since the current owner has had it for more than a month, we have deemed this uaid(${args[1]}) as CLEAN :white_check_mark:`)
} else {
comped_detected = false
Object.keys(owners).forEach(x => {
var item = owners[x][0]
if (item && parseInt(x) + 2628000 >= Date.now() / 1000) {
fetch(`https://avatar.roblox.com/v1/users/${item}/avatar`).then(res => res.json().catch(err => { })).then(avatar => {
avatar.assets.forEach(a => {
if (badassets[a.id] != undefined) {
comped_detected = true
}
})
fetch("https://inventory.roblox.com/v1/users/" + item + "/assets/collectibles?sortOrder=Asc&limit=100").then(res => res.json().catch(err => { })).then(p => {
// clog(p)
var amt = 0
if (p.data) {
p.data.forEach(l => {
amt = amt + itemdata[l.assetId][4]
})
if (amt < 5000) {
comped_detected = true
}
}
})
})
}
})
}
}
}
)}
}
}
client
.login(token)
.catch(consola.error)
});
Again sorry if this sounds very dumb, I just started Javascript (node). Oh and one more thing! I am trying for it to work on discord with a discord command. Thanks for any help.
First off, if you're using intents, I assume you're using discord.js v13. The client.on("message" in that case would be client.on("messageCreate".
You don't need to input node index.js in repl.it. Instead, go to the 3 dots on your file like below and click on "Show Hidden Files". Once you see the .replit file, go into it and write on the first line: run = "npm start". Then, go into package.json (not package-lock.json) and write the code on the other screenshot (I highlighted the code so it's easier for you to read). That should fix all your problems! If you need additional reference, I have pasted some very helpful YouTube tutorials that I definitely recommend to watch.
Tutorial - Command handler and help command
Tutorial - How to use Discord.js v13 in repl.it
Your code seems to be in the form:
const { Client, Intents } = require('discord.js');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
const {token} = require('./token.json');
var jsonconfig = require("./config.json")
var jsonconfig,DISCORD_ID
var CMDS = jsonconfig.CMDS
var prefix = 'p!'
client.on("message", message => {
// stuff
})
so basically it seems to attach some kind of listener, and then reaches the end. So it does nothing...

tmi.js How to check if user already ran a certain command

I'm working on the twich bot and I'm trying to check if specific user already ran a command. I have this piece of code:
if (message === '!iq') {
var iqNum = Math.floor(Math.random() * 200) + 1;
client.action('jimmytag', `${user['display-name']} Your IQ is ` + iqNum);
}
It just randomizes the number between 1-200. But I want it to check if user already ran it before, and print the difference. So if I type the command two times, the first time for example it will print "Your IQ is 100"; But the second time it should be "Your IQ is 150 (+50)". How can I do that?
Create an empty object (below const client)
const userIQ = {};
Code for the Twich chat command
if (message.toLowerCase() === '!iq') {
const hasIQ = userIQ.hasOwnProperty('userid');
if (hasIQ == true) {
var oldiqNum = userIQ['useriq']
var newiqNum = Math.floor(Math.random() * 200) + 1;
var iqDif = newiqNum-oldiqNum;
userIQ.useriq = newiqNum;
if(iqDif>0){
client.action(channel, `#${userstate.username} Your IQ is ` + newiqNum + `(` + `+` + iqDif + `)`);
} else {
client.action(channel, `#${userstate.username} Your IQ is ` + newiqNum + `(` + iqDif + `)`);
}
} else {
var iqNum = Math.floor(Math.random() * 200) + 1;
var userid = userstate['user-id'];
userIQ.userid = userid;
userIQ.useriq = iqNum;
client.action(channel, `#${userstate.username} Your IQ is ` + iqNum);
}
}

Show hourly weather from API using DOM

I am trying to show the hourly weather on my website from this API: https://opendata-download-metfcst.smhi.se/api/category/pmp3g/version/2/geotype/point/lon/18.1489/lat/57.3081/data.json
I have a hard time understanding the functions needed to do so. I think I need some sort of loop, but can't figure out what to put in it. This is my code so far:
export async function getWeather() {
var res = await fetch("https://opendata-download-metfcst.smhi.se/api/category/pmp3g/version/2/geotype/point/lon/18.1489/lat/57.3081/data.json");
if (res.ok)
return await res.json();
else
alert('HTTP Error: ' + res.status);
}
--My other file--
import {getWeather} from './fetch.js'
async function generate_weather() {
var jsonRes = await getWeather();
var i = 0;
if(jsonRes.timeSeries[i].validTime == timeNow())
{
document.createTextNode(jsonRes.timeSeries[i].parameters[i].values[0] + " grader");
}
}
function timeNow() {
var date = new Date();
var hours = date.getHours();
return hours;
}
generate_weather();
I tried the example below, but it didn't work. Am I missing a step?
async function generate_weather() {
var jsonRes = await getWeather();
for (let times in jsonRes.timeSeries) {
let currentTime = times.validTime;
let date = new Date(currentTime);
let currentHour = date.getHours();
for (let param in times.parameters) {
let value = param.values[0];
let unit = param.unit;
}
for (var i = 0; i == currentHour;) {
var newElement = document.createElement('h2');
var newElementText = document.createTextNode(jsonRes.timeSeries[i].times[i].parameters[0]);
newElement.appendChild(newElementText);
document.getElementById("body").appendChild(newElement);
}
}
}
generate_weather();
In response, you have two arrays one for timeseries and other for parameters inside the timeseries-
So, you will have to use loop inside the loop like this in generate_weather function -
for (let times in jsonRes.timeSeries) {
let currentTime = times.validTime;
let date = new Date(currentTime);
let currentHour = date.getHours();
for (let param in times.parameters) {
let name = param.name;
let value = param.values[0];
let unit = param.unit;
Console.log('Tempreture of ' + name + ' is ' + value + ' ' + unit); // Tempreture of t is 14.8 Cel
}
}
Above code will show the tempreture of every name per every hour, if you need to show the tempreture for any specific name then you can use if/else statement.

Having issues writing to a JSON file, after reading it (discord.js)

I've been working on a project for a friend's discord server, where I want to keep sort of a 'database' on our members, like a warning (or strike) count, their age (because we've been having issues with underage members) and some notes. I've been using tutorials as I'm pretty new to javascript, and really new to Discord.js, so, I'm not really sure on what I'm doing yet.
(to clarify, I'm not getting any errors, it's just not updating to the new file)
Here are the resources I've used:
https://www.youtube.com/watch?v=JB1rWJRafRA
https://discordjs.guide/popular-topics/collectors.html#message-collectors
https://www.youtube.com/watch?v=J2bKyv5pp-M
And my code: (sorry in advance, it's really messy)
const Discord = require('discord.js');
const fs = require('fs');
const jsonfile = require('jsonfile');
const Client = new Discord.Client();
var data = {}; //start of member activeness tracker
if (fs.existsSync('data.json')) {
data = jsonfile.readFileSync('data.json');
}
console.log("Bot Starting...");
Client.on("ready", () => console.log('ServerMgr is ready! Now managing servers!')); //bot init complete
Client.on("message", (message) => {
if (message.guild.id in data === false) {data[message.guild.id] = {} } //if new guild
const guildData = data[message.guild.id];
if (message.author.id in guildData === false) {
guildData[message.author.id] = {
username: message.author.username,
message_count: 0,
last_message: 0,
age: 0,
times_left: 0,
strikes: 0,
notes: ""
}
}
const userData = guildData[message.author.id];
userData.message_count ++
userData.last_message = Date.now();
jsonfile.writeFileSync('data.json', data)
const parts = message.content.split(' ')
if(parts[0] === ';ping') {message.reply('```SeverMgr is online!\nCurrent Ping: ' + (Math.abs(Date.now() - message.createdTimestamp))/ 100 + " ms```")}
if(parts[0] === ';read') {
if (message.mentions.members.first()) {
var user = message.mentions.users.first()
const id = user.id
const userData = guildData[id]
const lastMessage = new Date(userData.last_message)
message.channel.send("Getting data for " + user.username + "#" + user.discriminator + "...")
message.channel.send("Sent " + userData.message_count + " messages\n" +
"Last message was sent at: " + lastMessage + "\n" +
"Age: " + userData.age + "\n" +
"Times user left server: " + userData.times_left + "\n" +
"Strikes: " + userData.strikes + "\n" +
userData.notes);
} else {
message.reply("You need to mention a user to get their data!");
}
}
if(parts[0] === ';write') {
if (message.mentions.members.first()) {
var user = message.mentions.users.first();
const id = user.id;
const userData = guildData[id];
message.channel.send("What data point do you want to edit? \n Accepted responses are: \n `message count` \n `age` \n `times left` \n `strikes` \n `notes` ")
let filter = m => m.content.includes('message count' || 'age' || 'times left' || 'strikes' || 'notes') && !m.author.bot ;
let collector = new Discord.MessageCollector(message.channel, filter);
collector.on('collect', (m,col) => {
var res = "";
let mess = m.content;
console.log(mess);
if (mess == ("message count")) {res = 'message_count' }
if (mess == ("age")) {res = 'age' }
if (mess == ("times left")) {res = 'times_left' }
if (mess == ("strikes")) {res = 'strikes' }
if (mess == ("notes")) {res = 'notes' }
console.log(res);
message.channel.send("Editing " + res + "\n The current value is:");
if (res == "message count") {message.channel.send(userData.message_count) }
if (res == "age") {message.channel.send(userData.age)}
if (res == "times left") {message.channel.send(userData.times_left)}
if (res == "strikes") {message.channel.send(userData.strikes)}
if (res == "notes") {message.channel.send(userData.notes)}
collector.stop();
message.channel.send("The value currently located inside of " + res + " will be overwritten, so if you want to edit the content directly, copy the message above, and paste it into the send box.");
let filter = m => !m.author.bot;
let collector2 = new Discord.MessageCollector(message.channel, filter);
});
collector2.on('collect', m => {
var mess = m.content;
if (res === "message count") {userData.message_count = mess }
if (res == "age") {userData.age = mess}
if (res == "times left") {userData.times_left = mess}
if (res == "strikes") {userData.strikes = mess}
if (res == "notes") {userData.notes = mess}
message.channel.send("Data saved!");
console.log("Saving " + mess);
var guildData = data[message.guild.id];
var userData = guildData[message.author.id];
var pointData = userData[res];
console.log("old data");
console.log(pointData);
pointData = mess;
console.log("new data");
console.log(pointData);
jsonfile.writeFileSync('data.json', data) //HERE IS THE ISSUE
collector2.stop();
});
} else {
message.reply("You need to mention a user to edit their data!");
}
}
});
Client.login('TOKEN');
The data is stored as such:
'779904676879007744': {
username: 'SeverMgr',
message_count: 129,
last_message: 1606028233445,
age: 0,
times_left: 0,
strikes: 0,
notes: ''
Thanks for any help!
The equal sign will create a copy of your variable. If you update the new variable it won't update the value of the previous one, since it's not a reference.
Example
var x = 1
var y = x
var y = 2
---
x will still be 1
y will be 2
So in your case you could do this to update the data variable
data[message.guild.id][message.author.id][res] = mess
Instead of this, since you are updating copies and not data directly.
var guildData = data[message.guild.id]
var userData = guildData[message.author.id]
var pointData = userData[res]
pointData = mess

Categories