From dcd62f3b270926151c04968cbff618df085defd6 Mon Sep 17 00:00:00 2001 From: NoLogicAlan <88591830+NoLogicAlan@users.noreply.github.com> Date: Thu, 23 Feb 2023 00:24:16 +0300 Subject: [PATCH] lessgoo adding image in embed --- commands/generate-image.js | 31 ++- generateImage.js | 16 +- index.js | 413 +++++++++++++++++++------------------ package.json | 1 + 4 files changed, 240 insertions(+), 221 deletions(-) diff --git a/commands/generate-image.js b/commands/generate-image.js index 18dd178..7e5a0bc 100644 --- a/commands/generate-image.js +++ b/commands/generate-image.js @@ -1,5 +1,6 @@ const { CommandBuilder } = require("../Commands.js"); const { ask } = require("../generateImage"); +const fetch = require('node-fetch'); module.exports = { command: new CommandBuilder() @@ -10,14 +11,30 @@ module.exports = { o.setName("prompt") .setRequired(true)), run: async function (message, data) { - const prompt = data.get("prompt").value + const prompt = data.get("prompt").value; const answer = await ask(prompt, message); - if (answer.success) { - answer.imageUrls.forEach(url => { - message.channel.sendMessage(`[Image](${url})`); + const imageUrl = answer.imageUrls[0]; // select the first URL from the array + try { + const response = await fetch(imageUrl); + const buffer = await response.buffer(); + const media = await upload.call(this, buffer, prompt); + message.channel.sendMessage({ + content: "", + embeds: [{ + title: "Image Generation", + description: "Here's your generated image:", + media, + colour: "#bb2525" + }] }); - } else { - message.channel.sendMessage(answer.error); + } catch (error) { + console.error(error); } } -} \ No newline at end of file +} + +async function upload(buffer, prompt) { + return new Promise((res, rej) => { + this.uploader.upload(buffer, `${prompt}`).then(res).catch(rej); + }); +} diff --git a/generateImage.js b/generateImage.js index dad2a4d..7ac07e4 100644 --- a/generateImage.js +++ b/generateImage.js @@ -2,7 +2,7 @@ const { Configuration, OpenAIApi } = require("openai"); const fs = require("fs"); const path = require("path"); -const API_KEY = "its ur problem"; +const API_KEY = "that ur problem"; const DEFAULT_MODEL = "image-alpha-001"; const AVAILABLE_MODELS = [ "image-alpha-001", @@ -15,7 +15,7 @@ const AVAILABLE_MODELS = [ "image-jukebox-001", ]; -const RATE_LIMIT_COUNT = 1000; +const RATE_LIMIT_COUNT = 100; const usageDataPath = path.join(__dirname, "usageData.json"); @@ -54,14 +54,14 @@ async function ask(prompt, message, model = DEFAULT_MODEL) { // Check if the user has exceeded the usage limit if (userUsage.count >= RATE_LIMIT_COUNT && now < userUsage.resetTime) { - const timeLeft = Math.ceil((userUsage.resetTime - now) / 1000); + const timeLeft = Math.ceil((userUsage.resetTime - now) / 100); throw new Error(`Usage limit reached for user ${userId}. Try again in ${timeLeft} seconds.`); } userUsage.count++; - // Check if the user has used the API 1000 times - if (userUsage.count === 1000) { + // Check if the user has used the API 100 times + if (userUsage.count === 100) { userUsage.limitReached = true; } @@ -70,7 +70,7 @@ async function ask(prompt, message, model = DEFAULT_MODEL) { saveUsageData(); if (userUsage.limitReached) { - return { success: false, error: "User" + `<@${userId}>` + "has reached 1000 API uses." }; + return { success: false, error: "User" + `<@${userId}>` + "has reached 100 API uses. want more [support](rvlt.gg/qvJEsmPt) us [images](https://autumn.revolt.chat/attachments/0s377fGbuwcX4AA0aa3b1k-HC2VDJv2YJIGScAKyeB/image.png)" }; } try { @@ -78,13 +78,13 @@ async function ask(prompt, message, model = DEFAULT_MODEL) { prompt, model, n: 1, - size: "1024x1024" + size: "512x512" }); const imageUrls = response?.data?.data?.map(({ url }) => url); return { success: true, imageUrls }; } catch (error) { console.error(error); - return { success: false, error: error.message + " or bad prompt (maybe)" }; + return { success: false, error: error.message + " or bad prompt [maybe]()" }; } } diff --git a/index.js b/index.js index de0f7df..4b921cb 100644 --- a/index.js +++ b/index.js @@ -1,206 +1,207 @@ -// TODO: rename to index.js -const { CommandHandler } = require("./Commands.js"); -const { Client } = require("revolt.js"); -const path = require("path"); -const fs = require("fs"); -const { SettingsManager } = require("./settings/Settings.js"); -require('console-stamp')(console, '[HH:MM:ss.l]'); - -let config; -if (fs.existsSync("./config.json")) { - config = require("./config.json"); -} else { - config = { - token: process.env.TOKEN - }; -} - -class Chatgpt { - constructor() { - this.client = new Client(); - this.client.config = config; - this.config = config; - this.presenceInterval = config.presenceInterval || 7000; - - this.observedUsers = new Map(); - - this.settingsMgr = new SettingsManager(); - this.settingsMgr.loadDefaultsSync("./storage/defaults.json"); - - this.client.on("ready", () => { - console.log("Logged in as " + this.client.user.username); - }); - this.client.once("ready", () => { - let state = 0; - let texts = config.presenceContents || ["Ping for prefix", "By RedTech | NoLogicAlan", "Servers: $serverCount"] - setInterval(() => { - this.client.users.edit({ - status: { - text: texts[state].replace(/\$serverCount/g, this.client.servers.size), - presence: "Online" - }, - }); - if (state == texts.length - 1) {state = 0} else {state++} - }, this.presenceInterval); - }); - this.client.on("message", (m) => { - if (!this.observedUsers.has(m.author_id + ";" + m.channel_id)) return; - this.observedUsers.get(m.author_id + ";" + m.channel_id)(m); - }); - - this.handler = new CommandHandler(this.client, config.prefix); - this.handler.setReplyHandler((t, msg) => { - msg.reply(this.em(t, msg), false); - }); - this.handler.addOwners(...this.config.owners); - this.handler.setRequestCallback((...data) => this.request(...data)); - this.handler.setOnPing(msg => { - let pref = this.handler.getPrefix(msg.channel.server_id); - let m = this.iconem(msg.channel.server.name, "My prefix in this server is: `" + pref + "`", (msg.channel.server.icon) ? "https://autumn.revolt.chat/icons/" + msg.channel.server.icon._id : null, msg); - msg.reply(m, false) - }); - const dir = path.join(__dirname, "commands"); - const files = fs.readdirSync(dir).filter(f => f.endsWith(".js")); - this.runnables = new Map(); - - // load command files - files.forEach(commandFile => { - const file = path.join(dir, commandFile); - const cData = require(file); - const builder = (typeof cData.command == "function") ? cData.command.call(this) : cData.command; - if (cData.export) this[cData.export.name] = cData.export.object; - this.handler.addCommand(builder); - if (cData.run) { - this.runnables.set(builder.uid, cData.run); - builder.subcommands.forEach(sub => { - this.runnables.set(sub.uid, cData.run); - }); - } - }); - this.handler.on("run", (data) => { - if (this.runnables.has(data.command.uid)) { - this.runnables.get(data.command.uid).call(this, data.message, data); - } - }); - - if (process.argv[2] == "usage") { - fs.writeFile("cmdUsage.md", this.handler.generateCommandOverviewMD(),()=>{ console.log("Done!"); process.exit(1) }); - } else if (process.argv[2] == "sreload") { - this.settingsMgr.syncDefaults(); // updates all guilds if they are missing defaults - this.settingsMgr.save(); - } - - try { - this.comHash = require('child_process') - .execSync('git rev-parse --short HEAD', {cwd: __dirname}) - .toString().trim(); - this.comHashLong = require('child_process') - .execSync('git rev-parse HEAD', {cwd: __dirname}) - .toString().trim(); - } catch(e) { - console.log("Git comhash error"); - this.comHash = "Newest"; - this.comHashLong = null; - } - - this.comLink = (this.comHashLong) ? "https://github.com/NoLogicAlan/ChatGPT/tree/" + this.comHashLong : "https://github.com/NoLogicAlan/ChatGPT"; - this.playerMap = new Map(); - this.currPort = -1; - this.channels = []; - this.freed = []; - - this.client.loginBot(config.token); - - return this; - } - request(d) { - switch(d.type) { - case "prefix": - return this.settingsMgr.getServer(d.data.channel.server_id).get("prefix"); - } - } - getSettings(message) { - const serverId = message.channel.server_id; - return this.settingsMgr.getServer(serverId); - } - observeUser(id, channel, cb) { - this.observedUsers.set(id + ";" + channel, cb); - return id + ";" + channel; - } - unobserveUser(i) { - return this.observedUsers.delete(i); - } - embedify(text = "", color = "#e9196c") { - return { - type: "Text", - description: "" + text, // convert bools and numbers to strings - colour: color, - } - } - em(text, msg) { // embedMessage - return { - content: " ", - embeds: [this.embedify(text)] - } - } - iconem(title, text, img, m) { - let e = this.embedify(text); - e.icon_url = img; - e.title = title; - return { - content: " ", - embeds: [e], - masquerade: this.masquerade(m) - } - } - isNumber(n) { - return !isNaN(n) && !isNaN(parseFloat(n)); - } - prettifyMS(milliseconds) { - const roundTowardsZero = milliseconds > 0 ? Math.floor : Math.ceil; - - const parsed = { - days: roundTowardsZero(milliseconds / 86400000), - hours: roundTowardsZero(milliseconds / 3600000) % 24, - minutes: roundTowardsZero(milliseconds / 60000) % 60, - seconds: roundTowardsZero(milliseconds / 1000) % 60, - milliseconds: roundTowardsZero(milliseconds) % 1000, - microseconds: roundTowardsZero(milliseconds * 1000) % 1000, - nanoseconds: roundTowardsZero(milliseconds * 1e6) % 1000 - }; - - const units = { - days: "d", - hours: "h", - minutes: "m", - seconds: "s" - } - - var result = ""; - for (let k in parsed) { - if (!parsed[k] || !units[k]) continue; - result += " " + parsed[k] + units[k]; - } - return result.trim(); - } -} - -new Chatgpt(); - -// God, please forgive us, this is just to keep the bot online at all cost -process.on("unhandledRejection", (reason, p) => { - console.log(" [Error_Handling] :: Unhandled Rejection/Catch"); - console.log(reason, p); -}); -process.on("uncaughtException", (err, origin) => { - console.log(" [Error_Handling] :: Uncaught Exception/Catch"); - console.log(err, origin); -}); -process.on("uncaughtExceptionMonitor", (err, origin) => { - console.log(" [Error_Handling] :: Uncaught Exception/Catch (MONITOR)"); - console.log(err, origin); -}); -process.on("multipleResolves", (type, promise, reason) => { - console.log(" [Error_Handling] :: Multiple Resolves"); - console.log(type, promise, reason); -}); +// TODO: rename to index.js +const { CommandHandler } = require("./Commands.js"); +const { Client } = require("revolt.js"); +const path = require("path"); +const fs = require("fs"); +const { SettingsManager } = require("./settings/Settings.js"); +require('console-stamp')(console, '[HH:MM:ss.l]'); +const Uploader = require("revolt-uploader"); + +let config; +if (fs.existsSync("./config.json")) { + config = require("./config.json"); +} else { + config = { + token: process.env.TOKEN + }; +} + +class Chatgpt { + constructor() { + this.client = new Client(); + this.client.config = config; + this.config = config; + this.presenceInterval = config.presenceInterval || 7000; + this.uploader = new Uploader(this.client); + + this.observedUsers = new Map(); + + this.settingsMgr = new SettingsManager(); + this.settingsMgr.loadDefaultsSync("./storage/defaults.json"); + + this.client.on("ready", () => { + console.log("Logged in as " + this.client.user.username); + }); + this.client.once("ready", () => { + let state = 0; + let texts = config.presenceContents || ["Ping for prefix", "By RedTech | NoLogicAlan", "Servers: $serverCount"] + setInterval(() => { + this.client.users.edit({ + status: { + text: texts[state].replace(/\$serverCount/g, this.client.servers.size), + presence: "Online" + }, + }); + if (state == texts.length - 1) {state = 0} else {state++} + }, this.presenceInterval); + }); + this.client.on("message", (m) => { + if (!this.observedUsers.has(m.author_id + ";" + m.channel_id)) return; + this.observedUsers.get(m.author_id + ";" + m.channel_id)(m); + }); + + this.handler = new CommandHandler(this.client, config.prefix); + this.handler.setReplyHandler((t, msg) => { + msg.reply(this.em(t, msg), false); + }); + this.handler.addOwners(...this.config.owners); + this.handler.setRequestCallback((...data) => this.request(...data)); + this.handler.setOnPing(msg => { + let pref = this.handler.getPrefix(msg.channel.server_id); + let m = this.iconem(msg.channel.server.name, "My prefix in this server is: `" + pref + "`", (msg.channel.server.icon) ? "https://autumn.revolt.chat/icons/" + msg.channel.server.icon._id : null, msg); + msg.reply(m, false) + }); + const dir = path.join(__dirname, "commands"); + const files = fs.readdirSync(dir).filter(f => f.endsWith(".js")); + this.runnables = new Map(); + + // load command files + files.forEach(commandFile => { + const file = path.join(dir, commandFile); + const cData = require(file); + const builder = (typeof cData.command == "function") ? cData.command.call(this) : cData.command; + if (cData.export) this[cData.export.name] = cData.export.object; + this.handler.addCommand(builder); + if (cData.run) { + this.runnables.set(builder.uid, cData.run); + builder.subcommands.forEach(sub => { + this.runnables.set(sub.uid, cData.run); + }); + } + }); + this.handler.on("run", (data) => { + if (this.runnables.has(data.command.uid)) { + this.runnables.get(data.command.uid).call(this, data.message, data); + } + }); + + if (process.argv[2] == "usage") { + fs.writeFile("cmdUsage.md", this.handler.generateCommandOverviewMD(),()=>{ console.log("Done!"); process.exit(1) }); + } else if (process.argv[2] == "sreload") { + this.settingsMgr.syncDefaults(); // updates all guilds if they are missing defaults + this.settingsMgr.save(); + } + + try { + this.comHash = require('child_process') + .execSync('git rev-parse --short HEAD', {cwd: __dirname}) + .toString().trim(); + this.comHashLong = require('child_process') + .execSync('git rev-parse HEAD', {cwd: __dirname}) + .toString().trim(); + } catch(e) { + console.log("Git comhash error"); + this.comHash = "Newest"; + this.comHashLong = null; + } + + this.comLink = (this.comHashLong) ? "https://github.com/NoLogicAlan/Chatgpt/tree/" + this.comHashLong : "https://github.com/NoLogicAlan/Chatgpt"; + this.playerMap = new Map(); + this.currPort = -1; + this.channels = []; + this.freed = []; + + this.client.loginBot(config.token); + + return this; + } + request(d) { + switch(d.type) { + case "prefix": + return this.settingsMgr.getServer(d.data.channel.server_id).get("prefix"); + } + } + getSettings(message) { + const serverId = message.channel.server_id; + return this.settingsMgr.getServer(serverId); + } + observeUser(id, channel, cb) { + this.observedUsers.set(id + ";" + channel, cb); + return id + ";" + channel; + } + unobserveUser(i) { + return this.observedUsers.delete(i); + } + embedify(text = "", color = "#e9196c") { + return { + type: "Text", + description: "" + text, // convert bools and numbers to strings + colour: color, + } + } + em(text, msg) { // embedMessage + return { + content: " ", + embeds: [this.embedify(text)] + } + } + iconem(title, text, img, m) { + let e = this.embedify(text); + e.icon_url = img; + e.title = title; + return { + content: " ", + embeds: [e], + } + } + isNumber(n) { + return !isNaN(n) && !isNaN(parseFloat(n)); + } + prettifyMS(milliseconds) { + const roundTowardsZero = milliseconds > 0 ? Math.floor : Math.ceil; + + const parsed = { + days: roundTowardsZero(milliseconds / 86400000), + hours: roundTowardsZero(milliseconds / 3600000) % 24, + minutes: roundTowardsZero(milliseconds / 60000) % 60, + seconds: roundTowardsZero(milliseconds / 1000) % 60, + milliseconds: roundTowardsZero(milliseconds) % 1000, + microseconds: roundTowardsZero(milliseconds * 1000) % 1000, + nanoseconds: roundTowardsZero(milliseconds * 1e6) % 1000 + }; + + const units = { + days: "d", + hours: "h", + minutes: "m", + seconds: "s" + } + + var result = ""; + for (let k in parsed) { + if (!parsed[k] || !units[k]) continue; + result += " " + parsed[k] + units[k]; + } + return result.trim(); + } +} + +new Chatgpt(); + +// God, please forgive us, this is just to keep the bot online at all cost +process.on("unhandledRejection", (reason, p) => { + console.log(" [Error_Handling] :: Unhandled Rejection/Catch"); + console.log(reason, p); +}); +process.on("uncaughtException", (err, origin) => { + console.log(" [Error_Handling] :: Uncaught Exception/Catch"); + console.log(err, origin); +}); +process.on("uncaughtExceptionMonitor", (err, origin) => { + console.log(" [Error_Handling] :: Uncaught Exception/Catch (MONITOR)"); + console.log(err, origin); +}); +process.on("multipleResolves", (type, promise, reason) => { + console.log(" [Error_Handling] :: Multiple Resolves"); + console.log(type, promise, reason); +}); diff --git a/package.json b/package.json index 6e84693..f555aa0 100644 --- a/package.json +++ b/package.json @@ -4,6 +4,7 @@ "console-stamp": "^3.1.0", "fs": "^0.0.1-security", "https": "^1.0.0", + "node-fetch": "^2.6.9", "openai": "^3.1.0", "path": "^0.12.7", "revolt-uploader": "^1.1.0",