Skip to content

Commit

Permalink
Merge pull request #15 from AkimotoRyou/AkimotoRyou-Repl.it-1
Browse files Browse the repository at this point in the history
Migrating to Repl.it
  • Loading branch information
AkimotoRyou authored Oct 28, 2020
2 parents c6e0540 + 7d7e8c3 commit c8deda8
Show file tree
Hide file tree
Showing 9 changed files with 154 additions and 92 deletions.
40 changes: 27 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,25 @@ This bot only support one pair of server per bot. One main server(where users ga
## Installation

1. Set up bot application in [Discord](https://discordjs.guide/preparations/setting-up-a-bot-application.html#your-token).
2. Create [Glitch](https://glitch.com/) account.
3. Create new `Hello-Express` project.
4. Import files from this repository. [`Tools` -> `Import and Export` -> `Import from GitHub` -> Type `AkimotoRyou/ModMail` -> click `ok`]*
5. At `.env.txt` file, add your bot [token](https://discordjs.guide/preparations/setting-up-a-bot-application.html#your-token) right after `TOKEN=` and then rename the file to `.env`.
6. At `config.json.txt` file, add your [DiscordID](https://support.discordapp.com/hc/en-us/articles/206346498-Where-can-I-find-my-User-Server-Message-ID-) between `""` character at `botOwnerID` section and rename the file to `config.json`.
7. If you have glitch [subscription](https://glitch.com/pricing), you can boost your project to make it run 24/7.
2. [Download](https://www.wikihow.com/Download-a-GitHub-Folder) or [clone](https://docs.github.com/en/free-pro-team@latest/github/creating-cloning-and-archiving-repositories/cloning-a-repository) files in this repository.
3. Create [Repl.it](https://repl.it/) account.
4. Click on `+ New repl`.
5. Choose `Node.js` as the language.
6. Rename your project. `*(Optional)`
7. Click `Create Repl`.
8. Drag and drop all the `(downloaded or cloned from github)` files to the box below `Files` on left side of the repl.it project page. `*(make sure to replace the index.js file)`
9. At `.env` file, add your bot [token](https://discordjs.guide/preparations/setting-up-a-bot-application.html#your-token) right after `TOKEN=`.
10. At `config.json` file, add your [DiscordID](https://support.discordapp.com/hc/en-us/articles/206346498-Where-can-I-find-my-User-Server-Message-ID-) between `""` character at `botOwnerID` section.
11. Click `Run` button on top center of the page.
12. If you have repl.it [Hacker subscription](https://repl.it/site/pricing) **when** the `Always-on repls` feature added, you can skip the instructions below.
13. Create [UptimeRobot](https://uptimerobot.com/) account and login.
14. On Dashboard, click `+ Add New Monitor`.
15. Change `Monitor Type *` to `HTTP(s)`.
16. Fill the name to your own liking.
17. On your Repl.it project, there should be a window showing a page that says `Bot is running.` copy the url on that window to UptimeRobot `URL (or IP)*` part. `*(The url should be something like: "https://projectName.replUsername.repl.co")`
18. Set the `Monitoring Interval *` to anything between 5 minutes and 45 minutes `(Recomended: 30 minutes)`.
19. Finally, click `Create Monitor`.

#### Notes:
1. Glitch banning pinging service like uptimerobot and any others alike read their announcement [here](https://support.glitch.com/t/an-update-on-pinging-services-glitch/27311).
2. I'm currently testing hosting the bot on [Repl.it](https://repl.it). I'll need to change some codes and instructions if the bot able to run without any problems there.

`* Only use import for the first time the project created cause import from github will rewrite all your data in Glitch project. You need to manually change the files if you want to sync it with this repository.`

## Requirements

Expand All @@ -34,13 +41,13 @@ To operate functionally the bot need the following :
#### ~ Owner Level ~
* **leave** : Leave a guild (server).
* **reload** : Reload a command.
* **turnoff** : Turn off the bot.
#### ~ Admin Level ~
* **bind** : Bind user thread to a channel.
* **configinfo** : Show a configuration information.
* **configuration** : Bot configuration.
* **guilds** : List of guilds (servers) that have this bot.
* **reset** : Reset all configuration values.
* **restart** : Restart the bot.
* **set** : Set specific configuration value.
#### ~ Moderator Level ~
* **aclose** : Anonymously close a user thread.
Expand All @@ -56,7 +63,7 @@ To operate functionally the bot need the following :
* **tagdelete** : Delete a saved response.
* **tagedit** : Edit a saved response.
* **taginfo** : Show a saved response information.
* **taglist** : Show a all tag names.
* **taglist** : Show all tag names.
* **threadinfo** : Show a user thread information.
* **threadlist** : Show all open threads.
* **unblock** : Unblock user from creating new thread.
Expand All @@ -78,3 +85,10 @@ To operate functionally the bot need the following :
## Testing

I made Discord server to test the bot, feel free to join at https://discord.gg/GGRWNgJ.

## Change Log

1. Turning `restart` command to `turnoff` command. `(Need to manually run the bot from repl.it after turned off.)`
2. Changing how cycling bot activities works to not abuse Discord API.
- Before : Changed every 7 seconds.
- Now : Changed when there's a new message every 7 seconds `(Anywhere from any users except bots)`.
28 changes: 28 additions & 0 deletions commands/turnoff.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
module.exports = {
name: 'turnoff',
aliases: ['shutdown', 'stop'],
level: 'Owner',
guildOnly: true,
args: false,
usage: false,
description: 'Turn off the bot.',
note: false,
async execute(param, message, args) {
const config = param.config;
const getEmbed = param.getEmbed;

const successEmbed = getEmbed.execute(param, config.info_color, "Turning Off", `**Turning off in** : **${Math.round(param.client.ws.ping)}** ms`);
const noPermEmbed = getEmbed.execute(param, config.warning_color, "Missing Permission", "You don't have permission to run this command.");

if (message.author.id === config.botOwnerID) {
// bot owner
console.log("Turning Off...");
message.channel.send(successEmbed).then(() => {
process.exit(1);
});
} else {
// Not bot owner
return message.channel.send(noPermEmbed);
}
}
};
19 changes: 19 additions & 0 deletions config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"prefix" : "=",
"botOwnerID" : "",
"cooldown" : "0",
"maintenance" : "0",
"mainServerID" : "",
"threadServerID" : "",
"categoryID" : "",
"logChannelID" : "",
"botChannelID" : "",
"adminRoleID" : "",
"modRoleID" : "",
"mentionedRoleID" : "",
"info_color" : "#add8e6",
"warning_color" : "#ffff00",
"error_color" : "#ff0000",
"received_color" : "#00ffff",
"sent_color" : "#00ff00"
}
7 changes: 2 additions & 5 deletions functions/configSync.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,8 @@ module.exports = {
async execute(param) {
const config = param.config;
const ConfigDB = param.ConfigDB;
const user = param.client.user;

console.log("[Syncing Configuration]")
user.setActivity("Syncing...");
console.log("[Syncing Configuration]");
const configKeys = Object.keys(config);
const syncPromise = new Promise(resolve => {
try {
Expand All @@ -30,9 +28,8 @@ module.exports = {
return console.log(error);
}
});
syncPromise.then(() => {
syncPromise.then(async () => {
console.log("[Synced]");
user.setActivity("[Ready]");
});
}
};
7 changes: 4 additions & 3 deletions functions/setFn.js
Original file line number Diff line number Diff line change
Expand Up @@ -133,10 +133,11 @@ module.exports = {
if(affectedRows > 0) {
console.log(`[${configName}] value changed to [${inputValue}]`);
await message.channel.send(successEmbed).then(async () => {
await configSync.execute(param);
if(configName == "maintenance" || configName == "prefix") {
process.exit(1);
} else {
return await configSync.execute(param);
setTimeout(async ()=> {
await param.updateActivity.execute(param);
}, 5000);
}
});
} else {
Expand Down
42 changes: 39 additions & 3 deletions functions/updateActivity.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,50 @@
module.exports = {
name: "updateActivity",
async execute(param) {
const activities = param.activities;
const client = param.client;
const config = param.config;
const prefix = config.prefix;
const activity = param.activity;
const ThreadDB = param.ThreadDB;

const threads = await ThreadDB.findAll({ attributes: ["userID"] }).catch(
error => {console.log(error)}
);
const threadServer = client.guilds.cache.get(config.threadServerID);
let maxThreads = "";
if (threadServer) {
const categoryChannel = threadServer.channels.cache.get(config.categoryID);
if (categoryChannel) {
const childSize = categoryChannel.children.size;
const threadSize = threads.length;
maxThreads = 50 - (childSize - threadSize);
} else {
maxThreads = 0;
}
} else {
maxThreads = 0;
}
const activities = [
`${threads.length}/${maxThreads} Active threads | ${prefix}commands`,
`Send me a message | ${prefix}help`,
`Schick mir eine Nachricht | ${prefix}helpDE`,
`Bana mesaj gönder | ${prefix}helpTR`,
`나에게 메세지를 보내 | ${prefix}helpKR`,
`Me mande uma mensagem | ${prefix}helpPT`,
`Envoyez-moi un message | ${prefix}helpFR`,
`Пришлите мне сообщение | ${prefix}helpRU`,
`给我发一条信息 | ${prefix}helpCHS`,
`給我發一條信息 | ${prefix}helpCHT`,
`Envíeme un mensaje | ${prefix}helpES`
]

activities.shift();
activities.unshift(`${threads.length} Threads | ${param.config.prefix}commands`);
if (config.maintenance == 0) {
client.user.setActivity(activities[activity.index]);
activity.index++;
if (activity.index == activities.length) activity.index = 0;
} else {
client.user.setActivity("~ Under Maintenance ~");
}
console.log(`> Activity Updated. Index : ${activity.index}`)
}
};
79 changes: 24 additions & 55 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ console.log("[Loading Dependencies]");
const Discord = require("discord.js");
const { Util, MessageAttachment } = require("discord.js");
const client = new Discord.Client();
const server = require("./server.js");
const keepAlive = require("./server.js");
const Sequelize = require("sequelize");
const fs = require("fs");
const moment = require("moment");
Expand Down Expand Up @@ -143,24 +143,9 @@ for (const file of functionFiles) {
const cooldowns = new Discord.Collection();

// #activities
const activities = [];
function addActivities(getPrefix, threads) {
if(getPrefix) {
activities.push(`${threads.length} Threads | ${getPrefix.input}commands`);
activities.push(`Send me a message | ${getPrefix.input }help`);
activities.push(`Schick mir eine Nachricht | ${getPrefix.input}helpDE`);
activities.push(`Bana mesaj gönder | ${getPrefix.input}helpTR`);
activities.push(`나에게 메세지를 보내 | ${getPrefix.input}helpKR`);
activities.push(`Me mande uma mensagem | ${getPrefix.input}helpPT`);
activities.push(`Envoyez-moi un message | ${getPrefix.input}helpFR`);
activities.push(`Пришлите мне сообщение | ${getPrefix.input}helpRU`);
activities.push(`给我发一条信息 | ${getPrefix.input}helpCHS`);
activities.push(`給我發一條信息 | ${getPrefix.input}helpCHT`);
activities.push(`Envíeme un mensaje | ${getPrefix.input}helpES`);
} else {
activities.push(`- Restart Me -`);
}
}
const activity = {
index: 0
};

// #parameter
const param = {
Expand All @@ -175,7 +160,7 @@ const param = {
QueueDB,
config,
defConfig,
activities,
activity,
}
// add every functions to param
client.functions.forEach(fn => param[fn.name] = client.functions.get(fn.name));
Expand All @@ -195,38 +180,9 @@ client.on('ready', async () => {

console.log(`Logged in as ${client.user.tag}!`);
// when i use local variable (config.maintenance), the configSync() is still in process that's why i use database value for this.
const getMaintenance = await ConfigDB.findOne({ where: { name: "maintenance" } }).catch(
error => {console.log(error)}
);
const getPrefix = await ConfigDB.findOne({ where: { name: "prefix" } }).catch(
error => {console.log(error)}
);
const threads = await ThreadDB.findAll({ attributes: ["userID"] }).catch(
error => {console.log(error)}
);

let isMaintenance;
if(!getMaintenance) {
isMaintenance = "0";
} else {
isMaintenance = await getMaintenance.input;
}

addActivities(getPrefix, threads);

if (isMaintenance == "0") {
let index = 0;
setInterval(() => {
client.user.setActivity(activities[index]);
index++;
if (index == activities.length) index = 0;
}, 10000);
} else {
// using timeout since i can't make the bot wait for configSync() function to finish :(
setTimeout(()=> {
client.user.setActivity("~ Under Maintenance ~");
}, 10000);
}
setTimeout(async ()=> {
await param.updateActivity.execute(param);
}, 5000);
});

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Expand All @@ -248,6 +204,20 @@ const escapeRegex = str => str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

client.on('message', async message => {
if(message.author.bot) return;

//Activity Cooldown
if (!cooldowns.has("botActivity")) {
cooldowns.set("botActivity", new Discord.Collection());
}
const now = Date.now();
const timestamps = cooldowns.get("botActivity");
const cooldownAmount = 7000; //7 Seconds
if (!timestamps.has("botActivity")) {
await param.updateActivity.execute(param);
}
timestamps.set("botActivity", now);
setTimeout(() => timestamps.delete("botActivity"), cooldownAmount);

try {
const authorID = message.author.id;
const maintenanceEmbed = param.getEmbed.execute(param, config.error_color, "Maintenance", "All functions are disabled.");
Expand Down Expand Up @@ -413,9 +383,8 @@ client.on('message', async message => {
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~LOGIN~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

keepAlive();
client.login(process.env.TOKEN);
require("https")
.createServer()
.listen();
require("https").createServer().listen();

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "ModMail",
"version": "2.0.0",
"version": "2.1.0",
"description": "A simple ModMail bot for Discord.",
"main": "index.js",
"scripts": {
Expand All @@ -24,10 +24,10 @@
"license": "GPL-3.0",
"keywords": [
"node",
"glitch",
"replit",
"express",
"discordjs",
"discord-bot",
"modmail-bot"
]
}
}
18 changes: 8 additions & 10 deletions server.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
const http = require('http');
const express = require('express');
const app = express();
app.get("/", (request, response) => {
console.log(Date.now() + " Ping Received");
response.sendStatus(200);
});
app.listen(process.env.PORT);
setInterval(() => {
http.get(`http://${process.env.PROJECT_DOMAIN}.glitch.me/`);
}, 280000);
const server = express();
server.all('/', (req, res) => {
res.send('Bot is running.')
})
function keepAlive(){
server.listen(3000, () => {console.log("Server is ready.")})
}
module.exports = keepAlive;

0 comments on commit c8deda8

Please sign in to comment.