micup.ts 1.0.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/README.md +93 -38
  2. package/README.tr.md +137 -0
  3. package/dist/bot/client.d.ts +79 -0
  4. package/dist/bot/client.js +299 -0
  5. package/dist/events/background.d.ts +7 -0
  6. package/dist/events/background.js +23 -0
  7. package/dist/events/catalog.d.ts +243 -0
  8. package/dist/events/catalog.js +1 -0
  9. package/dist/events/guild-tag.d.ts +9 -0
  10. package/dist/events/guild-tag.js +38 -0
  11. package/dist/events/mux.d.ts +20 -5
  12. package/dist/events/names.d.ts +1 -0
  13. package/dist/events/names.js +71 -0
  14. package/dist/events/safe.d.ts +9 -0
  15. package/dist/events/safe.js +27 -0
  16. package/dist/gateway/compression.d.ts +9 -0
  17. package/dist/gateway/compression.js +119 -0
  18. package/dist/gateway/connection.js +42 -17
  19. package/dist/gateway/protocol.d.ts +4 -1
  20. package/dist/gateway/protocol.js +9 -3
  21. package/dist/gateway/subscription.d.ts +10 -0
  22. package/dist/gateway/subscription.js +26 -0
  23. package/dist/index.d.ts +48 -4
  24. package/dist/index.js +19 -3
  25. package/dist/model/components.d.ts +82 -0
  26. package/dist/model/components.js +74 -0
  27. package/dist/model/constants.d.ts +330 -0
  28. package/dist/model/constants.js +330 -0
  29. package/dist/model/embed.d.ts +59 -0
  30. package/dist/model/embed.js +40 -0
  31. package/dist/model/entities.d.ts +125 -0
  32. package/dist/model/entities.js +12 -0
  33. package/dist/model/format.d.ts +32 -0
  34. package/dist/model/format.js +61 -0
  35. package/dist/model/guild.d.ts +114 -1
  36. package/dist/model/helpers.d.ts +88 -0
  37. package/dist/model/helpers.js +185 -0
  38. package/dist/model/interaction.d.ts +1 -1
  39. package/dist/model/locale.d.ts +15 -0
  40. package/dist/model/locale.js +55 -0
  41. package/dist/model/media.d.ts +23 -0
  42. package/dist/model/media.js +65 -0
  43. package/dist/model/permissions.d.ts +5 -0
  44. package/dist/model/permissions.js +31 -0
  45. package/dist/rest/attachments.d.ts +26 -0
  46. package/dist/rest/attachments.js +82 -0
  47. package/dist/rest/channels.d.ts +87 -3
  48. package/dist/rest/channels.js +181 -2
  49. package/dist/rest/commands.d.ts +1 -0
  50. package/dist/rest/commands.js +17 -0
  51. package/dist/rest/discovery.d.ts +35 -0
  52. package/dist/rest/discovery.js +33 -0
  53. package/dist/rest/errors.d.ts +38 -0
  54. package/dist/rest/errors.js +46 -0
  55. package/dist/rest/expressions.d.ts +65 -0
  56. package/dist/rest/expressions.js +89 -0
  57. package/dist/rest/guilds.d.ts +102 -1
  58. package/dist/rest/guilds.js +127 -0
  59. package/dist/rest/identity.d.ts +1 -0
  60. package/dist/rest/identity.js +15 -0
  61. package/dist/rest/interactions.d.ts +1 -1
  62. package/dist/rest/messages.d.ts +54 -30
  63. package/dist/rest/messages.js +32 -12
  64. package/dist/rest/rooms.d.ts +142 -0
  65. package/dist/rest/rooms.js +133 -0
  66. package/dist/rest/sounds.d.ts +44 -0
  67. package/dist/rest/sounds.js +89 -0
  68. package/dist/rest/transport.d.ts +8 -2
  69. package/dist/rest/transport.js +38 -5
  70. package/dist/rest/users.d.ts +65 -0
  71. package/dist/rest/users.js +63 -0
  72. package/dist/rest/webhooks.d.ts +56 -0
  73. package/dist/rest/webhooks.js +94 -0
  74. package/dist/session/inventory.d.ts +22 -0
  75. package/dist/session/inventory.js +159 -0
  76. package/dist/session/session.d.ts +21 -2
  77. package/dist/session/session.js +61 -4
  78. package/dist/session/voice.d.ts +1 -0
  79. package/dist/session/voice.js +25 -17
  80. package/dist/shard/manager.d.ts +38 -1
  81. package/dist/shard/manager.js +87 -0
  82. package/dist/state/cache.d.ts +6 -1
  83. package/dist/state/cache.js +45 -1
  84. package/docs/README.md +13 -0
  85. package/docs/commands-and-interactions.md +120 -0
  86. package/docs/errors-and-limits.md +79 -0
  87. package/docs/gateway-and-sharding.md +102 -0
  88. package/docs/getting-started.md +79 -0
  89. package/docs/migrating.md +44 -0
  90. package/docs/rest-reference.md +101 -0
  91. package/docs/voice.md +95 -0
  92. package/package.json +25 -7
  93. package/dist/rest/client.d.ts +0 -48
  94. package/dist/rest/client.js +0 -151
