cidlookup/index.js
2024-12-08 19:14:30 -07:00

93 lines
2.7 KiB
JavaScript

require("dotenv").config()
const Discord = require("discord.js")
const Client = new Discord.Client({
intents: [
"DirectMessages"
]
})
const {
REST,
Routes
} = require('discord.js');
const rest = new REST({
version: '10'
}).setToken(process.env.TOKEN);
const axios = require("axios");
const jsondb = require("node-json-db")
const db = new jsondb.JsonDB(new jsondb.Config("cache", true, true, "/", true))
db.push
const commands = [
{
name: "lookup",
description: "Lookup a CallerID",
contexts: [0, 1, 2],
integration_types: [0, 1],
options: [
{
name: "number",
description: "The number to look up (11 digit US only!)",
type: 4,
required: true
},
{
name: "show",
description: "Whether to show the response to everyone or not.",
type: 5
}
]
}
]
Client.on("ready", async () => {
console.log(`Logged in as ${Client.user.displayName}`);
await (async () => {
try {
//Global
console.log(`Registering global commands`);
await rest.put(Routes.applicationCommands(Client.user.id), { body: commands })
} catch (error) {
console.error(error);
}
})();
})
Client.on("interactionCreate", async (interaction) => {
switch(interaction.type) {
case Discord.InteractionType.ApplicationCommand:
let show = !interaction.options.getBoolean("show");
if (show == null) show = true;
let number = interaction.options.getInteger("number")
if (!/^\d{11}$/.test(number)) return interaction.reply({ephemeral: true, content: "<:invalid:1305271064993071185> That's not a valid number! (11 digit US only)"});
if (await db.exists(`/cache/${number}`)) {
cached = await db.getData(`/cache/${number}`);
} else {
cached = {}
}
if (!cached.cnam || new Date() > new Date(cached?.expires)) {
// Old, get from API
interaction.reply({ephemeral: show, content: `<:checking:1305271116134092842> Looking up \`${number}\``}).then(() => {
axios.get(process.env.API_URL.replaceAll("%n", number)).then((response) => {
db.push(`/cache/${number}`, {
timestamp: new Date(),
expires: new Date(new Date().getTime() + 7 * 24 * 60 * 60 * 1000),
cnam: response.data
});
interaction.editReply({ephemeral: show, content: `<:success:1305271084806963220> CNAM for \`${number}\` is \`${response.data}\``})
}).catch((err) => {
interaction.editReply({ephemeral: show, content: `<:server_error:1305271074551758868> There was a server error when trying to get that!`})
})
});
} else {
// Spit out cached version
interaction.reply({ephemeral: show, content: `<:cached:1305276187966443612> CNAM for \`${number}\` is \`${cached.cnam}\`\n-# This was cached <t:${Math.floor(cached.timestamp / 1000)}:f>`})
}
break;
}
});
Client.login(process.env.TOKEN)