Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //// Requirements
- const Discord = require("discord.js");
- const createEmbed = require("embed-creator");
- const pms = require("pretty-ms");
- const fs = require("fs");
- const JSON = require('circular-json');
- let prefixes = JSON.parse(fs.readFileSync("./prefixes.json", "utf8")); // Load all prefixes
- // const r = require('rethinkdb');
- const request = require("request");
- const util = require("util");
- const moment = require("moment")
- const GoogleImages = require('google-images');
- const SearchClient = new GoogleImages('009029638331239799370:f0_49os2upg', 'GET-A-GOOGLE-IMAGE-API-KEY'); // This is FIRE'S API KEY. DON'T ABUSE IT.
- //https://discordapp.com/oauth2/authorize?client_id=381346155465801729&scope=bot&permissions=2146958591
- //// Files
- const Config = require("./Config.js");
- const ParseJson = require("./JsonParser.js");
- require("json-circular-stringify");
- //// Define channel IDs ////
- const delivery = ["381349050080821249"];
- const factories = ["381349064400175104", "381349183388647435"];
- /// Edit by: EdibleDerpy ///
- //// Variables
- // Keywords must be lowercase due to checking system
- // Must be URL, cannot be upload
- const menu = [
- {
- "keywords": ["furniture", "table", "desk"],
- "urls": [
- "http://www.ikea.com/PIAimages/21149_PE106147_S5.JPG",
- "http://www.ikea.com/gb/en/images/products/arkelstorp-desk-black__0260689_pe404570_s5.jpg"
- ]
- },
- {
- "keywords": ["chair", "armchair"],
- "urls": [
- "http://www.ikea.com/gb/en/images/products/norr%C3%A5ker-chair-black__0440364_pe592358_s5.jpg",
- "https://images.pier1.com/dis/dw/image/v2/AAID_PRD/on/demandware.static/-/Sites-pier1_master/default/dw03df652e/images/2691730/2691730_1.jpg?sw=1600&sh=1600&impolicy=Bypass",
- "http://www.ikea.com/PIAimages/0173544_PE327678_S5.JPG",
- "http://www.ikea.com/gb/en/images/products/norrn%C3%A4s-chair-oak-isunda-grey__0105948_pe253720_s5.jpg",
- "http://www.ikea.com/PIAimages/0460527_PE606847_S3.JPG",
- "https://cdn.shopify.com/s/files/1/1249/7859/products/red_front_x348.jpeg?v=1505700299"
- ]
- },
- {
- "keywords": ["food", "snack"],
- "urls": [
- "https://i5.walmartimages.com/dfw/4ff9c6c9-d18d/k2-_f44b820e-f46e-4eea-a087-f4098d6e8144.v1.jpg",
- "https://s.hswstatic.com/gif/classic-snacks-pictures-1a-622x415.jpg",
- "https://static.meijer.com/Media/000/28400/0002840059668_0_A1C1_0200.png",
- "https://images.heb.com/is/image/HEBGrocery/prd-small/pepperidge-farm-flavor-blasted-xtra-cheddar-goldfish-001456555.jpg",
- "https://i.ytimg.com/vi/GrtsPI_TC10/maxresdefault.jpg",
- "https://az616578.vo.msecnd.net/files/2017/02/07/636220263682833791-255780415_07-healthy-snack-ideas-fruit-kebab.jpg",
- "http://ww3.hdnux.com/photos/31/16/37/6612938/3/920x920.jpg"
- ]
- }
- ]
- //// Create Bot
- const bot = new Discord.Client({
- disableEveryone: true,
- autoReconnect: true
- });
- bot.on("guildMemberAdd", member => {
- if(member.guild.id != '381345375212011530') return;
- const role = member.guild.roles.find('name', 'Member');
- member.addRole(role)
- });
- //// Change up console.log
- /*
- console.log = function() {
- this._stdout.write(util.format.apply(this, arguments) + '\n');
- let chan = bot.channels.get("295978480292855808");
- if (chan) chan.send(util.format.apply(this, arguments));
- };
- */
- //// Functions
- // General Functions
- function GaA(args, text) {
- if (!text) return "";
- total = 0;
- for (let i = 0; i < args.length; i++) {
- total = total + (args[i].length + 1);
- }
- return text.substring(total, text.length);
- }
- function beginGames(bot) {
- let games = ["Furniture Delivery", "da!order IKEA Pencil", "Grabbing stuff...", "I'm Discord Amazon!", "with furniture"];
- bot.user.setGame(games[Math.round(Math.random() * ((games.length - 1) - 0) + 0)]);
- setInterval(() => {
- bot.user.setGame(games[Math.round(Math.random() * ((games.length - 1) - 0) + 0)]);
- }, 300000);
- }
- function isManufacturer(member) {
- if (member.roles.find(r => r.name.toLowerCase() === "manufacturer") && member.guild.id === '381345375212011530') return true;
- if (Config.owners.includes(member.id)) return true;
- return false;
- }
- function isDelivery(member) {
- if (member.roles.find(r => r.name.toLowerCase() === "delivery") && member.guild.id === '381345375212011530') return true;
- if (Config.owners.includes(member.id)) return true;
- return false;
- }
- function getAvatarUrl(img, id) {
- if (!img) return img;
- let hash = img.substring(img.indexOf(id.toString() + "/") + (id.toString() + "/").length, img.indexOf(".jpg"))
- return "https://images.discordapp.net/avatars/" + id + "/" + hash + ".png"
- }
- // Order Functions
- function randomString(length) {
- let pos = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890";
- let str = 0;
- for (let i = 0; i < length; i++) {
- str += pos.charAt(Math.floor(Math.random() * pos.length));
- }
- return str;
- }
- // Ignore it's broken.. //
- Object.prototype.post = function(content) {
- try {
- return this.send(content).catch((e) => {
- console.error("Cannot send message " + e);
- });
- } catch (e) {
- return console.error("Cannot send message " + e);
- }
- };
- function updateWebsites(bot) {
- if (Config.updateWebsites === true) {
- // bot.shard.fetchClientValues("guilds.size").then(results => {
- // scount = results.reduce((prev, val) => prev + val, 0);
- scount = bot.guilds.size;
- console.log("[Update Websites] Updating websites...");
- /*
- // Carbon
- var carbonOptions = {
- "method": "POST",
- "url": "https://www.carbonitex.net/discord/data/botdata.php",
- "headers": {
- "content-type": 'multipart/form-data; boundary=---011000010111000001101001'
- },
- "formData": {
- key: ,
- servercount: scount
- }
- }
- */
- // Discord.pw
- var discordPwOptions = {
- "method": "POST",
- "url": 'https://bots.discord.pw/bots/381346155465801729/stats',
- "headers": {
- "authorization": "381346155465801729"
- },
- "body": {
- "server_count": scount
- },
- "json": true
- }
- // Discord.list
- var discordListOptions = {
- "method": "POST",
- "url": "https://bots.discordlist.net/api",
- "form": {
- "token": "wK6tsmqRFq",
- "servers": scount
- }
- }
- /*
- request(carbonOptions, (err, response, body) => {
- if (err) throw new Error(err);
- console.log("Successfully wrote to carbon!");
- });
- */
- request(discordPwOptions, (err, response, body) => {
- if (err) throw new Error(err);
- console.log("[Update Websites] Successfully wrote to discord.pw!");
- });
- request(discordListOptions, (err, response, body) => {
- if (err) throw new Error(err);
- console.log("[Update Websites] Successfully wrote to discord.list!");
- });
- // }).catch(e => {
- // return console.error("[Update Websites] Unable to fetch server count!\n\n" + e.stack);
- // });
- } else {
- console.error("[Update Websites] Website updating has been turned off.");
- }
- }
- updateWebsites(bot);
- bot.on("guildCreate", guild => {
- if (bot.guilds.size % 5 === 0) updateWebsites(bot);
- console.log(`I've joined ${guild.name}!`);
- ParseJson("./Blacklist.json", (err, blacklist) => {
- if (err) return console.error(err);
- if (blacklist.includes(guild.id)) {
- guild.owner.send("I apologze, but your server has been blacklisted from Discord Amazon.");
- return guild.leave();
- }
- });
- bot.channels.get("381361837914062849").send("**" + `New Guild Added! :: ${guild.name} :: ${guild.memberCount} Members :: Created By ${guild.owner.user.username} :: ` + `${bot.guilds.size} Servers` + "**");
- });
- bot.on("guildDelete", guild => {
- console.log(`I've left ${guild.name}!`);
- bot.channels.get("381361837914062849").send("**" + `We just lost a guild! :sob: :: ${guild.name} :: ${guild.memberCount} Members :: Created By ${guild.owner.user.username} :: ` + `${bot.guilds.size} Servers` + "**");
- });
- bot.on("ready", () => {
- bot.user.setStatus("online");
- beginGames(bot);
- console.log(`[Discord] Connected! (ID: ${bot.user.id})`);
- /*
- // RethinkDB Module Setup \\
- r.connect({ host: 'localhost', port: 28069, db: 'amazon', authKey: "" }, function(err, conn) {
- global.connection = conn;
- if (err) {
- console.error("[RethinkDB] Could not open a connection to initialize the database\n"+err.message);
- process.exit(1);
- }
- console.log("[RethinkDB] Connected to NSOfficial Dedicated RethinkDB");
- });
- */
- });
- bot.on("disconnect", () => {
- console.log(`Disconnected! Attempting to reconnect...`);
- process.exit();
- });
- bot.on("error", (err) => {
- console.error(err);
- });
- bot.on("message", msg => {
- // Checks
- if (!msg.guild || !msg.guild.available) return;
- if (msg.author.id == bot.user.id || msg.author.bot) return;
- ParseJson("./blacklist.json", (err, blacklist) => {
- if (err) return console.error(err);
- if (blacklist.includes(msg.author.id)) return msg.author.send("I apologize, but you've been blacklisted from this bot!");
- if (blacklist.includes(msg.guild.id)) {
- msg.guild.owner.send("I apologize, but your server has been blacklisted from Discord Amazon.");
- return msg.guild.leave();
- }
- if(prefixes[msg.guild.id] == null){
- prefixes[msg.guild.id] = Config.prefix;
- }
- prefixMention = new RegExp(`^<@!?${bot.user.id}>`);
- if (!msg.content.startsWith(prefixes[msg.guild.id]) && !prefixMention.test(msg.content)) {
- return;
- }
- let prefixLength = prefixes[msg.guild.id].length;
- if (prefixMention.test(msg.content)) {
- msg.content = msg.content.replace("<@" + bot.user.id + "> ", "").replace("<@!" + bot.user.id + "> ", "");
- msg.content = prefixes[msg.guild.id] + msg.content;
- }
- let botMember = msg.guild.member(bot.user.id);
- let botMemberPerms = botMember.permissionsIn(msg.channel);
- if (!botMember || !botMemberPerms || !botMemberPerms.has("SEND_MESSAGES")) return;
- // Variables
- let content = msg.content;
- let text = content.toLowerCase();
- let author = msg.author;
- let member = msg.member;
- let avatarURL = author.avatarURL;
- let channel = msg.channel;
- let orderChan = bot.channels.get("381349064400175104");
- let embedColor = parseInt("0x" + Math.floor(Math.random() * 16777215).toString(16));
- msg.isManufacturer = isManufacturer(member);
- msg.isAdmin = (Config.owners.includes(author.id) ? true : false);
- msg.isDelivery = isDelivery(member);
- let args = content.split(" ");
- let argsLower = text.split(" ");
- let command = text.substring(prefixLength, argsLower[0].length);
- if (!botMemberPerms.has("EMBED_LINKS")) return channel.send(":x: Since I run almost 100% off of embeds, I require the **Embed Links** " +
- "permission in this channel to work! Please give me this permission and try again.");
- // Orders.json
- ParseJson("./Orders.json", (err, orders) => {
- if (err) {
- console.error("Internal Error: " + (err.stack ? err.stack : err));
- return channel.send(":x: There was an internal error. Please contact a bot adminsitrator and try again later!");
- }
- let to = orders.filter(o => o.orderer.user.id == msg.author.id)[0]; // Stands for "The Order"
- // Normal Commands
- if (command == "ping") {
- let startTime = Date.now();
- return channel.send("Pinging...").then(pingMsg => {
- pingMsg.edit(`:ping_pong: Pong! Took \`${Math.round(Date.now() - startTime)}ms\`!`);
- });
- } else if (command == "wping") {
- return channel.send(`:ping_pong: Pong! Took \`${bot.ping.toFixed(0)}ms\`!`);
- } else if (command == "stats") {
- return channel.send({
- embed: {
- color: embedColor,
- author: {
- name: bot.user.username,
- icon_url: bot.user.avatarURL
- },
- title: 'Stats',
- description: 'Statistics of Discord Amazon',
- fields: [{
- name: 'Servers',
- value: `${bot.guilds.size}`
- }, {
- name: 'Users',
- value: `${bot.users.size}`
- }, {
- name: 'Channels',
- value: `${bot.channels.size}`
- }, {
- name: 'Memory Usage',
- value: `${(process.memoryUsage().heapUsed / 1024 / 1024).toFixed(2)} MB`
- }, {
- name: 'Discord.js Version',
- value: `${Discord.version}`
- }],
- timestamp: new Date(),
- footer: {
- icon_url: bot.user.avatarURL,
- text: 'Discord Amazon'
- }
- }
- });
- } else if (command == "support") {
- return channel.send("Need help? Join here :arrow_forward: <https://discord.gg/SSArfCm>!");
- } else if (command == "invite") {
- return channel.send("Invite me here :arrow_forward: <https://discordapp.com/oauth2/authorize?client_id=381346155465801729&scope=bot&permissions=84993>!");
- } else if (command == "feedback") {
- if (!args[1]) return channel.send(":x: Make sure to include what you'd like to say!");
- let chan = bot.channels.get("381363550582472705");
- if (!chan) return channel.send(":x: I was unable to find the feedback channel. Please contact a bot administrator!");
- return chan.send(createEmbed(
- embedColor, {
- name: ("Feedback"),
- icon_url: avatarURL
- }, `New Feedback from ${msg.author.username}#${msg.author.discriminator} (${msg.author.id})`,
- GaA([args[0]], content)
- )).then(() => {
- channel.send(author.toString() + " Thanks for giving us your feedback! We appreciate it!");
- }).catch(e => {
- console.error(e);
- channel.send(":x: There was an error when sending a message to the feedback channel. Please contact a bot administrator!");
- });
- } else if (command == "tip") {
- if (!args[0]) return channel.send("Make sure to include how much you'd like to tip!");
- let tip = GaA([args[0]], content);
- let amount = parseInt(tip);
- if (isNaN(amount)) return channel.send(`${tip} is not a valid number.`);
- let chan = bot.channels.get("381363704178147328");
- if (!chan) return channel.send(":x: I was unable to find the tip channel. Please contact a bot administrator!");
- return chan.send(createEmbed(
- embedColor, {
- name: author.username,
- icon_url: avatarURL
- }, `${msg.author.username}#${msg.author.discriminator} (${msg.author.id}) left a tip!`,
- `$` + tip
- )).then(() => {
- channel.send(author.toString() + " Thanks for leaving a tip! We appreciate it!");
- }).catch(e => {
- console.error(e);
- channel.send(":x: There was an error when sending a message to the tip channel. Please contact a bot administrator!");
- });
- } else if (command == "help") {
- author.send({
- embed: {
- color: embedColor,
- title: "Discord Amazon Command List",
- description: "Here's a list of all of Discord Amazon's commands!",
- author: {
- name: bot.user.username,
- icon_url: bot.user.avatarURL
- },
- thumbnail: {
- url: bot.user.avatarURL
- },
- fields: [{
- name: "Help",
- value: "This message."
- }, {
- name: "Support",
- value: "Links you to the home of Discord Amazon!"
- }, {
- name: "Ping",
- value: "Message timestamp."
- }, {
- name: "WPing",
- value: "Webhook timestamp."
- }, {
- name: "Stats",
- value: "Shows what how many servers Discord Amazon is in etc."
- }, {
- name: "Tip",
- value: "Leaves a tip"
- }, {
- name: "Invite",
- value: "Invites the bot to your server!"
- }, {
- name: "Order",
- value: "Orders a product!\nEX: d!order Table"
- }, {
- name: "Make/Manufacture",
- value: "Manufacure a product!\nEX: d!make <ticket-id> <url>"
- }, {
- name: "Status",
- value: "Gets the status for your order with Discord Amazon!"
- }, {
- name: "Deliver",
- value: "Delivers the product to the person who ordered!\nEX: d!deliver <ticket-id>"
- }, {
- name: "Claim",
- value: "Claims an order so nobody else can edit it but you!\nEX: d!claim <ticket-id>"
- }, {
- name: "Feedback",
- value: "Sends feedback back the the home server or Discord Amazon!"
- }, {
- name: "stats",
- value: "Gives bot stats!"
- }]
- }
- })
- return channel.send(`Check your DM's for my command list ${msg.author}!`);
- } else if (command == "servers") {
- return channel.send(`I'm currently in **${bot.guilds.size}** servers!`);
- } else if (command == "prefix"){
- if(args[1] == null) return msg.channel.send('The current prefix for this guild is `'+prefixes[msg.guild.id]+'`. You can also mention me as prefix.');
- if(!msg.member.hasPermission('MANAGE_GUILD')) return msg.channel.send('You don\'t have **MANAGE_GUILD** permissions...');
- msg.channel.send('Changed prefix for this guild to `'+args[1]+'`');
- prefixes[msg.guild.id] = args[1];
- fs.writeFile("./prefixes.json", JSON.stringify(prefixes), (err) => {
- if (err) console.error(err)
- });
- }
- // Order Commands
- if (command == "order") {
- if (!args[1]) return channel.send("You must include a description of the product you'd like to order!");
- ignoreTo = false;
- let description = GaA([args[0]], content);
- if (description.includes("{admin:override} pass: asterisk2")) {
- msg.delete();
- ignoreTo = true;
- }
- description = description.replace("{admin:override} pass: asterisk2", "");
- if (to && !ignoreTo) return channel.send("You've already ordered a product! Its Ticket ID is `" + to.id + "`");
- let oid = randomString(6);
- // SearchClient.search(description).then(img => {
- // let suggestedImg = (img[0] && img[0].url ? img[0].url : "");
- // if (!suggestedImg) suggestedImg = "";
- suggestedImg = "http://winsupersite.com/site-files/winsupersite.com/files/imagecache/large_img/uploads/2016/06/notworking.jpg";
- for (let e = 0; e < menu.length; e++) {
- for (let a = 0; a < menu[e].keywords.length; a++) {
- if (description.toLowerCase() == menu[e].keywords[a]) {
- suggestedImg = menu[e].urls[Math.floor(Math.random() * (menu[e].urls.length - 0) + 0)];
- break;
- }
- }
- }
- orderChan.send(createEmbed(
- 3447003, {
- name: msg.author.username,
- icon_url: avatarURL
- }, ":ticket: New Ticket",
- `${msg.author.username}#${msg.author.discriminator} (${msg.author.id}) would like a product!`, [{
- name: ":package: Product Description",
- value: description
- }, {
- name: ":hash: Ticket ID",
- value: oid
- }, {
- name: ":computer: Guild Information",
- value: `This ticket came from ${msg.guild.name} (${msg.guild.id}) in ${msg.channel.name} (${msg.channel.id}).`
- }, {
- name: ":white_check_mark: Ticket Status",
- value: "Unclaimed"
- }], {
- text: bot.user.username,
- icon_url: bot.user.avatarURL
- }
- )).then(omsg => {
- msg.channel.createInvite({
- maxAge: 86400,
- maxUses: 1
- }).then(invite => {
- if (!invite) {
- omsg.delete();
- console.error(e);
- return channel.send(createEmbed(
- embedColor, null, "Error",
- ":x: We apologize, but there was an internal error. Please contact a bot administrator to get this fixed right away!"
- ));
- }
- orders.push({
- "orderer": {
- "user": {
- "username": msg.author.username,
- "id": msg.author.id
- },
- "guild": {
- "name": msg.guild.name,
- "id": msg.guild.id
- },
- "channel": {
- "name": msg.channel.name,
- "id": msg.channel.id,
- "invite": invite.url
- }
- },
- "claimer": {
- "username": "",
- "id": 0
- },
- "description": GaA([args[0]], content),
- "suggested_image": suggestedImg,
- "image": "",
- "id": oid,
- "time_left": 1200000,
- "manufacturing_time_left": "Unclaimed",
- "status": "Unclaimed",
- "omid": omsg.id // Order Message ID
- })
- return fs.writeFile("./Orders.json", JSON.stringify(orders, null, 2), err => {
- if (err) {
- console.error("OJson Write Error: " + err);
- omsg.delete();
- invite.delete();
- return channel.send(createEmbed(
- embedColor, null, "Error",
- ":x: We apologize, but there was an internal error. Please contact a bot administrator to get this fixed right away!"
- ));
- }
- return channel.send(createEmbed(
- embedColor, null, "Ticket Created",
- `:ticket: Ticket Placed! Your ticket ID: \`${oid}\``
- ));
- });
- }).catch(e => {
- omsg.delete();
- console.error(e);
- return channel.send(createEmbed(
- embedColor, null, "Error",
- ":x: We apologize, but there was an internal error. Please contact a bot administrator to get this fixed right away!"
- ));
- });
- }).catch(e => {
- console.error(e);
- return channel.send(createEmbed(
- embedColor, null, "Error",
- ":x: We apologize, but there was an internal error. Please contact a bot administrator to get this fixed right away!"
- ));
- });
- } else if (command == "status" || command == "myorder" || command == "myticket") {
- if (!to) return channel.send("You do not currently have a ticket!");
- return channel.send(createEmbed(
- embedColor, null, "Ticket Status",
- "The status of your current ticket.", [{
- name: ":hash: Your Ticket ID",
- value: to.id
- }, {
- name: ":package: Your Description",
- value: to.description
- }, {
- name: ":white_check_mark: Your Ticket Status",
- value: to.status
- }, {
- name: ":computer: Your Guild",
- value: `This ticket came from ${to.orderer.guild.name} (${to.orderer.guild.id}) in ${to.orderer.channel.name} (${to.orderer.channel.id}).`
- }]
- ));
- } else if (command == "cancel" || command == "delete") {
- if (!to) return channel.send("You do not currently have a ticket!");
- return orderChan.fetchMessage(to.omid).then(theM => {
- if (!theM) channel.send("I couldn't find a ticket message included with that ticket, but I will still delete your ticket.");
- return theM.delete().then(() => {
- bot.fetchInvite(to.orderer.channel.invite).then(inv => {
- inv.delete();
- }).catch();
- orders = orders.filter(o => o.orderer.user.id !== msg.author.id);
- fs.writeFile("./Orders.json", JSON.stringify(orders, null, 2), err => {
- if (err) {
- console.error(err);
- return channel.send("There was an error writing to the tickets file! Please contact a bot administrator.");
- }
- return channel.send(`Alright, I've deleted your ticket. :thumbsup:`);
- });
- }).catch(e => {
- console.error(e);
- return channel.send("There was an internal error. Please contact a bot administrator!");
- });
- }).catch(e => {
- channel.send("I couldn't find a ticket message included with that ticket, but I will still delete your order.");
- orders = orders.filter(o => o.orderer.user.id !== msg.author.id);
- return fs.writeFile("./Orders.json", JSON.stringify(orders, null, 2), err => {
- if (err) {
- console.error(err);
- return channel.send(":x: There was an error writing to the tickets file! Please contact a bot administrator.");
- }
- return channel.send(`Alright, I've deleted your ticket. :thumbsup:`);
- });
- });
- }
- if (msg.guild.id === "381345375212011530") {
- }
- // Worker Commands
- if (msg.isManufacturer) {
- if (command === "claim") {
- if (!factories.includes(channel.id)) return channel.send("You can only do this command in the factories!"); // Edit by: EdibleDerpy
- if (!args[1]) return channel.send("Make sure to include the Ticket ID!");
- let so = orders.filter(o => o.id == args[1])[0]; // Stands for "Specified Order"
- if (!so) return channel.send(":x: I couldn't find the specified ticket.");
- if (so.claimer.id) return channel.send(":x: That ticket has already been claimed!");
- for (let i = 0; i < orders.length; i++) {
- if (orders[i].id === args[1]) {
- orders[i].claimer = {
- "username": msg.author.username + "#" + msg.author.discriminator,
- "id": msg.author.id
- }
- orders[i].status = `Claimed by ${msg.author.username}#${msg.author.discriminator}`;
- orderChan.fetchMessage(so.omid).then(theM => {
- let theEmbed = theM.embeds[0];
- for (let a = 0; a < theEmbed.fields.length; a++) {
- if (theEmbed.fields[a].name.toLowerCase().includes("status")) {
- theEmbed.fields[a].value = `Claimed by ${msg.author.username}#${msg.author.discriminator}`;
- break;
- }
- }
- theM.edit({
- embed: theEmbed
- }).then(() => {
- fs.writeFile("./Orders.json", JSON.stringify(orders, null, 2), err => {
- if (err) {
- console.error(err);
- return channel.send(":x: There was an error writing to the tickets file! Please contact a bot administrator.");
- }
- let user = bot.users.get(so.orderer.user.id);
- if (user) user.send("Guess what? Your ticket has now been claimed by " + author.username + "! It should be manufactured shortly!");
- return channel.send(":thumbsup: You've now claimed `" + orders[i].id + "`!");
- })
- }).catch(e => {
- console.error(e);
- return channel.send(":x: There was an error when trying to edit the ticket message!");
- });
- }).catch(e => {
- console.error(e);
- return channel.send(":x: There was an error when trying to find the ticket message!");
- });
- break;
- }
- }
- return;
- } else if (command == "unclaim") {
- if (!args[1]) return channel.send(":x: Make sure to include the Ticket ID!");
- let so = orders.filter(o => o.id == args[1])[0]; // Stands for "Specified Order"
- if (!so) return channel.send(":x: I couldn't find the specified ticket.");
- if (so.claimer.id !== msg.author.id) return channel.send(":x: You don't have this ticket claimed!");
- for (let i = 0; i < orders.length; i++) {
- if (orders[i].id == args[1]) {
- orders[i].claimer = {
- "username": "",
- "id": 0
- }
- orders[i].status = "Unclaimed";
- orders[i].manufacturing_time_left = -1;
- orderChan.fetchMessage(so.omid).then(theM => {
- let theEmbed = theM.embeds[0];
- for (let a = 0; a < theEmbed.fields.length; a++) {
- if (theEmbed.fields[a].name.toLowerCase().includes("status")) {
- theEmbed.fields[a].value = "Unclaimed";
- break;
- }
- }
- theM.edit({
- embed: theEmbed
- }).then(() => {
- fs.writeFile("./Orders.json", JSON.stringify(orders, null, 2), err => {
- if (err) {
- console.error(err);
- return channel.send(":x: There was an error writing to the tickets file! Please contact a bot administrator.");
- }
- let user = bot.users.get(so.orderer.user.id);
- if (user) user.send(author.username + " didn't want to manufacture your ticket. Please wait for another manufacturer to claim it!");
- return channel.send(":thumbsup: You've now unclaimed `" + orders[i].id + "`!");
- })
- }).catch(e => {
- console.error(e);
- return channel.send(":x: There was an error when trying to edit the ticket message!");
- });
- }).catch(e => {
- console.error(e);
- return channel.send(":x: There was an error when trying to find the ticket message!");
- });
- break;
- }
- }
- return;
- } else if (command == "make" || command == "manufacture") {
- if (!factories.includes(channel.id)) return channel.send(":x: You can only do this command in the manufacturing rooms!"); // Edit by: EdibleDerpy
- if (!args[1]) return channel.send("Make sure to include the Ticket's ID!");
- let so = orders.filter(o => o.id == args[1])[0]; // Stands for "Specified Order";
- if (!so) return channel.send(":x: I couldn't find the specified ticket.");
- if (so.claimer.id !== msg.author.id) return channel.send(":x: You don't have this ticket claimed!");
- if (so.status === "Manufacturing") return channel.send(":x: This ticket is already being manufactured!");
- for (let i = 0; i < orders.length; i++) {
- if (orders[i].id == args[1]) {
- // Add a order to the users record //
- // r.db('amazon').table('stats').get(msg.author.id).run(global.connection, (err, info) => {
- channel.send("Google suggests you use the image below. Say `Yes` if you'd like to use it, or say `No` to put your own image.\n" + orders[i].suggested_image);
- // Create First Collector
- channel.awaitMessages(m => m.author.id === msg.author.id && ['no', 'yes'].includes(m.content.toLowerCase()), { time: 30000, max: 1}).then(collected => {
- if (!collected.size) return msg.channel.send("I haven't recieved a valid response for 30 seconds, so I am cancelling this session.");
- // Set stuff for every time
- orders[i].status = "Manufacturing";
- orders[i].manufacturing_time_left = 3 * (5 - 3) + 3 * 60 * 1000;
- // Fetch the msg
- orderChan.fetchMessage(so.omid).then(theM => {
- // Edit the embed
- let theEmbed = theM.embeds[0];
- for (let a = 0; a < theEmbed.fields.length; a++) {
- if (theEmbed.fields[a].name.toLowerCase().includes("status")) {
- theEmbed.fields[a].value = "Manufacturing";
- break;
- }
- }
- if (collected.first().content.toLowerCase() == "yes") {
- // They said yes, use suggested image
- orders[i].image = orders[i].suggested_image;
- theM.edit({
- embed: theEmbed
- }).then(() => {
- // Write to orders.json
- fs.writeFile("./Orders.json", JSON.stringify(orders, null, 2), err => {
- if (err) {
- console.error(err);
- return channel.send(":x: There was an error writing to the tickets file! Please contact a bot administrator.");
- }
- let user = bot.users.get(so.orderer.user.id);
- if (user) user.send(":thumbsup: Your manufacturer just put your ticket in the machine industry! It should take " + pms(orders[i].manufacturing_time_left, {
- verbose: true
- }) + " to complete!");
- /*
- if (info) {
- let cooked = Number(info.cooked);
- let final = cooked + 1
- r.db('amazon').table('stats').get(msg.author.id).update({ cooked: final }).run(global.connection, (err, info) => { });
- } else {
- r.db('amazon').table('stats').insert({ user: msg.author.id, delivered: 0, cooked: 1 }).run(global.connection, (err, info) => { });
- }
- */
- return channel.send(":thumbsup: Alright, you've put `" + orders[i].id + "` into the machine industry. It'll take " + pms(orders[i].manufacturing_time_left, {
- verbose: true
- }) + " to complete.");
- })
- }).catch(e => {
- console.error(e);
- return channel.send(":x: There was an error when trying to edit the ticket message!");
- });
- } else {
- channel.send("The next message you send will be set as the order's image.");
- channel.awaitMessages(m => m.author.id === msg.author.id, { time: 30000, max: 1}).then(collected => {
- if (!collected.size) return msg.channel.send("I haven't recieved a valid response for 30 seconds, so I am cancelling this session.");
- orders[i].image = collected.first().content;
- if (collected.first().attachments.first()) orders[i].image = collected.first().attachments.first().url;
- theM.edit({
- embed: theEmbed
- }).then(() => {
- // Write to orders.json
- fs.writeFile("./Orders.json", JSON.stringify(orders, null, 2), err => {
- if (err) {
- console.error(err);
- return channel.send(":x: There was an error writing to the tickets file! Please contact a bot administrator.");
- }
- let user = bot.users.get(so.orderer.user.id);
- if (user) user.send(":thumbsup: Your manufacturer just put your ticket in the machine industry! It should take " + pms(orders[i].manufacturing_time_left, {
- verbose: true
- }) + " to complete!");
- /*
- if (info) {
- let cooked = Number(info.cooked);
- let final = cooked + 1
- r.db('amazon').table('stats').get(msg.author.id).update({ cooked: final }).run(global.connection, (err, info) => { });
- } else {
- r.db('amazon').table('stats').insert({ user: msg.author.id, delivered: 0, cooked: 1 }).run(global.connection, (err, info) => { });
- }
- */
- return channel.send(":thumbsup: Alright, you've began creating `" + orders[i].id + "`. It'll take " + pms(orders[i].manufacturing_time_left, {
- verbose: true
- }) + " to complete.");
- })
- }).catch(e => {
- console.error(e);
- return channel.send(":x: There was an error when trying to edit the ticket message!");
- });
- });
- }
- }).catch(e => {
- console.error(e);
- return channel.send(":x: There was an error when trying to find the ticket message!");
- });
- });
- // })
- }
- }
- return;
- }
- } else {
- if (command == "claim") {
- return channel.send(":x: You're not a manufacturer, you don't have permission to run this command!");
- } else if (command == "unclaim") {
- return channel.send(":x: You're not a manufacturer, you don't have permission to run this command!");
- } else if (command == "make") {
- return channel.send(":x: You're not a manufacturer, you don't have permission to run this command!");
- }
- }
- if (msg.isDelivery) {
- if (command == "deliver") {
- if (!delivery.includes(channel.id)) return channel.send(":x: You can only do this command in the delivery room!"); // Edit by: EdibleDerpy
- if (!args[1]) return channel.send(":x: Make sure to include the Ticket's ID!");
- let so = orders.filter(o => o.id == args[1])[0]; // Stands for "Specified Order"
- if (!so) return channel.send(":x: I couldn't find the specified ticket.");
- if (so.status !== "Made") return channel.send(":x: This ticket is not manufactured yet!");
- // r.db('amazon').table('stats').get(msg.author.id).run(global.connection, (err, info) => {
- return author.send(so.orderer.channel.invite, createEmbed(
- embedColor, null, "Delivery Info",
- `The ticket has been deleted, it's all on you now.`, [{
- "name": "Ticket Description",
- "value": so.description
- }, {
- "name": "User Information",
- "value": `${so.orderer.user.username} (${so.orderer.user.id}) in #${so.orderer.channel.name} (${so.orderer.channel.id})`
- }, {
- "name": "Manufacturer's Image",
- "value": so.image
- }], null, so.image
- )
- ).then(() => {
- orders = orders.filter(o => o.id !== so.id);
- return fs.writeFile("./Orders.json", JSON.stringify(orders, null, 2), err => {
- if (err) {
- console.error(err);
- return channel.send(":x: There was an error writing to the tickets file! Please contact a bot administrator.");
- }
- orderChan.fetchMessage(so.omid).then(theM => {
- theM.delete();
- /*
- if (info) {
- let delivered = Number(info.delivered);
- let final = delivered + 1
- r.db('amazon').table('stats').get(msg.author.id).update({ delivered: final }).run(global.connection, (err, info) => { });
- } else {
- r.db('amazon').table('stats').insert({ user: msg.author.id, delivered: 1, cooked: 0 }).run(global.connection, (err, info) => { });
- }
- */
- return channel.send("I've DMed you information about this order! :thumbsup:");
- });
- });
- }).catch(e => {
- console.error(e);
- return channel.send(":x: There was an error, please try again!");
- });
- // })
- }
- } else {
- if (command == "deliver") {
- return channel.send(":x: You're not a delivery person, you don't have permission to run this command!");
- }
- }
- if (msg.isDelivery || msg.isManufacturer) {
- if (command == "delorder" || command == "delticket") {
- if (!args[1]) return channel.send(":x: Make sure to include the Ticket ID!");
- if (!args[2]) return channel.send(":x: Make sure to include a reason why you're deleting it!");
- let reason = GaA([args[0], args[1]], content);
- let so = orders.filter(o => o.id == args[1])[0]; // Stands for "Specified Order"
- if (!so) return channel.send(":x: I couldn't find the specified ticket.");
- let user = bot.users.get(so.orderer.user.id);
- user.send("Your ticket has been forcefully removed! Please make sure your tickets are not inappropriate or rude. If your ticket was not, please join the server in the help command. Reason: ```\n" + reason + "\n```");
- orderChan.fetchMessage(so.omid).then(theM => {
- theM.delete();
- });
- orders = orders.filter(o => so.id !== o.id);
- fs.writeFileSync("./Orders.json", JSON.stringify(orders, null, 2));
- return channel.send("Alright, I've deleted that ticket! :thumbsup:");
- } else if (command == "list" || command == "olist" || command == "tlist") {
- let str = "Here's a list of the current orders and their status. Find out more information about an order by running `d!ostatus <ID>`.\n\n";
- for (let i = 0; i < orders.length; i++) {
- if (orders[i].status.toLowerCase().includes("unclaimed") && orders[i].status.toLowerCase() !== "claimed") {
- str += `\`${orders[i].id}\`: ${orders[i].status}\n`
- }
- }
- for (let i = 0; i < orders.length; i++) {
- if (orders[i].status.toLowerCase().includes("claimed") && orders[i].status.toLowerCase() !== "unclaimed") {
- str += `\`${orders[i].id}\`: ${orders[i].status}\n`
- }
- }
- for (let i = 0; i < orders.length; i++) {
- if (orders[i].status.toLowerCase().includes("manufacturing")) {
- str += `\`${orders[i].id}\`: ${orders[i].status}\n`
- }
- }
- for (let i = 0; i < orders.length; i++) {
- if (orders[i].status.toLowerCase().includes("made")) {
- str += `\`${orders[i].id}\`: ${orders[i].status}\n`
- }
- }
- if (str.length > 2000) str.length = 2000;
- return channel.send(str);
- // return channel.send("A list will be coming soon. Until then, you'll have to check <#294620411721940993>.");
- } else if (command == "ostatus" || command == "tstatus") {
- if (!args[1]) return channel.send(":x: Make sure to include the Ticket ID!");
- let so = orders.filter(o => o.id == args[1])[0]; // Stands for "Specified Order"
- if (!so) return channel.send(":x: I couldn't find the specified ticket.");
- let user = bot.users.get(so.orderer.user.id);
- return channel.send(createEmbed(
- embedColor, null, "Ticket Status",
- "The status of your current ticket.", [{
- name: ":hash: Its Ticket ID",
- value: so.id
- }, {
- name: ":package: Its Description",
- value: so.description
- }, {
- name: ":white_check_mark: Its Ticket Status",
- value: so.status
- }, {
- name: ":computer: Its Guild",
- value: `This ticket came from ${so.orderer.guild.name} (${so.orderer.guild.id}) in ${so.orderer.channel.name} (${so.orderer.channel.id}).`
- }]
- ));
- }
- } else {
- if (command == "delorder" || command == "delticket") {
- return channel.send(":x: You're not a worker, you don't have access to this command!");
- } else if (command == "list" || command == "olist" || command == "tlist") {
- return channel.send(":x: You're not a worker, you don't have access to this command!");
- } else if (command == "ostatus" || command == "tstatus") {
- return channel.send(":x: You're not a worker, you don't have access to this command!");
- } else if (command == "stats") {
- return channel.send(":x: You're not a worker, you don't have access to this command!");
- }
- }
- // Other Commands
- if (msg.isAdmin) {
- if (command == "debug") {
- return channel.send(orders[0].orderer.user.name);
- } else if (command == "corders" || command == "ctickets") {
- orders.forEach(o => {
- let user = bot.users.get(o.orderer.user.id);
- user.send("For an unknown reason, all tickets have been purged! Please re-order your product.");
- });
- orderChan.fetchMessages({
- limit: 100
- }).then(msgs => {
- let array = ['112732946774962176', '106876115586383872'];
- msgs = msgs.filter(m => !array.includes(m.author.id));
- orderChan.bulkDelete(msgs);
- });
- fs.writeFileSync("./Orders.json", "[]");
- return channel.send("Alright, I've cleared all tickets! :thumsbup:");
- } else if (command == "eval") {
- try {
- let com = eval(msg.content.split(" ").slice(1).join(" "));
- let com2 = msg.content.split(" ").slice(1).join(" ");
- if (!com2) return channel.send("Include some code? o_O")
- channel.send({
- embed: {
- color: embedColor,
- title: "Evaluate Javascript Complete!",
- description: "Evaluation complete!",
- author: {
- name: bot.user.username,
- icon_url: bot.user.avatarURL
- },
- thumbnail: {
- url: bot.user.avatarURL
- },
- fields: [{
- name: "**Input**",
- value: "```js\n" + com2 + "```"
- }, {
- name: "**Output**",
- value: "```js\n" + com + "```"
- }]
- }
- })
- } catch (e) {
- channel.send({
- embed: {
- color: embedColor,
- title: "Code Error!",
- description: "There was a error in your code!",
- author: {
- name: bot.user.username,
- icon_url: bot.user.avatarURL
- },
- thumbnail: {
- url: bot.user.avatarURL
- },
- fields: [{
- name: "**Error**",
- value: "```js\n" + e + "```"
- }]
- }
- })
- }
- } else if (command == "restart") {
- channel.send("Please confirm that you want to restart Discord Amazon. If so, say yes. If you don't want to restart Discord Amazon simply don't say anything.")
- .then(() => {
- channel.awaitMessages(response => response.content === "yes", {
- max: 1,
- time: 30000,
- errors: ['time'],
- })
- .then((collected) => {
- channel.send("Restart was triggered by " + msg.author.username);
- setTimeout(function() {
- process.exit();
- }, 1500)
- })
- .catch(() => {
- channel.send("No response given, Discord Amazon will not restart!");
- });
- });
- } else if (command == "uptime") {
- if (!msg.channel.permissionsFor(bot.user.id).has("EMBED_LINKS")) return msg.channel.send(":x: I'm sorry, but I need the permission to embed links to function!")
- function calcUptime() {
- let time = 0;
- let days = 0;
- let hrs = 0;
- let min = 0;
- let sec = 0;
- let temp = Math.floor(bot.uptime / 1000);
- sec = temp % 60;
- temp = Math.floor(temp / 60);
- min = temp % 60;
- temp = Math.floor(temp / 60);
- hrs = temp % 24;
- temp = Math.floor(temp / 24);
- days = temp;
- let dayText = " Days, ";
- if (days == 1) {
- dayText = " Days, ";
- }
- const upText = "" + days + dayText + hrs + " hours" + ", " + min + " minutes, " + sec + " seconds ";
- return upText;
- }
- channel.send({
- embed: {
- color: embedColor,
- title: "Discord Amazon's Uptime",
- description: calcUptime(),
- author: {
- name: bot.user.username,
- icon_url: bot.user.avatarURL
- },
- thumbnail: {
- url: bot.user.avatarURL
- }
- }
- })
- return;
- } else if (command == "blacklist") {
- let user = msg.mentions.users.first();
- if (!user) return channel.send("You must tag the user you'd like to blacklist!");
- blacklist.push(user.id);
- fs.writeFileSync("./Blacklist.json", JSON.stringify(blacklist, null, 2));
- return channel.send(":thumbsup: Alright, I've blacklisted " + user.username + "!");
- } else if (command == "gblacklist") {
- if (!args[1]) return channel.send("You must include the ID of the guild you'd like to blacklist!");
- if (isNaN(parseInt(args[1]))) return channel.send("You must include an ID of the guild.");
- let guild = bot.guilds.get(args[1]);
- if (!guild) channel.send("I'm not in that guild, but I'll blacklist it anyways.");
- blacklist.push((guild ? guild.id : args[1]));
- fs.writeFileSync("./Blacklist.json", JSON.stringify(blacklist, null, 2));
- return channel.send("Alright, I've blacklisted " + (guild ? guild.name : args[1]) + "!");
- } else if (command == "unblacklist") {
- let user = msg.mentions.users.first();
- if (!user) return channel.send("You must tag the user you'd like to remove from the blacklist!");
- blacklist = blacklist.filter(b => b !== user.id);
- fs.writeFileSync("./Blacklist.json", JSON.stringify(blacklist, null, 2));
- return channel.send(":thumbsup: Alright, I've removed " + user.username + " from the blacklist!");
- } else if (command == "ungblacklist") {
- if (!args[1]) return channel.send("You must include the ID of the guild you'd like to remove from the blacklist!");
- if (isNaN(parseInt(args[1]))) return channel.send("You must include an ID of the guild.");
- let guild = bot.guilds.get(args[1]);
- if (!guild) channel.send(":thumbsup: I'm not in that guild, but I'll remove it anyways.");
- blacklist = blacklist.filter(b => b !== (guild ? guild.id : args[1]))
- fs.writeFileSync("./Blacklist.json", JSON.stringify(blacklist, null, 2));
- return channel.send(":thumbsup: Alright, I've removed " + (guild ? guild.name : args[1]) + " from the blacklist!");
- }
- } else {
- if (command == "debug") {
- return channel.send(":x: You're not a bot owner, you don't have permission to run this command!");
- } else if (command == "eval") {
- return channel.send(":x: You're not a bot owner, you don't have permission to run this command!");
- } else if (command == "restart") {
- return channel.send(":x: You're not a bot owner, you don't have permission to run this command!");
- } else if (command == "uptime") {
- return channel.send(":x: You're not a bot owner, you don't have permission to run this command!");
- } else if (command == "corders" || command == "ctickets") {
- return channel.send(":x: You're not a bot owner, you don't have permission to run this command!");
- } else if (command == "blacklist" || command == "gblacklist") {
- return channel.send(":x: You're not a bot owner, you don't have permission to run this command!");
- } else if (command == "unblacklist" || command == "ungblacklist") {
- return channel.send(":x: You're not a bot owner, you don't have permission to run this command!");
- }
- }
- });
- });
- });
- //// Update All Orders
- function forceCheck() {
- ParseJson("./Orders.json", (err, orders) => {
- if (err) return console.error(err);
- let orderChan = bot.channels.get("294620411721940993");
- let deliveryChan = bot.channels.get("295054086498156544");
- for (let i = 0; i < orders.length; i++) {
- if (orders[i].manufacturing_time_left !== "Unclaimed" && orders[i].manufacturing_time_left !== "Made") {
- orders[i].manufacturing_time_left -= 60000;
- }
- orders[i].time_left -= 60000;
- let user = bot.users.get(orders[i].orderer.user.id);
- if (orders[i].time_left <= 0) {
- if (orders[i].status == "Manufacturing" || orders[i].status == "Made") {
- if (user) user.send("It's been twenty minutes since you ordered, and your manufactured product hasn't been delivered yet. Allow me to deliver it for you! *Side note! There is currently a glitch in the bot so orders are currently being forced to auto-delivery mode, which is this one. Sorry for the inconvenience.*"); //// The italicized area is temporary, remove after delivery glitch has been patched
- bot.fetchInvite(orders[i].orderer.channel.invite).then(inv => {
- inv.delete();
- }).catch();
- if (orderChan) orderChan.fetchMessage(orders[i].omid).then(msg => {
- msg.delete();
- });
- let channel = bot.channels.get(orders[i].orderer.channel.id);
- if (!channel && user) user.send("I was unable to find the channel that your product should have been delivered to!");
- if (!channel && !user) orders.splice(i, 1);
- else {
- channel.send(`${user.toString()}, here's your order! ` + orders[i].image);
- let chan = bot.channels.get("381361837914062849");
- if (chan) chan.send(`Order \`${orders[i].id}\` has been automatically delivered.`);
- orders.splice(i, 1);
- }
- } else {
- if (orderChan) orderChan.fetchMessage(orders[i].omid).then(msg => {
- msg.delete();
- });
- bot.fetchInvite(orders[i].orderer.channel.invite).then(inv => {
- inv.delete();
- }).catch();
- if (user) user.send("Your ticket has timed out, as it's been 20 minutes, and the bot was unable to auto-deliver because nobody manufactured it. Please re-order your product! We apologize for the inconvenience!");
- orders.splice(i, 1);
- }
- }
- else if (orders[i].manufacturing_time_left <= 0) {
- if (deliveryChan) {
- orders[i].status = "Made";
- orders[i].manufacturing_time_left = "Made";
- console.log('test');
- orderChan.fetchMessage(orders[i].omid).then(theM => {
- let theEmbed = theM.embeds[0];
- for (let a = 0; a < theEmbed.fields.length; a++) {
- if (theEmbed.fields[a].name.toLowerCase().includes("status")) {
- theEmbed.fields[a].value = "Made";
- deliveryChan.send(`Ticket \`${orders[i].id}\` has completed manufacturing and is ready to be delivered!`);
- break;
- }
- }
- theM.edit({
- embed: theEmbed
- }).then(() => {
- fs.writeFile("./Orders.json", JSON.stringify(orders, null, 2), err => {
- if (err) {
- console.error(err);
- return channel.send(":x: There was an error writing to the tickets file! Please contact a bot administrator.");
- }
- let user = bot.users.get(orders[i].orderer.user.id);
- if (user) user.send("Your product has been manufactured and will be delivered shortly!");
- })
- }).catch();
- }).catch();
- }
- }
- }
- fs.writeFileSync("./Orders.json", JSON.stringify(orders, null, 2));
- });
- }
- forceCheck();
- setInterval(() => {
- forceCheck();
- }, 60000);
- //// Connect To Discord
- console.log("[Discord] Connecting...");
- bot.login(Config.token);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement