-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
181 lines (150 loc) · 6.83 KB
/
index.js
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
const Discord = require("discord.js")
const SQLite = require("better-sqlite3")
const sql = new SQLite('./mainDB.sqlite')
const { join } = require("path")
const { readdirSync } = require("fs");
const client = new Discord.Client()
client.commands = new Discord.Collection();
const cooldowns = new Discord.Collection();
const talkedRecently = new Map();
// Token, Prefix, and Owner ID
const config = require("./config.json")
// Events
client.login(config.token)
client.on("ready", () => {
// Check if the table "points" exists.
const levelTable = sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'levels';").get();
if (!levelTable['count(*)']) {
sql.prepare("CREATE TABLE levels (id TEXT PRIMARY KEY, user TEXT, guild TEXT, xp INTEGER, level INTEGER, totalXP INTEGER);").run();
}
client.getLevel = sql.prepare("SELECT * FROM levels WHERE user = ? AND guild = ?");
client.setLevel = sql.prepare("INSERT OR REPLACE INTO levels (id, user, guild, xp, level, totalXP) VALUES (@id, @user, @guild, @xp, @level, @totalXP);");
// Role table for levels
const roleTable = sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'roles';").get();
if (!roleTable['count(*)']) {
sql.prepare("CREATE TABLE roles (guildID TEXT, roleID TEXT, level INTEGER);").run();
}
// Prefix table
const prefixTable = sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'prefix';").get();
if (!prefixTable['count(*)']) {
sql.prepare("CREATE TABLE prefix (serverprefix TEXT, guild TEXT PRIMARY KEY);").run();
}
console.log(`Logged in as ${client.user.username}`)
});
// Command Handler
const commandFiles = readdirSync(join(__dirname, "commands")).filter((file) => file.endsWith(".js"));
for (const file of commandFiles) {
const command = require(join(__dirname, "commands", `${file}`));
client.commands.set(command.name, command);
}
// Message Events
client.on("message", (message) => {
if (message.author.bot) return;
if (!message.guild) return;
const currentPrefix = sql.prepare("SELECT * FROM prefix WHERE guild = ?").get(message.guild.id);
const Prefix = config.prefix;
var getPrefix;
if(!currentPrefix) {
sql.prepare("INSERT OR REPLACE INTO prefix (serverprefix, guild) VALUES (?,?);").run(Prefix, message.guild.id)
getPrefix = Prefix;
} else {
getPrefix = currentPrefix.serverprefix;
}
const escapeRegex = (str) => str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
const prefixRegex = new RegExp(`^(<@!?${client.user.id}>|${escapeRegex(getPrefix)})\\s*`);
if (!prefixRegex.test(message.content)) return;
const [, matchedPrefix] = message.content.match(prefixRegex);
const args = message.content.slice(matchedPrefix.length).trim().split(/ +/);
const commandName = args.shift().toLowerCase();
const command =
client.commands.get(commandName) ||
client.commands.find((cmd) => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
if (!cooldowns.has(command.name)) {
cooldowns.set(command.name, new Discord.Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.name);
const cooldownAmount = (command.cooldown || 1) * 1000;
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return message.reply(
`Please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${command.name}\` command.`
);
}
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply("There was an error executing that command.").catch(console.error);
}
});
// XP Messages
client.on("message", message => {
if (message.author.bot) return;
if (!message.guild) return;
// get level and set level
const level = client.getLevel.get(message.author.id, message.guild.id)
if(!level) {
let insertLevel = sql.prepare("INSERT OR REPLACE INTO levels (id, user, guild, xp, level, totalXP) VALUES (?,?,?,?,?,?);");
insertLevel.run(`${message.author.id}-${message.guild.id}`, message.author.id, message.guild.id, 0, 0, 0)
return;
}
const lvl = level.level;
// xp system
const generatedXp = Math.floor(Math.random() * 5);
const nextXP = level.level * 2 * 30 + 30
// message content or characters length has to be more than 4 characters also cooldown
if(talkedRecently.get(message.author.id)) {
return;
} else { // cooldown is 10 seconds
level.xp += generatedXp;
level.totalXP += generatedXp;
// level up!
if(level.xp >= nextXP) {
level.xp = 0;
level.level += 1;
let embed = new Discord.MessageEmbed()
.setAuthor(message.author.tag, message.author.displayAvatarURL({ dynamic: true }))
.setDescription(`**Congratulations** ${message.author}! You have now leveled up to **level ${level.level}** 🍉`)
.setColor("RANDOM")
.setThumbnail(message.author.displayAvatarURL({ dynamic: true }))
.setTimestamp();
// using try catch if bot have perms to send EMBED_LINKS
try {
client.channels.cache.get('channelID').send(`${message.author}`)
.then(msg => {
msg.delete({ timeout: 10000 })
})
.catch(console.error);
client.channels.cache.get('channelID').send(embed);
} catch (err) {
client.channels.cache.get('channelID').send(`Congratulations, ${message.author}! You have now leveled up to **Level ${level.level}** 🍉`)
}
};
client.setLevel.run(level);
// add cooldown to user
talkedRecently.set(message.author.id, Date.now() + 10 * 1000);
setTimeout(() => talkedRecently.delete(message.author.id, Date.now() + 10 * 1000))
}
// level up, time to add level roles
const member = message.member;
let Roles = sql.prepare("SELECT * FROM roles WHERE guildID = ? AND level = ?")
let roles = Roles.get(message.guild.id, lvl)
if(!roles) return;
if(lvl >= roles.level) {
if(roles) {
if (member.roles.cache.get(roles.roleID)) {
return;
}
if(!message.guild.me.hasPermission("MANAGE_ROLES")) {
return
}
member.roles.add(roles.roleID);
}}
})