for err in ["unhandledRejection", "uncaughtException"] process.on err, console.log client = require "./client" express = require "express" fs = require "fs" { Events } = require "whatsapp-web.js" rateLimit = require "express-rate-limit" { STATUS_CODES } = require "http" { tmpdir } = require "os" v8 = require "v8" { GROUP_ID, PORT } = process.env app = express() app.set "json spaces", 4 app.set "trust proxy", ["loopback", "uniquelocal"] app.use express.json() app.use express.urlencoded extended: true app.use "/file", express.static tmpdir() app.use (req, res, next) -> time = new Date().toLocaleString "fr" param = Object.assign req.query, req.body console.log "\n[#{time}] #{req.method}: #{req.url}\n", param next() app.all "/", (_, res) -> res.json data: uptime: new Date(process.uptime() * 1e3).toUTCString().split(" ")[4], memoryUsage: process.memoryUsage(), v8HeapStats: v8.getHeapStatistics() imagineLimiter = rateLimit windowMs: 60 * 1000, max: 20 app.all "/imagine", imagineLimiter, (req, res) -> unless req.method is "GET" or req.method is "POST" res.status(405).json message: STATUS_CODES["405"] try { prompt } = Object.assign req.query, req.body unless prompt res.status(400).json message: STATUS_CODES["400"] botId = ["13135550002", "@c.us"] # Meta AI Bot filePath = "#{tmpdir()}/#{Math.random().toString(36).slice(2)}.jpg" await client.sendMessage GROUP_ID, "@#{botId[0]} imagine #{prompt}", mentions: [botId.join ""], invokedBotWid: botId.join "" client.on Events.MESSAGE_CREATE, (msg) -> # console.log msg.from, msg.author, msg.type if msg.from is GROUP_ID and msg.author is botId.join "" # console.log msg if msg.type is "image" image = await msg.downloadMedia() image = Buffer.from image.data, "base64" fs.writeFile filePath, image, (e) -> unless e client.removeAllListeners Events.MESSAGE_CREATE filePath = filePath.replace tmpdir(), "file" fileUrl = "https://#{req.hostname}/#{filePath}" res.redirect fileUrl else res.status(500).json message: String e else text = msg.body client.removeAllListeners Events.MESSAGE_CREATE res.status(400).json message: text catch e console.log e e = String e text = if e.startsWith "[object " then STATUS_CODES["500"] else e res.status(500).json message: text setImmediate () -> await client.initialize() process.nextTick () -> app.listen PORT or 7860