@@ -35,14 +35,12 @@ export class SessionVoice {
35
35
  const signal = parent ? AbortSignal.any([parent, timeout]) : timeout;
36
36
  signal.throwIfAborted();
37
37
  let join;
38
- const pending = new Promise((resolve, reject) => {
39
- join = { channelId, resolve, reject };
40
- });
41
- const abort = () => join.reject(signal.reason);
38
+ const pending = new Promise((wake) => { join = { channelId, wake }; });
39
+ const abort = () => this.#fail(join, signal.reason);
42
40
  this.#joins.set(guildId, join);
43
41
  signal.addEventListener('abort', abort, { once: true });
44
42
  try {
45
- const [, grant] = await Promise.all([
43
+ await Promise.all([
46
44
  this.send(GatewayOpcode.VoiceStateUpdate, {
47
45
  guild_id: guildId, channel_id: channelId,
48
46
  self_mute: options.selfMute ?? false, self_deaf: options.selfDeaf ?? false,
@@ -51,10 +49,12 @@ export class SessionVoice {
51
49
  pending,
52
50
  ]);
53
51
  signal.throwIfAborted();
54
- if (this.#joins.get(guildId) !== join)
52
+ if (join.error)
53
+ throw join.error;
54
+ if (this.#joins.get(guildId) !== join || !join.grant)
55
55
  throw new Error('Micup voice join was invalidated');
56
- this.#grants.set(guildId, grant);
57
- return { ...grant };
56
+ this.#grants.set(guildId, join.grant);
57
+ return { ...join.grant };
58
58
  }
59
59
  finally {
60
60
  signal.removeEventListener('abort', abort);
@@ -96,11 +96,12 @@ export class SessionVoice {
96
96
  const code = data?.code;
97
97
  if (!code || !refusalCodes.has(code))
98
98
  return;
99
- const oldest = this.#joins.entries().next();
100
- if (oldest.done)
99
+ for (const [guildId, pending] of this.#joins) {
100
+ if (pending.error || pending.grant)
101
+ continue;
102
+ this.#fail(pending, new VoiceRefusedError(guildId, code));
101
103
  return;
102
- const [guildId, pending] = oldest.value;
103
- pending.reject(new VoiceRefusedError(guildId, code));
104
+ }
104
105
  }
105
106
  invalidate() {
106
107
  const joins = [...this.#joins.values()];
@@ -108,7 +109,7 @@ export class SessionVoice {
108
109
  this.#joins.clear();
109
110
  this.#grants.clear();
110
111
  for (const join of joins)
111
- join.reject(new Error('Micup Gateway voice session ended'));
112
+ this.#fail(join, new Error('Micup Gateway voice session ended'));
112
113
  for (const grant of grants)
113
114
  this.options.onVoiceLost?.(grant.guild_id, grant.connection_id);
114
115
  }
@@ -127,7 +128,8 @@ export class SessionVoice {
127
128
  const previous = this.#grants.get(guildId);
128
129
  const channel = packet.channel_id || join?.channelId || previous?.channel_id;
129
130
  if (!packet.endpoint || !packet.token || !packet.connection_id || !channel) {
130
- join?.reject(new Error('Micup returned an incomplete voice grant'));
131
+ if (join)
132
+ this.#fail(join, new Error('Micup returned an incomplete voice grant'));
131
133
  if (previous)
132
134
  this.#lose(previous);
133
135
  return;
@@ -143,9 +145,11 @@ export class SessionVoice {
143
145
  };
144
146
  if (join) {
145
147
  if (join.channelId !== channel)
146
- join.reject(new Error('Micup granted a different voice channel'));
147
- else
148
- join.resolve(grant);
148
+ this.#fail(join, new Error('Micup granted a different voice channel'));
149
+ else if (!join.error) {
150
+ join.grant = grant;
151
+ join.wake();
152
+ }
149
153
  return;
150
154
  }
151
155
  if (!previous)
@@ -161,6 +165,10 @@ export class SessionVoice {
161
165
  this.#lose(previous);
162
166
  }
163
167
  }
168
+ #fail(join, error) {
169
+ join.error ??= error;
170
+ join.wake();
171
+ }
164
172
  #lose(grant) {
165
173
  this.#grants.delete(grant.guild_id);
166
174
  this.options.onVoiceLost?.(grant.guild_id, grant.connection_id);
@@ -1,4 +1,9 @@
1
1
  import { GatewaySession, type GatewaySessionConfig, type GatewaySessionOptions } from '../session/session.js';
2
+ import type { CustomStatus, Presence, PresenceStatus } from '../model/presence.js';
3
+ import type { MicupMember } from '../model/guild.js';
4
+ import type { ChannelMemberCount, GuildCount, GuildMembersRequest } from '../session/requests.js';
5
+ import type { VoiceJoinOptions, VoiceServerUpdate } from '../session/voice.js';
6
+ import { type GatewaySubscription } from '../gateway/subscription.js';
2
7
  export interface ShardManagerOptions {
3
8
  readonly shardCount: number;
4
9
  readonly shardIds?: readonly number[];
@@ -9,11 +14,43 @@ export declare function shardForGuild(guildId: string, shardCount: number): numb
9
14
  export declare class ShardManager {
10
15
  #private;
11
16
  readonly shardCount: number;
12
- constructor(config: Pick<GatewaySessionConfig, 'endpoint' | 'token' | 'botId'>, options: ShardManagerOptions);
17
+ constructor(config: Pick<GatewaySessionConfig, 'endpoint' | 'token' | 'botId' | 'lookupChannel' | 'lookupMembers'>, options: ShardManagerOptions);
13
18
  get ready(): boolean;
14
19
  get shards(): GatewaySession[];
15
20
  shard(id: number): GatewaySession | undefined;
16
21
  forGuild(guildId: string): GatewaySession;
22
+ memberInventories(): import('../session/inventory.js').GuildMemberInventory[];
23
+ get guildCount(): number;
24
+ get latency(): number | undefined;
25
+ get presence(): Presence;
26
+ updatePresence(presence: Presence, options?: {
27
+ signal?: AbortSignal;
28
+ }): Promise<void>;
29
+ setStatus(status: PresenceStatus, options?: {
30
+ signal?: AbortSignal;
31
+ }): Promise<void>;
32
+ setCustomStatus(status: CustomStatus | null, options?: {
33
+ signal?: AbortSignal;
34
+ }): Promise<void>;
35
+ resolveGuild(channelId: string, options?: {
36
+ signal?: AbortSignal;
37
+ }): Promise<string | undefined>;
38
+ joinVoice(guildId: string, channelId: string, options?: VoiceJoinOptions): Promise<VoiceServerUpdate>;
39
+ leaveVoice(guildId: string, connectionId: string, options?: {
40
+ signal?: AbortSignal;
41
+ }): Promise<void>;
42
+ voice(guildId: string): VoiceServerUpdate | undefined;
43
+ updateVoiceState(guildId: string, options: VoiceJoinOptions): Promise<void>;
44
+ requestGuildMembers(guildId: string, options?: GuildMembersRequest): Promise<MicupMember[]>;
45
+ requestChannelMemberCounts(guildId: string, channelIds: readonly string[], options?: {
46
+ signal?: AbortSignal;
47
+ }): Promise<ChannelMemberCount[]>;
48
+ requestGuildCounts(guildIds: readonly string[], options?: {
49
+ signal?: AbortSignal;
50
+ }): Promise<GuildCount[]>;
51
+ subscribe(subscriptions: Readonly<Record<string, GatewaySubscription>>, options?: {
52
+ signal?: AbortSignal;
53
+ }): Promise<void>;
17
54
  run({ signal }?: {
18
55
  signal?: AbortSignal;
19
56
  }): Promise<void>;
@@ -1,5 +1,6 @@
1
1
  import { setTimeout as delay } from 'node:timers/promises';
2
2
  import { GatewaySession } from '../session/session.js';
3
+ import { validateSubscriptions } from '../gateway/subscription.js';
3
4
  const maxSnowflake = (1n << 64n) - 1n;
4
5
  export function shardForGuild(guildId, shardCount) {
5
6
  if (!Number.isSafeInteger(shardCount) || shardCount < 1)
@@ -15,6 +16,7 @@ export function shardForGuild(guildId, shardCount) {
15
16
  export class ShardManager {
16
17
  #sessions = new Map();
17
18
  shardCount;
19
+ #lookup;
18
20
  #running = false;
19
21
  constructor(config, options) {
20
22
  const { shardCount, identifyIntervalMs = 5000 } = options;
@@ -27,6 +29,7 @@ export class ShardManager {
27
29
  if (new Set(ids).size !== ids.length)
28
30
  throw new RangeError('Shard IDs must be unique');
29
31
  this.shardCount = shardCount;
32
+ this.#lookup = config.lookupChannel;
30
33
  let nextIdentify = 0;
31
34
  const beforeIdentify = async (signal) => {
32
35
  await options.session.beforeIdentify?.(signal);
@@ -62,6 +65,90 @@ export class ShardManager {
62
65
  throw new Error('This shard manager does not own the guild');
63
66
  return shard;
64
67
  }
68
+ memberInventories() {
69
+ return this.shards.flatMap((shard) => shard.memberInventories()).sort((a, b) => a.guildId.localeCompare(b.guildId));
70
+ }
71
+ get guildCount() {
72
+ return this.shards.reduce((count, shard) => count + shard.state.guildCount, 0);
73
+ }
74
+ get latency() {
75
+ const measured = this.shards.flatMap((shard) => shard.latency === undefined ? [] : [shard.latency]);
76
+ return measured.length ? measured.reduce((sum, latency) => sum + latency, 0) / measured.length : undefined;
77
+ }
78
+ get presence() {
79
+ return this.shards[0].presence;
80
+ }
81
+ async updatePresence(presence, options) {
82
+ await Promise.all(this.shards.map((shard) => shard.updatePresence(presence, options)));
83
+ }
84
+ async setStatus(status, options) {
85
+ await Promise.all(this.shards.map((shard) => shard.setStatus(status, options)));
86
+ }
87
+ async setCustomStatus(status, options) {
88
+ await Promise.all(this.shards.map((shard) => shard.setCustomStatus(status, options)));
89
+ }
90
+ async resolveGuild(channelId, options) {
91
+ for (const shard of this.shards) {
92
+ const guildId = shard.state.guildForChannel(channelId);
93
+ if (guildId)
94
+ return guildId;
95
+ }
96
+ if (!this.#lookup)
97
+ throw new Error('No channel lookup is configured');
98
+ const channel = await this.#lookup(channelId, options);
99
+ if (channel.id !== channelId)
100
+ throw new Error('Micup returned a different channel');
101
+ if (channel.guild_id)
102
+ this.shard(shardForGuild(channel.guild_id, this.shardCount))?.state.rememberChannel(channel);
103
+ return channel.guild_id;
104
+ }
105
+ joinVoice(guildId, channelId, options) {
106
+ return this.forGuild(guildId).joinVoice(guildId, channelId, options);
107
+ }
108
+ leaveVoice(guildId, connectionId, options) {
109
+ return this.forGuild(guildId).leaveVoice(guildId, connectionId, options);
110
+ }
111
+ voice(guildId) {
112
+ return this.forGuild(guildId).voice(guildId);
113
+ }
114
+ updateVoiceState(guildId, options) {
115
+ return this.forGuild(guildId).updateVoiceState(guildId, options);
116
+ }
117
+ requestGuildMembers(guildId, options) {
118
+ return this.forGuild(guildId).requestGuildMembers(guildId, options);
119
+ }
120
+ requestChannelMemberCounts(guildId, channelIds, options) {
121
+ return this.forGuild(guildId).requestChannelMemberCounts(guildId, channelIds, options);
122
+ }
123
+ async requestGuildCounts(guildIds, options) {
124
+ if (!guildIds.length)
125
+ throw new TypeError('At least one guild ID is required');
126
+ const groups = this.#groupGuilds([...new Set(guildIds)]);
127
+ const work = [];
128
+ for (const [shard, ids] of groups) {
129
+ for (let index = 0; index < ids.length; index += 100) {
130
+ work.push(shard.requestGuildCounts(ids.slice(index, index + 100), options));
131
+ }
132
+ }
133
+ return (await Promise.all(work)).flat();
134
+ }
135
+ async subscribe(subscriptions, options) {
136
+ validateSubscriptions(subscriptions);
137
+ const groups = this.#groupGuilds(Object.keys(subscriptions));
138
+ await Promise.all([...groups].map(([shard, ids]) => shard.subscribe(Object.fromEntries(ids.map((id) => [id, subscriptions[id]])), options)));
139
+ }
140
+ #groupGuilds(guildIds) {
141
+ const groups = new Map();
142
+ for (const guildId of guildIds) {
143
+ const shard = this.forGuild(guildId);
144
+ const ids = groups.get(shard);
145
+ if (ids)
146
+ ids.push(guildId);
147
+ else
148
+ groups.set(shard, [guildId]);
149
+ }
150
+ return groups;
151
+ }
65
152
  async run({ signal } = {}) {
66
153
  if (this.#running)
67
154
  throw new Error('Micup shard manager is already running');
@@ -1,15 +1,20 @@
1
1
  import type { GatewayDispatch } from '../gateway/protocol.js';
2
- import type { MicupChannel, MicupGuild, MicupMember } from '../model/guild.js';
2
+ import type { MicupChannel, MicupGuild, MicupMember, MicupRole } from '../model/guild.js';
3
3
  export declare class GatewayState {
4
4
  #private;
5
5
  get guildCount(): number;
6
6
  clear(): void;
7
7
  guild(id: string): MicupGuild | undefined;
8
8
  channel(id: string): MicupChannel | undefined;
9
+ rememberChannel(channel: MicupChannel): void;
9
10
  guildForChannel(channelId: string): string | undefined;
10
11
  member(guildId: string, userId: string): MicupMember | undefined;
11
12
  voiceChannel(guildId: string, userId: string): string | undefined;
12
13
  voiceMembers(guildId: string, channelId: string): string[];
14
+ channels(guildId: string): MicupChannel[];
15
+ threads(guildId: string): MicupChannel[];
16
+ highestRole(guildId: string, userId: string): MicupRole | undefined;
17
+ canManage(guildId: string, actorId: string, targetId: string): boolean;
13
18
  permissions(guildId: string, userId: string, channelId?: string): bigint | undefined;
14
19
  apply(event: GatewayDispatch): void;
15
20
  }
@@ -20,6 +20,9 @@ export class GatewayState {
20
20
  channel(id) {
21
21
  return structuredClone(this.#channels.get(id));
22
22
  }
23
+ rememberChannel(channel) {
24
+ this.#storeChannel(channel);
25
+ }
23
26
  guildForChannel(channelId) {
24
27
  return this.#channels.get(channelId)?.guild_id;
25
28
  }
@@ -33,6 +36,37 @@ export class GatewayState {
33
36
  const voices = this.#guilds.get(guildId)?.voices.values() ?? [];
34
37
  return [...voices].filter((voice) => voice.channel_id === channelId).map((voice) => voice.user_id).sort();
35
38
  }
39
+ channels(guildId) {
40
+ return [...this.#channels.values()].filter((channel) => channel.guild_id === guildId).map((channel) => structuredClone(channel));
41
+ }
42
+ threads(guildId) {
43
+ return this.channels(guildId).filter((channel) => isThread(channel.type));
44
+ }
45
+ highestRole(guildId, userId) {
46
+ const guild = this.#guilds.get(guildId);
47
+ if (!guild || guild.info.unavailable)
48
+ return undefined;
49
+ let highest = guild.roles.get(guildId);
50
+ for (const id of guild.members.get(userId)?.roles ?? []) {
51
+ const role = guild.roles.get(id);
52
+ if (role && (!highest || role.position > highest.position))
53
+ highest = role;
54
+ }
55
+ return structuredClone(highest);
56
+ }
57
+ canManage(guildId, actorId, targetId) {
58
+ const guild = this.#guilds.get(guildId);
59
+ if (!guild || guild.info.unavailable)
60
+ return false;
61
+ const owner = guild.info.owner_id;
62
+ if (owner && owner === actorId)
63
+ return true;
64
+ if (targetId === owner)
65
+ return false;
66
+ const actor = this.highestRole(guildId, actorId);
67
+ const target = this.highestRole(guildId, targetId);
68
+ return Boolean(actor && target && actor.position > target.position);
69
+ }
36
70
  permissions(guildId, userId, channelId) {
37
71
  const guild = this.#guilds.get(guildId);
38
72
  if (!guild || guild.info.unavailable || !guild.roles.has(guildId))
@@ -145,7 +179,17 @@ export class GatewayState {
145
179
  case 'THREAD_UPDATE':
146
180
  this.#storeChannel(data);
147
181
  break;
148
- case 'CHANNEL_DELETE':
182
+ case 'CHANNEL_DELETE': {
183
+ const id = data.id;
184
+ if (!id)
185
+ return;
186
+ this.#channels.delete(id);
187
+ for (const [child, channel] of this.#channels) {
188
+ if (channel.parent_id === id && isThread(channel.type))
189
+ this.#channels.delete(child);
190
+ }
191
+ break;
192
+ }
149
193
  case 'THREAD_DELETE':
150
194
  this.#channels.delete(data.id);
151
195
  break;
package/docs/README.md ADDED
@@ -0,0 +1,13 @@
1
+ # micup.ts documentation
2
+
3
+ | Guide | Read it when you want to |
4
+ | --- | --- |
5
+ | [Getting started](getting-started.md) | install the SDK, get a token, invite the bot and run a first bot |
6
+ | [Commands and interactions](commands-and-interactions.md) | register slash commands and answer commands, buttons, select menus and modals |
7
+ | [Gateway and sharding](gateway-and-sharding.md) | keep a bot connected, handle events, read cached state and run several shards |
8
+ | [REST reference](rest-reference.md) | find the method for a guild, channel, member, message, webhook or other resource |
9
+ | [Voice](voice.md) | play audio, move between channels, use the soundboard and voice rooms |
10
+ | [Errors and limits](errors-and-limits.md) | handle failures, rate limits and cancellation, and log permission problems |
11
+ | [Migrating](migrating.md) | move a bot from micup.js, micup.gg.js or discord.js |
12
+
13
+ The package README has a [feature overview](../README.md#what-is-inside). Every method takes an optional `AbortSignal`. Examples are ES modules for Node.js 22 or later.
@@ -0,0 +1,120 @@
1
+ # Commands and interactions
2
+
3
+ ## Register commands
4
+
5
+ `client.commands` manages the bot's commands. Pass `{ guildId }` for a server scope and omit it for global commands.
6
+
7
+ | Method | What it does |
8
+ | --- | --- |
9
+ | `list(scope)`, `get(id, scope)` | read commands |
10
+ | `create(definition, scope)` | add one command |
11
+ | `edit(id, changes, scope)` | change one command |
12
+ | `delete(id, scope)` | remove one command |
13
+ | `set(definitions, scope)` | replace the whole set of that scope |
14
+ | `clear(scope)` | remove every command of that scope |
15
+
16
+ `set()` and `clear()` replace or empty the scope, so they also remove commands another process registered. Use `create()` when you only add one.
17
+
18
+ ```js
19
+ import { CommandOptionType, CommandType } from 'micup.ts';
20
+
21
+ await client.commands.create({
22
+ name: 'tool',
23
+ description: 'Small tools',
24
+ type: CommandType.ChatInput,
25
+ options: [
26
+ { type: CommandOptionType.Subcommand, name: 'echo', description: 'Repeat text',
27
+ options: [{ type: CommandOptionType.String, name: 'text', description: 'What to repeat', required: true }] },
28
+ { type: CommandOptionType.Subcommand, name: 'pick', description: 'Pick a fruit',
29
+ options: [{ type: CommandOptionType.String, name: 'fruit', description: 'Fruit', required: true, autocomplete: true }] },
30
+ ],
31
+ }, { guildId });
32
+ ```
33
+
34
+ Definitions are validated before they are sent (name and option limits, choices, localizations). Context menu commands use `CommandType.User` and `CommandType.Message`. Micup accepts name and description translations but shows the default text in every language; use a `MessageCatalog` to translate replies.
35
+
36
+ ## Route interactions
37
+
38
+ ```js
39
+ import { EventMux, InteractionRouter } from 'micup.ts';
40
+
41
+ const router = new InteractionRouter()
42
+ .command('tool echo', (interaction, signal) => { /* ... */ })
43
+ .autocomplete('tool pick', (interaction, signal) => { /* ... */ })
44
+ .component('confirm', (interaction, signal) => { /* ... */ })
45
+ .modal('feedback', (interaction, signal) => { /* ... */ });
46
+
47
+ const events = new EventMux();
48
+ events.on('INTERACTION_CREATE', (interaction, event, signal) => router.handle(interaction, signal));
49
+ ```
50
+
51
+ Command and autocomplete routes use the command path: the name, then the subcommand group and subcommand separated by spaces. Component and modal routes use the `custom_id`. `router.handle()` resolves to `false` when no route matches.
52
+
53
+ ## Read the input
54
+
55
+ ```js
56
+ import { focusedOption, modalValue, optionInteger, optionMember, optionString, selectedUsers, targetUser } from 'micup.ts';
57
+
58
+ optionString(interaction.data, 'text'); // string | undefined
59
+ optionInteger(interaction.data, 'count');
60
+ optionMember(interaction.data, 'who'); // resolved member with its user
61
+ focusedOption(interaction.data); // the option being typed in autocomplete
62
+ targetUser(interaction.data); // user context menu target
63
+ modalValue(interaction.data, 'subject'); // text input of a modal submit
64
+ selectedUsers(interaction.data); // resolved users of a user select
65
+ ```
66
+
67
+ Related helpers: `optionNumber`, `optionBoolean`, `optionUser`, `optionRole`, `optionChannel`, `optionAttachment`, `commandOption`, `leafOptions`, `targetMessage`, `selectedMembers`, `selectedRoles`, `selectedChannels`, `isButtonInteraction`, `isSelectInteraction`, `interactionCustomId` and `interactionInvoker`.
68
+
69
+ ## Answer
70
+
71
+ `client.interactions` answers an interaction. Each call takes the interaction and an optional `{ signal }`.
72
+
73
+ | Method | Use |
74
+ | --- | --- |
75
+ | `respond(interaction, message, { ephemeral })` | answer with a message; `ephemeral: true` shows it only to the invoker |
76
+ | `defer(interaction, { ephemeral })` | acknowledge now and answer later |
77
+ | `editResponse(interaction, message)` | edit the first answer or fill a deferred one |
78
+ | `followUp(interaction, message, { ephemeral })` | send another message; use it for file uploads |
79
+ | `update(interaction, message)` | replace the message that carried the clicked component |
80
+ | `deferUpdate(interaction)` | acknowledge a component click without changing the message |
81
+ | `modal(interaction, modal)` | open a modal from a command or component |
82
+ | `autocomplete(interaction, choices)` | answer an autocomplete request with up to 25 choices |
83
+ | `getResponse`, `deleteResponse` | read or delete the first answer |
84
+
85
+ Answer within three seconds, or defer first; a later first answer fails with `INTERACTION_EXPIRED`. Autocomplete requests cannot be deferred. Interaction replies cannot carry files; attach them in a follow-up after acknowledging.
86
+
87
+ ## Components
88
+
89
+ ```js
90
+ import { actionRow, dangerButton, linkButton, primaryButton, selectOption, selectRow, stringSelect, disableButtons } from 'micup.ts';
91
+
92
+ const components = [
93
+ actionRow(primaryButton('confirm', 'Confirm'), dangerButton('cancel', 'Cancel'), linkButton('https://micup.gg', 'Site')),
94
+ selectRow(stringSelect('color', selectOption('Red', 'red'), selectOption('Blue', 'blue'))),
95
+ ];
96
+ await client.interactions.respond(interaction, { content: 'Choose', components }, { signal });
97
+ ```
98
+
99
+ Builders: `primaryButton`, `secondaryButton`, `successButton`, `dangerButton`, `linkButton`, `stringSelect`, `userSelect`, `roleSelect`, `mentionableSelect`, `channelSelect`, `selectOption`, `shortInput`, `paragraphInput`. `disableButtons(rows)` disables buttons and keeps links and selects. A row holds up to five buttons or one select menu.
100
+
101
+ ## Modals
102
+
103
+ ```js
104
+ import { modalRows, shortInput, paragraphInput } from 'micup.ts';
105
+
106
+ await client.interactions.modal(interaction, {
107
+ title: 'Feedback',
108
+ custom_id: 'feedback',
109
+ components: modalRows(shortInput('subject', 'Subject'), paragraphInput('body', 'Details')),
110
+ }, { signal });
111
+ ```
112
+
113
+ A modal takes one to five text inputs. The submit arrives as an interaction routed by the modal `custom_id`.
114
+
115
+ ## Good to know
116
+
117
+ - People click buttons and use commands; a bot cannot click a component.
118
+ - After a reconnect the Gateway can replay an interaction. A second answer fails with `INTERACTION_TOKEN_CONSUMED`; wrap handlers with `safeHandler()` or catch that code.
119
+ - `Components V2` layouts and thread routes depend on the service switches and can answer `403` or `404`.
120
+ - Interaction files live for the interaction (15 minutes). Download them if you need them longer.
@@ -0,0 +1,79 @@
1
+ # Errors and limits
2
+
3
+ ## API errors
4
+
5
+ Failed HTTP requests throw `MicupAPIError`.
6
+
7
+ ```js
8
+ import { MicupAPIError, MicupErrorCode } from 'micup.ts';
9
+
10
+ try {
11
+ await client.guilds.kick(guildId, userId, { reason: 'spam' });
12
+ } catch (error) {
13
+ if (!(error instanceof MicupAPIError)) throw error;
14
+ if (error.code === MicupErrorCode.MissingPermissions) return explainPermissions();
15
+ if (error.notFound) return;
16
+ if (error.rateLimited) console.warn('retry in', error.retryAfterMs, 'ms');
17
+ if (error.hasFieldCode('USER_IS_NOT_BANNED')) return;
18
+ throw error;
19
+ }
20
+ ```
21
+
22
+ | Property | Meaning |
23
+ | --- | --- |
24
+ | `status` | HTTP status |
25
+ | `code` | Micup error code, for example `MISSING_PERMISSIONS` |
26
+ | `errors` | field errors: `{ path, code, message }` |
27
+ | `retryAfter`, `retryAfterMs` | wait before retrying, from the response |
28
+ | `global` | the rate limit is global |
29
+ | `requestId` | the `x-request-id` header, for support requests |
30
+ | `notFound`, `forbidden`, `rateLimited` | status checks |
31
+ | `hasFieldCode(code)` | a field error carries this code |
32
+
33
+ `MicupErrorCode` names the codes the SDK knows, including `NEW_DM_RATE_LIMITED` (the bot messaged too many new people) and `SPAM_BLOCKED`. A request can also fail with `FEATURE_TEMPORARILY_DISABLED` when the service has a feature switched off.
34
+
35
+ Other errors: `GatewayCloseError` (the Gateway closed; `fatal` says whether the SDK stops), `GatewayRequestError` (a member or count request failed), `VoiceRefusedError` (the channel is full or a voice option is unavailable) and plain `TypeError` or `RangeError` when an argument is invalid. The SDK checks arguments before it sends a request.
36
+
37
+ ## Rate limits and retries
38
+
39
+ The SDK waits for rate-limit windows and retries on its own:
40
+
41
+ - `429` waits for `Retry-After` and tries again; waits longer than 30 seconds fail instead.
42
+ - `423` retries after at least one second.
43
+ - `5xx` and network errors retry with exponential backoff for requests that are safe to repeat (`GET`, `PUT`, `DELETE`, and `POST` calls marked idempotent).
44
+ - `maxRestAttempts` (1 to 5, default 5) limits the tries.
45
+
46
+ Repeated rejected requests can get an address blocked, so do not loop on a failing call: a deleted webhook, a revoked token or a missing permission.
47
+
48
+ ## Cancellation
49
+
50
+ Pass `{ signal }` to any method. `AbortSignal.timeout(ms)` gives a deadline. Gateway handlers receive a signal that aborts when the connection or session is replaced; pass it on to your requests.
51
+
52
+ ## Permission warnings
53
+
54
+ ```js
55
+ const client = await MicupClient.connect({
56
+ token: process.env.MICUP_BOT_TOKEN,
57
+ logger: { warn: (message, fields) => console.warn(message, fields) },
58
+ });
59
+ ```
60
+
61
+ The logger receives `bot lacks permission for this request` with the method, path, code and server ID, at most once a minute for each route. It is off unless you pass a logger.
62
+
63
+ ## Handler safety
64
+
65
+ ```js
66
+ import { safeHandler } from 'micup.ts';
67
+
68
+ events.on('MESSAGE_CREATE', safeHandler(handle, {
69
+ timeoutMs: 10_000,
70
+ onError: (error, event) => console.error(event.name, error),
71
+ retry: (error) => error instanceof MicupAPIError && error.status >= 500,
72
+ }));
73
+ ```
74
+
75
+ `safeHandler()` logs failures instead of crashing or forcing a reconnect, stops slow work after `timeoutMs` and rethrows only the errors `retry` selects, so the event is delivered again. `background(task, { timeoutMs, name, onError })` runs slow work outside the handler and never rejects.
76
+
77
+ ## Limits
78
+
79
+ `Limits` holds the documented sizes, for example `Limits.EmbedTitle` (256), `Limits.EmbedFields` (25), `Limits.Embeds` (10), `Limits.BulkDelete` (100), `Limits.SelectOptions` (25) and `Limits.CommandChoices` (25). The SDK validates embeds, components, commands and attachments against them before sending.
@@ -0,0 +1,102 @@
1
+ # Gateway and sharding
2
+
3
+ ## Sessions
4
+
5
+ `client.newSession(options)` returns a `GatewaySession`. `session.run({ signal })` keeps it connected until the signal aborts: it reconnects with backoff, resumes from the last processed sequence and starts a new session when the old one is invalid. `session.runOnce({ signal })` connects once and returns when the connection ends, for applications that manage reconnects.
6
+
7
+ ```js
8
+ const session = client.newSession({
9
+ handler: events.handle,
10
+ compress: true,
11
+ trackMembers: true,
12
+ presence: { status: 'online', custom_status: { text: 'Merhaba' } },
13
+ onReady: (resumed) => console.log(resumed ? 'resumed' : 'ready'),
14
+ onDisconnect: (error) => console.warn('disconnected', error),
15
+ });
16
+ await session.run({ signal: stop.signal });
17
+ ```
18
+
19
+ | Option | Meaning |
20
+ | --- | --- |
21
+ | `handler` | required; called with every dispatch and an `AbortSignal` that aborts when the connection or session is replaced |
22
+ | `ignoredEvents` | event names the session does not need |
23
+ | `compress` | continuous Zstandard stream; needs Node.js 22.15 or later |
24
+ | `trackMembers` | maintain paginated member inventories, read through `session.memberInventories()` |
25
+ | `presence` | initial presence |
26
+ | `minBackoffMs`, `maxBackoffMs` | reconnect delay bounds (1 s and 15 s by default) |
27
+ | `flags` | Gateway feature flags (`GatewayFlag`) |
28
+ | `onReady`, `onDisconnect`, `onGatewayError`, `beforeIdentify` | lifecycle hooks |
29
+ | `onVoiceLost`, `onVoiceEmpty`, `onVoiceGrant` | voice hooks, see [Voice](voice.md) |
30
+
31
+ A handler that throws is retried with the same event, so keep side effects safe to repeat. Wrap handlers with `safeHandler()` to log failures, time out slow work or replay only selected errors.
32
+
33
+ ## Events
34
+
35
+ `EventMux` routes dispatches by name with typed payloads.
36
+
37
+ ```js
38
+ import { EventMux, safeHandler } from 'micup.ts';
39
+
40
+ const events = new EventMux();
41
+ const off = events.on('MESSAGE_CREATE', (message, event, signal) => { /* ... */ });
42
+ events.on('GUILD_MEMBER_ADD', safeHandler((event, signal) => { /* ... */ }, { timeoutMs: 5_000, onError: console.error }));
43
+ ```
44
+
45
+ `knownGatewayEvents` lists every typed event: messages, reactions, guilds, members, roles, channels, threads, invites, webhooks, bans, audit log entries, presence, typing, voice states, calls, soundboard changes and playback, and more. Unknown names can be registered and carry an `unknown` payload. Use `onGuildTagChange()` to follow guild tag changes.
46
+
47
+ Do slow work such as searches outside the handler so the next event is not delayed:
48
+
49
+ ```js
50
+ import { background } from 'micup.ts';
51
+ void background((signal) => search(signal), { timeoutMs: 30_000, name: 'search' });
52
+ ```
53
+
54
+ ## Presence
55
+
56
+ ```js
57
+ await session.setStatus('idle');
58
+ await session.setCustomStatus({ text: 'Merhaba' });
59
+ await session.setCustomStatus(null);
60
+ ```
61
+
62
+ Statuses are `online`, `idle`, `dnd` and `invisible`. Micup has no activities, only a custom status text.
63
+
64
+ ## Requests over the Gateway
65
+
66
+ ```js
67
+ const members = await session.requestGuildMembers(guildId, { query: 'ad', limit: 10 });
68
+ const counts = await session.requestGuildCounts([guildId]);
69
+ const online = await session.requestChannelMemberCounts(guildId, [channelId]);
70
+ await session.subscribe({ [guildId]: { active: true, typing: true, threads: true } });
71
+ ```
72
+
73
+ `subscribe()` takes subscriptions keyed by server ID (`active`, `sync`, `typing`, `members`, `threads`, `member_list_channels`, `thread_member_lists`). Member and count requests carry a nonce and reject with `GatewayRequestError` on rate limits or timeouts.
74
+
75
+ ## State cache
76
+
77
+ Each session keeps `session.state` (a `GatewayState`) up to date from the stream.
78
+
79
+ ```js
80
+ const guild = session.state.guild(guildId);
81
+ const channel = session.state.channel(channelId);
82
+ const permissions = session.state.permissions(guildId, userId, channelId);
83
+ const canManage = session.state.canManage(guildId, actorId, targetId);
84
+ const inVoice = session.state.voiceMembers(guildId, channelId);
85
+ const botChannel = session.state.voiceChannel(guildId, client.self.id);
86
+ ```
87
+
88
+ Also available: `member`, `channels`, `threads`, `highestRole` and `guildForChannel`. Permission helpers `computePermissions`, `hasPermissions`, `missingPermissions`, `permissionNames` and `parsePermission` work on plain `bigint` masks.
89
+
90
+ ## Sharding
91
+
92
+ Micup recommends one shard for each 1,000 servers. `await client.recommendedShards()` counts the servers and asks the service.
93
+
94
+ ```js
95
+ const manager = client.newShardManager({
96
+ shardCount: await client.recommendedShards(),
97
+ session: { handler: events.handle, compress: true },
98
+ });
99
+ await manager.run({ signal: stop.signal });
100
+ ```
101
+
102
+ The manager spaces IDENTIFY commands (`identifyIntervalMs`), runs `shardIds` when you split shards across processes, and exposes `shard(id)`, `forGuild(guildId)`, `shards`, `guildCount`, `latency`, `ready`, presence setters and the voice and request helpers of a session. `shardForGuild(guildId, shardCount)` returns the shard that owns a server; a server's events arrive only on its own shard.