File size: 9,871 Bytes
80ce16c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 | /**
* @author NTKhang
* ! The source code is written by NTKhang, please don't change the author's name everywhere. Thank you for using
* ! Official source code: https://github.com/ntkhang03/Goat-Bot-V2
* ! If you do not download the source code from the above address, you are using an unknown version and at risk of having your account hacked
*
* English:
* ! Please do not change the below code, it is very important for the project.
* It is my motivation to maintain and develop the project for free.
* ! If you change it, you will be banned forever
* Thank you for using
*
* Vietnamese:
* ! Vui lòng không thay đổi mã bên dưới, nó rất quan trọng đối với dự án.
* Nó là động lực để tôi duy trì và phát triển dự án miễn phí.
* ! Nếu thay đổi nó, bạn sẽ bị cấm vĩnh viễn
* Cảm ơn bạn đã sử dụng
*/
process.on('unhandledRejection', error => console.log(error));
process.on('uncaughtException', error => console.log(error));
const axios = require("axios");
const fs = require("fs-extra");
const google = require("googleapis").google;
const nodemailer = require("nodemailer");
const { execSync } = require('child_process');
const log = require('./logger/log.js');
const path = require("path");
process.env.BLUEBIRD_W_FORGOTTEN_RETURN = 0; // Disable warning: "Warning: a promise was created in a handler but was not returned from it"
function validJSON(pathDir) {
try {
if (!fs.existsSync(pathDir))
throw new Error(`File "${pathDir}" not found`);
execSync(`npx jsonlint "${pathDir}"`, { stdio: 'pipe' });
return true;
}
catch (err) {
let msgError = err.message;
msgError = msgError.split("\n").slice(1).join("\n");
const indexPos = msgError.indexOf(" at");
msgError = msgError.slice(0, indexPos != -1 ? indexPos - 1 : msgError.length);
throw new Error(msgError);
}
}
const { NODE_ENV } = process.env;
const dirConfig = path.normalize(`${__dirname}/config${['production', 'development'].includes(NODE_ENV) ? '.dev.json' : '.json'}`);
const dirConfigCommands = path.normalize(`${__dirname}/configCommands${['production', 'development'].includes(NODE_ENV) ? '.dev.json' : '.json'}`);
const dirAccount = path.normalize(`${__dirname}/account${['production', 'development'].includes(NODE_ENV) ? '.dev.txt' : '.txt'}`);
for (const pathDir of [dirConfig, dirConfigCommands]) {
try {
validJSON(pathDir);
}
catch (err) {
log.error("CONFIG", `Invalid JSON file "${pathDir.replace(__dirname, "")}":\n${err.message.split("\n").map(line => ` ${line}`).join("\n")}\nPlease fix it and restart bot`);
process.exit(0);
}
}
const config = require(dirConfig);
if (config.whiteListMode?.whiteListIds && Array.isArray(config.whiteListMode.whiteListIds))
config.whiteListMode.whiteListIds = config.whiteListMode.whiteListIds.map(id => id.toString());
const configCommands = require(dirConfigCommands);
global.GoatBot = {
startTime: Date.now() - process.uptime() * 1000, // time start bot (ms)
commands: new Map(), // store all commands
eventCommands: new Map(), // store all event commands
commandFilesPath: [], // [{ filePath: "", commandName: [] }
eventCommandsFilesPath: [], // [{ filePath: "", commandName: [] }
aliases: new Map(), // store all aliases
onFirstChat: [], // store all onFirstChat [{ commandName: "", threadIDsChattedFirstTime: [] }}]
onChat: [], // store all onChat
onEvent: [], // store all onEvent
onReply: new Map(), // store all onReply
onReaction: new Map(), // store all onReaction
onAnyEvent: [], // store all onAnyEvent
config, // store config
configCommands, // store config commands
envCommands: {}, // store env commands
envEvents: {}, // store env events
envGlobal: {}, // store env global
reLoginBot: function () { }, // function relogin bot, will be set in bot/login/login.js
Listening: null, // store current listening handle
oldListening: [], // store old listening handle
callbackListenTime: {}, // store callback listen
storage5Message: [], // store 5 message to check listening loop
fcaApi: null, // store fca api
botID: null // store bot id
};
global.db = {
// all data
allThreadData: [],
allUserData: [],
allDashBoardData: [],
allGlobalData: [],
// model
threadModel: null,
userModel: null,
dashboardModel: null,
globalModel: null,
// handle data
threadsData: null,
usersData: null,
dashBoardData: null,
globalData: null,
receivedTheFirstMessage: {}
// all will be set in bot/login/loadData.js
};
global.client = {
dirConfig,
dirConfigCommands,
dirAccount,
countDown: {},
cache: {},
database: {
creatingThreadData: [],
creatingUserData: [],
creatingDashBoardData: [],
creatingGlobalData: []
},
commandBanned: configCommands.commandBanned
};
const utils = require("./utils.js");
global.utils = utils;
const { colors } = utils;
global.temp = {
createThreadData: [],
createUserData: [],
createThreadDataError: [], // Can't get info of groups with instagram members
filesOfGoogleDrive: {
arraybuffer: {},
stream: {},
fileNames: {}
},
contentScripts: {
cmds: {},
events: {}
}
};
// watch dirConfigCommands file and dirConfig
const watchAndReloadConfig = (dir, type, prop, logName) => {
let lastModified = fs.statSync(dir).mtimeMs;
let isFirstModified = true;
fs.watch(dir, (eventType) => {
if (eventType === type) {
const oldConfig = global.GoatBot[prop];
setTimeout(() => {
try {
if (isFirstModified) {
isFirstModified = false;
return;
}
if (lastModified === fs.statSync(dir).mtimeMs) {
return;
}
global.GoatBot[prop] = JSON.parse(fs.readFileSync(dir, 'utf-8'));
log.success(logName, `Reloaded ${dir.replace(process.cwd(), "")}`);
}
catch (err) {
log.warn(logName, `Can't reload ${dir.replace(process.cwd(), "")}`);
global.GoatBot[prop] = oldConfig;
}
finally {
lastModified = fs.statSync(dir).mtimeMs;
}
}, 200);
}
});
};
watchAndReloadConfig(dirConfigCommands, 'change', 'configCommands', 'CONFIG COMMANDS');
watchAndReloadConfig(dirConfig, 'change', 'config', 'CONFIG');
global.GoatBot.envGlobal = global.GoatBot.configCommands.envGlobal;
global.GoatBot.envCommands = global.GoatBot.configCommands.envCommands;
global.GoatBot.envEvents = global.GoatBot.configCommands.envEvents;
// ———————————————— LOAD LANGUAGE ———————————————— //
const getText = global.utils.getText;
// ———————————————— AUTO RESTART ———————————————— //
if (config.autoRestart) {
const time = config.autoRestart.time;
if (!isNaN(time) && time > 0) {
utils.log.info("AUTO RESTART", getText("Goat", "autoRestart1", utils.convertTime(time, true)));
setTimeout(() => {
utils.log.info("AUTO RESTART", "Restarting...");
process.exit(2);
}, time);
}
else if (typeof time == "string" && time.match(/^((((\d+,)+\d+|(\d+(\/|-|#)\d+)|\d+L?|\*(\/\d+)?|L(-\d+)?|\?|[A-Z]{3}(-[A-Z]{3})?) ?){5,7})$/gmi)) {
utils.log.info("AUTO RESTART", getText("Goat", "autoRestart2", time));
const cron = require("node-cron");
cron.schedule(time, () => {
utils.log.info("AUTO RESTART", "Restarting...");
process.exit(2);
});
}
}
(async () => {
// ———————————————— SETUP MAIL ———————————————— //
const { gmailAccount } = config.credentials;
const { email, clientId, clientSecret, refreshToken } = gmailAccount;
const OAuth2 = google.auth.OAuth2;
const OAuth2_client = new OAuth2(clientId, clientSecret);
OAuth2_client.setCredentials({ refresh_token: refreshToken });
let accessToken;
try {
accessToken = await OAuth2_client.getAccessToken();
}
catch (err) {
throw new Error(getText("Goat", "googleApiTokenExpired"));
}
const transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
service: 'Gmail',
auth: {
type: 'OAuth2',
user: email,
clientId,
clientSecret,
refreshToken,
accessToken
}
});
async function sendMail({ to, subject, text, html, attachments }) {
const transporter = nodemailer.createTransport({
host: 'smtp.gmail.com',
service: 'Gmail',
auth: {
type: 'OAuth2',
user: email,
clientId,
clientSecret,
refreshToken,
accessToken
}
});
const mailOptions = {
from: email,
to,
subject,
text,
html,
attachments
};
const info = await transporter.sendMail(mailOptions);
return info;
}
global.utils.sendMail = sendMail;
global.utils.transporter = transporter;
// ———————————————— CHECK VERSION ———————————————— //
const { data: { version } } = await axios.get("https://raw.githubusercontent.com/ntkhang03/Goat-Bot-V2/main/package.json");
const currentVersion = require("./package.json").version;
if (compareVersion(version, currentVersion) === 1)
utils.log.master("NEW VERSION", getText("Goat", "newVersionDetected", colors.gray(currentVersion), colors.hex("#eb6a07", version)));
// —————————— CHECK FOLDER GOOGLE DRIVE —————————— //
const parentIdGoogleDrive = await utils.drive.checkAndCreateParentFolder("GoatBot");
utils.drive.parentID = parentIdGoogleDrive;
// ———————————————————— LOGIN ———————————————————— //
require(`./bot/login/login${NODE_ENV === 'development' ? '.dev.js' : '.js'}`);
})();
function compareVersion(version1, version2) {
const v1 = version1.split(".");
const v2 = version2.split(".");
for (let i = 0; i < 3; i++) {
if (parseInt(v1[i]) > parseInt(v2[i]))
return 1; // version1 > version2
if (parseInt(v1[i]) < parseInt(v2[i]))
return -1; // version1 < version2
}
return 0; // version1 = version2
}
|