micup.ts 1.0.0 → 1.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 +93 -38
- package/README.tr.md +137 -0
- package/dist/bot/client.d.ts +79 -0
- package/dist/bot/client.js +299 -0
- package/dist/events/background.d.ts +7 -0
- package/dist/events/background.js +23 -0
- package/dist/events/catalog.d.ts +243 -0
- package/dist/events/catalog.js +1 -0
- package/dist/events/guild-tag.d.ts +9 -0
- package/dist/events/guild-tag.js +38 -0
- package/dist/events/mux.d.ts +20 -5
- package/dist/events/names.d.ts +1 -0
- package/dist/events/names.js +71 -0
- package/dist/events/safe.d.ts +9 -0
- package/dist/events/safe.js +27 -0
- package/dist/gateway/compression.d.ts +9 -0
- package/dist/gateway/compression.js +119 -0
- package/dist/gateway/connection.js +42 -17
- package/dist/gateway/protocol.d.ts +4 -1
- package/dist/gateway/protocol.js +9 -3
- package/dist/gateway/subscription.d.ts +10 -0
- package/dist/gateway/subscription.js +26 -0
- package/dist/index.d.ts +48 -4
- package/dist/index.js +19 -3
- package/dist/model/components.d.ts +82 -0
- package/dist/model/components.js +74 -0
- package/dist/model/constants.d.ts +330 -0
- package/dist/model/constants.js +330 -0
- package/dist/model/embed.d.ts +59 -0
- package/dist/model/embed.js +40 -0
- package/dist/model/entities.d.ts +125 -0
- package/dist/model/entities.js +12 -0
- package/dist/model/format.d.ts +32 -0
- package/dist/model/format.js +61 -0
- package/dist/model/guild.d.ts +114 -1
- package/dist/model/helpers.d.ts +88 -0
- package/dist/model/helpers.js +185 -0
- package/dist/model/interaction.d.ts +1 -1
- package/dist/model/locale.d.ts +15 -0
- package/dist/model/locale.js +55 -0
- package/dist/model/media.d.ts +23 -0
- package/dist/model/media.js +65 -0
- package/dist/model/permissions.d.ts +5 -0
- package/dist/model/permissions.js +31 -0
- package/dist/rest/attachments.d.ts +26 -0
- package/dist/rest/attachments.js +82 -0
- package/dist/rest/channels.d.ts +87 -3
- package/dist/rest/channels.js +181 -2
- package/dist/rest/commands.d.ts +1 -0
- package/dist/rest/commands.js +17 -0
- package/dist/rest/discovery.d.ts +35 -0
- package/dist/rest/discovery.js +33 -0
- package/dist/rest/errors.d.ts +38 -0
- package/dist/rest/errors.js +46 -0
- package/dist/rest/expressions.d.ts +65 -0
- package/dist/rest/expressions.js +89 -0
- package/dist/rest/guilds.d.ts +102 -1
- package/dist/rest/guilds.js +127 -0
- package/dist/rest/identity.d.ts +1 -0
- package/dist/rest/identity.js +15 -0
- package/dist/rest/interactions.d.ts +1 -1
- package/dist/rest/messages.d.ts +54 -30
- package/dist/rest/messages.js +32 -12
- package/dist/rest/rooms.d.ts +142 -0
- package/dist/rest/rooms.js +133 -0
- package/dist/rest/sounds.d.ts +44 -0
- package/dist/rest/sounds.js +89 -0
- package/dist/rest/transport.d.ts +8 -2
- package/dist/rest/transport.js +38 -5
- package/dist/rest/users.d.ts +65 -0
- package/dist/rest/users.js +63 -0
- package/dist/rest/webhooks.d.ts +56 -0
- package/dist/rest/webhooks.js +94 -0
- package/dist/session/inventory.d.ts +22 -0
- package/dist/session/inventory.js +159 -0
- package/dist/session/session.d.ts +21 -2
- package/dist/session/session.js +61 -4
- package/dist/session/voice.d.ts +1 -0
- package/dist/session/voice.js +25 -17
- package/dist/shard/manager.d.ts +38 -1
- package/dist/shard/manager.js +87 -0
- package/dist/state/cache.d.ts +6 -1
- package/dist/state/cache.js +45 -1
- package/docs/README.md +13 -0
- package/docs/commands-and-interactions.md +120 -0
- package/docs/errors-and-limits.md +79 -0
- package/docs/gateway-and-sharding.md +102 -0
- package/docs/getting-started.md +79 -0
- package/docs/migrating.md +44 -0
- package/docs/rest-reference.md +101 -0
- package/docs/voice.md +95 -0
- package/package.json +25 -7
- package/dist/rest/client.d.ts +0 -48
- package/dist/rest/client.js +0 -151
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
# Getting started
|
|
2
|
+
|
|
3
|
+
## Requirements
|
|
4
|
+
|
|
5
|
+
- Node.js 22 or later. Zstandard Gateway compression (`compress: true`) needs 22.15 or later.
|
|
6
|
+
- A Micup bot token. Create an application in the Micup developer area, enable its bot and copy the token.
|
|
7
|
+
- An ES module project: set `"type": "module"` in `package.json` or use `.mjs` files. TypeScript projects use `"module": "NodeNext"`.
|
|
8
|
+
|
|
9
|
+
Keep the token in an environment variable such as `MICUP_BOT_TOKEN`. Never commit it, and regenerate it if it leaks.
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm install micup.ts
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Connect
|
|
16
|
+
|
|
17
|
+
`MicupClient.connect()` discovers the API, checks that the token belongs to a bot and loads the bot identity.
|
|
18
|
+
|
|
19
|
+
```js
|
|
20
|
+
import { MicupClient } from 'micup.ts';
|
|
21
|
+
|
|
22
|
+
const client = await MicupClient.connect({ token: process.env.MICUP_BOT_TOKEN });
|
|
23
|
+
console.log(client.self.id, client.self.username);
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Options: `origin` (default `https://micup.gg`), `maxRestAttempts` (1 to 5, default 5) and `logger` (see [Errors and limits](errors-and-limits.md)).
|
|
27
|
+
|
|
28
|
+
`client.self` is the bot user. `await client.application()` reads the application once and caches it. `client.tokenId` reads the bot ID from the token without a request.
|
|
29
|
+
|
|
30
|
+
## Invite the bot
|
|
31
|
+
|
|
32
|
+
```js
|
|
33
|
+
import { Permission } from 'micup.ts';
|
|
34
|
+
|
|
35
|
+
const url = client.botInviteURL({
|
|
36
|
+
permissions: Permission.ViewChannel | Permission.SendMessages | Permission.EmbedLinks,
|
|
37
|
+
});
|
|
38
|
+
console.log(url);
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
Pass `guildId` to preselect a server. Permissions are `bigint` values; `permissionNames(bits)` lists their names.
|
|
42
|
+
|
|
43
|
+
## A first bot
|
|
44
|
+
|
|
45
|
+
```js
|
|
46
|
+
import { EventMux, MicupClient } from 'micup.ts';
|
|
47
|
+
|
|
48
|
+
const client = await MicupClient.connect({ token: process.env.MICUP_BOT_TOKEN });
|
|
49
|
+
const events = new EventMux();
|
|
50
|
+
|
|
51
|
+
events.on('MESSAGE_CREATE', async (message, event, signal) => {
|
|
52
|
+
if (message.author.bot || message.content !== '!ping') return;
|
|
53
|
+
await client.sendMessage(message.channel_id, 'pong', { replyTo: message.id, signal });
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
const stop = new AbortController();
|
|
57
|
+
process.once('SIGINT', () => stop.abort());
|
|
58
|
+
process.once('SIGTERM', () => stop.abort());
|
|
59
|
+
await client.newSession({ handler: events.handle }).run({ signal: stop.signal });
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Message events arrive for the servers the bot is in. Use [slash commands](commands-and-interactions.md) for anything users invoke on purpose.
|
|
63
|
+
|
|
64
|
+
## Suggested layout
|
|
65
|
+
|
|
66
|
+
```
|
|
67
|
+
src/
|
|
68
|
+
index.js connect, create the session, wire shutdown
|
|
69
|
+
commands/ one file per command: a definition and a handler
|
|
70
|
+
events/ event handlers registered on the EventMux
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
Register command definitions at startup with `client.commands.create()` or `client.commands.set()`, and route interactions with an `InteractionRouter`.
|
|
74
|
+
|
|
75
|
+
## Next steps
|
|
76
|
+
|
|
77
|
+
- [Commands and interactions](commands-and-interactions.md)
|
|
78
|
+
- [Gateway and sharding](gateway-and-sharding.md)
|
|
79
|
+
- [REST reference](rest-reference.md)
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# Migrating
|
|
2
|
+
|
|
3
|
+
micup.ts is lower level than discord.js-style libraries: you create the client, then build a session, an event mux and a router. In return you get resume, sharding, typed events, real components and every bot route of the service.
|
|
4
|
+
|
|
5
|
+
## From micup.js or micup.gg.js
|
|
6
|
+
|
|
7
|
+
| Task | micup.js / micup.gg.js | micup.ts |
|
|
8
|
+
| --- | --- | --- |
|
|
9
|
+
| Log in | `new Client(); await client.login(token)` | `await MicupClient.connect({ token })` |
|
|
10
|
+
| Listen | `client.on('messageCreate', ...)` | `events.on('MESSAGE_CREATE', ...)` on an `EventMux`, then `client.newSession({ handler: events.handle }).run()` |
|
|
11
|
+
| Reply | `message.reply('text')` | `client.sendMessage(message.channel_id, 'text', { replyTo: message.id })` |
|
|
12
|
+
| Send | `client.send(channelId, 'text')` | `client.sendMessage(channelId, 'text')` |
|
|
13
|
+
| Raw call | `client.rest('GET', '/users/@me')` | `client.request('GET', '/users/@me')` |
|
|
14
|
+
| Buttons and menus | emulated with reactions (micup.js) | real components: `actionRow(primaryButton(...))`, `selectRow(stringSelect(...))` |
|
|
15
|
+
| Slash commands | not available (micup.js) or `client.rest.createGlobalApplicationCommand` | `client.commands.create/set` and an `InteractionRouter` |
|
|
16
|
+
| Voice | `connection.play(url)` | `VoiceConnection.connect(session, guildId, channelId)` then `connection.play(url)` from `@micupts/voice` |
|
|
17
|
+
| Presence | `client.setPresence(...)` | `session.setStatus()` and `session.setCustomStatus()` |
|
|
18
|
+
| Shards | not available | `client.newShardManager()` |
|
|
19
|
+
|
|
20
|
+
Differences to expect:
|
|
21
|
+
|
|
22
|
+
- Entities are plain JSON objects with the field names of the API (`channel_id`, `author`), not class instances with methods.
|
|
23
|
+
- Methods that change state live on resources: `client.guilds.kick()`, `client.channels.pin()`, `client.webhooks.execute()`.
|
|
24
|
+
- Every call takes an `AbortSignal`, and failures throw `MicupAPIError`.
|
|
25
|
+
- micup.ts sends no telemetry.
|
|
26
|
+
- Node.js 22 or later and ES modules.
|
|
27
|
+
|
|
28
|
+
## From discord.js
|
|
29
|
+
|
|
30
|
+
The concepts match; the names are closer to the wire format.
|
|
31
|
+
|
|
32
|
+
| discord.js | micup.ts |
|
|
33
|
+
| --- | --- |
|
|
34
|
+
| `new Client({ intents })`, `client.login()` | `MicupClient.connect()`; Micup has no intents |
|
|
35
|
+
| `client.on('interactionCreate')` | `events.on('INTERACTION_CREATE')` and `InteractionRouter` |
|
|
36
|
+
| `interaction.reply()`, `deferReply()`, `editReply()`, `followUp()` | `client.interactions.respond()`, `defer()`, `editResponse()`, `followUp()` |
|
|
37
|
+
| `interaction.options.getString('x')` | `optionString(interaction.data, 'x')` |
|
|
38
|
+
| `ActionRowBuilder`, `ButtonBuilder` | `actionRow(primaryButton(id, label))` |
|
|
39
|
+
| `EmbedBuilder` | `EmbedBuilder` with `.title()`, `.description()`, `.field()`, `.build()` |
|
|
40
|
+
| `PermissionsBitField` | `Permission` (bigint masks), `permissionNames()`, `hasPermissions()` |
|
|
41
|
+
| `ShardingManager` | `client.newShardManager()` |
|
|
42
|
+
| `@discordjs/voice` | `@micupts/voice` (LiveKit) |
|
|
43
|
+
|
|
44
|
+
Micup does not have polls, auto moderation rules, scheduled events, stage channels or bulk bans.
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
# REST reference
|
|
2
|
+
|
|
3
|
+
`MicupClient` exposes one object for each resource. Every method returns a promise, validates IDs before sending (`TypeError` for a bad ID) and takes an optional `{ signal }`. Methods that change server state also take `{ reason }`, which becomes the audit log reason.
|
|
4
|
+
|
|
5
|
+
## Client
|
|
6
|
+
|
|
7
|
+
| Method | Purpose |
|
|
8
|
+
| --- | --- |
|
|
9
|
+
| `sendMessage(channelId, content, { replyTo })` | send text or a message with embeds, components, files, uploads and stickers |
|
|
10
|
+
| `getMessage`, `listMessages`, `iterateMessages` | read one message, a page, or every message |
|
|
11
|
+
| `editMessage`, `deleteMessage`, `bulkDeleteMessages` | change or remove messages (1 to 100 IDs for bulk) |
|
|
12
|
+
| `suppressEmbeds(channelId, messageId, suppress)` | hide or show embeds and keep the other flags |
|
|
13
|
+
| `forwardMessage`, `crosspostMessage`, `deleteAttachment` | forward, publish, remove an attachment |
|
|
14
|
+
| `searchMessages(search)` | search a server or channel |
|
|
15
|
+
| `triggerTyping`, `sendDM` | typing indicator, direct message |
|
|
16
|
+
| `newSession()`, `newShardManager()`, `recommendedShards()` | Gateway entry points |
|
|
17
|
+
| `botInviteURL()`, `getCurrentUser()`, `application()`, `applicationId()`, `request()` | invite link, identity, raw request |
|
|
18
|
+
|
|
19
|
+
## `client.guilds`
|
|
20
|
+
|
|
21
|
+
| Group | Methods |
|
|
22
|
+
| --- | --- |
|
|
23
|
+
| Server | `get`, `edit`, `channels`, `moveChannels`, `vanityUrl`, `editVanityUrl`, `transferOwnership`, `deleteOwnMessages`, `auditLog`, `iterateAuditLog` |
|
|
24
|
+
| Roles | `roles`, `role`, `createRole`, `editRole`, `deleteRole`, `moveRoles`, `moveHoistedRoles`, `resetHoistedRoles` |
|
|
25
|
+
| Members | `member`, `currentMember`, `members`, `iterateMembers`, `editMember`, `editCurrentMember`, `setNickname`, `addMemberRole`, `removeMemberRole`, `kick`, `timeout`, `clearTimeout`, `findMembers`, `searchMembers` |
|
|
26
|
+
| Bans | `bans`, `getBan`, `ban`, `unban` |
|
|
27
|
+
|
|
28
|
+
## `client.channels`
|
|
29
|
+
|
|
30
|
+
| Group | Methods |
|
|
31
|
+
| --- | --- |
|
|
32
|
+
| Channels | `get`, `create`, `edit`, `delete`, `setPermission`, `deletePermission`, `addRecipient`, `removeRecipient`, `follow`, `followerStats`, `crosspostSource`, `deleteOwnMessages` |
|
|
33
|
+
| Pins and reactions | `pin`, `unpin`, `pins`, `iteratePins`, `addReaction`, `removeReaction`, `deleteReaction`, `reactionUsers`, `iterateReactionUsers` |
|
|
34
|
+
| Threads | `startThread`, `activeThreads`, `archivedThreads`, `searchThreads`, `joinThread`, `leaveThread`, `archiveThread`, `lockThread`, `addThreadMember`, `removeThreadMember`, `threadMember`, `threadMembers`, `iterateThreadMembers` |
|
|
35
|
+
| Forums | `createForumPost`, `createForumTag`, `editForumTag`, `deleteForumTag`, `forumPostData` |
|
|
36
|
+
| Invites | `createInvite`, `invites`, `guildInvites`, `getInvite`, `deleteInvite` |
|
|
37
|
+
|
|
38
|
+
## Other resources
|
|
39
|
+
|
|
40
|
+
| Object | Methods |
|
|
41
|
+
| --- | --- |
|
|
42
|
+
| `client.users` | `get`, `profile`, `createDM`, `application`, `publicApplication`, `editCurrentUser` (username, avatar, banner), `guilds`, `iterateGuilds`, `leaveGuild` |
|
|
43
|
+
| `client.webhooks` | `channel`, `guild`, `create`, `get`, `edit`, `delete`, `execute`, `message`, `editMessage`, `deleteMessage` |
|
|
44
|
+
| `client.expressions` | `listEmojis`, `listStickers`, `emoji`, `sticker`, `createEmoji`, `createSticker`, `createEmojis`, `createStickers`, `cloneEmoji`, `cloneSticker`, `renameEmoji`, `editSticker`, `delete`, `metadata`, `source` |
|
|
45
|
+
| `client.attachments` | `upload` (direct multipart upload for large files), `refresh` (refresh expiring URLs) |
|
|
46
|
+
| `client.commands` | `list`, `get`, `create`, `edit`, `delete`, `clear`, `set` |
|
|
47
|
+
| `client.interactions` | `respond`, `defer`, `deferUpdate`, `update`, `autocomplete`, `modal`, `editResponse`, `getResponse`, `deleteResponse`, `followUp` |
|
|
48
|
+
| `client.sounds` | `list`, `create`, `edit`, `delete`, `play`, `setGuildNotification`, `clearGuildNotification`, `setChannelNotification`, `clearChannelNotification` |
|
|
49
|
+
| `client.rooms` | `stage`, `setStage`, `clearStage`, `stageEffect`, `tournament`, `openTournament`, `reorderTournament`, `startTournament`, `cancelTournament` |
|
|
50
|
+
| `client.discovery` | `status`, `apply`, `edit`, `withdraw` |
|
|
51
|
+
| `client.media` | builds CDN URLs for avatars, banners, icons, emoji and stickers |
|
|
52
|
+
|
|
53
|
+
## Patterns
|
|
54
|
+
|
|
55
|
+
Paginate with the `iterate*` generators; they follow the cursor rules of each route:
|
|
56
|
+
|
|
57
|
+
```js
|
|
58
|
+
import { AuditAction } from 'micup.ts';
|
|
59
|
+
|
|
60
|
+
for await (const member of client.guilds.iterateMembers(guildId)) console.log(member.user?.username);
|
|
61
|
+
for await (const entry of client.guilds.iterateAuditLog(guildId, { actionType: AuditAction.MemberBanAdd })) console.log(entry.id);
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
Send a message with an embed and an upload:
|
|
65
|
+
|
|
66
|
+
```js
|
|
67
|
+
import { EmbedBuilder } from 'micup.ts';
|
|
68
|
+
|
|
69
|
+
const upload = await client.attachments.upload(channelId, { name: 'report.txt', data: new Blob(['hello']), description: 'Report' });
|
|
70
|
+
await client.sendMessage(channelId, {
|
|
71
|
+
content: 'Report ready',
|
|
72
|
+
embeds: [new EmbedBuilder().title('Report').description('Done').color(0x5865f2).field('Rows', '42', true).build()],
|
|
73
|
+
uploads: [upload],
|
|
74
|
+
});
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
Clear a nullable field by passing `null` (for example `setNickname(guildId, null)` or `edit(channelId, { topic: null })`); leave a field out to keep it.
|
|
78
|
+
|
|
79
|
+
Call a route the SDK has no method for with `client.request(method, path, { body, query, reason, signal })`. Paths are relative to the versioned API.
|
|
80
|
+
|
|
81
|
+
## Sound and rooms
|
|
82
|
+
|
|
83
|
+
Upload a soundboard sound as bytes or base64 (MP3 or Ogg, up to 512000 bytes and 5.2 seconds), then play it while the bot is in the voice channel:
|
|
84
|
+
|
|
85
|
+
```js
|
|
86
|
+
import { readFile } from 'node:fs/promises';
|
|
87
|
+
|
|
88
|
+
const sound = await client.sounds.create(guildId, { name: 'airhorn', audio: await readFile('airhorn.mp3'), volume: 0.8 });
|
|
89
|
+
await client.sounds.play(channelId, sound.id, { sessionId: session.sessionId, connectionId: grant.connection_id });
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Run the room stage of a voice channel (the service must have room stages switched on, and the bot needs `ManageRoomStage`):
|
|
93
|
+
|
|
94
|
+
```js
|
|
95
|
+
await client.rooms.setStage(channelId, {
|
|
96
|
+
tv: { type: 'board', title: 'Scores', scores: [{ name: 'Ada', value: 12 }] },
|
|
97
|
+
host: { character: 'ithp-gunluk' },
|
|
98
|
+
ttl_seconds: 600,
|
|
99
|
+
});
|
|
100
|
+
await client.rooms.stageEffect(channelId, { type: 'confetti' });
|
|
101
|
+
```
|
package/docs/voice.md
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
# Voice
|
|
2
|
+
|
|
3
|
+
Micup carries voice over LiveKit. micup.ts joins a voice channel through the Gateway and gives you a short-lived grant; the optional [`@micupts/voice`](../packages/voice) package connects to LiveKit with that grant and publishes audio.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npm install @micupts/voice
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
Install FFmpeg to decode files, URLs and streams. You can skip it if you only play raw PCM. The package supports unencrypted rooms; a grant with `e2ee_key` or `p2p` is refused.
|
|
10
|
+
|
|
11
|
+
## Play audio
|
|
12
|
+
|
|
13
|
+
`VoiceConnection` joins, connects, owns a player and leaves when it closes.
|
|
14
|
+
|
|
15
|
+
```js
|
|
16
|
+
import { VoiceConnection } from '@micupts/voice';
|
|
17
|
+
|
|
18
|
+
const session = client.newSession({
|
|
19
|
+
handler: events.handle,
|
|
20
|
+
onVoiceGrant: (grant) => connections.get(grant.guild_id)?.regrant(grant),
|
|
21
|
+
});
|
|
22
|
+
void session.run({ signal: stop.signal });
|
|
23
|
+
|
|
24
|
+
const connection = await VoiceConnection.connect(session, guildId, channelId, { selfDeaf: true, volume: 0.8 });
|
|
25
|
+
connections.set(guildId, connection);
|
|
26
|
+
connection.on('finish', ({ stopped }) => console.log(stopped ? 'stopped' : 'ended'));
|
|
27
|
+
await connection.play('./song.mp3');
|
|
28
|
+
await connection.disconnect();
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Wait for the session to be ready before you connect. The bot needs `Connect` and `Speak` in the channel.
|
|
32
|
+
|
|
33
|
+
### Play options
|
|
34
|
+
|
|
35
|
+
`play(input, options)` takes a file path, an `http(s)` URL or a `Readable`.
|
|
36
|
+
|
|
37
|
+
| Option | Meaning |
|
|
38
|
+
| --- | --- |
|
|
39
|
+
| `volume` | 0 to 2 for this track |
|
|
40
|
+
| `seek` | start position in seconds |
|
|
41
|
+
| `ffmpegArgs` | extra FFmpeg arguments inserted before the output, for example `['-af', 'bass=g=5']`; treat them as trusted input |
|
|
42
|
+
| `ffmpeg` | path of the FFmpeg binary; `FFMPEG_PATH` and `PATH` are used otherwise |
|
|
43
|
+
| `raw` | the input is 48 kHz stereo signed 16-bit PCM, from a stream or an async iterable, and FFmpeg is not used |
|
|
44
|
+
| `signal` | abort the track |
|
|
45
|
+
|
|
46
|
+
URLs reconnect automatically after a dropped connection. A new `play()` replaces the current track.
|
|
47
|
+
|
|
48
|
+
### Controls and events
|
|
49
|
+
|
|
50
|
+
`stop()`, `pause()`, `resume()` and `setVolume(0..2)` act on the current track. `playing`, `paused`, `volume`, `status`, `memberCount`, `guildId`, `channelId` and `connectionId` report state.
|
|
51
|
+
|
|
52
|
+
| Event | When |
|
|
53
|
+
| --- | --- |
|
|
54
|
+
| `start` | a track starts |
|
|
55
|
+
| `finish` | a track ends; `{ stopped: true }` when it was stopped or replaced |
|
|
56
|
+
| `status` | `connecting`, `ready`, `reconnecting` or `disconnected` |
|
|
57
|
+
| `memberJoin`, `memberLeave` | another participant joins or leaves the room |
|
|
58
|
+
| `disconnect` | the connection closed; the second argument is the reason |
|
|
59
|
+
| `error` | a source failed; the promise of `play()` rejects as well |
|
|
60
|
+
|
|
61
|
+
If the LiveKit room drops, the connection leaves the channel and emits `disconnect`. Use it to reconnect or to leave empty channels.
|
|
62
|
+
|
|
63
|
+
## Move between channels
|
|
64
|
+
|
|
65
|
+
When the bot is moved, the Gateway sends a new grant. Pass it to `regrant()`; it stops the current track, closes the old room and connects to the new one, and the volume stays.
|
|
66
|
+
|
|
67
|
+
```js
|
|
68
|
+
const session = client.newSession({
|
|
69
|
+
handler: events.handle,
|
|
70
|
+
onVoiceGrant: (grant) => connections.get(grant.guild_id)?.regrant(grant),
|
|
71
|
+
onVoiceLost: (guildId, connectionId) => connections.delete(guildId),
|
|
72
|
+
onVoiceEmpty: (guildId, channelId) => connections.get(guildId)?.disconnect(),
|
|
73
|
+
});
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
`onVoiceEmpty` fires when the last other member leaves the bot's channel.
|
|
77
|
+
|
|
78
|
+
## Lower level
|
|
79
|
+
|
|
80
|
+
`VoiceRoom.connect(grant)` connects without the player; it emits `memberJoin`, `memberLeave` and `disconnected` and gives `openTrack()` for several independent tracks. `Player` plays any PCM source on a track, with `pause()`, `resume()`, `skip()` and `setVolume()`. `openSource(input, options)` decodes with FFmpeg. See the [package README](../packages/voice/README.md).
|
|
81
|
+
|
|
82
|
+
## Soundboard
|
|
83
|
+
|
|
84
|
+
Guild soundboard sounds play in the voice channel the bot is in. Upload and play with `client.sounds`:
|
|
85
|
+
|
|
86
|
+
```js
|
|
87
|
+
const sound = await client.sounds.create(guildId, { name: 'airhorn', audio: await readFile('airhorn.mp3') });
|
|
88
|
+
await client.sounds.play(channelId, sound.id, { sessionId: session.sessionId, connectionId: connection.connectionId });
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Sounds are MP3 or Ogg, at most 512000 bytes and 5.2 seconds. The `GUILD_SOUNDBOARD_SOUNDS_UPDATE` and `GUILD_SOUNDBOARD_SOUND_PLAY` events report changes and playback. Guild and channel notification sounds are set with `setGuildNotification()` and `setChannelNotification()`.
|
|
92
|
+
|
|
93
|
+
## Voice rooms
|
|
94
|
+
|
|
95
|
+
`client.rooms` runs the 3D room of a voice channel: `setStage()` shows a board or a YouTube video on the room TV and a host character, `stageEffect()` sends confetti, a spotlight or a host emote, and `openTournament()`, `reorderTournament()`, `startTournament()` and `cancelTournament()` run a 1v1 tournament. The bot needs `ManageRoomStage` and the service must have the feature on; otherwise requests answer `403 FEATURE_TEMPORARILY_DISABLED`.
|
package/package.json
CHANGED
|
@@ -1,18 +1,20 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "micup.ts",
|
|
3
|
-
"version": "1.
|
|
4
|
-
"description": "TypeScript SDK for Micup bots
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "The TypeScript SDK for Micup bots: Gateway sessions and shards, REST, slash commands, buttons, modals, soundboard and voice",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
7
7
|
"types": "./dist/index.d.ts",
|
|
8
8
|
"default": "./dist/index.js"
|
|
9
9
|
},
|
|
10
10
|
"files": [
|
|
11
|
-
"dist"
|
|
11
|
+
"dist",
|
|
12
|
+
"docs",
|
|
13
|
+
"README.tr.md"
|
|
12
14
|
],
|
|
13
15
|
"scripts": {
|
|
14
16
|
"build": "tsc",
|
|
15
|
-
"test": "npm run build && node --test \"test/*.test.js\" && npm run test --workspaces",
|
|
17
|
+
"test": "npm run build && node --test \"test/*.test.js\" && npm run test --workspaces && tsc -p test/tsconfig.json",
|
|
16
18
|
"prepack": "npm run build"
|
|
17
19
|
},
|
|
18
20
|
"engines": {
|
|
@@ -21,8 +23,23 @@
|
|
|
21
23
|
"license": "MIT",
|
|
22
24
|
"keywords": [
|
|
23
25
|
"micup",
|
|
24
|
-
"
|
|
25
|
-
"
|
|
26
|
+
"micup-bot",
|
|
27
|
+
"micup-api",
|
|
28
|
+
"bot",
|
|
29
|
+
"sdk",
|
|
30
|
+
"typescript",
|
|
31
|
+
"gateway",
|
|
32
|
+
"websocket",
|
|
33
|
+
"rest",
|
|
34
|
+
"slash-commands",
|
|
35
|
+
"interactions",
|
|
36
|
+
"components",
|
|
37
|
+
"buttons",
|
|
38
|
+
"modals",
|
|
39
|
+
"sharding",
|
|
40
|
+
"voice",
|
|
41
|
+
"livekit",
|
|
42
|
+
"soundboard"
|
|
26
43
|
],
|
|
27
44
|
"repository": {
|
|
28
45
|
"type": "git",
|
|
@@ -37,5 +54,6 @@
|
|
|
37
54
|
},
|
|
38
55
|
"workspaces": [
|
|
39
56
|
"packages/voice"
|
|
40
|
-
]
|
|
57
|
+
],
|
|
58
|
+
"homepage": "https://github.com/yestefir/micup.ts#readme"
|
|
41
59
|
}
|
package/dist/rest/client.d.ts
DELETED
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
import { GatewaySession, type GatewaySessionConfig, type GatewaySessionOptions } from '../session/session.js';
|
|
2
|
-
import { ShardManager, type ShardManagerOptions } from '../shard/manager.js';
|
|
3
|
-
import { type MicupRequestOptions, type RestMethod, type RestRequestOptions } from './transport.js';
|
|
4
|
-
import { type ListMessageOptions, type MessageInput } from './messages.js';
|
|
5
|
-
import { MicupCommands } from './commands.js';
|
|
6
|
-
import { MicupInteractions } from './interactions.js';
|
|
7
|
-
import { MicupGuilds } from './guilds.js';
|
|
8
|
-
import { MicupChannels } from './channels.js';
|
|
9
|
-
export interface MicupClientOptions {
|
|
10
|
-
token: string;
|
|
11
|
-
origin?: string;
|
|
12
|
-
maxRestAttempts?: number;
|
|
13
|
-
}
|
|
14
|
-
export interface MicupUser {
|
|
15
|
-
id: string;
|
|
16
|
-
username: string;
|
|
17
|
-
bot?: boolean;
|
|
18
|
-
}
|
|
19
|
-
export interface MicupMessage {
|
|
20
|
-
id: string;
|
|
21
|
-
channel_id: string;
|
|
22
|
-
content: string;
|
|
23
|
-
author: MicupUser;
|
|
24
|
-
}
|
|
25
|
-
export declare class MicupClient {
|
|
26
|
-
#private;
|
|
27
|
-
readonly interactions: MicupInteractions;
|
|
28
|
-
readonly guilds: MicupGuilds;
|
|
29
|
-
readonly channels: MicupChannels;
|
|
30
|
-
private constructor();
|
|
31
|
-
static connect({ token, origin, maxRestAttempts }: MicupClientOptions, { signal }?: MicupRequestOptions): Promise<MicupClient>;
|
|
32
|
-
get commands(): MicupCommands;
|
|
33
|
-
newSession(options: GatewaySessionOptions, shard?: Pick<GatewaySessionConfig, 'shardId' | 'shardCount'>): GatewaySession;
|
|
34
|
-
newShardManager(options: ShardManagerOptions): ShardManager;
|
|
35
|
-
getCurrentUser({ signal }?: MicupRequestOptions): Promise<MicupUser>;
|
|
36
|
-
sendMessage(channelId: string, content: string | MessageInput, { replyTo, signal }?: MicupRequestOptions & {
|
|
37
|
-
replyTo?: string;
|
|
38
|
-
}): Promise<MicupMessage>;
|
|
39
|
-
getMessage(channelId: string, messageId: string, options?: MicupRequestOptions): Promise<MicupMessage>;
|
|
40
|
-
listMessages(channelId: string, options?: ListMessageOptions): Promise<MicupMessage[]>;
|
|
41
|
-
iterateMessages(channelId: string, options?: Omit<ListMessageOptions, 'around' | 'limit'>): AsyncGenerator<MicupMessage>;
|
|
42
|
-
editMessage(channelId: string, messageId: string, edit: MessageInput, options?: MicupRequestOptions): Promise<MicupMessage>;
|
|
43
|
-
deleteMessage(channelId: string, messageId: string, options?: MicupRequestOptions & {
|
|
44
|
-
reason?: string;
|
|
45
|
-
}): Promise<void>;
|
|
46
|
-
triggerTyping(channelId: string, options?: MicupRequestOptions): Promise<void>;
|
|
47
|
-
request<T = unknown>(method: RestMethod, path: string, options?: RestRequestOptions): Promise<T>;
|
|
48
|
-
}
|
package/dist/rest/client.js
DELETED
|
@@ -1,151 +0,0 @@
|
|
|
1
|
-
import { GatewaySession } from '../session/session.js';
|
|
2
|
-
import { ShardManager } from '../shard/manager.js';
|
|
3
|
-
import { MicupAPIError } from './errors.js';
|
|
4
|
-
import { RestTransport } from './transport.js';
|
|
5
|
-
import { messageBody, messageQuery, messagesPath, snowflake } from './messages.js';
|
|
6
|
-
import { MicupCommands } from './commands.js';
|
|
7
|
-
import { MicupInteractions } from './interactions.js';
|
|
8
|
-
import { MicupGuilds } from './guilds.js';
|
|
9
|
-
import { MicupChannels } from './channels.js';
|
|
10
|
-
const defaultOrigin = 'https://micup.gg';
|
|
11
|
-
const connection = Symbol('Micup connection');
|
|
12
|
-
export class MicupClient {
|
|
13
|
-
#token;
|
|
14
|
-
#rest;
|
|
15
|
-
#gateway;
|
|
16
|
-
#botId;
|
|
17
|
-
#commands;
|
|
18
|
-
interactions;
|
|
19
|
-
guilds;
|
|
20
|
-
channels;
|
|
21
|
-
constructor(key, token, api, gateway, maxAttempts) {
|
|
22
|
-
if (key !== connection) {
|
|
23
|
-
throw new TypeError('Use MicupClient.connect() to create a client');
|
|
24
|
-
}
|
|
25
|
-
this.#token = token;
|
|
26
|
-
this.#rest = new RestTransport(api, token, maxAttempts);
|
|
27
|
-
this.interactions = new MicupInteractions(this.#rest);
|
|
28
|
-
this.guilds = new MicupGuilds(this.#rest);
|
|
29
|
-
this.channels = new MicupChannels(this.#rest);
|
|
30
|
-
this.#gateway = gateway;
|
|
31
|
-
}
|
|
32
|
-
static async connect({ token, origin = defaultOrigin, maxRestAttempts }, { signal } = {}) {
|
|
33
|
-
if (typeof token !== 'string' || !/^[\x21-\x7E]+$/.test(token)) {
|
|
34
|
-
throw new TypeError('A valid Micup bot token is required');
|
|
35
|
-
}
|
|
36
|
-
const url = new URL(origin);
|
|
37
|
-
if (url.protocol !== 'https:' || url.username || url.password ||
|
|
38
|
-
url.pathname !== '/' || url.search || url.hash) {
|
|
39
|
-
throw new TypeError('Micup origin must be an HTTPS origin');
|
|
40
|
-
}
|
|
41
|
-
const response = await fetch(new URL('/.well-known/fluxer', url), {
|
|
42
|
-
redirect: 'error',
|
|
43
|
-
signal,
|
|
44
|
-
});
|
|
45
|
-
if (!response.ok) {
|
|
46
|
-
await response.body?.cancel();
|
|
47
|
-
throw new MicupAPIError(response);
|
|
48
|
-
}
|
|
49
|
-
const discovery = await response.json();
|
|
50
|
-
const endpoint = discovery?.endpoints?.api_public;
|
|
51
|
-
if (typeof endpoint !== 'string') {
|
|
52
|
-
throw new Error('Micup discovery returned no API endpoint');
|
|
53
|
-
}
|
|
54
|
-
const api = new URL(endpoint);
|
|
55
|
-
if (api.origin !== url.origin || api.username || api.password || api.search || api.hash) {
|
|
56
|
-
throw new Error('Micup discovery returned an invalid API endpoint');
|
|
57
|
-
}
|
|
58
|
-
const gateway = discovery.endpoints?.gateway;
|
|
59
|
-
if (gateway !== undefined) {
|
|
60
|
-
if (typeof gateway !== 'string')
|
|
61
|
-
throw new Error('Micup discovery returned an invalid Gateway endpoint');
|
|
62
|
-
const endpoint = new URL(gateway);
|
|
63
|
-
if (endpoint.protocol !== 'wss:' || endpoint.host !== url.host || endpoint.username ||
|
|
64
|
-
endpoint.password || endpoint.hash) {
|
|
65
|
-
throw new Error('Micup discovery returned an invalid Gateway endpoint');
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
const client = new MicupClient(connection, token, `${api.href.replace(/\/+$/, '')}/v1`, gateway, maxRestAttempts);
|
|
69
|
-
const user = await client.getCurrentUser({ signal });
|
|
70
|
-
if (user?.bot !== true) {
|
|
71
|
-
throw new Error('The credential must belong to a Micup bot');
|
|
72
|
-
}
|
|
73
|
-
client.#botId = user.id;
|
|
74
|
-
return client;
|
|
75
|
-
}
|
|
76
|
-
get commands() {
|
|
77
|
-
if (!this.#botId)
|
|
78
|
-
throw new Error('Micup did not return the bot ID');
|
|
79
|
-
return this.#commands ??= new MicupCommands(this.#rest, this.#botId);
|
|
80
|
-
}
|
|
81
|
-
newSession(options, shard = {}) {
|
|
82
|
-
if (!this.#gateway)
|
|
83
|
-
throw new Error('Micup discovery returned no Gateway endpoint');
|
|
84
|
-
return new GatewaySession({ ...shard, endpoint: this.#gateway, token: this.#token, botId: this.#botId }, options);
|
|
85
|
-
}
|
|
86
|
-
newShardManager(options) {
|
|
87
|
-
if (!this.#gateway)
|
|
88
|
-
throw new Error('Micup discovery returned no Gateway endpoint');
|
|
89
|
-
return new ShardManager({ endpoint: this.#gateway, token: this.#token, botId: this.#botId }, options);
|
|
90
|
-
}
|
|
91
|
-
getCurrentUser({ signal } = {}) {
|
|
92
|
-
return this.request('GET', '/users/@me', { signal });
|
|
93
|
-
}
|
|
94
|
-
sendMessage(channelId, content, { replyTo, signal } = {}) {
|
|
95
|
-
const path = messagesPath(channelId);
|
|
96
|
-
const input = typeof content === 'string' ? { content } : content;
|
|
97
|
-
if (!input?.content?.trim() && !input?.embeds?.length && !input?.components?.length &&
|
|
98
|
-
!input?.files?.length && !input?.attachments?.length) {
|
|
99
|
-
throw new TypeError('Message content, embeds, components or attachments are required');
|
|
100
|
-
}
|
|
101
|
-
const reply = replyTo === undefined ? undefined : { message_id: snowflake(replyTo, 'Reply message ID'), channel_id: channelId };
|
|
102
|
-
return this.request('POST', path, { body: messageBody(input, reply), signal });
|
|
103
|
-
}
|
|
104
|
-
getMessage(channelId, messageId, options) {
|
|
105
|
-
return this.request('GET', messagesPath(channelId, messageId), options);
|
|
106
|
-
}
|
|
107
|
-
listMessages(channelId, options = {}) {
|
|
108
|
-
return this.request('GET', messagesPath(channelId), { query: messageQuery(options), signal: options.signal });
|
|
109
|
-
}
|
|
110
|
-
async *iterateMessages(channelId, options = {}) {
|
|
111
|
-
if (options.before !== undefined && options.after !== undefined)
|
|
112
|
-
throw new TypeError('Only one message cursor can be used');
|
|
113
|
-
let cursor = options.after ?? options.before;
|
|
114
|
-
const forward = options.after !== undefined;
|
|
115
|
-
while (true) {
|
|
116
|
-
const page = await this.listMessages(channelId, {
|
|
117
|
-
...(forward ? { after: cursor } : { before: cursor }), limit: 100, signal: options.signal,
|
|
118
|
-
});
|
|
119
|
-
if (!page.length)
|
|
120
|
-
return;
|
|
121
|
-
page.sort((a, b) => {
|
|
122
|
-
const x = BigInt(a.id);
|
|
123
|
-
const y = BigInt(b.id);
|
|
124
|
-
if (x === y)
|
|
125
|
-
return 0;
|
|
126
|
-
return (x < y) === forward ? -1 : 1;
|
|
127
|
-
});
|
|
128
|
-
for (const message of page) {
|
|
129
|
-
if (cursor === undefined || (forward ? BigInt(message.id) > BigInt(cursor) : BigInt(message.id) < BigInt(cursor))) {
|
|
130
|
-
yield message;
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
const next = page.at(-1).id;
|
|
134
|
-
if (page.length < 100 || next === cursor || (cursor !== undefined && (forward ? BigInt(next) <= BigInt(cursor) : BigInt(next) >= BigInt(cursor))))
|
|
135
|
-
return;
|
|
136
|
-
cursor = next;
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
editMessage(channelId, messageId, edit, options) {
|
|
140
|
-
return this.request('PATCH', messagesPath(channelId, messageId), { ...options, body: messageBody(edit) });
|
|
141
|
-
}
|
|
142
|
-
deleteMessage(channelId, messageId, options) {
|
|
143
|
-
return this.request('DELETE', messagesPath(channelId, messageId), options);
|
|
144
|
-
}
|
|
145
|
-
triggerTyping(channelId, options) {
|
|
146
|
-
return this.request('POST', '/channels/' + snowflake(channelId, 'Channel ID') + '/typing', options);
|
|
147
|
-
}
|
|
148
|
-
request(method, path, options) {
|
|
149
|
-
return this.#rest.request(method, path, options);
|
|
150
|
-
}
|
|
151
|
-
}
|