-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
86 lines (77 loc) · 2.34 KB
/
index.js
File metadata and controls
86 lines (77 loc) · 2.34 KB
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
/* eslint-disable require-jsdoc */
/* eslint-disable max-len */
const EventEmitter = require('events');
const fetch = require('node-fetch');
const isalibrary = (library, client) => {
try {
const alib = require.cache[require.resolve(library)];
return alib && client instanceof alib.exports.Client;
} catch (e) {
return false;
}
};
const isCompatible = (client) => isalibrary('discord.js', client) || isalibrary('eris', client);
class TCAPI extends EventEmitter {
/**
*
* @param {string} token The token for the client to be able to post to the API
* @param {any} options webhook options
* @param {any} client the bots client
*/
constructor(token, options, client) {
super();
this.token = token;
this.client = client;
this.options = options || {};
if (options) {
const TCAPIWebhook = require('./webhook.js');
this.webhook = new TCAPIWebhook(options.port, options.path);
}
if (!token) throw new Error('[TCAPI] You have not provided an API key.');
if (!client) {
return;
}
if (client && isCompatible(client)) {
/**
* This is emited if the post was successful
* @event success
*/
/**
* This is emited if the post had an error
* @event error
* @param {error} error the actual error i guess
*/
client.on('ready', () =>{
this.post()
.then(() => this.emit('success'))
.catch((e) => this.emit('error', e));
});
setInterval(() => {
this.post()
.then(() => this.emit('success'))
.catch((e) => this.emit('error', e));
// Posts every 30 minutes
}, 1800000);
} else {
throw new Error('[TCAPI] Your client is not compatible, to post your stats please read https://docs.topcord.xyz/#/API');
}
}
/**
* @param {any} body the body to send to the api
* @returns body
*/
post() {
const body = {'guilds': this.client.guilds.size || this.client.guilds.cache.size, 'shards': this.client.options.shardCount};
return fetch(`https://api.topcord.xyz/bot/${this.client.user.id}/stats`, {
method: 'post',
body: JSON.stringify(body),
headers: {
'Content-Type': 'application/json',
'Authorization': this.token,
},
}).then((body) => {
console.log(`[TCAPI.JS API RESPONSE] ${body.statusText}`); return body;
});
}
}
module.exports = TCAPI;