-
Notifications
You must be signed in to change notification settings - Fork 1
/
bot.js
223 lines (180 loc) · 7.53 KB
/
bot.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
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
const fs = require('fs')
const {Client, Collection, GatewayIntentBits, Partials} = require('discord.js')
const dotenv = require('dotenv')
const {DB, React, Token, Lang, Log, Account} = require('./utils')
const express = require('express')
const app = express()
const cors = require('cors')
const CryptoJS = require('crypto-js')
const {REST} = require('@discordjs/rest')
const {Routes} = require('discord-api-types/v9')
dotenv.config()
const clientId = process.env.CLIENT_ID
const guildId = process.env.GUILD_ID
const token = process.env.DISCORD_TOKEN
/************************************************************/
/* BOT
/************************************************************/
// Create a new client instance
const client = new Client({intents: [GatewayIntentBits.Guilds], partials: [Partials.Channel]})
// When the client is ready, run this code (only once)
client.once('ready', () => {
console.log('Ready!')
})
const commands = []
client.commands = new Collection()
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'))
for (const file of commandFiles) {
const command = require(`./commands/${file}`)
client.commands.set(command.data.name, command)
commands.push(command.data.toJSON())
}
const rest = new REST({version: '10'}).setToken(token)
rest.put(Routes.applicationGuildCommands(clientId, guildId), {body: commands})
.then(() => console.log('Successfully registered application commands.'))
.catch(console.error)
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return
await interaction.deferReply()
const command = client.commands.get(interaction.commandName)
if (!command) return
try {
console.log(`COMMAND INCOMING`) // REMOVE
await command.execute(interaction)
} catch (error) {
await Log.error(interaction, 1, error)
return await React.error(interaction, 1, Lang.trans(interaction, 'error.title.general'), Lang.trans(interaction, 'error.description.error_occurred'), true)
}
})
// Login to Discord with your client's token
client.login(process.env.DISCORD_TOKEN).then(async function () {
console.log('Connected as:')
console.log(`${client.user.username} #${client.user.discriminator}`)
await DB.syncDatabase()
console.log('Database synced')
await getTokenInfo()
await setPresence()
setInterval(getTokenInfo, 30000)
setInterval(setPresence, 5000)
setInterval(async () => await accountRoles(client), 5000)
})
// Set price presence
let jewelPriceUsd,
jewelPriceChange,
crystalPriceUsd,
crystalPriceChange,
jadePriceUsd,
jadePriceChange = 0
let presence = 'jewel'
async function setPresence()
{
if (presence === 'jewel') {
await client.user.setPresence({activities: [{name: `1JE at $${jewelPriceUsd} (${jewelPriceChange}%)`, type: 3}]})
presence = 'crystal'
} else if (presence === 'crystal') {
await client.user.setPresence({activities: [{name: `1CR at $${crystalPriceUsd} (${crystalPriceChange}%)`, type: 3}]})
presence = 'jade'
} else if (presence === 'jade') {
await client.user.setPresence({activities: [{name: `1JA at $${jadePriceUsd} (${jadePriceChange}%)`, type: 3}]})
presence = 'jewel'
}
}
async function getTokenInfo()
{
try {
const jewelInfo = await Token.jewelInfo()
const crystalInfo = await Token.crystalInfo()
const jadeInfo = await Token.jadeInfo()
jewelPriceUsd = parseFloat(jewelInfo.priceUsd).toFixed(3)
jewelPriceChange = jewelInfo.priceChange.h24
crystalPriceUsd = parseFloat(crystalInfo.priceUsd).toFixed(3)
crystalPriceChange = crystalInfo.priceChange.h24
jadePriceUsd = parseFloat(jadeInfo.priceUsd).toFixed(3)
jadePriceChange = jadeInfo.priceChange.h24
} catch (error) {
console.warn('Unable to get price')
jewelPriceUsd, jewelPriceChange, crystalPriceUsd, crystalPriceChange, jadePriceUsd, jadePriceChange = 0
}
}
async function accountRoles()
{
const accounts = await DB.accountHolders.findAll({
where: {
role: false
}
})
for (const account of accounts) {
try {
const role = client.guilds.cache.get(process.env.GUILD_ID).roles.cache.find(role => role.id === process.env.ACCOUNT_ROLE)
const member = client.guilds.cache.get(process.env.GUILD_ID).members.cache.find(member => member.id === account.user)
if (role && member) {
await member.roles.add(role)
await account.update({role: true})
}
} catch (error) {
console.log(error)
}
}
}
/************************************************************/
/* API
/************************************************************/
app.use(cors())
app.options('*', cors())
// app.use(express.json())
// Add headers before the routes are defined
app.use(function (req, res, next) {
// Website you wish to allow connecting
res.setHeader('Access-Control-Allow-Origin', '*')
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', '*')
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', '*')
// Pass to next layer of middleware
next()
})
app.get('/ping', async function (request, response) {
response.writeHead(200, {'Content-Type': 'application/json'})
response.write(JSON.stringify({success: true, message: `pong`}))
response.end()
})
app.post('/verify-account', async function (request, response) {
await DB.accountHolders.sync()
for (const param of ['id', 'address']) {
if (typeof request.body[param] === 'undefined') {
response.writeHead(400, {'Content-Type': 'application/json'})
response.write(JSON.stringify({success: false, message: `Missing parameter "${param}"`}))
response.end()
return
}
}
try {
const id = await CryptoJS.AES.decrypt(request.body['id'].replaceAll(':p:', '+').replaceAll(':s:', '/'), process.env.CREATE_ACCOUNT_CYPHER_SECRET).toString(CryptoJS.enc.Utf8)
const address = await request.body['address']
if (await Account.verified(address)) {
response.writeHead(403, {'Content-Type': 'application/json'})
response.write(JSON.stringify({success: false, message: `Account already verified`}))
response.end()
return
}
await Account.verify(address, id)
await DB.accountHolders.create({
user : id,
address: address,
role : false
})
response.writeHead(200, {'Content-Type': 'application/json'})
response.write(JSON.stringify({success: true, id: id}))
response.end()
} catch (error) {
console.log(error)
response.writeHead(500, {'Content-Type': 'application/json'})
response.write(JSON.stringify({success: false, message: `An error occurred`}))
response.end()
}
})
const api = app.listen(process.env.PORT, '0.0.0.0', function () {
const host = api.address().address
const port = api.address().port
console.log('Barkeep Kessing API listening at https://%s:%s', host, port)
})