@squord/sdk 0.0.0-stage → 0.1.0
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/README.md +544 -2
- package/dist/api-DbHoBFJY.d.cts +726 -0
- package/dist/api-DbHoBFJY.d.ts +726 -0
- package/dist/index.cjs +3881 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +2340 -0
- package/dist/index.d.ts +2340 -0
- package/dist/index.js +3779 -0
- package/dist/index.js.map +1 -0
- package/dist/testing/index.cjs +789 -0
- package/dist/testing/index.cjs.map +1 -0
- package/dist/testing/index.d.cts +261 -0
- package/dist/testing/index.d.ts +261 -0
- package/dist/testing/index.js +763 -0
- package/dist/testing/index.js.map +1 -0
- package/package.json +70 -4
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,2340 @@
|
|
|
1
|
+
import { B as ButtonStyle, A as APIButton, a as APISelectOption, b as APISelectMenu, c as APIComponentRow, d as APIEmbedInput, e as APIEmbed, f as AllowedMentions, S as Snowflake, g as APIMessageCreateBody, h as APICommand, i as APICommandInput, j as APIBot, k as APICurrentUser, l as APIChannel, m as APIChannelTreeNode, n as APIThreadCreateBody, o as APIThread, p as APIForumPostCreateBody, q as APIThreadListParams, r as APIThreadPage, s as APIInteractionCallbackBody, t as APIInteractionReplyData, u as APIGuild, v as APIMember, C as CursorPaginationParams, w as APIMemberPage, x as APIMemberEditBody, I as ISODate, y as APIRole, z as APIMemberBanBody, D as APIMemberBan, E as APIMessage, F as APIMessageListParams, G as APIMessagePage, H as APIReaction, J as APIUploadCreateBody, K as APIUploadReservation, L as APIUploadConfirmBody, M as APIUpload, N as APIUser, O as MessageType, T as ThreadAutoArchiveMinutes, P as ChannelType, Q as APIInteraction, R as APIInteractionCommandData, U as APIInteractionComponentData, V as CommandOptionType, W as PermissionBits, X as APIChannelOverwrite, Y as APICommandOptionInput, Z as Page, _ as APIErrorBody, $ as APIValidationIssue } from './api-DbHoBFJY.js';
|
|
2
|
+
export { a0 as APIAttachment, a1 as APICommandOption, a2 as APICommandOptionChoice, a3 as APIForumTag, a4 as APIGuildRule, a5 as APIGuildSelf, a6 as APIMessageEditBody, a7 as APIMessageReplyTo, a8 as APIUploadTarget, a9 as AttachmentScanStatus, aa as Cursor, ab as GuildFlags, ac as InteractionCallbackType, ad as InteractionType, ae as MemberType, af as Nonce, ag as RoleManagedKind, ah as UploadStatus, ai as UserFlags, aj as channelMention, ak as roleMention, al as userMention } from './api-DbHoBFJY.js';
|
|
3
|
+
import { Readable } from 'node:stream';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Event emitter tipado, sem dependências externas.
|
|
7
|
+
*
|
|
8
|
+
* Suporta `on`, `once`, `off` e `emit`, com mapa de eventos estritamente
|
|
9
|
+
* tipado. Handlers síncronos e assíncronos são aceitos; erros de handlers
|
|
10
|
+
* assíncronos são capturados e entregues ao evento `error` da mesma instância
|
|
11
|
+
* (ou `uncaught`), sem derrubar o processo.
|
|
12
|
+
*/
|
|
13
|
+
type EventHandler<K> = [K] extends [unknown[]] ? (...args: K) => unknown : (payload: K) => unknown;
|
|
14
|
+
/** Converte o tipo de payload em tupla de argumentos (sem distribuir unions). */
|
|
15
|
+
type ArgsOf<K> = [K] extends [unknown[]] ? K : [K];
|
|
16
|
+
interface EventMap {
|
|
17
|
+
[event: string]: unknown;
|
|
18
|
+
}
|
|
19
|
+
declare class TypedEmitter<Events extends EventMap> {
|
|
20
|
+
private handlers;
|
|
21
|
+
/** Registra um handler. Devolve uma função que o remove. */
|
|
22
|
+
on<E extends keyof Events>(event: E, handler: EventHandler<Events[E]>): () => void;
|
|
23
|
+
/** Registra um handler que é removido após a primeira chamada. */
|
|
24
|
+
once<E extends keyof Events>(event: E, handler: EventHandler<Events[E]>): () => void;
|
|
25
|
+
/** Remove um handler (ou todos do evento, se omitido). */
|
|
26
|
+
off<E extends keyof Events>(event: E, handler?: EventHandler<Events[E]>): void;
|
|
27
|
+
/** Remove todos os handlers de todos os eventos. */
|
|
28
|
+
removeAllListeners(): void;
|
|
29
|
+
/** Emite um evento. Erros síncronos de handlers propagam para `error`. */
|
|
30
|
+
emit<E extends keyof Events>(event: E, ...args: ArgsOf<Events[E]>): boolean;
|
|
31
|
+
/** Quantos handlers estão registrados para um evento. */
|
|
32
|
+
listenerCount<E extends keyof Events>(event: E): number;
|
|
33
|
+
/** Nomes de eventos com pelo menos um handler. */
|
|
34
|
+
eventNames(): Array<keyof Events>;
|
|
35
|
+
private handleAsyncError;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Builders de componentes: botões e menus de seleção.
|
|
40
|
+
*
|
|
41
|
+
* Regras do Squord: uma mensagem tem até 5 linhas; cada linha guarda até 5
|
|
42
|
+
* botões **ou** exatamente 1 menu (nunca os dois); `customId` é único na
|
|
43
|
+
* mensagem (até 100 caracteres); `link` tem `url` e não tem `customId`.
|
|
44
|
+
*/
|
|
45
|
+
|
|
46
|
+
declare const ComponentLimits: {
|
|
47
|
+
readonly RowsPerMessage: 5;
|
|
48
|
+
readonly ButtonsPerRow: 5;
|
|
49
|
+
readonly CustomId: 100;
|
|
50
|
+
readonly Label: 80;
|
|
51
|
+
readonly OptionsPerMenu: 25;
|
|
52
|
+
};
|
|
53
|
+
declare class ButtonBuilder {
|
|
54
|
+
private readonly style;
|
|
55
|
+
private labelValue;
|
|
56
|
+
private customIdValue;
|
|
57
|
+
private urlValue;
|
|
58
|
+
private disabledValue;
|
|
59
|
+
constructor(style: ButtonStyle, labelValue: string);
|
|
60
|
+
/** Identificador da ação; obrigatório (e único na mensagem) fora do estilo `link`. */
|
|
61
|
+
setCustomId(customId: string): this;
|
|
62
|
+
/** URL aberta ao clicar; obrigatória e exclusiva do estilo `link`. */
|
|
63
|
+
setURL(url: string): this;
|
|
64
|
+
setDisabled(disabled: boolean): this;
|
|
65
|
+
setLabel(label: string): this;
|
|
66
|
+
build(): APIButton;
|
|
67
|
+
}
|
|
68
|
+
declare class SelectMenuBuilder {
|
|
69
|
+
private readonly customId;
|
|
70
|
+
private placeholderValue;
|
|
71
|
+
private minValuesValue;
|
|
72
|
+
private maxValuesValue;
|
|
73
|
+
private disabledValue;
|
|
74
|
+
private optionsValue;
|
|
75
|
+
constructor(customId: string);
|
|
76
|
+
setPlaceholder(placeholder: string): this;
|
|
77
|
+
setMinValues(min: number): this;
|
|
78
|
+
setMaxValues(max: number): this;
|
|
79
|
+
setDisabled(disabled: boolean): this;
|
|
80
|
+
addOption(option: APISelectOption): this;
|
|
81
|
+
addOptions(...options: APISelectOption[]): this;
|
|
82
|
+
build(): APISelectMenu;
|
|
83
|
+
}
|
|
84
|
+
declare class ActionRowBuilder {
|
|
85
|
+
private components;
|
|
86
|
+
/** Adiciona um botão (até 5 por linha). */
|
|
87
|
+
addButton(button: ButtonBuilder | APIButton): this;
|
|
88
|
+
/** Define o menu da linha (exatamente 1, sozinho). */
|
|
89
|
+
setSelectMenu(menu: SelectMenuBuilder | APISelectMenu): this;
|
|
90
|
+
addComponents(...components: Array<ButtonBuilder | SelectMenuBuilder | APIButton | APISelectMenu>): this;
|
|
91
|
+
build(): APIComponentRow;
|
|
92
|
+
}
|
|
93
|
+
/** Atalhos para botões dos quatro estilos. */
|
|
94
|
+
declare const Buttons: {
|
|
95
|
+
primary: (label: string) => ButtonBuilder;
|
|
96
|
+
secondary: (label: string) => ButtonBuilder;
|
|
97
|
+
danger: (label: string) => ButtonBuilder;
|
|
98
|
+
link: (label: string) => ButtonBuilder;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* `EmbedBuilder`: cria embeds tipados com validação local dos limites reais
|
|
103
|
+
* da plataforma (antes de gastar uma chamada com um `422 VALIDATION_FAILED`).
|
|
104
|
+
*
|
|
105
|
+
* Limites do Squord: 10 embeds por mensagem, 25 campos por embed, título 256,
|
|
106
|
+
* descrição 4096, nome de campo 256, valor de campo 1024, rodapé 2048,
|
|
107
|
+
* autor 256 e 6000 caracteres somando o texto dos embeds da mensagem.
|
|
108
|
+
*/
|
|
109
|
+
|
|
110
|
+
declare const EmbedLimits: {
|
|
111
|
+
readonly EmbedsPerMessage: 10;
|
|
112
|
+
readonly FieldsPerEmbed: 25;
|
|
113
|
+
readonly Title: 256;
|
|
114
|
+
readonly Description: 4096;
|
|
115
|
+
readonly FieldName: 256;
|
|
116
|
+
readonly FieldValue: 1024;
|
|
117
|
+
readonly FooterText: 2048;
|
|
118
|
+
readonly AuthorName: 256;
|
|
119
|
+
readonly TotalTextPerMessage: 6000;
|
|
120
|
+
};
|
|
121
|
+
interface EmbedFieldInput {
|
|
122
|
+
name: string;
|
|
123
|
+
value: string;
|
|
124
|
+
inline?: boolean;
|
|
125
|
+
}
|
|
126
|
+
interface EmbedAuthorInput {
|
|
127
|
+
name: string;
|
|
128
|
+
url?: string | null;
|
|
129
|
+
iconUrl?: string | null;
|
|
130
|
+
}
|
|
131
|
+
interface EmbedFooterInput {
|
|
132
|
+
text: string;
|
|
133
|
+
iconUrl?: string | null;
|
|
134
|
+
}
|
|
135
|
+
/** Converte cores: `#rrggbb` → inteiro, inteiro → `#rrggbb`. */
|
|
136
|
+
declare function normalizeEmbedColor(color: number | string): number;
|
|
137
|
+
declare class EmbedBuilder {
|
|
138
|
+
private titleValue;
|
|
139
|
+
private descriptionValue;
|
|
140
|
+
private urlValue;
|
|
141
|
+
private colorValue;
|
|
142
|
+
private timestampValue;
|
|
143
|
+
private authorValue;
|
|
144
|
+
private footerValue;
|
|
145
|
+
private imageValue;
|
|
146
|
+
private thumbnailValue;
|
|
147
|
+
private fieldsValue;
|
|
148
|
+
/** Título do embed (até 256 caracteres). */
|
|
149
|
+
setTitle(title: string): this;
|
|
150
|
+
/** Descrição (até 4096 caracteres). */
|
|
151
|
+
setDescription(description: string): this;
|
|
152
|
+
/** URL do título (só `http://` ou `https://`). */
|
|
153
|
+
setURL(url: string): this;
|
|
154
|
+
/** Cor: inteiro de 0 a 16777215 ou `#rrggbb`. */
|
|
155
|
+
setColor(color: number | string): this;
|
|
156
|
+
/** Momento exibido no rodapé. Um `Date` ou string ISO 8601 com fuso. */
|
|
157
|
+
setTimestamp(timestamp?: Date | string): this;
|
|
158
|
+
/** Autor exibido no topo (nome até 256 caracteres). */
|
|
159
|
+
setAuthor(author: EmbedAuthorInput | null): this;
|
|
160
|
+
/** Rodapé (texto até 2048 caracteres). */
|
|
161
|
+
setFooter(footer: EmbedFooterInput | null): this;
|
|
162
|
+
/** Imagem principal (baixada e hospedada pelo Squord em segundo plano). */
|
|
163
|
+
setImage(url: string): this;
|
|
164
|
+
/** Miniatura. */
|
|
165
|
+
setThumbnail(url: string): this;
|
|
166
|
+
/** Adiciona um campo (nome até 256, valor até 1024). */
|
|
167
|
+
addField(name: string, value: string, inline?: boolean): this;
|
|
168
|
+
/** Adiciona vários campos. */
|
|
169
|
+
addFields(...fields: EmbedFieldInput[]): this;
|
|
170
|
+
/** Remove todos os campos. */
|
|
171
|
+
clearFields(): this;
|
|
172
|
+
/** Payload pronto para o campo `embeds` (só campos preenchidos). */
|
|
173
|
+
build(): APIEmbedInput;
|
|
174
|
+
/** Soma dos textos do embed (para conferir o limite de 6000 por mensagem). */
|
|
175
|
+
get textLength(): number;
|
|
176
|
+
/** Cria um builder a partir de um payload existente. */
|
|
177
|
+
static from(embed: APIEmbed | APIEmbedInput): EmbedBuilder;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Normalização de payloads de mensagem: aceita strings, objetos crus e
|
|
182
|
+
* builders, e devolve o corpo aceito pela API.
|
|
183
|
+
*
|
|
184
|
+
* Menções são seguras por padrão: quando `allowedMentions` não é informado,
|
|
185
|
+
* o SDK envia `{ users: true, roles: false, everyone: false }` — o padrão
|
|
186
|
+
* da plataforma — evitando menções acidentais em massa.
|
|
187
|
+
*/
|
|
188
|
+
|
|
189
|
+
/** Payload de envio/edição aceito pelos métodos `send`/`reply`/`edit`. */
|
|
190
|
+
interface MessagePayload {
|
|
191
|
+
content?: string;
|
|
192
|
+
embeds?: Array<APIEmbedInput | EmbedBuilder>;
|
|
193
|
+
components?: Array<APIComponentRow | ActionRowBuilder>;
|
|
194
|
+
allowedMentions?: AllowedMentions;
|
|
195
|
+
replyToId?: Snowflake;
|
|
196
|
+
attachmentIds?: Snowflake[];
|
|
197
|
+
nonce?: string;
|
|
198
|
+
ephemeral?: boolean;
|
|
199
|
+
}
|
|
200
|
+
/** Uma mensagem pode ser passada como string (só `content`) ou como payload. */
|
|
201
|
+
type MessagePayloadLike = string | MessagePayload;
|
|
202
|
+
/** Converte builders e valores crus no formato da API. */
|
|
203
|
+
declare function resolveMessagePayload(payload: MessagePayloadLike): APIMessageCreateBody & {
|
|
204
|
+
ephemeral?: boolean;
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Logger estruturado com redação automática de segredos.
|
|
209
|
+
*
|
|
210
|
+
* Tokens de bot (`sqb_...`) e tokens de interação são substituídos por
|
|
211
|
+
* `[REDACTED]` antes de qualquer entrega. O logger nunca registra o conteúdo
|
|
212
|
+
* de mensagens por conta própria: os eventos são emitidos, mas o logger só
|
|
213
|
+
* fala de metadados operacionais.
|
|
214
|
+
*/
|
|
215
|
+
type LogLevel = "debug" | "info" | "warn" | "error" | "silent";
|
|
216
|
+
interface Logger {
|
|
217
|
+
debug(message: string, meta?: Record<string, unknown>): void;
|
|
218
|
+
info(message: string, meta?: Record<string, unknown>): void;
|
|
219
|
+
warn(message: string, meta?: Record<string, unknown>): void;
|
|
220
|
+
error(message: string, meta?: Record<string, unknown>): void;
|
|
221
|
+
/** Cria um logger filho com campos fixos (ex.: `rest`, `gateway`). */
|
|
222
|
+
child(prefix: string): Logger;
|
|
223
|
+
}
|
|
224
|
+
/** Redação aplicada a todas as saídas do logger padrão. */
|
|
225
|
+
declare function redact(input: string): string;
|
|
226
|
+
interface ConsoleLoggerOptions {
|
|
227
|
+
/** Nível mínimo exibido. Padrão: `silent` (o SDK não imprime nada). */
|
|
228
|
+
level?: LogLevel;
|
|
229
|
+
/** Destino dos logs. Padrão: `console`. */
|
|
230
|
+
write?: (line: string) => void;
|
|
231
|
+
}
|
|
232
|
+
declare function createConsoleLogger(options?: ConsoleLoggerOptions): Logger;
|
|
233
|
+
/** Logger que descarta tudo. Útil como padrão e em testes. */
|
|
234
|
+
declare const noopLogger: Logger;
|
|
235
|
+
/**
|
|
236
|
+
* Atende por `process.env.SQUORD_LOG` (`debug|info|warn|error`) e cria o
|
|
237
|
+
* logger padrão. `debug` também é habilitado por `SQUORD_DEBUG=1`.
|
|
238
|
+
*/
|
|
239
|
+
declare function loggerFromEnv(): Logger;
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Cliente REST do Squord.
|
|
243
|
+
*
|
|
244
|
+
* Encapsula `https://api.squord.com.br/api/v1` com:
|
|
245
|
+
* - autenticação por token de bot (`Authorization: Bot sqb_...`);
|
|
246
|
+
* - timeout configurável e cancelamento via `AbortSignal`;
|
|
247
|
+
* - `x-request-id` em toda requisição (o valor volta nos erros);
|
|
248
|
+
* - respeito aos limites de taxa: espera `details.retryAfter` em 429,
|
|
249
|
+
* observa os headers `X-RateLimit-*` e aplica um teto global conservador;
|
|
250
|
+
* - retentativas para falhas transitórias (5xx, rede, 429) **somente em
|
|
251
|
+
* operações idempotentes ou protegidas por `nonce`** — a regra de ouro:
|
|
252
|
+
* nunca repetir automaticamente uma operação sem saber se a primeira foi
|
|
253
|
+
* processada;
|
|
254
|
+
* - erros tipados (veja `../errors`).
|
|
255
|
+
*/
|
|
256
|
+
|
|
257
|
+
type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
|
|
258
|
+
interface RestClientOptions {
|
|
259
|
+
/** URL base da API. Padrão: `https://api.squord.com.br/api/v1`. */
|
|
260
|
+
baseURL?: string;
|
|
261
|
+
/** Token do bot (`sqb_...`). O SDK adiciona o prefixo `Bot `. */
|
|
262
|
+
token: string;
|
|
263
|
+
/** Timeout por requisição, em milissegundos. Padrão: 15000. */
|
|
264
|
+
timeoutMs?: number;
|
|
265
|
+
/**
|
|
266
|
+
* Retentativas automáticas adicionais para falhas transitórias
|
|
267
|
+
* (429, 5xx, rede). Padrão: 3.
|
|
268
|
+
*/
|
|
269
|
+
maxRetries?: number;
|
|
270
|
+
/**
|
|
271
|
+
* Teto global de requisições por segundo, abaixo do `BOT_GLOBAL`
|
|
272
|
+
* oficial (50/s). Padrão: 45. Use `0` para desligar.
|
|
273
|
+
*/
|
|
274
|
+
globalRequestsPerSecond?: number;
|
|
275
|
+
/** Implementação de fetch (injetável para testes). Padrão: global `fetch`. */
|
|
276
|
+
fetchImpl?: typeof fetch;
|
|
277
|
+
/** Logger. O SDK não imprime nada por padrão. */
|
|
278
|
+
logger?: Logger;
|
|
279
|
+
}
|
|
280
|
+
interface RequestOptions {
|
|
281
|
+
/** Parâmetros de query string (valores `undefined`/`null` são omitidos). */
|
|
282
|
+
query?: Record<string, string | number | boolean | undefined | null>;
|
|
283
|
+
/** Corpo JSON da requisição. */
|
|
284
|
+
body?: unknown;
|
|
285
|
+
/** Sinal de cancelamento externo. */
|
|
286
|
+
signal?: AbortSignal;
|
|
287
|
+
/** Id de requisição para rastreamento (`x-request-id`). */
|
|
288
|
+
requestId?: string;
|
|
289
|
+
/**
|
|
290
|
+
* `false` para rotas públicas, como os callbacks de interação
|
|
291
|
+
* (`/interactions/{id}/{token}/callback`), que não levam o header
|
|
292
|
+
* `Authorization`. Padrão: `true`.
|
|
293
|
+
*/
|
|
294
|
+
auth?: boolean;
|
|
295
|
+
/**
|
|
296
|
+
* Se a operação pode ser repetida com segurança após falha incerta
|
|
297
|
+
* (timeout de rede, 5xx). Padrão: `true` para GET/PUT/DELETE e `false`
|
|
298
|
+
* para POST. Operações POST protegidas por `nonce` (envio de mensagens,
|
|
299
|
+
* confirmação de upload) devem marcar `true`.
|
|
300
|
+
*/
|
|
301
|
+
retryable?: boolean;
|
|
302
|
+
}
|
|
303
|
+
interface RestResponse<T> {
|
|
304
|
+
data: T;
|
|
305
|
+
status: number;
|
|
306
|
+
headers: Headers;
|
|
307
|
+
requestId: string | null;
|
|
308
|
+
request: Request;
|
|
309
|
+
}
|
|
310
|
+
/** Headers de rate limit de uma resposta. */
|
|
311
|
+
interface RateLimitState {
|
|
312
|
+
limit: number | null;
|
|
313
|
+
remaining: number | null;
|
|
314
|
+
/** Quando a janela renova, em segundos Unix. */
|
|
315
|
+
reset: number | null;
|
|
316
|
+
}
|
|
317
|
+
declare class RestClient {
|
|
318
|
+
readonly baseURL: string;
|
|
319
|
+
private readonly token;
|
|
320
|
+
private readonly timeoutMs;
|
|
321
|
+
private readonly maxRetries;
|
|
322
|
+
private readonly fetchImpl;
|
|
323
|
+
private readonly logger;
|
|
324
|
+
private readonly bucketStates;
|
|
325
|
+
private readonly bucketBlockedUntil;
|
|
326
|
+
private readonly globalWindow;
|
|
327
|
+
private readonly globalLimit;
|
|
328
|
+
private destroyed;
|
|
329
|
+
constructor(options: RestClientOptions);
|
|
330
|
+
/** GET tipado. */
|
|
331
|
+
get<T>(path: string, options?: RequestOptions): Promise<T>;
|
|
332
|
+
/** Implementação de fetch em uso (exposta para uploads e testes). */
|
|
333
|
+
get fetch(): typeof fetch;
|
|
334
|
+
/** POST tipado. Não é retentável por padrão. */
|
|
335
|
+
post<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T>;
|
|
336
|
+
/** PUT tipado (idempotente). */
|
|
337
|
+
put<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T>;
|
|
338
|
+
/** PATCH tipado (retentável por padrão quando idempotente pelo caller). */
|
|
339
|
+
patch<T>(path: string, body?: unknown, options?: RequestOptions): Promise<T>;
|
|
340
|
+
/** DELETE tipado. Resposta 204 devolve `null`. */
|
|
341
|
+
delete<T = null>(path: string, options?: RequestOptions): Promise<T | null>;
|
|
342
|
+
/** Executa uma requisição com política completa de erros, retries e rate limits. */
|
|
343
|
+
request<T>(method: HttpMethod, path: string, options?: RequestOptions): Promise<T>;
|
|
344
|
+
/** Como `request`, mas devolve também status, headers e `x-request-id`. */
|
|
345
|
+
requestRaw<T>(method: HttpMethod, path: string, options?: RequestOptions): Promise<RestResponse<T>>;
|
|
346
|
+
/** Encerra o cliente: novas requisições falham imediatamente. */
|
|
347
|
+
destroy(): void;
|
|
348
|
+
/** Estado de rate limit conhecido para uma rota (diagnóstico). */
|
|
349
|
+
bucketState(method: HttpMethod, path: string): RateLimitState | undefined;
|
|
350
|
+
private buildUrl;
|
|
351
|
+
private parseBody;
|
|
352
|
+
private toAPIError;
|
|
353
|
+
private toNetworkError;
|
|
354
|
+
private recordBucketState;
|
|
355
|
+
private waitForRouteBucket;
|
|
356
|
+
private acquireGlobalSlot;
|
|
357
|
+
}
|
|
358
|
+
/**
|
|
359
|
+
* Chave de bucket de rate limit: método + caminho com ids substituídos.
|
|
360
|
+
* Ex.: `POST /channels/{id}/messages` para qualquer canal.
|
|
361
|
+
*/
|
|
362
|
+
declare function routeKeyOf(method: string, path: string): string;
|
|
363
|
+
|
|
364
|
+
/**
|
|
365
|
+
* Manager de comandos de aplicação (slash).
|
|
366
|
+
*
|
|
367
|
+
* Registrar é uma **sobrescrita em bloco** (`PUT`): a lista enviada substitui
|
|
368
|
+
* a anterior — comandos fora da lista são apagados; um comando cujo nome
|
|
369
|
+
* continua mantém o `id`. O padrão é registrar a lista inteira na partida
|
|
370
|
+
* do bot, sempre a mesma.
|
|
371
|
+
*
|
|
372
|
+
* Escopos: global (`PUT /bots/@me/commands`, vale em todos os Spaces do bot)
|
|
373
|
+
* ou por Space (`PUT /bots/@me/guilds/{guild.id}/commands`). O limite é
|
|
374
|
+
* `COMMANDS_UPDATE`: 10 sobrescritas por minuto.
|
|
375
|
+
*/
|
|
376
|
+
|
|
377
|
+
declare class ApplicationCommandsManager {
|
|
378
|
+
private readonly rest;
|
|
379
|
+
constructor(rest: RestClient);
|
|
380
|
+
/** Lista os comandos globais do bot. */
|
|
381
|
+
listGlobal(signal?: AbortSignal): Promise<APICommand[]>;
|
|
382
|
+
/** Sobrescreve os comandos globais (idempotente por ser PUT). */
|
|
383
|
+
setGlobal(commands: APICommandInput[], signal?: AbortSignal): Promise<APICommand[]>;
|
|
384
|
+
/** Lista os comandos de um Space. */
|
|
385
|
+
listGuild(guildId: Snowflake, signal?: AbortSignal): Promise<APICommand[]>;
|
|
386
|
+
/** Sobrescreve os comandos de um Space (o bot precisa estar instalado nele). */
|
|
387
|
+
setGuild(guildId: Snowflake, commands: APICommandInput[], signal?: AbortSignal): Promise<APICommand[]>;
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Manager do próprio bot e de usuários.
|
|
392
|
+
*/
|
|
393
|
+
|
|
394
|
+
declare class BotManager {
|
|
395
|
+
private readonly rest;
|
|
396
|
+
constructor(rest: RestClient);
|
|
397
|
+
/** `GET /bots/@me`: o bot na visão do dono (inclui as intents configuradas). */
|
|
398
|
+
fetchCurrent(signal?: AbortSignal): Promise<APIBot>;
|
|
399
|
+
/** `GET /bots/{botId}`: o cartão público de um bot. */
|
|
400
|
+
fetch(botId: Snowflake, signal?: AbortSignal): Promise<APIBot>;
|
|
401
|
+
}
|
|
402
|
+
declare class UsersManager {
|
|
403
|
+
private readonly rest;
|
|
404
|
+
constructor(rest: RestClient);
|
|
405
|
+
/** `GET /users/@me`: a própria conta (em um bot, campos privados são padrão). */
|
|
406
|
+
fetchMe(signal?: AbortSignal): Promise<APICurrentUser>;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* Manager de canais e threads: consultar, listar a árvore do Space e
|
|
411
|
+
* criar threads e posts de fórum.
|
|
412
|
+
*/
|
|
413
|
+
|
|
414
|
+
declare class ChannelsManager {
|
|
415
|
+
private readonly rest;
|
|
416
|
+
constructor(rest: RestClient);
|
|
417
|
+
/** Busca um canal (ou uma thread, que também é canal) pelo id. */
|
|
418
|
+
fetch(channelId: Snowflake, signal?: AbortSignal): Promise<APIChannel>;
|
|
419
|
+
/**
|
|
420
|
+
* Lista a árvore de canais do Space: grupos por categoria.
|
|
421
|
+
* Requer que o bot veja os canais (`VIEW_CHANNEL` do cargo dele).
|
|
422
|
+
*/
|
|
423
|
+
fetchTree(guildId: Snowflake, signal?: AbortSignal): Promise<APIChannelTreeNode[]>;
|
|
424
|
+
/** Cria uma thread em um canal de texto ou de anúncios. */
|
|
425
|
+
createThread(channelId: Snowflake, body: APIThreadCreateBody, options?: {
|
|
426
|
+
signal?: AbortSignal;
|
|
427
|
+
}): Promise<APIThread>;
|
|
428
|
+
/** Cria um post em um canal de fórum (a primeira mensagem vai no corpo). */
|
|
429
|
+
createForumPost(channelId: Snowflake, body: APIForumPostCreateBody, options?: {
|
|
430
|
+
signal?: AbortSignal;
|
|
431
|
+
}): Promise<APIThread>;
|
|
432
|
+
/** Cria uma thread a partir de uma mensagem de um canal de texto/anúncios. */
|
|
433
|
+
createThreadFromMessage(channelId: Snowflake, messageId: Snowflake, body: APIThreadCreateBody, options?: {
|
|
434
|
+
signal?: AbortSignal;
|
|
435
|
+
}): Promise<APIThread>;
|
|
436
|
+
/** Lista uma página de threads do canal (`cursor` = `nextCursor` anterior). */
|
|
437
|
+
listThreads(channelId: Snowflake, params?: APIThreadListParams, signal?: AbortSignal): Promise<APIThreadPage>;
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
/**
|
|
441
|
+
* Manager de interações: callback da primeira resposta e follow-ups.
|
|
442
|
+
*
|
|
443
|
+
* As rotas são públicas: o token da interação vai no caminho e não se envia
|
|
444
|
+
* o header `Authorization`. A janela é de **15 minutos**; a primeira resposta
|
|
445
|
+
* é a única aceita como callback (`409 INTERACTION_ALREADY_ACKNOWLEDGED` na
|
|
446
|
+
* segunda), e follow-up antes da primeira resposta dá
|
|
447
|
+
* `409 INTERACTION_NOT_ACKNOWLEDGED`. O limite por interação é de
|
|
448
|
+
* 5 respostas (callback + follow-ups) a cada 5 segundos.
|
|
449
|
+
*
|
|
450
|
+
* O padrão para trabalho demorado é `DEFERRED` + follow-up.
|
|
451
|
+
*/
|
|
452
|
+
|
|
453
|
+
declare class InteractionsManager {
|
|
454
|
+
private readonly rest;
|
|
455
|
+
constructor(rest: RestClient);
|
|
456
|
+
/**
|
|
457
|
+
* Primeira resposta a uma interação (`type`: `MESSAGE`, `DEFERRED`,
|
|
458
|
+
* `UPDATE` ou `DEFERRED_UPDATE`). Resolve em `204` (sem corpo).
|
|
459
|
+
*
|
|
460
|
+
* Não é retentável automaticamente: uma repetição pode encontrar
|
|
461
|
+
* `409 INTERACTION_ALREADY_ACKNOWLEDGED`. O SDK trata esse 409 como
|
|
462
|
+
* "resposta já entregue" e resolve sem erro (veja `reply`).
|
|
463
|
+
*/
|
|
464
|
+
callback(interactionId: string, interactionToken: string, body: APIInteractionCallbackBody, signal?: AbortSignal): Promise<void>;
|
|
465
|
+
/**
|
|
466
|
+
* Follow-up depois da primeira resposta. Age como `MESSAGE`: cria uma
|
|
467
|
+
* mensagem (ou resposta efêmera). Responde `204`.
|
|
468
|
+
*/
|
|
469
|
+
followup(interactionId: string, interactionToken: string, data: APIInteractionReplyData, signal?: AbortSignal): Promise<void>;
|
|
470
|
+
/**
|
|
471
|
+
* Resposta `MESSAGE` com payload conveniente (string ou objeto).
|
|
472
|
+
* Um `409 INTERACTION_ALREADY_ACKNOWLEDGED` é tratado como sucesso:
|
|
473
|
+
* significa que a resposta já foi entregue (por exemplo, após um timeout
|
|
474
|
+
* de rede em que a primeira tentativa chegou ao servidor).
|
|
475
|
+
*/
|
|
476
|
+
reply(interactionId: string, interactionToken: string, payload: MessagePayloadLike, options?: {
|
|
477
|
+
ephemeral?: boolean;
|
|
478
|
+
signal?: AbortSignal;
|
|
479
|
+
}): Promise<void>;
|
|
480
|
+
/** `DEFERRED`: avisa que o bot está processando ("pensando"). Depois, use follow-ups. */
|
|
481
|
+
defer(interactionId: string, interactionToken: string, options?: {
|
|
482
|
+
signal?: AbortSignal;
|
|
483
|
+
}): Promise<void>;
|
|
484
|
+
/** `UPDATE` (só componente): edita a mensagem que tinha o componente clicado. */
|
|
485
|
+
update(interactionId: string, interactionToken: string, payload: MessagePayloadLike, options?: {
|
|
486
|
+
signal?: AbortSignal;
|
|
487
|
+
}): Promise<void>;
|
|
488
|
+
/** `DEFERRED_UPDATE` (só componente): confirma o clique sem mudar nada. */
|
|
489
|
+
acknowledgeComponent(interactionId: string, interactionToken: string, options?: {
|
|
490
|
+
signal?: AbortSignal;
|
|
491
|
+
}): Promise<void>;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
/**
|
|
495
|
+
* Manager de Spaces (guilds), membros, cargos e moderação.
|
|
496
|
+
*
|
|
497
|
+
* A nomenclatura do SDK usa "Space" na documentação, mas a API chama o
|
|
498
|
+
* recurso de `guild` (`/guilds/...`), o que o SDK preserva nos caminhos.
|
|
499
|
+
*/
|
|
500
|
+
|
|
501
|
+
declare class GuildsManager {
|
|
502
|
+
private readonly rest;
|
|
503
|
+
constructor(rest: RestClient);
|
|
504
|
+
/** Busca um Space pelo id, com o bloco `self` do bot nele. */
|
|
505
|
+
fetch(guildId: Snowflake, signal?: AbortSignal): Promise<APIGuild>;
|
|
506
|
+
}
|
|
507
|
+
interface MemberListParams extends CursorPaginationParams {
|
|
508
|
+
/** Só membros com este cargo. */
|
|
509
|
+
roleId?: Snowflake;
|
|
510
|
+
/** Prefixo do `username` ou parte do `displayName`. */
|
|
511
|
+
search?: string;
|
|
512
|
+
/** Só membros que enxergam este canal (threads valem pelo canal pai). */
|
|
513
|
+
channelId?: Snowflake;
|
|
514
|
+
}
|
|
515
|
+
declare class MembersManager {
|
|
516
|
+
private readonly rest;
|
|
517
|
+
constructor(rest: RestClient);
|
|
518
|
+
/** Busca um membro de um Space. */
|
|
519
|
+
fetch(guildId: Snowflake, userId: Snowflake, signal?: AbortSignal): Promise<APIMember>;
|
|
520
|
+
/** Lista membros com paginação por cursor e filtros. */
|
|
521
|
+
list(guildId: Snowflake, params?: MemberListParams, signal?: AbortSignal): Promise<APIMemberPage>;
|
|
522
|
+
/**
|
|
523
|
+
* Edita um membro: apelido, cargos (substituem o conjunto), timeout,
|
|
524
|
+
* silenciamento. O bot precisa das permissões correspondentes.
|
|
525
|
+
*/
|
|
526
|
+
edit(guildId: Snowflake, userId: Snowflake, body: APIMemberEditBody, options?: {
|
|
527
|
+
signal?: AbortSignal;
|
|
528
|
+
}): Promise<APIMember>;
|
|
529
|
+
/** Aplica um timeout até a data informada (`TIMEOUT_MEMBERS`). */
|
|
530
|
+
timeout(guildId: Snowflake, userId: Snowflake, until: ISODate, options?: {
|
|
531
|
+
signal?: AbortSignal;
|
|
532
|
+
}): Promise<APIMember>;
|
|
533
|
+
/** Remove o timeout de um membro. */
|
|
534
|
+
removeTimeout(guildId: Snowflake, userId: Snowflake, options?: {
|
|
535
|
+
signal?: AbortSignal;
|
|
536
|
+
}): Promise<APIMember>;
|
|
537
|
+
/** Expulsa um membro (`KICK_MEMBERS`). Ele pode voltar com um novo convite. */
|
|
538
|
+
kick(guildId: Snowflake, userId: Snowflake, reason?: string, options?: {
|
|
539
|
+
signal?: AbortSignal;
|
|
540
|
+
}): Promise<void>;
|
|
541
|
+
/** Dá um cargo a um membro (`MANAGE_ROLES`, hierarquia abaixo do bot). */
|
|
542
|
+
addRole(guildId: Snowflake, userId: Snowflake, roleId: Snowflake, options?: {
|
|
543
|
+
signal?: AbortSignal;
|
|
544
|
+
}): Promise<void>;
|
|
545
|
+
/** Tira um cargo de um membro. */
|
|
546
|
+
removeRole(guildId: Snowflake, userId: Snowflake, roleId: Snowflake, options?: {
|
|
547
|
+
signal?: AbortSignal;
|
|
548
|
+
}): Promise<void>;
|
|
549
|
+
}
|
|
550
|
+
declare class RolesManager {
|
|
551
|
+
private readonly rest;
|
|
552
|
+
constructor(rest: RestClient);
|
|
553
|
+
/** Lista os cargos de um Space. */
|
|
554
|
+
list(guildId: Snowflake, signal?: AbortSignal): Promise<APIRole[]>;
|
|
555
|
+
}
|
|
556
|
+
/** Moderação: banimentos e desbanimentos (por enquanto o que a API expõe a bots). */
|
|
557
|
+
declare class ModerationManager {
|
|
558
|
+
private readonly rest;
|
|
559
|
+
constructor(rest: RestClient);
|
|
560
|
+
/**
|
|
561
|
+
* Ban um membro (`BAN_MEMBERS`). Pode apagar até 7 dias de histórico
|
|
562
|
+
* recente com `deleteMessageSeconds`. Não é retentável por padrão.
|
|
563
|
+
*/
|
|
564
|
+
ban(guildId: Snowflake, userId: Snowflake, body?: APIMemberBanBody, options?: {
|
|
565
|
+
signal?: AbortSignal;
|
|
566
|
+
}): Promise<APIMemberBan>;
|
|
567
|
+
/** Desbane (`BAN_MEMBERS`). Banimentos da plataforma não podem ser desfeitos. */
|
|
568
|
+
unban(guildId: Snowflake, userId: Snowflake, options?: {
|
|
569
|
+
signal?: AbortSignal;
|
|
570
|
+
}): Promise<void>;
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
/**
|
|
574
|
+
* Manager de mensagens: enviar, editar, apagar, reagir, fixar e consultar.
|
|
575
|
+
*/
|
|
576
|
+
|
|
577
|
+
interface SendOptions {
|
|
578
|
+
/** Anula a requisição. */
|
|
579
|
+
signal?: AbortSignal;
|
|
580
|
+
/**
|
|
581
|
+
* Chave de idempotência da mensagem. Se omitida, o SDK gera uma — o que
|
|
582
|
+
* torna seguro repetir o envio após falha de rede sem duplicar a mensagem.
|
|
583
|
+
*/
|
|
584
|
+
nonce?: string;
|
|
585
|
+
}
|
|
586
|
+
declare class MessagesManager {
|
|
587
|
+
private readonly rest;
|
|
588
|
+
constructor(rest: RestClient);
|
|
589
|
+
/** Busca uma mensagem pelo id. */
|
|
590
|
+
fetch(channelId: Snowflake, messageId: Snowflake): Promise<APIMessage>;
|
|
591
|
+
/** Lista uma página do histórico do canal (padrão: 50, máximo 100). */
|
|
592
|
+
list(channelId: Snowflake, params?: APIMessageListParams, signal?: AbortSignal): Promise<APIMessagePage>;
|
|
593
|
+
/**
|
|
594
|
+
* Envia uma mensagem. O SDK anexa um `nonce` automático (idempotência),
|
|
595
|
+
* então a operação pode ser repetida com segurança pelo cliente REST em
|
|
596
|
+
* falhas transitórias.
|
|
597
|
+
*/
|
|
598
|
+
send(channelId: Snowflake, payload: MessagePayloadLike, options?: SendOptions): Promise<APIMessage>;
|
|
599
|
+
/** Edita uma mensagem (do próprio bot). `embeds`/`components` substituem a lista inteira. */
|
|
600
|
+
edit(channelId: Snowflake, messageId: Snowflake, payload: MessagePayloadLike, options?: {
|
|
601
|
+
signal?: AbortSignal;
|
|
602
|
+
}): Promise<APIMessage>;
|
|
603
|
+
/** Apaga uma mensagem (própria ou de outros, com `MANAGE_MESSAGES`). Responde 204. */
|
|
604
|
+
delete(channelId: Snowflake, messageId: Snowflake, options?: {
|
|
605
|
+
signal?: AbortSignal;
|
|
606
|
+
}): Promise<void>;
|
|
607
|
+
/** Reage a uma mensagem (`ADD_REACTIONS`). `emoji` é o caractere ou `<:nome:id>`. */
|
|
608
|
+
react(channelId: Snowflake, messageId: Snowflake, emoji: string, options?: {
|
|
609
|
+
signal?: AbortSignal;
|
|
610
|
+
}): Promise<void>;
|
|
611
|
+
/** Remove a reação do bot. */
|
|
612
|
+
removeReaction(channelId: Snowflake, messageId: Snowflake, emoji: string, options?: {
|
|
613
|
+
signal?: AbortSignal;
|
|
614
|
+
}): Promise<void>;
|
|
615
|
+
/** Lista as reações de uma mensagem. */
|
|
616
|
+
listReactions(channelId: Snowflake, messageId: Snowflake, signal?: AbortSignal): Promise<APIReaction[]>;
|
|
617
|
+
/** Fixa uma mensagem no canal (`PIN_MESSAGES`). */
|
|
618
|
+
pin(channelId: Snowflake, messageId: Snowflake, options?: {
|
|
619
|
+
signal?: AbortSignal;
|
|
620
|
+
}): Promise<void>;
|
|
621
|
+
/** Desafixa uma mensagem. */
|
|
622
|
+
unpin(channelId: Snowflake, messageId: Snowflake, options?: {
|
|
623
|
+
signal?: AbortSignal;
|
|
624
|
+
}): Promise<void>;
|
|
625
|
+
/** Lista as mensagens fixadas do canal. */
|
|
626
|
+
listPins(channelId: Snowflake, signal?: AbortSignal): Promise<APIMessage[]>;
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/**
|
|
630
|
+
* Manager de uploads: o fluxo oficial de anexos do Squord.
|
|
631
|
+
*
|
|
632
|
+
* Anexos não vão no JSON da mensagem. O fluxo tem três passos:
|
|
633
|
+
* 1. **Reservar** (`POST /uploads`): devolve o upload e um alvo assinado.
|
|
634
|
+
* 2. **Enviar os bytes** com `PUT` ao alvo (fora da API do Squord, sem o
|
|
635
|
+
* header `Authorization`, repetindo os headers do alvo exatamente).
|
|
636
|
+
* 3. **Confirmar** (`POST /uploads/{id}/confirm`): o Squord confere o que
|
|
637
|
+
* chegou (tipo, tamanho, primeiros bytes). Confirmar de novo devolve o
|
|
638
|
+
* mesmo resultado — a rota é idempotente.
|
|
639
|
+
*
|
|
640
|
+
* Depois, o `id` do upload entra em `attachmentIds` da mensagem
|
|
641
|
+
* (até 10 por mensagem; cada upload só entra em uma).
|
|
642
|
+
*
|
|
643
|
+
* Nota: `Readable` é consumido em memória antes do `PUT`. Para arquivos
|
|
644
|
+
* muito grandes, prefira passar o caminho (`path`) e confira o limite do
|
|
645
|
+
* plano do Space (25 MB no gratuito; o teto da API é 500 MB).
|
|
646
|
+
*/
|
|
647
|
+
|
|
648
|
+
type UploadSource = Buffer | Uint8Array | string | Readable;
|
|
649
|
+
interface UploadOptions {
|
|
650
|
+
/** Space do canal onde o anexo será usado. Bots sempre informam. */
|
|
651
|
+
guildId: Snowflake;
|
|
652
|
+
/** Nome do arquivo (1 a 256 caracteres). Padrão: nome do caminho. */
|
|
653
|
+
filename?: string;
|
|
654
|
+
/** Tipo de conteúdo, ex.: `image/png`. Precisa bater com os bytes. */
|
|
655
|
+
contentType?: string;
|
|
656
|
+
/** Caminho local do arquivo. */
|
|
657
|
+
path?: string;
|
|
658
|
+
/** Conteúdo em memória ou stream. */
|
|
659
|
+
data?: UploadSource;
|
|
660
|
+
/** Tamanho em bytes (obrigatório ao usar stream). */
|
|
661
|
+
size?: number;
|
|
662
|
+
/** Anula a operação. */
|
|
663
|
+
signal?: AbortSignal;
|
|
664
|
+
}
|
|
665
|
+
declare class UploadsManager {
|
|
666
|
+
private readonly rest;
|
|
667
|
+
private readonly logger;
|
|
668
|
+
constructor(rest: RestClient, logger?: Logger);
|
|
669
|
+
/** Reserva um upload (`POST /uploads`). Não é idempotente. */
|
|
670
|
+
reserve(body: APIUploadCreateBody, signal?: AbortSignal): Promise<APIUploadReservation>;
|
|
671
|
+
/** Confirma um upload (`POST /uploads/{id}/confirm`). Idempotente. */
|
|
672
|
+
confirm(uploadId: Snowflake, body?: APIUploadConfirmBody, signal?: AbortSignal): Promise<APIUpload>;
|
|
673
|
+
/**
|
|
674
|
+
* Fluxo completo: reserva, envia os bytes e confirma. Devolve o upload em
|
|
675
|
+
* `status: "READY"`, pronto para `attachmentIds`.
|
|
676
|
+
*
|
|
677
|
+
* Aceita caminho local (`path`), `Buffer`/`Uint8Array` ou `Readable`
|
|
678
|
+
* (informe `size`). Streams são sempre encerrados, mesmo em falha.
|
|
679
|
+
*/
|
|
680
|
+
upload(options: UploadOptions): Promise<APIUpload>;
|
|
681
|
+
/** Atalho: envia um arquivo e devolve o `id` pronto para `attachmentIds`. */
|
|
682
|
+
uploadForAttachment(options: UploadOptions): Promise<Snowflake>;
|
|
683
|
+
private collectStream;
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
/**
|
|
687
|
+
* Contrato que o `SquordClient` cumpre para as estruturas (evita ciclo de
|
|
688
|
+
* import em tempo de execução: estruturas importam apenas **tipos** dos
|
|
689
|
+
* managers; as instâncias vêm do cliente).
|
|
690
|
+
*/
|
|
691
|
+
|
|
692
|
+
interface ClientLike {
|
|
693
|
+
readonly rest: RestClient;
|
|
694
|
+
readonly messages: MessagesManager;
|
|
695
|
+
readonly channels: ChannelsManager;
|
|
696
|
+
readonly guilds: GuildsManager;
|
|
697
|
+
readonly members: MembersManager;
|
|
698
|
+
readonly roles: RolesManager;
|
|
699
|
+
readonly moderation: ModerationManager;
|
|
700
|
+
readonly uploads: UploadsManager;
|
|
701
|
+
readonly interactions: InteractionsManager;
|
|
702
|
+
readonly commands: ApplicationCommandsManager;
|
|
703
|
+
readonly bot: BotManager;
|
|
704
|
+
readonly users: UsersManager;
|
|
705
|
+
/** Id da conta do bot (disponível após o login). */
|
|
706
|
+
readonly userId: SnowflakeLike;
|
|
707
|
+
}
|
|
708
|
+
type SnowflakeLike = string | null;
|
|
709
|
+
/** Base das estruturas: guarda o payload cru e a referência ao cliente. */
|
|
710
|
+
declare class Structure {
|
|
711
|
+
protected readonly client: ClientLike;
|
|
712
|
+
/** O payload cru devolvido pela API/gateway. */
|
|
713
|
+
readonly raw: Record<string, unknown>;
|
|
714
|
+
constructor(client: ClientLike,
|
|
715
|
+
/** O payload cru devolvido pela API/gateway. */
|
|
716
|
+
raw: Record<string, unknown>);
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
/**
|
|
720
|
+
* Estruturas de usuário, membro, cargo e Space.
|
|
721
|
+
*/
|
|
722
|
+
|
|
723
|
+
/** Conta de usuário (pessoa ou bot). */
|
|
724
|
+
declare class User extends Structure {
|
|
725
|
+
constructor(client: ClientLike, raw: APIUser);
|
|
726
|
+
get data(): APIUser;
|
|
727
|
+
get id(): Snowflake;
|
|
728
|
+
get username(): string;
|
|
729
|
+
get displayName(): string;
|
|
730
|
+
get avatarUrl(): string | null;
|
|
731
|
+
/** `true` para contas de bot (flag `BOT`). */
|
|
732
|
+
get isBot(): boolean;
|
|
733
|
+
/** `true` para bots verificados pelo Squord. */
|
|
734
|
+
get isVerifiedBot(): boolean;
|
|
735
|
+
get deleted(): boolean;
|
|
736
|
+
get suspended(): boolean;
|
|
737
|
+
/** Menção `<@id>` para usar no conteúdo de mensagens. */
|
|
738
|
+
get mention(): string;
|
|
739
|
+
/** Busca o membro correspondente em um Space. */
|
|
740
|
+
member(guildId: Snowflake): Promise<Member | null>;
|
|
741
|
+
}
|
|
742
|
+
/** Perfil de um usuário dentro de um Space. */
|
|
743
|
+
declare class Member extends Structure {
|
|
744
|
+
constructor(client: ClientLike, raw: APIMember);
|
|
745
|
+
get data(): APIMember;
|
|
746
|
+
/** Id da participação (não confundir com o id da conta). */
|
|
747
|
+
get id(): Snowflake;
|
|
748
|
+
get guildId(): Snowflake;
|
|
749
|
+
get userId(): Snowflake;
|
|
750
|
+
get user(): User;
|
|
751
|
+
get nickname(): string | null;
|
|
752
|
+
/** Nome de exibição efetivo: apelido no Space ou `displayName`. */
|
|
753
|
+
get displayName(): string;
|
|
754
|
+
get roleIds(): Snowflake[];
|
|
755
|
+
get joinedAt(): ISODate;
|
|
756
|
+
/** `null` ou data futura: enquanto futura, o membro está de castigo. */
|
|
757
|
+
get timeoutUntil(): ISODate | null;
|
|
758
|
+
get isTimedOut(): boolean;
|
|
759
|
+
get isBot(): boolean;
|
|
760
|
+
get mention(): string;
|
|
761
|
+
/** Menciona o cargo do membro? Cargos não mencionáveis não notificam. */
|
|
762
|
+
get mentionNicknameOnly(): string;
|
|
763
|
+
/** Recarrega o membro da API. */
|
|
764
|
+
fetch(): Promise<Member>;
|
|
765
|
+
/** Lista os cargos do membro no Space. */
|
|
766
|
+
fetchRoles(): Promise<Role[]>;
|
|
767
|
+
/** Dá um cargo ao membro (respeita hierarquia; cargos gerenciados dão `400 ROLE_MANAGED`). */
|
|
768
|
+
addRole(roleId: Snowflake): Promise<void>;
|
|
769
|
+
/** Tira um cargo do membro. */
|
|
770
|
+
removeRole(roleId: Snowflake): Promise<void>;
|
|
771
|
+
/** Muda o apelido (`MANAGE_NICKNAMES`, ou `CHANGE_NICKNAME` em si mesmo). */
|
|
772
|
+
setNickname(nickname: string | null): Promise<Member>;
|
|
773
|
+
/** Aplica timeout até uma data (`TIMEOUT_MEMBERS`). */
|
|
774
|
+
timeout(until: ISODate | Date): Promise<Member>;
|
|
775
|
+
/** Remove o timeout. */
|
|
776
|
+
removeTimeout(): Promise<Member>;
|
|
777
|
+
/** Expulsa o membro (`KICK_MEMBERS`). Ele pode voltar com novo convite. */
|
|
778
|
+
kick(reason?: string): Promise<void>;
|
|
779
|
+
/** Bane o membro (`BAN_MEMBERS`). */
|
|
780
|
+
ban(options?: {
|
|
781
|
+
reason?: string;
|
|
782
|
+
deleteMessageSeconds?: number;
|
|
783
|
+
}): Promise<void>;
|
|
784
|
+
}
|
|
785
|
+
/** Um cargo do Space. */
|
|
786
|
+
declare class Role extends Structure {
|
|
787
|
+
constructor(client: ClientLike, raw: APIRole);
|
|
788
|
+
get data(): APIRole;
|
|
789
|
+
get id(): Snowflake;
|
|
790
|
+
get guildId(): Snowflake;
|
|
791
|
+
get name(): string;
|
|
792
|
+
get color(): string | null;
|
|
793
|
+
get position(): number;
|
|
794
|
+
/** Bits como `BigInt` (permissões trafegam como string decimal). */
|
|
795
|
+
get permissions(): bigint;
|
|
796
|
+
/** Testa se o cargo concede um conjunto de permissões. */
|
|
797
|
+
has(...flags: bigint[]): boolean;
|
|
798
|
+
get managed(): boolean;
|
|
799
|
+
get managedKind(): string | null;
|
|
800
|
+
get mentionable(): boolean;
|
|
801
|
+
/** Menção `<@&id>`; só notifica se o cargo for mencionável. */
|
|
802
|
+
get mention(): string;
|
|
803
|
+
/** `true` para o cargo @everyone (o id é o próprio id do Space). */
|
|
804
|
+
get isEveryone(): boolean;
|
|
805
|
+
}
|
|
806
|
+
/** Um Space (comunidade). */
|
|
807
|
+
declare class Guild extends Structure {
|
|
808
|
+
constructor(client: ClientLike, raw: APIGuild);
|
|
809
|
+
get data(): APIGuild;
|
|
810
|
+
get id(): Snowflake;
|
|
811
|
+
get name(): string;
|
|
812
|
+
get slug(): string;
|
|
813
|
+
get ownerId(): Snowflake;
|
|
814
|
+
get memberCount(): number;
|
|
815
|
+
get iconUrl(): string | null;
|
|
816
|
+
get boostCount(): number;
|
|
817
|
+
/** O bot neste Space: id de participação, cargos e permissões no nível do Space. */
|
|
818
|
+
get self(): {
|
|
819
|
+
memberId: Snowflake;
|
|
820
|
+
roleIds: Snowflake[];
|
|
821
|
+
permissions: bigint;
|
|
822
|
+
isOwner: boolean;
|
|
823
|
+
};
|
|
824
|
+
/** Testa permissões do bot no nível do Space (overwrites de canal à parte). */
|
|
825
|
+
botHas(...flags: bigint[]): boolean;
|
|
826
|
+
/** Recarrega o Space. */
|
|
827
|
+
fetch(): Promise<Guild>;
|
|
828
|
+
/** Árvore de canais do Space, agrupada por categorias. */
|
|
829
|
+
fetchChannelTree(): Promise<ChannelTreeGroup[]>;
|
|
830
|
+
/** Lista os cargos do Space. */
|
|
831
|
+
fetchRoles(): Promise<Role[]>;
|
|
832
|
+
/** Busca um membro pelo id da conta. */
|
|
833
|
+
fetchMember(userId: Snowflake): Promise<Member>;
|
|
834
|
+
}
|
|
835
|
+
/** Grupo da árvore de canais (categoria e seus canais). */
|
|
836
|
+
interface ChannelTreeGroup {
|
|
837
|
+
category: Channel | null;
|
|
838
|
+
channels: Channel[];
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
/**
|
|
842
|
+
* Estrutura de mensagem: leitura e ações de alto nível
|
|
843
|
+
* (responder, editar, apagar, reagir, fixar, abrir thread).
|
|
844
|
+
*/
|
|
845
|
+
|
|
846
|
+
declare class Message extends Structure {
|
|
847
|
+
constructor(client: ClientLike, raw: APIMessage);
|
|
848
|
+
get data(): APIMessage;
|
|
849
|
+
get id(): Snowflake;
|
|
850
|
+
get guildId(): Snowflake | null;
|
|
851
|
+
get channelId(): Snowflake;
|
|
852
|
+
get authorId(): Snowflake;
|
|
853
|
+
get author(): User;
|
|
854
|
+
get type(): MessageType;
|
|
855
|
+
get content(): string;
|
|
856
|
+
get replyToId(): Snowflake | null;
|
|
857
|
+
get pinned(): boolean;
|
|
858
|
+
get editedAt(): ISODate | null;
|
|
859
|
+
get moderated(): boolean;
|
|
860
|
+
get attachments(): APIMessage["attachments"];
|
|
861
|
+
get embeds(): APIMessage["embeds"];
|
|
862
|
+
get components(): APIMessage["components"];
|
|
863
|
+
get reactions(): APIReaction[];
|
|
864
|
+
get createdAt(): ISODate;
|
|
865
|
+
/** Apelido do autor no Space (quando houver). */
|
|
866
|
+
get memberNickname(): string | null;
|
|
867
|
+
/** Nome de exibição efetivo do autor (apelido ou displayName). */
|
|
868
|
+
get authorDisplayName(): string;
|
|
869
|
+
/** `true` se a mensagem veio do próprio bot. */
|
|
870
|
+
get fromMe(): boolean;
|
|
871
|
+
/** `true` se o bot foi mencionado (`<@id>` no conteúdo). */
|
|
872
|
+
get mentionsMe(): boolean;
|
|
873
|
+
/** Ids mencionados na mensagem (só as menções que valeram). */
|
|
874
|
+
get mentionedUserIds(): Snowflake[];
|
|
875
|
+
get mentionedRoleIds(): Snowflake[];
|
|
876
|
+
get mentionsEveryone(): boolean;
|
|
877
|
+
/** Recarrega a mensagem (ela pode ter sido apagada; isso lança 404). */
|
|
878
|
+
fetch(): Promise<Message>;
|
|
879
|
+
/** Busca o canal da mensagem (uma thread também é canal). */
|
|
880
|
+
fetchChannel(): Promise<Channel | Thread | null>;
|
|
881
|
+
/** Responde a mensagem (usa `replyToId`). Idempotente por `nonce`. */
|
|
882
|
+
reply(payload: MessagePayloadLike, options?: {
|
|
883
|
+
signal?: AbortSignal;
|
|
884
|
+
nonce?: string;
|
|
885
|
+
}): Promise<Message>;
|
|
886
|
+
/** Edita a mensagem (só mensagens do próprio bot). */
|
|
887
|
+
edit(payload: MessagePayloadLike, options?: {
|
|
888
|
+
signal?: AbortSignal;
|
|
889
|
+
}): Promise<Message>;
|
|
890
|
+
/** Apaga a mensagem (a do bot sempre; de outros, com `MANAGE_MESSAGES`). */
|
|
891
|
+
delete(options?: {
|
|
892
|
+
signal?: AbortSignal;
|
|
893
|
+
}): Promise<void>;
|
|
894
|
+
/** Reage com um emoji Unicode ou `<:nome:id>`. */
|
|
895
|
+
react(emoji: string, options?: {
|
|
896
|
+
signal?: AbortSignal;
|
|
897
|
+
}): Promise<void>;
|
|
898
|
+
/** Remove a reação do bot. */
|
|
899
|
+
removeReaction(emoji: string, options?: {
|
|
900
|
+
signal?: AbortSignal;
|
|
901
|
+
}): Promise<void>;
|
|
902
|
+
/** Fixa a mensagem no canal (`PIN_MESSAGES`). */
|
|
903
|
+
pin(options?: {
|
|
904
|
+
signal?: AbortSignal;
|
|
905
|
+
}): Promise<void>;
|
|
906
|
+
/** Desafixa a mensagem. */
|
|
907
|
+
unpin(options?: {
|
|
908
|
+
signal?: AbortSignal;
|
|
909
|
+
}): Promise<void>;
|
|
910
|
+
/** Cria uma thread a partir desta mensagem (canais de texto e anúncios). */
|
|
911
|
+
startThread(body: {
|
|
912
|
+
name: string;
|
|
913
|
+
autoArchiveMinutes?: ThreadAutoArchiveMinutes;
|
|
914
|
+
}): Promise<Thread>;
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
/**
|
|
918
|
+
* Estruturas de canal e thread.
|
|
919
|
+
*
|
|
920
|
+
* Uma thread também é canal: use o `id` dela como `channelId` nas rotas
|
|
921
|
+
* de mensagem. Threads não têm overwrites: vale o canal pai.
|
|
922
|
+
*/
|
|
923
|
+
|
|
924
|
+
/** Um canal de texto, anúncios, categoria, fórum, voz ou palco. */
|
|
925
|
+
declare class Channel extends Structure {
|
|
926
|
+
constructor(client: ClientLike, raw: APIChannel);
|
|
927
|
+
get data(): APIChannel;
|
|
928
|
+
get id(): Snowflake;
|
|
929
|
+
get guildId(): Snowflake;
|
|
930
|
+
get name(): string;
|
|
931
|
+
get type(): ChannelType;
|
|
932
|
+
get topic(): string | null;
|
|
933
|
+
get categoryId(): Snowflake | null;
|
|
934
|
+
get isPrivate(): boolean;
|
|
935
|
+
/** Modo lento em segundos (0 desligado). */
|
|
936
|
+
get rateLimitPerUser(): number;
|
|
937
|
+
get chatEnabled(): boolean;
|
|
938
|
+
get lastMessageId(): Snowflake | null;
|
|
939
|
+
/** Menção `<#id>`. */
|
|
940
|
+
get mention(): string;
|
|
941
|
+
get isText(): boolean;
|
|
942
|
+
get isVoice(): boolean;
|
|
943
|
+
get isForum(): boolean;
|
|
944
|
+
/** Recarrega o canal. */
|
|
945
|
+
fetch(): Promise<Channel>;
|
|
946
|
+
/** Envia uma mensagem no canal (idempotente por `nonce`). */
|
|
947
|
+
send(payload: MessagePayloadLike, options?: {
|
|
948
|
+
signal?: AbortSignal;
|
|
949
|
+
nonce?: string;
|
|
950
|
+
}): Promise<Message>;
|
|
951
|
+
/** Envia um arquivo como anexo do canal (fluxo completo de upload). */
|
|
952
|
+
sendFile(options: {
|
|
953
|
+
path?: string;
|
|
954
|
+
data?: Buffer | Uint8Array;
|
|
955
|
+
filename?: string;
|
|
956
|
+
contentType?: string;
|
|
957
|
+
}, content?: string): Promise<Message>;
|
|
958
|
+
/** Busca uma mensagem do canal pelo id. */
|
|
959
|
+
fetchMessage(messageId: Snowflake): Promise<Message>;
|
|
960
|
+
/** Lista uma página do histórico (use `client.paginate` para iterar tudo). */
|
|
961
|
+
fetchMessages(params?: {
|
|
962
|
+
limit?: number;
|
|
963
|
+
before?: string;
|
|
964
|
+
after?: string;
|
|
965
|
+
}): Promise<{
|
|
966
|
+
items: Message[];
|
|
967
|
+
hasMore: boolean;
|
|
968
|
+
prevCursor: string | null;
|
|
969
|
+
nextCursor: string | null;
|
|
970
|
+
}>;
|
|
971
|
+
/** Mensagens fixadas do canal. */
|
|
972
|
+
fetchPins(): Promise<Message[]>;
|
|
973
|
+
/** Cria uma thread neste canal (texto/anúncios) ou um post (fórum). */
|
|
974
|
+
createThread(body: APIThreadCreateBody): Promise<Thread>;
|
|
975
|
+
/** Lista as threads do canal (`cursor` = `nextCursor` da página anterior). */
|
|
976
|
+
fetchThreads(params?: {
|
|
977
|
+
limit?: number;
|
|
978
|
+
cursor?: string;
|
|
979
|
+
archived?: "true" | "false";
|
|
980
|
+
tagId?: Snowflake;
|
|
981
|
+
}): Promise<{
|
|
982
|
+
items: Thread[];
|
|
983
|
+
hasMore: boolean;
|
|
984
|
+
nextCursor: string | null;
|
|
985
|
+
}>;
|
|
986
|
+
}
|
|
987
|
+
/** Uma thread ou post de fórum. */
|
|
988
|
+
declare class Thread extends Structure {
|
|
989
|
+
constructor(client: ClientLike, raw: APIThread);
|
|
990
|
+
get data(): APIThread;
|
|
991
|
+
get id(): Snowflake;
|
|
992
|
+
get guildId(): Snowflake;
|
|
993
|
+
get parentId(): Snowflake;
|
|
994
|
+
get name(): string;
|
|
995
|
+
get ownerId(): Snowflake;
|
|
996
|
+
get isForumPost(): boolean;
|
|
997
|
+
get archived(): boolean;
|
|
998
|
+
get locked(): boolean;
|
|
999
|
+
get autoArchiveMinutes(): ThreadAutoArchiveMinutes;
|
|
1000
|
+
get messageCount(): number;
|
|
1001
|
+
get lastMessageId(): Snowflake | null;
|
|
1002
|
+
get lastMessageAt(): ISODate;
|
|
1003
|
+
get appliedTagIds(): Snowflake[];
|
|
1004
|
+
get mention(): string;
|
|
1005
|
+
/** Envia uma mensagem na thread (usa o id dela como channelId). */
|
|
1006
|
+
send(payload: MessagePayloadLike, options?: {
|
|
1007
|
+
signal?: AbortSignal;
|
|
1008
|
+
nonce?: string;
|
|
1009
|
+
}): Promise<Message>;
|
|
1010
|
+
/** Busca uma mensagem da thread. */
|
|
1011
|
+
fetchMessage(messageId: Snowflake): Promise<Message>;
|
|
1012
|
+
}
|
|
1013
|
+
|
|
1014
|
+
/**
|
|
1015
|
+
* Estrutura de interação: um comando de barra usado ou um clique em
|
|
1016
|
+
* componente de mensagem do bot.
|
|
1017
|
+
*
|
|
1018
|
+
* O bot responde em até ~10 segundos (o app avisa "não respondeu" depois
|
|
1019
|
+
* disso); use `defer()` e follow-ups para trabalho demorado. A janela total
|
|
1020
|
+
* de resposta é de 15 minutos, e o limite é de 5 respostas a cada 5 segundos
|
|
1021
|
+
* por interação.
|
|
1022
|
+
*/
|
|
1023
|
+
|
|
1024
|
+
declare class Interaction extends Structure {
|
|
1025
|
+
constructor(client: ClientLike, raw: APIInteraction);
|
|
1026
|
+
get data(): APIInteraction;
|
|
1027
|
+
get id(): string;
|
|
1028
|
+
/** Credencial da interação (15 minutos de validade). Trate como segredo. */
|
|
1029
|
+
get token(): string;
|
|
1030
|
+
get type(): "COMMAND" | "COMPONENT";
|
|
1031
|
+
get guildId(): Snowflake;
|
|
1032
|
+
get channelId(): Snowflake;
|
|
1033
|
+
/** Quem invocou o comando ou clicou no componente. */
|
|
1034
|
+
get user(): User;
|
|
1035
|
+
/** O membro que invocou (com cargos do Space), quando disponível. */
|
|
1036
|
+
get member(): Member | null;
|
|
1037
|
+
get createdAt(): string;
|
|
1038
|
+
get isCommand(): boolean;
|
|
1039
|
+
get isComponent(): boolean;
|
|
1040
|
+
/** Dados do comando (presentes quando `isCommand`). */
|
|
1041
|
+
get command(): APIInteractionCommandData | null;
|
|
1042
|
+
/** Dados do componente (presentes quando `isComponent`). */
|
|
1043
|
+
get component(): APIInteractionComponentData | null;
|
|
1044
|
+
/** O `customId` do componente clicado (ou `null`). */
|
|
1045
|
+
get customId(): string | null;
|
|
1046
|
+
/** Os valores escolhidos em um menu (vazio em botões). */
|
|
1047
|
+
get values(): string[];
|
|
1048
|
+
/** Lista as opções preenchidas da invocação (já validadas pelo Squord). */
|
|
1049
|
+
get options(): Array<{
|
|
1050
|
+
name: string;
|
|
1051
|
+
type: CommandOptionType;
|
|
1052
|
+
value: string | number | boolean;
|
|
1053
|
+
}>;
|
|
1054
|
+
/** Valor bruto de uma opção pelo nome. */
|
|
1055
|
+
getOption(name: string): string | number | boolean | undefined;
|
|
1056
|
+
/** Opção `STRING`. */
|
|
1057
|
+
getString(name: string, required?: boolean): string | undefined;
|
|
1058
|
+
/** Opção `INTEGER`. */
|
|
1059
|
+
getInteger(name: string, required?: boolean): number | undefined;
|
|
1060
|
+
/** Opção `BOOLEAN`. */
|
|
1061
|
+
getBoolean(name: string, required?: boolean): boolean | undefined;
|
|
1062
|
+
/** Opção `USER`/`CHANNEL`/`ROLE`: o valor é o id (string). */
|
|
1063
|
+
getId(name: string, required?: boolean): Snowflake | undefined;
|
|
1064
|
+
/** Primeira resposta como mensagem. `ephemeral: true` mostra só para quem invocou. */
|
|
1065
|
+
reply(payload: MessagePayloadLike, options?: {
|
|
1066
|
+
ephemeral?: boolean;
|
|
1067
|
+
signal?: AbortSignal;
|
|
1068
|
+
}): Promise<void>;
|
|
1069
|
+
/** Resposta efêmera: só quem invocou vê; não é salva; só botões de link. */
|
|
1070
|
+
replyEphemeral(payload: MessagePayloadLike, options?: {
|
|
1071
|
+
signal?: AbortSignal;
|
|
1072
|
+
}): Promise<void>;
|
|
1073
|
+
/** `DEFERRED`: mostra o bot "pensando" enquanto o trabalho roda. */
|
|
1074
|
+
defer(options?: {
|
|
1075
|
+
signal?: AbortSignal;
|
|
1076
|
+
}): Promise<void>;
|
|
1077
|
+
/**
|
|
1078
|
+
* `UPDATE` (só componente): edita a mensagem que tinha o componente.
|
|
1079
|
+
* O caso típico: marcar a escolha, mudar de página.
|
|
1080
|
+
*/
|
|
1081
|
+
update(payload: MessagePayloadLike, options?: {
|
|
1082
|
+
signal?: AbortSignal;
|
|
1083
|
+
}): Promise<void>;
|
|
1084
|
+
/** `DEFERRED_UPDATE` (só componente): confirma o clique sem mudar nada. */
|
|
1085
|
+
acknowledge(options?: {
|
|
1086
|
+
signal?: AbortSignal;
|
|
1087
|
+
}): Promise<void>;
|
|
1088
|
+
/**
|
|
1089
|
+
* Follow-up: mensagem extra depois da primeira resposta
|
|
1090
|
+
* (o padrão para trabalho demorado é `defer()` + follow-up).
|
|
1091
|
+
*/
|
|
1092
|
+
followup(payload: MessagePayloadLike, options?: {
|
|
1093
|
+
ephemeral?: boolean;
|
|
1094
|
+
signal?: AbortSignal;
|
|
1095
|
+
}): Promise<void>;
|
|
1096
|
+
/** Busca a mensagem do componente clicado (quando `isComponent`). */
|
|
1097
|
+
fetchComponentMessage(): Promise<Message | null>;
|
|
1098
|
+
}
|
|
1099
|
+
|
|
1100
|
+
/**
|
|
1101
|
+
* Tipos do protocolo do gateway do Squord.
|
|
1102
|
+
*
|
|
1103
|
+
* Referência: https://docs.squord.com.br/gateway/visao-geral
|
|
1104
|
+
*
|
|
1105
|
+
* Todo frame é um objeto JSON em texto UTF-8. Os frames enviados pelo bot têm
|
|
1106
|
+
* `{ op, d, requestId? }`; os recebidos têm `{ op, d, timestamp, ... }`.
|
|
1107
|
+
*/
|
|
1108
|
+
|
|
1109
|
+
/** Opcodes que o bot pode enviar. */
|
|
1110
|
+
type ClientOpcode = "identify" | "resume" | "heartbeat" | "presence.update" | "subscribe" | "unsubscribe" | "typing.start" | "voice.state.update";
|
|
1111
|
+
/** Opcodes que o servidor envia. */
|
|
1112
|
+
type ServerOpcode = "hello" | "ready" | "resumed" | "heartbeat.ack" | "invalid_session" | "reconnect" | "error" | "event";
|
|
1113
|
+
/** `hello`: o primeiro frame, assim que a conexão é aceita. */
|
|
1114
|
+
interface GatewayHello {
|
|
1115
|
+
heartbeatIntervalMs: number;
|
|
1116
|
+
sessionId: string;
|
|
1117
|
+
protocolVersion: number;
|
|
1118
|
+
}
|
|
1119
|
+
/** `ready`: resposta ao `identify`. */
|
|
1120
|
+
interface GatewayReady {
|
|
1121
|
+
sessionId: string;
|
|
1122
|
+
/** Id da conta do bot (igual ao id do bot). */
|
|
1123
|
+
userId: Snowflake;
|
|
1124
|
+
/** Spaces onde o bot está instalado: `id`, `name`, `iconUrl`. */
|
|
1125
|
+
guilds: Array<{
|
|
1126
|
+
id: Snowflake;
|
|
1127
|
+
name: string;
|
|
1128
|
+
iconUrl: string | null;
|
|
1129
|
+
}>;
|
|
1130
|
+
resumeGatewayUrl: string;
|
|
1131
|
+
}
|
|
1132
|
+
/** `resumed`: resposta ao `resume` (os eventos perdidos chegam antes dele). */
|
|
1133
|
+
interface GatewayResumed {
|
|
1134
|
+
sessionId: string;
|
|
1135
|
+
replayed: number;
|
|
1136
|
+
sequence: number;
|
|
1137
|
+
}
|
|
1138
|
+
/** `invalid_session`: o `resume` foi recusado; a conexão continua aberta. */
|
|
1139
|
+
interface GatewayInvalidSession {
|
|
1140
|
+
resumable: boolean;
|
|
1141
|
+
}
|
|
1142
|
+
/** `reconnect`: o servidor pediu reconexão; seguido do fechamento 4007. */
|
|
1143
|
+
interface GatewayReconnect {
|
|
1144
|
+
reason: string;
|
|
1145
|
+
resumable: boolean;
|
|
1146
|
+
}
|
|
1147
|
+
/** `error`: um frame foi recusado sem fechar a conexão. */
|
|
1148
|
+
interface GatewayError$1 {
|
|
1149
|
+
code: string;
|
|
1150
|
+
message: string;
|
|
1151
|
+
details?: unknown;
|
|
1152
|
+
}
|
|
1153
|
+
type PresenceStatus = "ONLINE" | "IDLE" | "DND" | "INVISIBLE";
|
|
1154
|
+
/** Corpo do `presence.update`. */
|
|
1155
|
+
interface GatewayPresenceUpdate {
|
|
1156
|
+
status?: PresenceStatus;
|
|
1157
|
+
/** Até 128 caracteres; `null` apaga. */
|
|
1158
|
+
customStatus?: string | null;
|
|
1159
|
+
afk?: boolean;
|
|
1160
|
+
}
|
|
1161
|
+
/** Um frame `event` recebido do gateway. */
|
|
1162
|
+
interface GatewayEventFrame<T = unknown> {
|
|
1163
|
+
op: "event";
|
|
1164
|
+
type: string;
|
|
1165
|
+
d: T;
|
|
1166
|
+
/** Sequência da sessão; cresce de um em um. Só em eventos duráveis. */
|
|
1167
|
+
s?: number;
|
|
1168
|
+
timestamp: number;
|
|
1169
|
+
}
|
|
1170
|
+
/** Qualquer frame recebido do servidor. */
|
|
1171
|
+
type ServerFrame = (GatewayEventFrame & {
|
|
1172
|
+
requestId?: string;
|
|
1173
|
+
}) | ({
|
|
1174
|
+
op: "hello";
|
|
1175
|
+
d: GatewayHello;
|
|
1176
|
+
timestamp: number;
|
|
1177
|
+
requestId?: string;
|
|
1178
|
+
}) | ({
|
|
1179
|
+
op: "ready";
|
|
1180
|
+
d: GatewayReady;
|
|
1181
|
+
timestamp: number;
|
|
1182
|
+
requestId?: string;
|
|
1183
|
+
}) | ({
|
|
1184
|
+
op: "resumed";
|
|
1185
|
+
d: GatewayResumed;
|
|
1186
|
+
timestamp: number;
|
|
1187
|
+
requestId?: string;
|
|
1188
|
+
}) | ({
|
|
1189
|
+
op: "heartbeat.ack";
|
|
1190
|
+
d: {
|
|
1191
|
+
sequence: number;
|
|
1192
|
+
};
|
|
1193
|
+
timestamp: number;
|
|
1194
|
+
requestId?: string;
|
|
1195
|
+
}) | ({
|
|
1196
|
+
op: "invalid_session";
|
|
1197
|
+
d: GatewayInvalidSession;
|
|
1198
|
+
timestamp: number;
|
|
1199
|
+
requestId?: string;
|
|
1200
|
+
}) | ({
|
|
1201
|
+
op: "reconnect";
|
|
1202
|
+
d: GatewayReconnect;
|
|
1203
|
+
timestamp: number;
|
|
1204
|
+
requestId?: string;
|
|
1205
|
+
}) | ({
|
|
1206
|
+
op: "error";
|
|
1207
|
+
d: GatewayError$1;
|
|
1208
|
+
timestamp: number;
|
|
1209
|
+
requestId?: string;
|
|
1210
|
+
});
|
|
1211
|
+
declare const GatewayCloseCodes: {
|
|
1212
|
+
readonly UnknownError: 4000;
|
|
1213
|
+
readonly UnknownOpcode: 4001;
|
|
1214
|
+
readonly DecodeError: 4002;
|
|
1215
|
+
readonly NotAuthenticated: 4003;
|
|
1216
|
+
readonly AuthenticationFailed: 4004;
|
|
1217
|
+
readonly AlreadyAuthenticated: 4005;
|
|
1218
|
+
readonly InvalidSequence: 4007;
|
|
1219
|
+
readonly RateLimited: 4008;
|
|
1220
|
+
readonly SessionTimeout: 4009;
|
|
1221
|
+
readonly InvalidProtocolVersion: 4012;
|
|
1222
|
+
readonly AccountSuspended: 4013;
|
|
1223
|
+
readonly BotSessionLimit: 4014;
|
|
1224
|
+
};
|
|
1225
|
+
type GatewayCloseCode = (typeof GatewayCloseCodes)[keyof typeof GatewayCloseCodes];
|
|
1226
|
+
/** Eventos duráveis entregues pelo gateway (campo `type` do frame `event`). */
|
|
1227
|
+
type GatewayEventName = "message.created" | "message.updated" | "message.deleted" | "message.bulk_deleted" | "poll.vote.cast" | "poll.vote.removed" | "reaction.added" | "reaction.removed" | "member.joined" | "member.updated" | "member.left" | "member.banned" | "member.unbanned" | "guild.updated" | "guild.deleted" | "guild.taken_down" | "guild.boost.added" | "guild.boost.removed" | "channel.created" | "channel.updated" | "channel.deleted" | "channel.tree.invalidated" | "role.created" | "role.updated" | "role.deleted" | "thread.created" | "thread.updated" | "thread.deleted" | "emoji.created" | "emoji.updated" | "emoji.deleted" | "sticker.created" | "sticker.updated" | "sticker.deleted" | "guild_event.created" | "guild_event.updated" | "guild_event.deleted" | "announcement.follow.created" | "announcement.follow.deleted" | "voice.state.updated" | "voice.room.updated" | "voice.member.moved" | "voice.e2ee.bot_key_requested" | "interaction.created" | "application_command.updated";
|
|
1228
|
+
interface PollResults {
|
|
1229
|
+
voterCount: number;
|
|
1230
|
+
answers: Array<{
|
|
1231
|
+
answerId: Snowflake;
|
|
1232
|
+
count: number;
|
|
1233
|
+
}>;
|
|
1234
|
+
}
|
|
1235
|
+
interface PollVotePayload {
|
|
1236
|
+
messageId: Snowflake;
|
|
1237
|
+
channelId: Snowflake;
|
|
1238
|
+
guildId: Snowflake | null;
|
|
1239
|
+
userId: Snowflake;
|
|
1240
|
+
results: PollResults;
|
|
1241
|
+
}
|
|
1242
|
+
interface ReactionAddedPayload {
|
|
1243
|
+
messageId: Snowflake;
|
|
1244
|
+
channelId: Snowflake;
|
|
1245
|
+
guildId: Snowflake | null;
|
|
1246
|
+
userId: Snowflake;
|
|
1247
|
+
/** A reação após a mudança. O `me` não é confiável num evento. */
|
|
1248
|
+
reaction: {
|
|
1249
|
+
emoji: string;
|
|
1250
|
+
count: number;
|
|
1251
|
+
userIds: Snowflake[];
|
|
1252
|
+
me: boolean;
|
|
1253
|
+
};
|
|
1254
|
+
/** Emoji customizado resolvido; `null` para emoji padrão. */
|
|
1255
|
+
customEmoji: {
|
|
1256
|
+
id: Snowflake;
|
|
1257
|
+
name: string;
|
|
1258
|
+
animated: boolean;
|
|
1259
|
+
url: string;
|
|
1260
|
+
} | null;
|
|
1261
|
+
}
|
|
1262
|
+
interface ReactionRemovedPayload {
|
|
1263
|
+
messageId: Snowflake;
|
|
1264
|
+
channelId: Snowflake;
|
|
1265
|
+
guildId: Snowflake | null;
|
|
1266
|
+
userId: Snowflake;
|
|
1267
|
+
emoji: string;
|
|
1268
|
+
}
|
|
1269
|
+
interface MessageDeletedPayload {
|
|
1270
|
+
messageId: Snowflake;
|
|
1271
|
+
channelId: Snowflake;
|
|
1272
|
+
guildId: Snowflake | null;
|
|
1273
|
+
/** Só quando o delete apagou a mensagem mais nova do canal. */
|
|
1274
|
+
lastMessageId?: Snowflake | null;
|
|
1275
|
+
}
|
|
1276
|
+
interface MessageBulkDeletedPayload {
|
|
1277
|
+
messageIds: Snowflake[];
|
|
1278
|
+
channelId: Snowflake;
|
|
1279
|
+
guildId: Snowflake | null;
|
|
1280
|
+
lastMessageId?: Snowflake | null;
|
|
1281
|
+
}
|
|
1282
|
+
interface MemberLeftPayload {
|
|
1283
|
+
guildId: Snowflake;
|
|
1284
|
+
userId: Snowflake;
|
|
1285
|
+
}
|
|
1286
|
+
interface MemberBannedPayload {
|
|
1287
|
+
guildId: Snowflake;
|
|
1288
|
+
userId: Snowflake;
|
|
1289
|
+
reason: string | null;
|
|
1290
|
+
}
|
|
1291
|
+
interface MemberUnbannedPayload {
|
|
1292
|
+
guildId: Snowflake;
|
|
1293
|
+
userId: Snowflake;
|
|
1294
|
+
}
|
|
1295
|
+
interface GuildDeletedPayload {
|
|
1296
|
+
guildId: Snowflake;
|
|
1297
|
+
}
|
|
1298
|
+
interface GuildTakenDownPayload {
|
|
1299
|
+
guildId: Snowflake;
|
|
1300
|
+
name: string;
|
|
1301
|
+
}
|
|
1302
|
+
interface GuildBoostPayload {
|
|
1303
|
+
guildId: Snowflake;
|
|
1304
|
+
userId: Snowflake;
|
|
1305
|
+
boostIds: Snowflake[];
|
|
1306
|
+
boostCount: number;
|
|
1307
|
+
boostLevel: number;
|
|
1308
|
+
previousLevel: number;
|
|
1309
|
+
/** Só em `guild.boost.removed`. */
|
|
1310
|
+
reason?: "REMOVED" | "MOVED" | "LEFT" | "LAPSED" | "SPACE_GONE" | "OPERATOR";
|
|
1311
|
+
}
|
|
1312
|
+
interface ChannelDeletedPayload {
|
|
1313
|
+
channelId: Snowflake;
|
|
1314
|
+
guildId: Snowflake;
|
|
1315
|
+
}
|
|
1316
|
+
interface ChannelTreeInvalidatedPayload {
|
|
1317
|
+
guildId: Snowflake;
|
|
1318
|
+
}
|
|
1319
|
+
interface RoleDeletedPayload {
|
|
1320
|
+
roleId: Snowflake;
|
|
1321
|
+
guildId: Snowflake;
|
|
1322
|
+
}
|
|
1323
|
+
interface ThreadDeletedPayload {
|
|
1324
|
+
threadId: Snowflake;
|
|
1325
|
+
parentId: Snowflake;
|
|
1326
|
+
guildId: Snowflake;
|
|
1327
|
+
}
|
|
1328
|
+
interface EmojiPayload {
|
|
1329
|
+
emoji: {
|
|
1330
|
+
id: Snowflake;
|
|
1331
|
+
guildId: Snowflake;
|
|
1332
|
+
name: string;
|
|
1333
|
+
url: string;
|
|
1334
|
+
creatorId: Snowflake | null;
|
|
1335
|
+
animated: boolean;
|
|
1336
|
+
roleIds: Snowflake[];
|
|
1337
|
+
available: boolean;
|
|
1338
|
+
createdAt: string;
|
|
1339
|
+
updatedAt: string;
|
|
1340
|
+
};
|
|
1341
|
+
}
|
|
1342
|
+
interface EmojiDeletedPayload {
|
|
1343
|
+
emojiId: Snowflake;
|
|
1344
|
+
guildId: Snowflake;
|
|
1345
|
+
}
|
|
1346
|
+
interface StickerPayload {
|
|
1347
|
+
sticker: {
|
|
1348
|
+
id: Snowflake;
|
|
1349
|
+
guildId: Snowflake;
|
|
1350
|
+
name: string;
|
|
1351
|
+
description: string | null;
|
|
1352
|
+
tags: string;
|
|
1353
|
+
url: string;
|
|
1354
|
+
format: string;
|
|
1355
|
+
animated: boolean;
|
|
1356
|
+
available: boolean;
|
|
1357
|
+
creatorId: Snowflake | null;
|
|
1358
|
+
createdAt: string;
|
|
1359
|
+
updatedAt: string;
|
|
1360
|
+
};
|
|
1361
|
+
}
|
|
1362
|
+
interface StickerDeletedPayload {
|
|
1363
|
+
stickerId: Snowflake;
|
|
1364
|
+
guildId: Snowflake;
|
|
1365
|
+
}
|
|
1366
|
+
interface GuildEventPayload {
|
|
1367
|
+
event: {
|
|
1368
|
+
id: Snowflake;
|
|
1369
|
+
guildId: Snowflake;
|
|
1370
|
+
name: string;
|
|
1371
|
+
description: string | null;
|
|
1372
|
+
startsAt: string;
|
|
1373
|
+
endsAt: string | null;
|
|
1374
|
+
channelId: Snowflake | null;
|
|
1375
|
+
location: string | null;
|
|
1376
|
+
coverUrl: string | null;
|
|
1377
|
+
recurrence: Record<string, unknown> | null;
|
|
1378
|
+
earlyReminderMinutes: number | null;
|
|
1379
|
+
status: "SCHEDULED" | "ACTIVE" | "COMPLETED" | "CANCELED";
|
|
1380
|
+
creatorId: Snowflake | null;
|
|
1381
|
+
interestedCount: number;
|
|
1382
|
+
createdAt: string;
|
|
1383
|
+
updatedAt: string;
|
|
1384
|
+
};
|
|
1385
|
+
}
|
|
1386
|
+
interface GuildEventDeletedPayload {
|
|
1387
|
+
eventId: Snowflake;
|
|
1388
|
+
guildId: Snowflake;
|
|
1389
|
+
}
|
|
1390
|
+
interface AnnouncementFollowCreatedPayload {
|
|
1391
|
+
/** Na origem: o seguidor. No destino: o vínculo. Uma das formas chega. */
|
|
1392
|
+
follower?: {
|
|
1393
|
+
id: Snowflake;
|
|
1394
|
+
sourceChannelId: Snowflake;
|
|
1395
|
+
guild: {
|
|
1396
|
+
id: Snowflake;
|
|
1397
|
+
name: string;
|
|
1398
|
+
iconUrl: string | null;
|
|
1399
|
+
};
|
|
1400
|
+
createdAt: string;
|
|
1401
|
+
};
|
|
1402
|
+
follow?: {
|
|
1403
|
+
id: Snowflake;
|
|
1404
|
+
targetChannelId: Snowflake;
|
|
1405
|
+
targetGuildId: Snowflake;
|
|
1406
|
+
source: {
|
|
1407
|
+
id: Snowflake;
|
|
1408
|
+
name: string;
|
|
1409
|
+
iconUrl: string | null;
|
|
1410
|
+
};
|
|
1411
|
+
createdBy: Snowflake;
|
|
1412
|
+
createdAt: string;
|
|
1413
|
+
};
|
|
1414
|
+
}
|
|
1415
|
+
interface AnnouncementFollowDeletedPayload {
|
|
1416
|
+
followId: Snowflake;
|
|
1417
|
+
sourceChannelId: Snowflake;
|
|
1418
|
+
targetChannelId?: Snowflake;
|
|
1419
|
+
}
|
|
1420
|
+
interface VoiceState {
|
|
1421
|
+
userId: Snowflake;
|
|
1422
|
+
guildId: Snowflake | null;
|
|
1423
|
+
channelId: Snowflake;
|
|
1424
|
+
sessionId: string;
|
|
1425
|
+
serverMute: boolean;
|
|
1426
|
+
serverDeaf: boolean;
|
|
1427
|
+
selfMute: boolean;
|
|
1428
|
+
selfDeaf: boolean;
|
|
1429
|
+
selfVideo: boolean;
|
|
1430
|
+
selfScreenShare: boolean;
|
|
1431
|
+
watchingUserId: Snowflake | null;
|
|
1432
|
+
suppressed: boolean;
|
|
1433
|
+
joinedAt: string;
|
|
1434
|
+
connectedAt: string | null;
|
|
1435
|
+
}
|
|
1436
|
+
interface VoiceStateUpdatedPayload {
|
|
1437
|
+
/** `null` quando a pessoa saiu da sala. */
|
|
1438
|
+
state: VoiceState | null;
|
|
1439
|
+
userId: Snowflake;
|
|
1440
|
+
channelId: Snowflake;
|
|
1441
|
+
}
|
|
1442
|
+
interface VoiceRoomUpdatedPayload {
|
|
1443
|
+
room: {
|
|
1444
|
+
channelId: Snowflake;
|
|
1445
|
+
participants: Array<{
|
|
1446
|
+
state: VoiceState;
|
|
1447
|
+
user: APIUser;
|
|
1448
|
+
}>;
|
|
1449
|
+
hasScreenShare: boolean;
|
|
1450
|
+
hasVideo: boolean;
|
|
1451
|
+
};
|
|
1452
|
+
}
|
|
1453
|
+
interface VoiceMemberMovedPayload {
|
|
1454
|
+
userId: Snowflake;
|
|
1455
|
+
guildId: Snowflake;
|
|
1456
|
+
fromChannelId: Snowflake;
|
|
1457
|
+
toChannelId: Snowflake;
|
|
1458
|
+
state: VoiceState;
|
|
1459
|
+
}
|
|
1460
|
+
interface VoiceBotKeyRequestedPayload {
|
|
1461
|
+
channelId: Snowflake;
|
|
1462
|
+
recipients: Array<{
|
|
1463
|
+
userId: Snowflake;
|
|
1464
|
+
publicKey: string;
|
|
1465
|
+
}>;
|
|
1466
|
+
}
|
|
1467
|
+
interface ApplicationCommandUpdatedPayload {
|
|
1468
|
+
guildId: Snowflake;
|
|
1469
|
+
botId: Snowflake;
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
/**
|
|
1473
|
+
* Mapa de eventos do `SquordClient`.
|
|
1474
|
+
*
|
|
1475
|
+
* Os eventos seguem os nomes reais do gateway do Squord (`message.created`,
|
|
1476
|
+
* `member.joined`, ...) — a documentação da plataforma é a referência de
|
|
1477
|
+
* quando cada um chega e qual intent ele exige. Eventos desconhecidos do
|
|
1478
|
+
* protocolo chegam em `unknownEvent`, garantindo compatibilidade futura.
|
|
1479
|
+
*/
|
|
1480
|
+
|
|
1481
|
+
/** Payload do evento `ready` do cliente. */
|
|
1482
|
+
interface ReadyEvent {
|
|
1483
|
+
/** A conta do bot. */
|
|
1484
|
+
user: User;
|
|
1485
|
+
/** Id da sessão do gateway (guarde para retomar). */
|
|
1486
|
+
sessionId: string;
|
|
1487
|
+
/** Spaces onde o bot está instalado no momento do ready. */
|
|
1488
|
+
guilds: Array<{
|
|
1489
|
+
id: Snowflake;
|
|
1490
|
+
name: string;
|
|
1491
|
+
iconUrl: string | null;
|
|
1492
|
+
}>;
|
|
1493
|
+
/** Latência já medida, se houver. */
|
|
1494
|
+
ping: number | null;
|
|
1495
|
+
}
|
|
1496
|
+
interface ClientEvents extends Record<string, unknown> {
|
|
1497
|
+
/** Sessão pronta: o bot autenticou e está online. */
|
|
1498
|
+
ready: ReadyEvent;
|
|
1499
|
+
/** Sessão retomada após queda: os eventos perdidos já chegaram antes. */
|
|
1500
|
+
resumed: GatewayResumed;
|
|
1501
|
+
/** Vai reconectar (backoff com jitter). */
|
|
1502
|
+
reconnecting: {
|
|
1503
|
+
attempt: number;
|
|
1504
|
+
delayMs: number;
|
|
1505
|
+
closeCode: number | null;
|
|
1506
|
+
reason: string;
|
|
1507
|
+
};
|
|
1508
|
+
/** Conexão caiu (com `fatal: true` quando não há retomada). */
|
|
1509
|
+
disconnect: {
|
|
1510
|
+
code: number | null;
|
|
1511
|
+
reason: string;
|
|
1512
|
+
fatal: boolean;
|
|
1513
|
+
};
|
|
1514
|
+
/** Erro de handler, de rede ou de protocolo. */
|
|
1515
|
+
error: Error;
|
|
1516
|
+
/** Avisos não fatais. */
|
|
1517
|
+
warn: string;
|
|
1518
|
+
/** Erro em um handler de comando registrado via `CommandRegistry`. */
|
|
1519
|
+
commandError: {
|
|
1520
|
+
error: unknown;
|
|
1521
|
+
command?: string;
|
|
1522
|
+
message?: Message;
|
|
1523
|
+
interaction?: Interaction;
|
|
1524
|
+
};
|
|
1525
|
+
/** Qualquer frame recebido do gateway (payload cru). */
|
|
1526
|
+
raw: ServerFrame;
|
|
1527
|
+
/** Evento do gateway com payload já hidratado em estruturas. */
|
|
1528
|
+
"message.created": Message;
|
|
1529
|
+
"message.updated": Message;
|
|
1530
|
+
"message.deleted": MessageDeletedPayload;
|
|
1531
|
+
"message.bulk_deleted": MessageBulkDeletedPayload;
|
|
1532
|
+
"poll.vote.cast": PollVotePayload;
|
|
1533
|
+
"poll.vote.removed": PollVotePayload;
|
|
1534
|
+
"reaction.added": ReactionAddedPayload;
|
|
1535
|
+
"reaction.removed": ReactionRemovedPayload;
|
|
1536
|
+
"member.joined": {
|
|
1537
|
+
guildId: Snowflake;
|
|
1538
|
+
member: Member;
|
|
1539
|
+
};
|
|
1540
|
+
"member.updated": {
|
|
1541
|
+
guildId: Snowflake;
|
|
1542
|
+
member: Member;
|
|
1543
|
+
};
|
|
1544
|
+
"member.left": MemberLeftPayload;
|
|
1545
|
+
"member.banned": MemberBannedPayload;
|
|
1546
|
+
"member.unbanned": MemberUnbannedPayload;
|
|
1547
|
+
"guild.updated": Guild;
|
|
1548
|
+
"guild.deleted": GuildDeletedPayload;
|
|
1549
|
+
"guild.taken_down": GuildTakenDownPayload;
|
|
1550
|
+
"guild.boost.added": GuildBoostPayload;
|
|
1551
|
+
"guild.boost.removed": GuildBoostPayload;
|
|
1552
|
+
"channel.created": Channel;
|
|
1553
|
+
"channel.updated": Channel;
|
|
1554
|
+
"channel.deleted": ChannelDeletedPayload;
|
|
1555
|
+
"channel.tree.invalidated": ChannelTreeInvalidatedPayload;
|
|
1556
|
+
"role.created": Role;
|
|
1557
|
+
"role.updated": Role;
|
|
1558
|
+
"role.deleted": RoleDeletedPayload;
|
|
1559
|
+
"thread.created": Thread;
|
|
1560
|
+
"thread.updated": Thread;
|
|
1561
|
+
"thread.deleted": ThreadDeletedPayload;
|
|
1562
|
+
"emoji.created": EmojiPayload;
|
|
1563
|
+
"emoji.updated": EmojiPayload;
|
|
1564
|
+
"emoji.deleted": EmojiDeletedPayload;
|
|
1565
|
+
"sticker.created": StickerPayload;
|
|
1566
|
+
"sticker.updated": StickerPayload;
|
|
1567
|
+
"sticker.deleted": StickerDeletedPayload;
|
|
1568
|
+
"guild_event.created": GuildEventPayload;
|
|
1569
|
+
"guild_event.updated": GuildEventPayload;
|
|
1570
|
+
"guild_event.deleted": GuildEventDeletedPayload;
|
|
1571
|
+
"announcement.follow.created": AnnouncementFollowCreatedPayload;
|
|
1572
|
+
"announcement.follow.deleted": AnnouncementFollowDeletedPayload;
|
|
1573
|
+
"voice.state.updated": VoiceStateUpdatedPayload;
|
|
1574
|
+
"voice.room.updated": VoiceRoomUpdatedPayload;
|
|
1575
|
+
"voice.member.moved": VoiceMemberMovedPayload;
|
|
1576
|
+
"voice.e2ee.bot_key_requested": VoiceBotKeyRequestedPayload;
|
|
1577
|
+
"interaction.created": Interaction;
|
|
1578
|
+
"application_command.updated": ApplicationCommandUpdatedPayload;
|
|
1579
|
+
/** Evento conhecido sem estrutura dedicada, com payload cru. */
|
|
1580
|
+
unknownEvent: {
|
|
1581
|
+
type: string;
|
|
1582
|
+
d: unknown;
|
|
1583
|
+
s?: number;
|
|
1584
|
+
timestamp: number;
|
|
1585
|
+
};
|
|
1586
|
+
}
|
|
1587
|
+
|
|
1588
|
+
/**
|
|
1589
|
+
* Abstração mínima de WebSocket usada pelo gateway.
|
|
1590
|
+
*
|
|
1591
|
+
* O SDK usa o `WebSocket` global do Node.js (22+) por padrão e aceita
|
|
1592
|
+
* qualquer implementação compatível — inclusive o pacote `ws` e os mocks
|
|
1593
|
+
* de teste (`@squord/sdk/testing`).
|
|
1594
|
+
*/
|
|
1595
|
+
interface WebSocketCloseEvent {
|
|
1596
|
+
code: number;
|
|
1597
|
+
reason: string;
|
|
1598
|
+
wasClean: boolean;
|
|
1599
|
+
}
|
|
1600
|
+
interface WebSocketHandlers {
|
|
1601
|
+
open: () => void;
|
|
1602
|
+
message: (data: string) => void;
|
|
1603
|
+
close: (event: WebSocketCloseEvent) => void;
|
|
1604
|
+
error: (error: unknown) => void;
|
|
1605
|
+
}
|
|
1606
|
+
interface WebSocketLike {
|
|
1607
|
+
send(data: string): void;
|
|
1608
|
+
close(code?: number, reason?: string): void;
|
|
1609
|
+
readonly readyState: number;
|
|
1610
|
+
}
|
|
1611
|
+
type WebSocketFactory = (url: string) => unknown;
|
|
1612
|
+
/** Envelopa a implementação escolhida e normaliza os eventos. */
|
|
1613
|
+
declare function attachWebSocket(ws: unknown, handlers: WebSocketHandlers): WebSocketLike;
|
|
1614
|
+
|
|
1615
|
+
/**
|
|
1616
|
+
* Gateway do Squord: WebSocket que entrega eventos em tempo real.
|
|
1617
|
+
*
|
|
1618
|
+
* Ciclo de vida (https://docs.squord.com.br/gateway/visao-geral):
|
|
1619
|
+
* 1. Abre a conexão; o servidor envia `hello` (intervalo de heartbeat).
|
|
1620
|
+
* 2. O bot envia `identify` com o token em até 15 segundos.
|
|
1621
|
+
* 3. O servidor responde `ready`; os eventos passam a chegar.
|
|
1622
|
+
* 4. O bot envia `heartbeat` a cada `heartbeatIntervalMs`; o servidor responde
|
|
1623
|
+
* `heartbeat.ack`. Sem ack dentro de um intervalo, a conexão é considerada
|
|
1624
|
+
* zumbi e é refeita com `resume`.
|
|
1625
|
+
* 5. Após uma queda, o bot reconecta e envia `resume` com a última sequência;
|
|
1626
|
+
* o servidor reenvia os eventos perdidos e depois envia `resumed`. Se não
|
|
1627
|
+
* puder retomar, responde `invalid_session` na mesma conexão, e o bot faz
|
|
1628
|
+
* `identify` de novo.
|
|
1629
|
+
*
|
|
1630
|
+
* Códigos de fechamento seguem a tabela oficial: 4004/4013/4014 não são
|
|
1631
|
+
* retomáveis; 4001/4002/4005/4012 são erros do bot; os demais reconectam com
|
|
1632
|
+
* backoff exponencial e jitter, tentando `resume`.
|
|
1633
|
+
*/
|
|
1634
|
+
|
|
1635
|
+
type GatewayStatus = "idle" | "connecting" | "ready" | "reconnecting" | "disconnected" | "destroyed";
|
|
1636
|
+
interface GatewayEvents extends Record<string, unknown> {
|
|
1637
|
+
ready: GatewayReady;
|
|
1638
|
+
resumed: GatewayResumed;
|
|
1639
|
+
reconnecting: {
|
|
1640
|
+
attempt: number;
|
|
1641
|
+
delayMs: number;
|
|
1642
|
+
closeCode: number | null;
|
|
1643
|
+
reason: string;
|
|
1644
|
+
};
|
|
1645
|
+
disconnect: {
|
|
1646
|
+
code: number | null;
|
|
1647
|
+
reason: string;
|
|
1648
|
+
fatal: boolean;
|
|
1649
|
+
};
|
|
1650
|
+
invalidSession: GatewayInvalidSession;
|
|
1651
|
+
serverError: GatewayError$1;
|
|
1652
|
+
raw: ServerFrame;
|
|
1653
|
+
event: {
|
|
1654
|
+
type: string;
|
|
1655
|
+
d: unknown;
|
|
1656
|
+
s?: number;
|
|
1657
|
+
timestamp: number;
|
|
1658
|
+
};
|
|
1659
|
+
error: Error;
|
|
1660
|
+
statusChange: GatewayStatus;
|
|
1661
|
+
}
|
|
1662
|
+
interface GatewayOptions {
|
|
1663
|
+
/** URL do gateway. Padrão: `wss://gateway.squord.com.br/gateway`. */
|
|
1664
|
+
url?: string;
|
|
1665
|
+
/** Token do bot (`sqb_...`), sem prefixo. */
|
|
1666
|
+
token: string;
|
|
1667
|
+
/** Fábrica de WebSocket (injetável para testes). Padrão: `WebSocket` global. */
|
|
1668
|
+
ws?: WebSocketFactory;
|
|
1669
|
+
/** Tempo máximo esperando `ready`/`resumed` após o `identify`/`resume`. Padrão: 20000 ms. */
|
|
1670
|
+
handshakeTimeoutMs?: number;
|
|
1671
|
+
/** `false` para não reconectar automaticamente. */
|
|
1672
|
+
autoReconnect?: boolean;
|
|
1673
|
+
/** Base do backoff de reconexão, em ms. Padrão: 1000 (dobra até 60000). */
|
|
1674
|
+
reconnectBaseMs?: number;
|
|
1675
|
+
/** Logger. */
|
|
1676
|
+
logger?: Logger;
|
|
1677
|
+
}
|
|
1678
|
+
declare class Gateway extends TypedEmitter<GatewayEvents> {
|
|
1679
|
+
readonly url: string;
|
|
1680
|
+
private readonly token;
|
|
1681
|
+
private readonly wsFactory;
|
|
1682
|
+
private readonly handshakeTimeoutMs;
|
|
1683
|
+
private readonly autoReconnect;
|
|
1684
|
+
private readonly reconnectBaseMs;
|
|
1685
|
+
private readonly logger;
|
|
1686
|
+
private ws;
|
|
1687
|
+
private statusValue;
|
|
1688
|
+
private reconnectAttempts;
|
|
1689
|
+
private connectLoop;
|
|
1690
|
+
private sessionId;
|
|
1691
|
+
private resumeUrl;
|
|
1692
|
+
private lastSequence;
|
|
1693
|
+
private established;
|
|
1694
|
+
private handshake;
|
|
1695
|
+
private handshakeTimer;
|
|
1696
|
+
private heartbeatIntervalMs;
|
|
1697
|
+
private heartbeatTimer;
|
|
1698
|
+
private awaitingAck;
|
|
1699
|
+
private lastHeartbeatSentAt;
|
|
1700
|
+
private destroyed;
|
|
1701
|
+
private closingByClient;
|
|
1702
|
+
private reconnectRequested;
|
|
1703
|
+
/** Latência do gateway: último heartbeat até o ack, em ms. */
|
|
1704
|
+
heartbeatLatencyMs: number | null;
|
|
1705
|
+
/** Quantas reconexões ocorreram desde a criação. */
|
|
1706
|
+
reconnectCount: number;
|
|
1707
|
+
/** Quantos frames de evento foram recebidos (incluindo duplicados). */
|
|
1708
|
+
eventsReceived: number;
|
|
1709
|
+
/** Quantos eventos foram descartados como duplicados. */
|
|
1710
|
+
eventsDropped: number;
|
|
1711
|
+
get sequence(): number | null;
|
|
1712
|
+
get session(): string | null;
|
|
1713
|
+
get status(): GatewayStatus;
|
|
1714
|
+
get isReady(): boolean;
|
|
1715
|
+
constructor(options: GatewayOptions);
|
|
1716
|
+
/**
|
|
1717
|
+
* Conecta ao gateway e resolve quando a sessão está pronta
|
|
1718
|
+
* (`ready` ou `resumed`). Em quedas transitórias, segue tentando com
|
|
1719
|
+
* backoff — a promise só é rejeitada em erros não retomáveis
|
|
1720
|
+
* (token inválido/revogado, conta suspensa, sessões demais, erro de
|
|
1721
|
+
* protocolo) ou se o gateway for destruído.
|
|
1722
|
+
*/
|
|
1723
|
+
connect(): Promise<GatewayReady>;
|
|
1724
|
+
/** Envia `presence.update`. O status escolhido vale também nas próximas conexões. */
|
|
1725
|
+
setPresence(presence: GatewayPresenceUpdate): void;
|
|
1726
|
+
/** Fecha a conexão, encerra as reconexões e descarta o estado de sessão. */
|
|
1727
|
+
destroy(): Promise<void>;
|
|
1728
|
+
/** Descarta o estado de sessão: a próxima conexão fará `identify` limpo. */
|
|
1729
|
+
invalidateSession(): void;
|
|
1730
|
+
/** Força uma reconexão imediata (que tentará `resume`). */
|
|
1731
|
+
reconnectNow(): void;
|
|
1732
|
+
private runConnectLoop;
|
|
1733
|
+
/** Abre um socket e resolve no `ready`/`resumed` (handshake completo). */
|
|
1734
|
+
private openSocketOnce;
|
|
1735
|
+
private resolveHandshake;
|
|
1736
|
+
private failHandshake;
|
|
1737
|
+
private clearHandshakeTimer;
|
|
1738
|
+
private handleMessage;
|
|
1739
|
+
private handleHello;
|
|
1740
|
+
private handleReady;
|
|
1741
|
+
private handleResumed;
|
|
1742
|
+
private handleHeartbeatAck;
|
|
1743
|
+
private handleInvalidSession;
|
|
1744
|
+
private handleReconnectRequest;
|
|
1745
|
+
private handleServerError;
|
|
1746
|
+
private handleEvent;
|
|
1747
|
+
private handleClose;
|
|
1748
|
+
private kickReconnectAfterDrop;
|
|
1749
|
+
private startHeartbeat;
|
|
1750
|
+
private stopHeartbeat;
|
|
1751
|
+
private sendHeartbeat;
|
|
1752
|
+
private sendFrame;
|
|
1753
|
+
private setStatus;
|
|
1754
|
+
}
|
|
1755
|
+
|
|
1756
|
+
/**
|
|
1757
|
+
* Permissões do Squord.
|
|
1758
|
+
*
|
|
1759
|
+
* Permissões são bits de um número inteiro de 64 bits. Trafegam como
|
|
1760
|
+
* **string decimal** e devem ser calculadas com `BigInt`: os bits mais
|
|
1761
|
+
* altos passam de 2^53, e um `number` de JavaScript perde precisão.
|
|
1762
|
+
*
|
|
1763
|
+
* @see https://docs.squord.com.br/referencia/permissoes
|
|
1764
|
+
*/
|
|
1765
|
+
|
|
1766
|
+
/** Flags de permissão. O bit 32 (`VIEW_AUDIT_LOG`) está na tabela oficial. */
|
|
1767
|
+
declare const Permissions: {
|
|
1768
|
+
readonly VIEW_CHANNEL: bigint;
|
|
1769
|
+
readonly MANAGE_CHANNELS: bigint;
|
|
1770
|
+
readonly MANAGE_GUILD: bigint;
|
|
1771
|
+
readonly MANAGE_ROLES: bigint;
|
|
1772
|
+
readonly MANAGE_INVITES: bigint;
|
|
1773
|
+
readonly VIEW_AUDIT_LOG: bigint;
|
|
1774
|
+
readonly MANAGE_EMOJIS: bigint;
|
|
1775
|
+
readonly MANAGE_WEBHOOKS: bigint;
|
|
1776
|
+
readonly KICK_MEMBERS: bigint;
|
|
1777
|
+
readonly BAN_MEMBERS: bigint;
|
|
1778
|
+
readonly TIMEOUT_MEMBERS: bigint;
|
|
1779
|
+
readonly CHANGE_NICKNAME: bigint;
|
|
1780
|
+
readonly MANAGE_NICKNAMES: bigint;
|
|
1781
|
+
readonly SEND_MESSAGES: bigint;
|
|
1782
|
+
readonly READ_MESSAGE_HISTORY: bigint;
|
|
1783
|
+
readonly MANAGE_MESSAGES: bigint;
|
|
1784
|
+
readonly ATTACH_FILES: bigint;
|
|
1785
|
+
readonly EMBED_LINKS: bigint;
|
|
1786
|
+
readonly ADD_REACTIONS: bigint;
|
|
1787
|
+
readonly MENTION_EVERYONE: bigint;
|
|
1788
|
+
readonly USE_EXTERNAL_EMOJIS: bigint;
|
|
1789
|
+
readonly PIN_MESSAGES: bigint;
|
|
1790
|
+
readonly CONNECT: bigint;
|
|
1791
|
+
readonly SPEAK: bigint;
|
|
1792
|
+
readonly VIDEO: bigint;
|
|
1793
|
+
readonly STREAM: bigint;
|
|
1794
|
+
readonly MUTE_MEMBERS: bigint;
|
|
1795
|
+
readonly DEAFEN_MEMBERS: bigint;
|
|
1796
|
+
readonly MOVE_MEMBERS: bigint;
|
|
1797
|
+
readonly PRIORITY_SPEAKER: bigint;
|
|
1798
|
+
readonly ADMINISTRATOR: bigint;
|
|
1799
|
+
readonly SEND_POLLS: bigint;
|
|
1800
|
+
/** O bit 32 foi aposentado e nunca é reutilizado. */
|
|
1801
|
+
readonly CREATE_INVITE: bigint;
|
|
1802
|
+
readonly APPROVE_JOIN_REQUESTS: bigint;
|
|
1803
|
+
readonly FORWARD_MESSAGES: bigint;
|
|
1804
|
+
readonly HANDLE_REPORTS: bigint;
|
|
1805
|
+
readonly PUBLISH_ANNOUNCEMENTS: bigint;
|
|
1806
|
+
readonly BYPASS_SLOWMODE: bigint;
|
|
1807
|
+
readonly CREATE_THREADS: bigint;
|
|
1808
|
+
readonly SEND_MESSAGES_IN_THREADS: bigint;
|
|
1809
|
+
readonly MANAGE_THREADS: bigint;
|
|
1810
|
+
readonly MANAGE_EVENTS: bigint;
|
|
1811
|
+
};
|
|
1812
|
+
type PermissionFlag = keyof typeof Permissions;
|
|
1813
|
+
/** Todas as permissões, somadas. */
|
|
1814
|
+
declare const ALL_PERMISSIONS: bigint;
|
|
1815
|
+
/** Converte bits para string decimal (o formato aceito pela API). */
|
|
1816
|
+
declare function permissionsToString(bits: bigint): PermissionBits;
|
|
1817
|
+
/** Lê uma string decimal vinda da API como `BigInt`. */
|
|
1818
|
+
declare function parsePermissions(value: PermissionBits | string): bigint;
|
|
1819
|
+
/** Testa se `bits` inclui todas as permissões em `flags`. */
|
|
1820
|
+
declare function hasPermissions(bits: bigint | PermissionBits, ...flags: bigint[]): boolean;
|
|
1821
|
+
/** Testa se `bits` inclui pelo menos uma das permissões em `flags`. */
|
|
1822
|
+
declare function hasAnyPermission(bits: bigint | PermissionBits, ...flags: bigint[]): boolean;
|
|
1823
|
+
/**
|
|
1824
|
+
* Resolve as permissões efetivas de um membro em um canal, seguindo o
|
|
1825
|
+
* algoritmo oficial: base do @everyone + OR dos cargos; `ADMINISTRATOR`
|
|
1826
|
+
* encerra a conta; overwrites (@everyone → cargos → membro); sem
|
|
1827
|
+
* `VIEW_CHANNEL`, o resultado é zero.
|
|
1828
|
+
*
|
|
1829
|
+
* O backend continua sendo a autoridade final: o resultado local é uma
|
|
1830
|
+
* conveniência para evitar chamadas, não uma garantia.
|
|
1831
|
+
*/
|
|
1832
|
+
declare function resolveChannelPermissions(options: {
|
|
1833
|
+
/** Permissões do cargo @everyone (o id do cargo é o próprio id do Space). */
|
|
1834
|
+
everyonePermissions: bigint;
|
|
1835
|
+
/** Permissões dos cargos do membro (sem contar @everyone). */
|
|
1836
|
+
rolePermissions: bigint[];
|
|
1837
|
+
/** Overwrites do canal (e da categoria, se houver, aplicados antes). */
|
|
1838
|
+
overwrites: APIChannelOverwrite[];
|
|
1839
|
+
/** Id do membro. */
|
|
1840
|
+
memberId: Snowflake;
|
|
1841
|
+
/** Id do cargo @everyone (o mesmo id do Space). */
|
|
1842
|
+
everyoneRoleId: Snowflake;
|
|
1843
|
+
/** Ids dos cargos do membro, sem contar @everyone. */
|
|
1844
|
+
memberRoleIds: Snowflake[];
|
|
1845
|
+
}): bigint;
|
|
1846
|
+
/**
|
|
1847
|
+
* Escopo mínimo usual para um bot que lê e responde em canais.
|
|
1848
|
+
* Útil para gerar o valor do link de instalação.
|
|
1849
|
+
*/
|
|
1850
|
+
declare const SUGGESTED_TEXT_BOT_PERMISSIONS: bigint;
|
|
1851
|
+
/** Escopo de moderação usual (exige confirmação na instalação). */
|
|
1852
|
+
declare const SUGGESTED_MODERATION_PERMISSIONS: bigint;
|
|
1853
|
+
|
|
1854
|
+
/**
|
|
1855
|
+
* Cache em memória opcional: TTL por item, limite de itens e invalidação.
|
|
1856
|
+
*
|
|
1857
|
+
* O padrão do SDK é armazenar apenas o necessário, com acesso sob demanda
|
|
1858
|
+
* aos demais dados. O cache **nunca** substitui a API: um item pode estar
|
|
1859
|
+
* defasado, e o backend continua sendo a autoridade.
|
|
1860
|
+
*/
|
|
1861
|
+
interface CacheOptions {
|
|
1862
|
+
/** Tempo de vida por item, em milissegundos. Padrão: 300000 (5 min). */
|
|
1863
|
+
ttlMs?: number;
|
|
1864
|
+
/** Máximo de itens guardados; os mais antigos são descartados. Padrão: 1000. */
|
|
1865
|
+
maxSize?: number;
|
|
1866
|
+
/** Função de agora, injetável para testes. */
|
|
1867
|
+
now?: () => number;
|
|
1868
|
+
}
|
|
1869
|
+
declare class Cache<K, V> {
|
|
1870
|
+
private readonly store;
|
|
1871
|
+
private readonly ttlMs;
|
|
1872
|
+
private readonly maxSize;
|
|
1873
|
+
private readonly now;
|
|
1874
|
+
constructor(options?: CacheOptions);
|
|
1875
|
+
get(key: K): V | undefined;
|
|
1876
|
+
set(key: K, value: V, ttlMs?: number): void;
|
|
1877
|
+
has(key: K): boolean;
|
|
1878
|
+
delete(key: K): boolean;
|
|
1879
|
+
clear(): void;
|
|
1880
|
+
get size(): number;
|
|
1881
|
+
/** Itera itens vivos. */
|
|
1882
|
+
entries(): IterableIterator<[K, V]>;
|
|
1883
|
+
private peek;
|
|
1884
|
+
private evictIfNeeded;
|
|
1885
|
+
private sweep;
|
|
1886
|
+
}
|
|
1887
|
+
|
|
1888
|
+
/**
|
|
1889
|
+
* `SquordClient`: o ponto central do SDK.
|
|
1890
|
+
*
|
|
1891
|
+
* Valida o token contra a API (`GET /bots/@me`), conecta ao gateway, entrega
|
|
1892
|
+
* eventos tipados e expõe os managers REST. O ciclo de vida completo —
|
|
1893
|
+
* reconexão, heartbeat, resume e deduplicação — fica a cargo do SDK.
|
|
1894
|
+
*/
|
|
1895
|
+
|
|
1896
|
+
interface ClientOptions {
|
|
1897
|
+
/** Token do bot (`sqb_<id>.<segredo>`), de preferência vindo do ambiente. */
|
|
1898
|
+
token: string;
|
|
1899
|
+
/** URL base da API REST. Padrão: `https://api.squord.com.br/api/v1`. */
|
|
1900
|
+
apiBaseURL?: string;
|
|
1901
|
+
/** URL do gateway. Padrão: `wss://gateway.squord.com.br/gateway`. */
|
|
1902
|
+
gatewayURL?: string;
|
|
1903
|
+
/** Timeout por requisição REST, em ms. Padrão: 15000. */
|
|
1904
|
+
restTimeoutMs?: number;
|
|
1905
|
+
/** Base do backoff de reconexão do gateway, em ms. Padrão: 1000. */
|
|
1906
|
+
gatewayReconnectBaseMs?: number;
|
|
1907
|
+
/** Retentativas REST para falhas transitórias. Padrão: 3. */
|
|
1908
|
+
restMaxRetries?: number;
|
|
1909
|
+
/** Teto global de requisições/segundo (o oficial é 50). Padrão: 45. */
|
|
1910
|
+
restGlobalPerSecond?: number;
|
|
1911
|
+
/** Implementação de fetch para testes. Padrão: `fetch` global. */
|
|
1912
|
+
fetchImpl?: typeof fetch;
|
|
1913
|
+
/** Fábrica de WebSocket para testes. Padrão: `WebSocket` global (Node 22+). */
|
|
1914
|
+
ws?: WebSocketFactory;
|
|
1915
|
+
/**
|
|
1916
|
+
* `true` para usar apenas o cliente REST (tarefas agendadas, CI), sem
|
|
1917
|
+
* gateway. Use `login()` normalmente; ele só valida o token.
|
|
1918
|
+
*/
|
|
1919
|
+
restOnly?: boolean;
|
|
1920
|
+
/** `true` para encerrar com SIGINT/SIGTERM automaticamente. Padrão: `false`. */
|
|
1921
|
+
gracefulShutdown?: boolean;
|
|
1922
|
+
/** Logger do SDK (`debug`, `info`, `warn`, `error`); `null` silencia. */
|
|
1923
|
+
logger?: Logger | null;
|
|
1924
|
+
/** Nível do logger automático (ignorado se `logger` for informado). */
|
|
1925
|
+
logLevel?: "debug" | "info" | "warn" | "error" | "silent";
|
|
1926
|
+
/**
|
|
1927
|
+
* Cache em memória opcional (TTL e limite configuráveis). Desativado por
|
|
1928
|
+
* padrão: o cliente busca os dados sob demanda.
|
|
1929
|
+
*/
|
|
1930
|
+
cache?: {
|
|
1931
|
+
enabled: boolean;
|
|
1932
|
+
/** TTL por item, em ms. Padrão: 300000 (5 min). */
|
|
1933
|
+
ttlMs?: number;
|
|
1934
|
+
/** Máximo de itens por cache. Padrão: 500. */
|
|
1935
|
+
maxEntries?: number;
|
|
1936
|
+
};
|
|
1937
|
+
}
|
|
1938
|
+
declare class SquordClient extends TypedEmitter<ClientEvents> {
|
|
1939
|
+
readonly rest: RestClient;
|
|
1940
|
+
readonly messages: MessagesManager;
|
|
1941
|
+
readonly channels: ChannelsManager;
|
|
1942
|
+
readonly guilds: GuildsManager;
|
|
1943
|
+
readonly members: MembersManager;
|
|
1944
|
+
readonly roles: RolesManager;
|
|
1945
|
+
readonly moderation: ModerationManager;
|
|
1946
|
+
readonly uploads: UploadsManager;
|
|
1947
|
+
readonly interactions: InteractionsManager;
|
|
1948
|
+
readonly commands: ApplicationCommandsManager;
|
|
1949
|
+
readonly bot: BotManager;
|
|
1950
|
+
readonly users: UsersManager;
|
|
1951
|
+
readonly logger: Logger;
|
|
1952
|
+
/** Caches opcionais, desativados por padrão (`cache.enabled`). */
|
|
1953
|
+
readonly caches: {
|
|
1954
|
+
guilds: Cache<Snowflake, APIGuild>;
|
|
1955
|
+
channels: Cache<Snowflake, APIChannel>;
|
|
1956
|
+
members: Cache<string, APIMember>;
|
|
1957
|
+
roles: Cache<Snowflake, APIRole[]>;
|
|
1958
|
+
} | null;
|
|
1959
|
+
private readonly options;
|
|
1960
|
+
private gatewayInstance;
|
|
1961
|
+
private botInfo;
|
|
1962
|
+
private userIdValue;
|
|
1963
|
+
private shutdownSignalsBound;
|
|
1964
|
+
private destroyed;
|
|
1965
|
+
constructor(options: ClientOptions);
|
|
1966
|
+
/** Opções com que o cliente foi criado (sem o token). */
|
|
1967
|
+
get optionsSafe(): Omit<ClientOptions, "token">;
|
|
1968
|
+
/** Id da conta do bot (disponível após `login()`). */
|
|
1969
|
+
get userId(): Snowflake | null;
|
|
1970
|
+
/** A conta do bot como `User` (após `login()`). */
|
|
1971
|
+
get user(): User | null;
|
|
1972
|
+
/** O bot na visão do dono (após `login()`). */
|
|
1973
|
+
get application(): APIBot | null;
|
|
1974
|
+
/** O gateway, se conectado (ou em conexão). */
|
|
1975
|
+
get gateway(): Gateway | null;
|
|
1976
|
+
/** `true` quando o gateway está autenticado e recebendo eventos. */
|
|
1977
|
+
isReady(): boolean;
|
|
1978
|
+
/** Latência do gateway (último heartbeat → ack), em ms. */
|
|
1979
|
+
get ping(): number | null;
|
|
1980
|
+
/**
|
|
1981
|
+
* Autentica e conecta. Valida o token (`GET /bots/@me`), conecta ao
|
|
1982
|
+
* gateway (a menos que `restOnly`) e resolve no `ready`.
|
|
1983
|
+
*/
|
|
1984
|
+
login(): Promise<void>;
|
|
1985
|
+
/**
|
|
1986
|
+
* Encerra o cliente: fecha o gateway, cancela requisições pendentes e
|
|
1987
|
+
* remove listeners. Seguro chamar mais de uma vez.
|
|
1988
|
+
*/
|
|
1989
|
+
destroy(): Promise<void>;
|
|
1990
|
+
/** Presença do bot: `ONLINE`, `IDLE`, `DND` ou `INVISIBLE`, com status personalizado. */
|
|
1991
|
+
setPresence(presence: {
|
|
1992
|
+
status?: PresenceStatus;
|
|
1993
|
+
customStatus?: string | null;
|
|
1994
|
+
afk?: boolean;
|
|
1995
|
+
}): void;
|
|
1996
|
+
/** Força reconexão do gateway (tenta `resume`). */
|
|
1997
|
+
reconnect(): void;
|
|
1998
|
+
/**
|
|
1999
|
+
* Permissões efetivas do bot em um canal, resolvidas localmente a partir
|
|
2000
|
+
* dos cargos e overwrites (com o cache, quando habilitado). O backend
|
|
2001
|
+
* continua sendo a autoridade final.
|
|
2002
|
+
*/
|
|
2003
|
+
myPermissionsIn(channelId: Snowflake): Promise<bigint>;
|
|
2004
|
+
/** Testa se o bot tem um conjunto de permissões em um canal. */
|
|
2005
|
+
hasPermissionsIn(channelId: Snowflake, ...flags: bigint[]): Promise<boolean>;
|
|
2006
|
+
/** Atalho para `Permissions` (evita import extra em código de bot). */
|
|
2007
|
+
get Permissions(): typeof Permissions;
|
|
2008
|
+
private ensureGateway;
|
|
2009
|
+
private dispatchGatewayEvent;
|
|
2010
|
+
}
|
|
2011
|
+
|
|
2012
|
+
/**
|
|
2013
|
+
* Registro de comandos: texto (com prefixo), slash (comandos de aplicação)
|
|
2014
|
+
* e componentes (botões e menus).
|
|
2015
|
+
*
|
|
2016
|
+
* - **Texto**: o SDK ouve `message.created`, faz o parse do prefixo e dos
|
|
2017
|
+
* argumentos e chama o handler. Suporta aliases, cooldowns e middleware.
|
|
2018
|
+
* - **Slash**: handlers para `interaction.created` de comandos. O registro
|
|
2019
|
+
* pode sincronizar as definições com o Squord (`PUT` em bloco) na partida
|
|
2020
|
+
* do bot — registrar é sobrescrever, então a lista deve ser a mesma sempre.
|
|
2021
|
+
* - **Componentes**: handlers para cliques em botões e escolhas em menus,
|
|
2022
|
+
* identificados pelo `customId` (aceito prefixo com `*` no final).
|
|
2023
|
+
*/
|
|
2024
|
+
|
|
2025
|
+
interface TextCommandDefinition {
|
|
2026
|
+
/** Nome principal (sem o prefixo). Letras minúsculas recomendadas. */
|
|
2027
|
+
name: string;
|
|
2028
|
+
/** Nomes alternativos. */
|
|
2029
|
+
aliases?: string[];
|
|
2030
|
+
/** Descrição usada em mensagens de erro e ajuda. */
|
|
2031
|
+
description?: string;
|
|
2032
|
+
/** Deixa o comando oculto em listagens de ajuda. */
|
|
2033
|
+
hidden?: boolean;
|
|
2034
|
+
/** Cooldown por usuário, em ms. Padrão: sem cooldown. */
|
|
2035
|
+
cooldownMs?: number;
|
|
2036
|
+
/** Caso a mensagem deve ignorar bots (padrão `true`). */
|
|
2037
|
+
ignoreBots?: boolean;
|
|
2038
|
+
/** Onde o comando vale: em qualquer Space ou em Spaces específicos. */
|
|
2039
|
+
guildIds?: Snowflake[];
|
|
2040
|
+
/** Middleware antes da execução; devolve `false` para abortar. */
|
|
2041
|
+
beforeExecute?: (context: TextCommandContext) => boolean | Promise<boolean>;
|
|
2042
|
+
execute: (context: TextCommandContext) => unknown | Promise<unknown>;
|
|
2043
|
+
}
|
|
2044
|
+
interface TextCommandContext {
|
|
2045
|
+
/** O cliente do bot. */
|
|
2046
|
+
client: SquordClient;
|
|
2047
|
+
/** A mensagem que invocou o comando. */
|
|
2048
|
+
message: Message;
|
|
2049
|
+
/** Nome invocado (pode ser um alias). */
|
|
2050
|
+
name: string;
|
|
2051
|
+
/** Definição do comando. */
|
|
2052
|
+
command: TextCommandDefinition;
|
|
2053
|
+
/** Argumentos crus, já com aspas tratadas. */
|
|
2054
|
+
args: string[];
|
|
2055
|
+
/** A linha de argumentos como veio (sem o nome do comando). */
|
|
2056
|
+
rawArgs: string;
|
|
2057
|
+
/** Responde no canal (sem citar). */
|
|
2058
|
+
reply(payload: string | Parameters<Message["reply"]>[0]): ReturnType<Message["reply"]>;
|
|
2059
|
+
/** Responde citando a mensagem original. */
|
|
2060
|
+
replyWithMention(payload: string | Parameters<Message["reply"]>[0]): ReturnType<Message["reply"]>;
|
|
2061
|
+
/** Reage à mensagem que invocou. */
|
|
2062
|
+
react(emoji: string): Promise<void>;
|
|
2063
|
+
}
|
|
2064
|
+
interface SlashCommandDefinition {
|
|
2065
|
+
/** Letras minúsculas, números, `_` e `-` (até 32 caracteres). */
|
|
2066
|
+
name: string;
|
|
2067
|
+
/** Até 100 caracteres. */
|
|
2068
|
+
description: string;
|
|
2069
|
+
/** Até 25 opções; as obrigatórias vêm antes das opcionais. */
|
|
2070
|
+
options?: APICommandOptionInput[];
|
|
2071
|
+
/** Onde publicar: `"global"` (padrão) ou Spaces específicos. */
|
|
2072
|
+
scope?: {
|
|
2073
|
+
kind: "global";
|
|
2074
|
+
} | {
|
|
2075
|
+
kind: "guild";
|
|
2076
|
+
guildIds: Snowflake[];
|
|
2077
|
+
};
|
|
2078
|
+
execute: (interaction: Interaction) => unknown | Promise<unknown>;
|
|
2079
|
+
}
|
|
2080
|
+
interface ComponentHandlerDefinition {
|
|
2081
|
+
/** `customId` do componente. Terminando em `*`, casa por prefixo. */
|
|
2082
|
+
customId: string;
|
|
2083
|
+
execute: (interaction: Interaction) => unknown | Promise<unknown>;
|
|
2084
|
+
}
|
|
2085
|
+
interface CommandRegistryOptions {
|
|
2086
|
+
/** Prefixo dos comandos de texto: string ou função (padrão `"!"`). */
|
|
2087
|
+
prefix?: string | ((message: Message) => string | null);
|
|
2088
|
+
/**
|
|
2089
|
+
* Sincronizar os slash commands com o Squord no login (PUT em bloco,
|
|
2090
|
+
* sobrescrevendo o que existir). Padrão: `true` quando houver comandos.
|
|
2091
|
+
*/
|
|
2092
|
+
syncOnLogin?: boolean;
|
|
2093
|
+
/** Se `true`, ignora mensagens de bots nos comandos de texto (padrão). */
|
|
2094
|
+
ignoreBots?: boolean;
|
|
2095
|
+
/** Handler para erros dos comandos (texto e slash). */
|
|
2096
|
+
onError?: (error: unknown, context: {
|
|
2097
|
+
command?: string;
|
|
2098
|
+
message?: Message;
|
|
2099
|
+
interaction?: Interaction;
|
|
2100
|
+
}) => void;
|
|
2101
|
+
}
|
|
2102
|
+
declare class CommandRegistry {
|
|
2103
|
+
private readonly client;
|
|
2104
|
+
private readonly options;
|
|
2105
|
+
private readonly textCommands;
|
|
2106
|
+
private readonly slashCommands;
|
|
2107
|
+
private readonly componentHandlers;
|
|
2108
|
+
private readonly cooldowns;
|
|
2109
|
+
private readonly prefixResolver;
|
|
2110
|
+
private attached;
|
|
2111
|
+
constructor(client: SquordClient, options?: CommandRegistryOptions);
|
|
2112
|
+
/** Registra um comando de texto. */
|
|
2113
|
+
text(definition: TextCommandDefinition): this;
|
|
2114
|
+
/** Registra um comando slash. */
|
|
2115
|
+
slash(definition: SlashCommandDefinition): this;
|
|
2116
|
+
/** Registra um handler de componente (botão ou menu). */
|
|
2117
|
+
component(definition: ComponentHandlerDefinition): this;
|
|
2118
|
+
/** Remove um handler de componente. */
|
|
2119
|
+
removeComponent(customId: string): this;
|
|
2120
|
+
/** Definições slash prontas para o `PUT` em bloco. */
|
|
2121
|
+
toCommandsInput(): APICommandInput[];
|
|
2122
|
+
/**
|
|
2123
|
+
* Sincroniza os slash commands com o Squord (PUT em bloco, sobrescrevendo
|
|
2124
|
+
* o que existir em cada escopo). Chame após `client.login()` — ou deixe o
|
|
2125
|
+
* registro fazer automaticamente no `ready` (`syncOnLogin`, o padrão).
|
|
2126
|
+
*/
|
|
2127
|
+
sync(): Promise<void>;
|
|
2128
|
+
/** Limpa os cooldowns (útil em testes). */
|
|
2129
|
+
clearCooldowns(): void;
|
|
2130
|
+
/** Processa manualmente uma mensagem como possível comando de texto (para testes). */
|
|
2131
|
+
handleTextMessage(message: Message): Promise<boolean>;
|
|
2132
|
+
/** Processa manualmente uma interação (para testes). */
|
|
2133
|
+
handleInteraction(interaction: Interaction): Promise<boolean>;
|
|
2134
|
+
private matchComponent;
|
|
2135
|
+
private resolvePrefix;
|
|
2136
|
+
private ensureAttached;
|
|
2137
|
+
private reportError;
|
|
2138
|
+
}
|
|
2139
|
+
|
|
2140
|
+
/**
|
|
2141
|
+
* Iteração sobre listas paginadas por cursor.
|
|
2142
|
+
*
|
|
2143
|
+
* A API devolve `{ items, prevCursor, nextCursor, hasMore }`. Este helper
|
|
2144
|
+
* converte uma função de página em um `AsyncGenerator` de itens, para
|
|
2145
|
+
* processar o histórico sem carregar tudo em memória.
|
|
2146
|
+
*/
|
|
2147
|
+
|
|
2148
|
+
type PageFetcher<T> = (params: CursorPaginationParams) => Promise<Page<T>>;
|
|
2149
|
+
/**
|
|
2150
|
+
* Percorre as páginas de uma lista, emitindo os itens um a um.
|
|
2151
|
+
*
|
|
2152
|
+
* @param fetchPage função que busca uma página (`limit`, `before`, `after`).
|
|
2153
|
+
* @param firstParams parâmetros da primeira página.
|
|
2154
|
+
* @param direction percorre para trás (`before`, o padrão do histórico)
|
|
2155
|
+
* ou para frente (`after`).
|
|
2156
|
+
*/
|
|
2157
|
+
declare function paginate<T>(fetchPage: PageFetcher<T>, firstParams?: CursorPaginationParams, direction?: "before" | "after"): AsyncGenerator<T, void, unknown>;
|
|
2158
|
+
/** Coleta todos os itens de uma paginação em um array (use com critério). */
|
|
2159
|
+
declare function collectPagination<T>(fetchPage: PageFetcher<T>, firstParams?: CursorPaginationParams, direction?: "before" | "after", maxItems?: number): Promise<T[]>;
|
|
2160
|
+
|
|
2161
|
+
/**
|
|
2162
|
+
* Hierarquia de erros do SDK.
|
|
2163
|
+
*
|
|
2164
|
+
* A API devolve um envelope único (`statusCode`, `code`, `message`, `details`,
|
|
2165
|
+
* `requestId`). Decida pelo `code`, nunca pela `message`. Cada erro do SDK
|
|
2166
|
+
* expõe propriedades consistentes: `code`, `status`, `requestId`,
|
|
2167
|
+
* `retryAfter` e `cause`, quando aplicáveis.
|
|
2168
|
+
*
|
|
2169
|
+
* @see https://docs.squord.com.br/referencia/erros
|
|
2170
|
+
*/
|
|
2171
|
+
|
|
2172
|
+
/** Base de todos os erros lançados pelo SDK. */
|
|
2173
|
+
declare class SquordError extends Error {
|
|
2174
|
+
/** Código estável do erro, em `SCREAMING_SNAKE`. */
|
|
2175
|
+
readonly code: string;
|
|
2176
|
+
constructor(code: string, message: string, options?: {
|
|
2177
|
+
cause?: unknown;
|
|
2178
|
+
});
|
|
2179
|
+
}
|
|
2180
|
+
/**
|
|
2181
|
+
* Erro devolvido pela API REST do Squord. Teste sempre pelo `code`
|
|
2182
|
+
* (ex.: `err.code === "MISSING_PERMISSION"`), nunca pela `message`.
|
|
2183
|
+
*/
|
|
2184
|
+
declare class SquordAPIError extends SquordError {
|
|
2185
|
+
/** Status HTTP da resposta. */
|
|
2186
|
+
readonly status: number;
|
|
2187
|
+
/** O mesmo valor do header `x-request-id` da resposta. */
|
|
2188
|
+
readonly requestId: string | null;
|
|
2189
|
+
/** Corpo bruto do erro (o envelope completo), quando disponível. */
|
|
2190
|
+
readonly responseBody: APIErrorBody | null;
|
|
2191
|
+
/** `details` do envelope, quando existe. */
|
|
2192
|
+
readonly details: unknown;
|
|
2193
|
+
constructor(body: APIErrorBody, status: number, requestId?: string | null);
|
|
2194
|
+
}
|
|
2195
|
+
/** `401 UNAUTHENTICATED` — não há credencial na requisição. */
|
|
2196
|
+
declare class AuthenticationError extends SquordAPIError {
|
|
2197
|
+
}
|
|
2198
|
+
/** `401 INVALID_TOKEN` — token malformado, revogado ou trocado, ou bot/dono excluído ou suspenso. */
|
|
2199
|
+
declare class InvalidTokenError extends AuthenticationError {
|
|
2200
|
+
}
|
|
2201
|
+
/** `403` — a credencial é válida, mas a ação não é permitida (`MISSING_PERMISSION`, `FORBIDDEN`, `NOT_A_MEMBER`, ...). */
|
|
2202
|
+
declare class PermissionError extends SquordAPIError {
|
|
2203
|
+
/** Nome da permissão que faltou, quando o erro é `MISSING_PERMISSION`. */
|
|
2204
|
+
readonly missingPermission: string | null;
|
|
2205
|
+
constructor(body: APIErrorBody, status: number, requestId?: string | null);
|
|
2206
|
+
}
|
|
2207
|
+
/** `404` — recurso inexistente ou invisível para o bot. */
|
|
2208
|
+
declare class NotFoundError extends SquordAPIError {
|
|
2209
|
+
}
|
|
2210
|
+
/** `422 VALIDATION_FAILED` — corpo bem formado, mas inválido. */
|
|
2211
|
+
declare class ValidationError extends SquordAPIError {
|
|
2212
|
+
/** Os itens de validação (campo, código do item, limite violado). */
|
|
2213
|
+
readonly issues: APIValidationIssue[];
|
|
2214
|
+
constructor(body: APIErrorBody, status: number, requestId?: string | null);
|
|
2215
|
+
}
|
|
2216
|
+
/** `429 RATE_LIMITED` — limite de taxa. Espere `retryAfter` segundos. */
|
|
2217
|
+
declare class RateLimitError extends SquordAPIError {
|
|
2218
|
+
/** Segundos de espera informados pelo servidor (mínimo 1). */
|
|
2219
|
+
readonly retryAfter: number;
|
|
2220
|
+
/** O bucket que recusou (`MESSAGE_CREATE`, `BOT_GLOBAL`, ...). */
|
|
2221
|
+
readonly bucket: string | null;
|
|
2222
|
+
/** `true` quando o SDK já esgotou as retentativas automáticas. */
|
|
2223
|
+
readonly exhaustedRetries: boolean;
|
|
2224
|
+
constructor(body: APIErrorBody, status: number, options?: {
|
|
2225
|
+
requestId?: string | null;
|
|
2226
|
+
exhaustedRetries?: boolean;
|
|
2227
|
+
});
|
|
2228
|
+
}
|
|
2229
|
+
/** Falha de rede antes de receber qualquer resposta (DNS, TCP, TLS). */
|
|
2230
|
+
declare class NetworkError extends SquordError {
|
|
2231
|
+
constructor(message: string, options?: {
|
|
2232
|
+
cause?: unknown;
|
|
2233
|
+
});
|
|
2234
|
+
}
|
|
2235
|
+
/** A requisição excedeu o tempo limite configurado. */
|
|
2236
|
+
declare class RequestTimeoutError extends SquordError {
|
|
2237
|
+
/** Milissegundos configurados de timeout. */
|
|
2238
|
+
readonly timeoutMs: number;
|
|
2239
|
+
/** Método HTTP da requisição que expirou. */
|
|
2240
|
+
readonly method: string;
|
|
2241
|
+
/** Caminho da requisição que expirou. */
|
|
2242
|
+
readonly path: string;
|
|
2243
|
+
constructor(method: string, path: string, timeoutMs: number, options?: {
|
|
2244
|
+
cause?: unknown;
|
|
2245
|
+
});
|
|
2246
|
+
}
|
|
2247
|
+
/** Erro de conexão/fechamento do gateway. */
|
|
2248
|
+
declare class GatewayError extends SquordError {
|
|
2249
|
+
/** Código de fechamento (4000+) ou `null` em falhas de rede. */
|
|
2250
|
+
readonly closeCode: number | null;
|
|
2251
|
+
/** Razão textual enviada pelo servidor (informativa; use `closeCode`). */
|
|
2252
|
+
readonly reason: string | null;
|
|
2253
|
+
constructor(closeCode: number | null, reason: string | null, message?: string);
|
|
2254
|
+
}
|
|
2255
|
+
/** Erro de uso incorreto da API do SDK (argumentos inválidos no cliente). */
|
|
2256
|
+
declare class SquordTypeError extends SquordError {
|
|
2257
|
+
constructor(message: string);
|
|
2258
|
+
}
|
|
2259
|
+
/**
|
|
2260
|
+
* Normaliza um corpo de erro em {@link SquordAPIError} ou uma subclasse.
|
|
2261
|
+
* Exportado para testes e uso avançado.
|
|
2262
|
+
*/
|
|
2263
|
+
declare function makeAPIError(body: APIErrorBody, status: number, requestId?: string | null): SquordAPIError;
|
|
2264
|
+
|
|
2265
|
+
/**
|
|
2266
|
+
* Intents do gateway.
|
|
2267
|
+
*
|
|
2268
|
+
* As intents são configuradas por bot (Configurações → Desenvolvedor, ou
|
|
2269
|
+
* `PATCH /bots/{bot.id}`) e **não** vão no `identify`: o gateway lê as
|
|
2270
|
+
* intents do bot no momento do identify. Este módulo serve para calcular,
|
|
2271
|
+
* exibir e comparar valores — por exemplo, ao gerenciar o bot pela API.
|
|
2272
|
+
*
|
|
2273
|
+
* O padrão de um bot novo é `GUILDS | GUILD_MESSAGES | GUILD_MESSAGE_REACTIONS`
|
|
2274
|
+
* (valor `13`).
|
|
2275
|
+
*
|
|
2276
|
+
* @see https://docs.squord.com.br/gateway/intents
|
|
2277
|
+
*/
|
|
2278
|
+
declare const Intents: {
|
|
2279
|
+
/** Space, canais, cargos, threads, emojis, stickers, eventos do Space. */
|
|
2280
|
+
readonly GUILDS: number;
|
|
2281
|
+
/** Entrada, saída, edição e ban de membros. */
|
|
2282
|
+
readonly GUILD_MEMBERS: number;
|
|
2283
|
+
/** `message.*` e votos de enquete. */
|
|
2284
|
+
readonly GUILD_MESSAGES: number;
|
|
2285
|
+
/** Reações. */
|
|
2286
|
+
readonly GUILD_MESSAGE_REACTIONS: number;
|
|
2287
|
+
/** Estado e salas de voz. */
|
|
2288
|
+
readonly GUILD_VOICE_STATES: number;
|
|
2289
|
+
/**
|
|
2290
|
+
* **Privilegiada.** Não liga evento nenhum: devolve o conteúdo das
|
|
2291
|
+
* mensagens. Sem ela, `content`, `embeds`, `attachments`, `components`
|
|
2292
|
+
* e `poll` chegam esvaziados — exceto mensagens do próprio bot e as que
|
|
2293
|
+
* o mencionam.
|
|
2294
|
+
*/
|
|
2295
|
+
readonly MESSAGE_CONTENT: number;
|
|
2296
|
+
};
|
|
2297
|
+
type IntentFlag = keyof typeof Intents;
|
|
2298
|
+
/** Intents padrão de um bot novo. */
|
|
2299
|
+
declare const DEFAULT_INTENTS: number;
|
|
2300
|
+
/** Soma flags de intent em um número (0 a 65535). */
|
|
2301
|
+
declare function intentsValue(...flags: number[]): number;
|
|
2302
|
+
/** Lista as flags conhecidas presentes em um valor de intents. */
|
|
2303
|
+
declare function listIntents(value: number): IntentFlag[];
|
|
2304
|
+
|
|
2305
|
+
/**
|
|
2306
|
+
* Backoff exponencial com jitter, para reconexões do gateway e retentativas
|
|
2307
|
+
* de REST. A recomendação da documentação: 1 s, 2 s, 4 s ... até 60 s, mais
|
|
2308
|
+
* um valor aleatório.
|
|
2309
|
+
*/
|
|
2310
|
+
interface BackoffOptions {
|
|
2311
|
+
/** Primeira espera, em milissegundos. Padrão 1000. */
|
|
2312
|
+
baseMs?: number;
|
|
2313
|
+
/** Multiplicador entre tentativas. Padrão 2. */
|
|
2314
|
+
factor?: number;
|
|
2315
|
+
/** Teto da espera base, em milissegundos. Padrão 60000. */
|
|
2316
|
+
maxMs?: number;
|
|
2317
|
+
/** Fração de jitter: 0.25 espera ±25%. Padrão 0.25. */
|
|
2318
|
+
jitter?: number;
|
|
2319
|
+
}
|
|
2320
|
+
/** Calcula a espera para a tentativa `attempt` (0-based). */
|
|
2321
|
+
declare function backoffDelay(attempt: number, options?: BackoffOptions): number;
|
|
2322
|
+
declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
|
|
2323
|
+
|
|
2324
|
+
/** Divide argumentos de uma linha de comando, respeitando aspas. */
|
|
2325
|
+
declare function splitArguments(input: string): string[];
|
|
2326
|
+
|
|
2327
|
+
/**
|
|
2328
|
+
* Validação e manipulação de ids do Squord.
|
|
2329
|
+
*
|
|
2330
|
+
* Ids são strings opacas: Snowflakes decimais de até 20 dígitos, ou o formato
|
|
2331
|
+
* antigo de 24 caracteres hexadecimais. Nunca converta para `number`.
|
|
2332
|
+
*/
|
|
2333
|
+
/** Verifica se um valor parece um id válido do Squord. */
|
|
2334
|
+
declare function isValidSnowflake(id: string): boolean;
|
|
2335
|
+
/** Lança `SquordTypeError` se o id não tiver o formato de id do Squord. */
|
|
2336
|
+
declare function assertSnowflake(id: string, label?: string): string;
|
|
2337
|
+
/** Compara dois ids por ordem numérica (seguro com ids grandes, via BigInt). */
|
|
2338
|
+
declare function compareSnowflakes(a: string, b: string): number;
|
|
2339
|
+
|
|
2340
|
+
export { ALL_PERMISSIONS, APIBot, APIChannel, APIChannelOverwrite, APIChannelTreeNode, APICommand, APICommandInput, APICommandOptionInput, APIComponentRow, APIEmbed, APIEmbedInput, APIForumPostCreateBody, APIGuild, APIInteraction, APIInteractionCallbackBody, APIInteractionCommandData, APIInteractionComponentData, APIInteractionReplyData, APIMember, APIMemberBan, APIMemberBanBody, APIMemberEditBody, APIMemberPage, APIMessage, APIMessageCreateBody, APIMessagePage, APIReaction, APIRole, APISelectMenu, APISelectOption, APIThread, APIThreadCreateBody, APIThreadListParams, APIThreadPage, APIUpload, APIUploadReservation, APIUser, ActionRowBuilder, AllowedMentions, ApplicationCommandsManager, AuthenticationError, BotManager, ButtonBuilder, ButtonStyle, Buttons, Cache, type CacheOptions, Channel, type ChannelTreeGroup, ChannelType, ChannelsManager, type ClientEvents, type ClientOpcode, type ClientOptions, CommandOptionType, CommandRegistry, type CommandRegistryOptions, type ComponentHandlerDefinition, ComponentLimits, CursorPaginationParams, DEFAULT_INTENTS, EmbedBuilder, EmbedLimits, Gateway, type GatewayCloseCode, GatewayCloseCodes, GatewayError, type GatewayEventName, type GatewayEvents, type GatewayOptions, type GatewayStatus, Guild, GuildsManager, type HttpMethod, ISODate, type IntentFlag, Intents, Interaction, InteractionsManager, InvalidTokenError, type LogLevel, type Logger, Member, type MemberListParams, MembersManager, Message, type MessagePayload, MessageType, MessagesManager, ModerationManager, NetworkError, NotFoundError, Page, type PageFetcher, PermissionBits, PermissionError, type PermissionFlag, Permissions, type PresenceStatus, RateLimitError, type ReadyEvent, type RequestOptions, RequestTimeoutError, RestClient, type RestClientOptions, type RestResponse, Role, RolesManager, SUGGESTED_MODERATION_PERMISSIONS, SUGGESTED_TEXT_BOT_PERMISSIONS, SelectMenuBuilder, type SendOptions, type ServerFrame, type ServerOpcode, type SlashCommandDefinition, Snowflake, SquordAPIError, SquordClient, SquordError, SquordTypeError, type TextCommandContext, type TextCommandDefinition, Thread, type UploadOptions, type UploadSource, UploadsManager, User, UsersManager, ValidationError, type WebSocketFactory, type WebSocketLike, assertSnowflake, attachWebSocket, backoffDelay, collectPagination, compareSnowflakes, createConsoleLogger, hasAnyPermission, hasPermissions, intentsValue, isValidSnowflake, listIntents, loggerFromEnv, makeAPIError, noopLogger, normalizeEmbedColor, paginate, parsePermissions, permissionsToString, redact, resolveChannelPermissions, resolveMessagePayload, routeKeyOf, sleep, splitArguments };
|