@discordanalytics/core 2.8.2 → 2.9.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts DELETED
@@ -1,136 +0,0 @@
1
- import { GuildsStatsData, InteractionData, LocaleData, TrackGuildType } from './types';
2
- /**
3
- * DiscordAnalytics Base Class
4
- * @class AnalyticsBase
5
- * @description Base class for DiscordAnalytics
6
- * @param {string} api_key The API key for DiscordAnalytics
7
- * @param {boolean} debug Optional flag to enable debug mode /!\ MUST BE USED ONLY FOR DEBUGGING PURPOSES
8
- * @returns {AnalyticsBase} An instance of the AnalyticsBase class
9
- * @example
10
- * const analytics = new AnalyticsBase('YOUR_API_KEY');
11
- * analytics.sendStats('YOUR_CLIENT_ID', 0, 0);
12
- */
13
- export declare class AnalyticsBase {
14
- private readonly _api_key;
15
- private readonly _headers;
16
- private readonly debug_mode;
17
- stats_data: {
18
- date: string;
19
- guilds: number;
20
- users: number;
21
- interactions: InteractionData[];
22
- locales: LocaleData[];
23
- guildsLocales: LocaleData[];
24
- guildMembers: {
25
- little: number;
26
- medium: number;
27
- big: number;
28
- huge: number;
29
- };
30
- guildsStats: GuildsStatsData[];
31
- addedGuilds: number;
32
- removedGuilds: number;
33
- users_type: {
34
- admin: number;
35
- moderator: number;
36
- new_member: number;
37
- other: number;
38
- private_message: number;
39
- };
40
- custom_events: Record<string, number>;
41
- user_install_count: number;
42
- };
43
- client_id: string;
44
- constructor(api_key: string, debug?: boolean);
45
- debug(...args: any[]): void;
46
- error(content: any, exit?: boolean): void;
47
- /**
48
- * Custom events
49
- * /!\ Advanced users only
50
- * /!\ You need to initialize the class first
51
- * @param event_key The event key to track
52
- * @returns {CustomEvent} The CustomEvent instance
53
- * @example
54
- * const event = analytics.events('my_custom_event');
55
- * event.increment(1);
56
- * event.decrement(1);
57
- * event.set(10);
58
- */
59
- events(event_key: string): CustomEvent;
60
- updateOrInsert<T>(array: T[], match: (item: T) => boolean, update: (item: T) => void, insert: () => T): void;
61
- calculateGuildMembers(guildMembers: number[]): {
62
- little: number;
63
- medium: number;
64
- big: number;
65
- huge: number;
66
- };
67
- /**
68
- * Track guilds
69
- * /!\ Advanced users only
70
- * /!\ You need to initialize the class first
71
- * @param {TrackGuildType} type 'create' if the event is guildCreate and 'delete' if is guildDelete
72
- */
73
- trackGuilds(type: TrackGuildType): void;
74
- /**
75
- * API call with retries
76
- * @param method The HTTP method to use (GET, POST, PUT, DELETE)
77
- * @param url The URL to call
78
- * @param body The body to send (optional)
79
- * @param max_retries The maximum number of retries (default: 5)
80
- * @param backoff_factor The backoff factor to use (default: 0.5)
81
- * @returns {Promise<void | Response>} The response from the API
82
- */
83
- api_call_with_retries(method: string, url: string, body?: string, max_retries?: number, backoff_factor?: number): Promise<void | Response>;
84
- /**
85
- * Send stats to the API
86
- * @param client_id The client ID of the bot
87
- * @param guild_count The number of guilds the bot is in (default: 0)
88
- * @param user_count The number of users the bot is in (default: 0)
89
- * @param user_install_count The number of user installs (default: 0)
90
- * @param guild_members The number of members in each guild (optional)
91
- * @returns {Promise<void>} A promise that resolves when the stats are sent
92
- */
93
- sendStats(client_id: string, guild_count?: number, user_count?: number, user_install_count?: number, guild_members?: number[]): Promise<void>;
94
- }
95
- /**
96
- * CustomEvent class
97
- * @class CustomEvent
98
- * @description Class for custom events
99
- * @param {AnalyticsBase} analytics The AnalyticsBase instance
100
- * @param {string} event_key The event key to track
101
- * @returns {CustomEvent} An instance of the CustomEvent class
102
- * @example
103
- * const event = analytics.events('my_custom_event');
104
- * event.increment(1);
105
- * event.decrement(1);
106
- * event.set(10);
107
- * event.get();
108
- */
109
- export declare class CustomEvent {
110
- private readonly _analytics;
111
- private readonly _event_key;
112
- private _last_action;
113
- constructor(analytics: AnalyticsBase, event_key: string);
114
- private ensure;
115
- /**
116
- * Increment the event by a value
117
- * @param value The value to increment the event by (default: 1)
118
- */
119
- increment(value?: number): void;
120
- /**
121
- * Decrement the event by a value
122
- * @param value The value to decrement the event by (default: 1)
123
- */
124
- decrement(value?: number): void;
125
- /**
126
- * Set the event to a value
127
- * @param value The value to set the event to
128
- */
129
- set(value: number): void;
130
- /**
131
- * Get the event value
132
- * @returns {number} The event value
133
- */
134
- get(): number;
135
- }
136
- export * from './types';
package/dist/index.js DELETED
@@ -1,293 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
- };
16
- Object.defineProperty(exports, "__esModule", { value: true });
17
- exports.CustomEvent = exports.AnalyticsBase = void 0;
18
- const types_1 = require("./types");
19
- /**
20
- * DiscordAnalytics Base Class
21
- * @class AnalyticsBase
22
- * @description Base class for DiscordAnalytics
23
- * @param {string} api_key The API key for DiscordAnalytics
24
- * @param {boolean} debug Optional flag to enable debug mode /!\ MUST BE USED ONLY FOR DEBUGGING PURPOSES
25
- * @returns {AnalyticsBase} An instance of the AnalyticsBase class
26
- * @example
27
- * const analytics = new AnalyticsBase('YOUR_API_KEY');
28
- * analytics.sendStats('YOUR_CLIENT_ID', 0, 0);
29
- */
30
- class AnalyticsBase {
31
- _api_key;
32
- _headers;
33
- debug_mode = false;
34
- stats_data = {
35
- date: new Date().toISOString().slice(0, 10),
36
- guilds: 0,
37
- users: 0,
38
- interactions: [],
39
- locales: [],
40
- guildsLocales: [],
41
- guildMembers: {
42
- little: 0,
43
- medium: 0,
44
- big: 0,
45
- huge: 0,
46
- },
47
- guildsStats: [],
48
- addedGuilds: 0,
49
- removedGuilds: 0,
50
- users_type: {
51
- admin: 0,
52
- moderator: 0,
53
- new_member: 0,
54
- other: 0,
55
- private_message: 0,
56
- },
57
- custom_events: {},
58
- user_install_count: 0,
59
- };
60
- client_id = '';
61
- constructor(api_key, debug = false) {
62
- this._api_key = api_key;
63
- this.debug_mode = debug;
64
- this._headers = {
65
- 'Content-Type': 'application/json',
66
- Authorization: `Bot ${this._api_key}`,
67
- };
68
- }
69
- debug(...args) {
70
- if (this.debug_mode)
71
- console.debug(...args);
72
- }
73
- error(content, exit = false) {
74
- console.error(content);
75
- if (exit)
76
- process.exit(1);
77
- }
78
- /**
79
- * Custom events
80
- * /!\ Advanced users only
81
- * /!\ You need to initialize the class first
82
- * @param event_key The event key to track
83
- * @returns {CustomEvent} The CustomEvent instance
84
- * @example
85
- * const event = analytics.events('my_custom_event');
86
- * event.increment(1);
87
- * event.decrement(1);
88
- * event.set(10);
89
- */
90
- events(event_key) {
91
- this.debug(`[DISCORDANALYTICS] Getting event ${event_key}`);
92
- if (typeof event_key !== 'string')
93
- throw new Error(`[DISCORDANALYTICS] ${types_1.ErrorCodes.INVALID_VALUE_TYPE}`);
94
- return new CustomEvent(this, event_key);
95
- }
96
- updateOrInsert(array, match, update, insert) {
97
- const item = array.find(match);
98
- if (item)
99
- update(item);
100
- else
101
- array.push(insert());
102
- }
103
- calculateGuildMembers(guildMembers) {
104
- return guildMembers.reduce((acc, count) => {
105
- if (count <= 100)
106
- acc.little++;
107
- else if (count <= 500)
108
- acc.medium++;
109
- else if (count <= 1500)
110
- acc.big++;
111
- else
112
- acc.huge++;
113
- return acc;
114
- }, { little: 0, medium: 0, big: 0, huge: 0 });
115
- }
116
- /**
117
- * Track guilds
118
- * /!\ Advanced users only
119
- * /!\ You need to initialize the class first
120
- * @param {TrackGuildType} type 'create' if the event is guildCreate and 'delete' if is guildDelete
121
- */
122
- trackGuilds(type) {
123
- this.debug(`[DISCORDANALYTICS] trackGuilds(${type}) triggered`);
124
- if (type === 'create')
125
- this.stats_data.addedGuilds++;
126
- else
127
- this.stats_data.removedGuilds++;
128
- }
129
- /**
130
- * API call with retries
131
- * @param method The HTTP method to use (GET, POST, PUT, DELETE)
132
- * @param url The URL to call
133
- * @param body The body to send (optional)
134
- * @param max_retries The maximum number of retries (default: 5)
135
- * @param backoff_factor The backoff factor to use (default: 0.5)
136
- * @returns {Promise<void | Response>} The response from the API
137
- */
138
- async api_call_with_retries(method, url, body, max_retries = 5, backoff_factor = 0.5) {
139
- let retries = 0;
140
- let response;
141
- while (retries < max_retries) {
142
- try {
143
- response = await fetch(url, {
144
- method,
145
- headers: this._headers,
146
- body,
147
- });
148
- if (response.ok)
149
- return response;
150
- else if (response.status === 401)
151
- return this.error(`[DISCORDANALYTICS] ${types_1.ErrorCodes.INVALID_API_TOKEN}`);
152
- else if (response.status === 423)
153
- return this.error(`[DISCORDANALYTICS] ${types_1.ErrorCodes.SUSPENDED_BOT}`);
154
- else if (response.status === 404 && url.includes('events'))
155
- return this.error(`[DISCORDANALYTICS] ${types_1.ErrorCodes.INVALID_EVENT_KEY}`, true);
156
- else if (response.status !== 200)
157
- return this.error(`[DISCORDANALYTICS] ${types_1.ErrorCodes.INVALID_RESPONSE}`);
158
- }
159
- catch (error) {
160
- retries++;
161
- const retry_after = Math.pow(2, retries) * backoff_factor;
162
- this.error(`[DISCORDANALYTICS] Error: ${error}. Retrying in ${retry_after} seconds...`);
163
- if (retries >= max_retries)
164
- return this.error(`[DISCORDANALYTICS] ${types_1.ErrorCodes.MAX_RETRIES_EXCEEDED}`);
165
- await new Promise((resolve) => setTimeout(resolve, retry_after * 1000));
166
- }
167
- }
168
- }
169
- /**
170
- * Send stats to the API
171
- * @param client_id The client ID of the bot
172
- * @param guild_count The number of guilds the bot is in (default: 0)
173
- * @param user_count The number of users the bot is in (default: 0)
174
- * @param user_install_count The number of user installs (default: 0)
175
- * @param guild_members The number of members in each guild (optional)
176
- * @returns {Promise<void>} A promise that resolves when the stats are sent
177
- */
178
- async sendStats(client_id, guild_count = 0, user_count = 0, user_install_count = 0, guild_members = []) {
179
- this.debug('[DISCORDANALYTICS] Sending stats...');
180
- const url = types_1.ApiEndpoints.EDIT_STATS_URL.replace(':id', client_id);
181
- const body = JSON.stringify(this.stats_data);
182
- await this.api_call_with_retries('POST', url, body);
183
- this.debug('[DISCORDANALYTICS] Stats sent to the API', body);
184
- this.stats_data = {
185
- date: new Date().toISOString().slice(0, 10),
186
- guilds: guild_count,
187
- users: user_count,
188
- interactions: [],
189
- locales: [],
190
- guildsLocales: [],
191
- guildMembers: this.calculateGuildMembers(guild_members),
192
- guildsStats: [],
193
- addedGuilds: 0,
194
- removedGuilds: 0,
195
- users_type: {
196
- admin: 0,
197
- moderator: 0,
198
- new_member: 0,
199
- other: 0,
200
- private_message: 0,
201
- },
202
- custom_events: this.stats_data.custom_events,
203
- user_install_count,
204
- };
205
- }
206
- }
207
- exports.AnalyticsBase = AnalyticsBase;
208
- /**
209
- * CustomEvent class
210
- * @class CustomEvent
211
- * @description Class for custom events
212
- * @param {AnalyticsBase} analytics The AnalyticsBase instance
213
- * @param {string} event_key The event key to track
214
- * @returns {CustomEvent} An instance of the CustomEvent class
215
- * @example
216
- * const event = analytics.events('my_custom_event');
217
- * event.increment(1);
218
- * event.decrement(1);
219
- * event.set(10);
220
- * event.get();
221
- */
222
- class CustomEvent {
223
- _analytics;
224
- _event_key;
225
- _last_action;
226
- constructor(analytics, event_key) {
227
- this._analytics = analytics;
228
- this._event_key = event_key;
229
- this._last_action = "";
230
- this.ensure();
231
- }
232
- async ensure() {
233
- if (typeof this._analytics.stats_data.custom_events[this._event_key] !== 'number' && process.env.NODE_ENV === 'production') {
234
- this._analytics.debug(`[DISCORDANALYTICS] Fetching value for event ${this._event_key}`);
235
- const url = types_1.ApiEndpoints.EVENT_URL.replace(':id', this._analytics.client_id).replace(':event', this._event_key);
236
- const res = await this._analytics.api_call_with_retries('GET', url);
237
- if (res instanceof Response && this._last_action !== 'set') {
238
- const data = await res.json();
239
- this._analytics.stats_data.custom_events[this._event_key] = (this._analytics.stats_data.custom_events[this._event_key] || 0) + (data.today_value || 0);
240
- }
241
- this._analytics.debug(`[DISCORDANALYTICS] Value fetched for event ${this._event_key}`);
242
- }
243
- }
244
- /**
245
- * Increment the event by a value
246
- * @param value The value to increment the event by (default: 1)
247
- */
248
- increment(value = 1) {
249
- this._analytics.debug(`[DISCORDANALYTICS] Incrementing event ${this._event_key} by ${value}`);
250
- if (typeof value !== 'number')
251
- throw new Error(`[DISCORDANALYTICS] ${types_1.ErrorCodes.INVALID_VALUE_TYPE}`);
252
- if (value < 0)
253
- throw new Error(`[DISCORDANALYTICS] ${types_1.ErrorCodes.INVALID_EVENTS_COUNT}`);
254
- this._analytics.stats_data.custom_events[this._event_key] = (this._analytics.stats_data.custom_events[this._event_key] || 0) + value;
255
- this._last_action = 'increment';
256
- }
257
- /**
258
- * Decrement the event by a value
259
- * @param value The value to decrement the event by (default: 1)
260
- */
261
- decrement(value = 1) {
262
- this._analytics.debug(`[DISCORDANALYTICS] Decrementing event ${this._event_key} by ${value}`);
263
- if (typeof value !== 'number')
264
- throw new Error(`[DISCORDANALYTICS] ${types_1.ErrorCodes.INVALID_VALUE_TYPE}`);
265
- if (value < 0 || this.get() - value < 0)
266
- throw new Error(`[DISCORDANALYTICS] ${types_1.ErrorCodes.INVALID_EVENTS_COUNT}`);
267
- this._analytics.stats_data.custom_events[this._event_key] -= value;
268
- this._last_action = 'decrement';
269
- }
270
- /**
271
- * Set the event to a value
272
- * @param value The value to set the event to
273
- */
274
- set(value) {
275
- this._analytics.debug(`[DISCORDANALYTICS] Setting event ${this._event_key} to ${value}`);
276
- if (typeof value !== 'number')
277
- throw new Error(`[DISCORDANALYTICS] ${types_1.ErrorCodes.INVALID_VALUE_TYPE}`);
278
- if (value < 0)
279
- throw new Error(`[DISCORDANALYTICS] ${types_1.ErrorCodes.INVALID_EVENTS_COUNT}`);
280
- this._analytics.stats_data.custom_events[this._event_key] = value;
281
- this._last_action = 'set';
282
- }
283
- /**
284
- * Get the event value
285
- * @returns {number} The event value
286
- */
287
- get() {
288
- this._analytics.debug(`[DISCORDANALYTICS] Getting event ${this._event_key}`);
289
- return this._analytics.stats_data.custom_events[this._event_key];
290
- }
291
- }
292
- exports.CustomEvent = CustomEvent;
293
- __exportStar(require("./types"), exports);
package/dist/types.d.ts DELETED
@@ -1,56 +0,0 @@
1
- export declare const api_url = "https://discordanalytics.xyz/api";
2
- export declare const ApiEndpoints: {
3
- EDIT_SETTINGS_URL: string;
4
- EDIT_STATS_URL: string;
5
- EVENT_URL: string;
6
- };
7
- export declare const ErrorCodes: {
8
- INVALID_CLIENT_TYPE: string;
9
- CLIENT_NOT_READY: string;
10
- INVALID_RESPONSE: string;
11
- INVALID_API_TOKEN: string;
12
- DATA_NOT_SENT: string;
13
- SUSPENDED_BOT: string;
14
- INSTANCE_NOT_INITIALIZED: string;
15
- INVALID_EVENTS_COUNT: string;
16
- INVALID_VALUE_TYPE: string;
17
- INVALID_EVENT_KEY: string;
18
- MAX_RETRIES_EXCEEDED: string;
19
- };
20
- export type Locale = 'id' | 'en-US' | 'en-GB' | 'bg' | 'zh-CN' | 'zh-TW' | 'hr' | 'cs' | 'da' | 'nl' | 'fi' | 'fr' | 'de' | 'el' | 'hi' | 'hu' | 'it' | 'ja' | 'ko' | 'lt' | 'no' | 'pl' | 'pt-BR' | 'ro' | 'ru' | 'es-ES' | 'sv-SE' | 'th' | 'tr' | 'uk' | 'vi';
21
- export declare enum InteractionType {
22
- Ping = 1,
23
- ApplicationCommand = 2,
24
- MessageComponent = 3,
25
- ApplicationCommandAutocomplete = 4,
26
- ModalSubmit = 5
27
- }
28
- export declare enum ApplicationCommandType {
29
- ChatInputCommand = 1,
30
- UserCommand = 2,
31
- MessageCommand = 3
32
- }
33
- export interface InteractionData {
34
- name: string;
35
- number: number;
36
- type: InteractionType;
37
- command_type?: ApplicationCommandType;
38
- }
39
- export interface LocaleData {
40
- locale: Locale;
41
- number: number;
42
- }
43
- export interface GuildsStatsData {
44
- guildId: string;
45
- name: string;
46
- icon: string | null;
47
- members: number;
48
- interactions: number;
49
- }
50
- export interface AnalyticsOptions {
51
- client: any;
52
- api_key: string;
53
- sharded?: boolean;
54
- debug?: boolean;
55
- }
56
- export type TrackGuildType = 'create' | 'delete';
package/dist/types.js DELETED
@@ -1,36 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.ApplicationCommandType = exports.InteractionType = exports.ErrorCodes = exports.ApiEndpoints = exports.api_url = void 0;
4
- exports.api_url = 'https://discordanalytics.xyz/api';
5
- exports.ApiEndpoints = {
6
- EDIT_SETTINGS_URL: `${exports.api_url}/bots/:id`,
7
- EDIT_STATS_URL: `${exports.api_url}/bots/:id/stats`,
8
- EVENT_URL: `${exports.api_url}/bots/:id/events/:event`,
9
- };
10
- exports.ErrorCodes = {
11
- INVALID_CLIENT_TYPE: 'Invalid client type, please use a valid client.',
12
- CLIENT_NOT_READY: 'Client is not ready, please start the client first.',
13
- INVALID_RESPONSE: 'Invalid response from the API, please try again later.',
14
- INVALID_API_TOKEN: 'Invalid API token, please get one at ' + exports.api_url.split('/api')[0] + ' and try again.',
15
- DATA_NOT_SENT: 'Data cannot be sent to the API, I will try again in a minute.',
16
- SUSPENDED_BOT: 'Your bot has been suspended, please check your mailbox for more information.',
17
- INSTANCE_NOT_INITIALIZED: 'It seem that you didn\'t initialize your instance. Please check the docs for more informations.',
18
- INVALID_EVENTS_COUNT: 'invalid events count',
19
- INVALID_VALUE_TYPE: 'invalid value type',
20
- INVALID_EVENT_KEY: 'invalid event key',
21
- MAX_RETRIES_EXCEEDED: 'Max retries exceeded, please check your network connection or the API status.',
22
- };
23
- var InteractionType;
24
- (function (InteractionType) {
25
- InteractionType[InteractionType["Ping"] = 1] = "Ping";
26
- InteractionType[InteractionType["ApplicationCommand"] = 2] = "ApplicationCommand";
27
- InteractionType[InteractionType["MessageComponent"] = 3] = "MessageComponent";
28
- InteractionType[InteractionType["ApplicationCommandAutocomplete"] = 4] = "ApplicationCommandAutocomplete";
29
- InteractionType[InteractionType["ModalSubmit"] = 5] = "ModalSubmit";
30
- })(InteractionType || (exports.InteractionType = InteractionType = {}));
31
- var ApplicationCommandType;
32
- (function (ApplicationCommandType) {
33
- ApplicationCommandType[ApplicationCommandType["ChatInputCommand"] = 1] = "ChatInputCommand";
34
- ApplicationCommandType[ApplicationCommandType["UserCommand"] = 2] = "UserCommand";
35
- ApplicationCommandType[ApplicationCommandType["MessageCommand"] = 3] = "MessageCommand";
36
- })(ApplicationCommandType || (exports.ApplicationCommandType = ApplicationCommandType = {}));