@theowlops/channelhub 1.0.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/LICENSE +21 -0
- package/README.md +179 -0
- package/bin/cli.ts +36 -0
- package/dist/bridges/mcp/index.d.ts +14 -0
- package/dist/bridges/mcp/index.js +96 -0
- package/dist/bridges/webhook/index.d.ts +32 -0
- package/dist/bridges/webhook/index.js +123 -0
- package/dist/channels/discord/adapter.d.ts +24 -0
- package/dist/channels/discord/index.d.ts +1 -0
- package/dist/channels/discord/index.js +130 -0
- package/dist/channels/slack/adapter.d.ts +20 -0
- package/dist/channels/slack/index.d.ts +1 -0
- package/dist/channels/slack/index.js +122 -0
- package/dist/channels/telegram/adapter.d.ts +21 -0
- package/dist/channels/telegram/index.d.ts +2 -0
- package/dist/channels/telegram/index.js +179 -0
- package/dist/channels/telegram/types.d.ts +6 -0
- package/dist/channels/zalo/adapter.d.ts +22 -0
- package/dist/channels/zalo/index.d.ts +5 -0
- package/dist/channels/zalo/index.js +38337 -0
- package/dist/commands/modules/general.d.ts +4 -0
- package/dist/commands/modules/group.d.ts +4 -0
- package/dist/commands/modules/reaction.d.ts +4 -0
- package/dist/commands/router.d.ts +7 -0
- package/dist/commands/types.d.ts +15 -0
- package/dist/config/env.d.ts +13 -0
- package/dist/core/adapter.d.ts +12 -0
- package/dist/core/bus.d.ts +12 -0
- package/dist/core/context.d.ts +9 -0
- package/dist/core/hub.d.ts +14 -0
- package/dist/core/index.d.ts +5 -0
- package/dist/core/index.js +99 -0
- package/dist/core/types.d.ts +63 -0
- package/dist/index.cjs +39235 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +39191 -0
- package/dist/login_personal.js +60 -0
- package/dist/oa/client.d.ts +25 -0
- package/dist/oa/index.d.ts +3 -0
- package/dist/oa/index.js +556 -0
- package/dist/personal/client.d.ts +162 -0
- package/dist/personal/index.d.ts +5 -0
- package/dist/personal/index.js +37098 -0
- package/package.json +107 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 TheOwlOps
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
<div align="center">
|
|
2
|
+
|
|
3
|
+
# 🌐 ChannelHub
|
|
4
|
+
|
|
5
|
+
*The Universal Multi-Channel Messaging SDK for AI Agents & Modern Applications*
|
|
6
|
+
|
|
7
|
+
[](https://www.npmjs.com/package/@theowlops/channelhub)
|
|
8
|
+
[](LICENSE)
|
|
9
|
+
[](https://bun.sh)
|
|
10
|
+
[](#ai-agent-integrations)
|
|
11
|
+
|
|
12
|
+
Unified messaging protocol & channel adapters across **Zalo**, **Telegram**, **Discord**, and **Slack**. Connect once, listen everywhere, reply with any AI framework.
|
|
13
|
+
|
|
14
|
+
[Highlights](#highlights) • [Quick Start](#quick-start) • [Channel Adapters](#channel-adapters) • [AI Integrations & MCP](#ai-agent-integrations) • [REST / SSE Webhook](#webhook-bridge)
|
|
15
|
+
|
|
16
|
+
</div>
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
## Highlights
|
|
21
|
+
|
|
22
|
+
- **Universal Multi-Channel Protocol**: Single `IChannelAdapter` contract and normalized `UnifiedMessage` across Zalo (Personal & OA), Telegram, Discord, and Slack.
|
|
23
|
+
- **AI Agent Native**: First-class support for Model Context Protocol (MCP), Hermes Agent, OpenClaw, LangChain, CrewAI, and n8n/Dify.
|
|
24
|
+
- **Zero Heavy Core**: Lightweight event-driven architecture running on standard Web APIs and `node:events`. Zero bloat.
|
|
25
|
+
- **Universal Packaging**: Dual ESM & CommonJS outputs with complete TypeScript declaration maps (`.d.ts`).
|
|
26
|
+
- **Backward Compatible**: Retains 100% full API compatibility with existing `@theowlops/zalohub` personal & OA bot callers.
|
|
27
|
+
|
|
28
|
+
---
|
|
29
|
+
|
|
30
|
+
## Installation
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
# bun (recommended)
|
|
34
|
+
bun add @theowlops/channelhub
|
|
35
|
+
|
|
36
|
+
# npm
|
|
37
|
+
npm install @theowlops/channelhub
|
|
38
|
+
|
|
39
|
+
# pnpm
|
|
40
|
+
pnpm add @theowlops/channelhub
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## Quick Start
|
|
46
|
+
|
|
47
|
+
### 1. Multi-Channel AI Bot (Native Event Loop)
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
import { ChannelHub } from "@theowlops/channelhub";
|
|
51
|
+
import { ZaloChannelAdapter } from "@theowlops/channelhub/zalo";
|
|
52
|
+
import { TelegramChannelAdapter } from "@theowlops/channelhub/telegram";
|
|
53
|
+
|
|
54
|
+
const hub = new ChannelHub();
|
|
55
|
+
|
|
56
|
+
// Register channels
|
|
57
|
+
hub.register(new ZaloChannelAdapter({ credentialsPath: "./credentials.json" }));
|
|
58
|
+
hub.register(new TelegramChannelAdapter({ botToken: process.env.TELEGRAM_BOT_TOKEN! }));
|
|
59
|
+
|
|
60
|
+
// Single unified message handler for all platforms
|
|
61
|
+
hub.onMessage(async (ctx) => {
|
|
62
|
+
console.log(`[${ctx.message.channel}] ${ctx.message.sender.name}: ${ctx.message.content.text}`);
|
|
63
|
+
|
|
64
|
+
// Auto-reply back to the originating chat
|
|
65
|
+
if (ctx.message.content.text === "/ping") {
|
|
66
|
+
await ctx.reply("Pong from ChannelHub! 🚀");
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// React with emoji
|
|
70
|
+
await ctx.react("❤️");
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
await hub.start();
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
---
|
|
77
|
+
|
|
78
|
+
## Channel Adapters
|
|
79
|
+
|
|
80
|
+
### Zalo Adapter (`@theowlops/channelhub/zalo`)
|
|
81
|
+
Supports both reverse-engineered personal web session (`zca-js`) and Official Account (OA) OpenAPI v3.
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
import { ZaloChannelAdapter } from "@theowlops/channelhub/zalo";
|
|
85
|
+
|
|
86
|
+
const zalo = new ZaloChannelAdapter({
|
|
87
|
+
credentialsPath: "./credentials.json", // Generated via `channelhub login zalo`
|
|
88
|
+
});
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
### Telegram Adapter (`@theowlops/channelhub/telegram`)
|
|
92
|
+
Zero-dependency Telegram bot engine with automatic long-polling or webhook integration.
|
|
93
|
+
|
|
94
|
+
```ts
|
|
95
|
+
import { TelegramChannelAdapter } from "@theowlops/channelhub/telegram";
|
|
96
|
+
|
|
97
|
+
const tele = new TelegramChannelAdapter({
|
|
98
|
+
botToken: "123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ",
|
|
99
|
+
});
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Discord Adapter (`@theowlops/channelhub/discord`)
|
|
103
|
+
Ultra-lightweight HTTP REST & gateway parser for Discord bots.
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
import { DiscordChannelAdapter } from "@theowlops/channelhub/discord";
|
|
107
|
+
|
|
108
|
+
const discord = new DiscordChannelAdapter({
|
|
109
|
+
botToken: process.env.DISCORD_BOT_TOKEN!,
|
|
110
|
+
});
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
### Slack Adapter (`@theowlops/channelhub/slack`)
|
|
114
|
+
Socket-mode & Event API adapter for workspace enterprise bots.
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
import { SlackChannelAdapter } from "@theowlops/channelhub/slack";
|
|
118
|
+
|
|
119
|
+
const slack = new SlackChannelAdapter({
|
|
120
|
+
botToken: process.env.SLACK_BOT_TOKEN!,
|
|
121
|
+
});
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
---
|
|
125
|
+
|
|
126
|
+
## AI Agent Integrations
|
|
127
|
+
|
|
128
|
+
### Model Context Protocol (MCP) Server
|
|
129
|
+
Expose ChannelHub directly to **Claude Desktop**, **Cursor**, **Codex**, or **Hermes Agent**:
|
|
130
|
+
|
|
131
|
+
```ts
|
|
132
|
+
import { ChannelHub } from "@theowlops/channelhub";
|
|
133
|
+
import { getChannelHubMcpTools, handleChannelHubMcpCall } from "@theowlops/channelhub/mcp";
|
|
134
|
+
|
|
135
|
+
// Tools provided:
|
|
136
|
+
// - channelhub_list_channels
|
|
137
|
+
// - channelhub_send_message
|
|
138
|
+
// - channelhub_add_reaction
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
### Webhook Bridge (REST & Server-Sent Events)
|
|
142
|
+
Run a local REST & SSE server for **n8n**, **Dify**, or **Flowise**:
|
|
143
|
+
|
|
144
|
+
```ts
|
|
145
|
+
import { ChannelHub } from "@theowlops/channelhub";
|
|
146
|
+
import { WebhookBridge } from "@theowlops/channelhub/webhook";
|
|
147
|
+
|
|
148
|
+
const hub = new ChannelHub();
|
|
149
|
+
const bridge = new WebhookBridge(hub, { port: 8788 });
|
|
150
|
+
|
|
151
|
+
await hub.start();
|
|
152
|
+
await bridge.start();
|
|
153
|
+
|
|
154
|
+
// Endpoints available:
|
|
155
|
+
// GET http://localhost:8788/health
|
|
156
|
+
// GET http://localhost:8788/channels
|
|
157
|
+
// POST http://localhost:8788/send { "channel": "telegram", "chatId": "...", "text": "Hi" }
|
|
158
|
+
// GET http://localhost:8788/events (SSE real-time stream of all incoming messages)
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
---
|
|
162
|
+
|
|
163
|
+
## Subpath Imports
|
|
164
|
+
|
|
165
|
+
```ts
|
|
166
|
+
import { ChannelHub, BaseChannel, type UnifiedMessage } from "@theowlops/channelhub";
|
|
167
|
+
import { ZaloChannelAdapter } from "@theowlops/channelhub/zalo";
|
|
168
|
+
import { TelegramChannelAdapter } from "@theowlops/channelhub/telegram";
|
|
169
|
+
import { DiscordChannelAdapter } from "@theowlops/channelhub/discord";
|
|
170
|
+
import { SlackChannelAdapter } from "@theowlops/channelhub/slack";
|
|
171
|
+
import { getChannelHubMcpTools } from "@theowlops/channelhub/mcp";
|
|
172
|
+
import { WebhookBridge } from "@theowlops/channelhub/webhook";
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
---
|
|
176
|
+
|
|
177
|
+
## License
|
|
178
|
+
|
|
179
|
+
MIT © [TheOwlOps](https://github.com/TheOwlOps)
|
package/bin/cli.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
|
|
6
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
7
|
+
const args = process.argv.slice(2);
|
|
8
|
+
const command = args[0] || "help";
|
|
9
|
+
|
|
10
|
+
switch (command) {
|
|
11
|
+
case "login": {
|
|
12
|
+
console.log("[ZaloHub CLI] Quet ma QR de dang nhap...");
|
|
13
|
+
import("../scripts/login_personal.ts");
|
|
14
|
+
break;
|
|
15
|
+
}
|
|
16
|
+
case "start": {
|
|
17
|
+
console.log("[ZaloHub CLI] Khoi dong Bot...");
|
|
18
|
+
import("../src/index.ts");
|
|
19
|
+
break;
|
|
20
|
+
}
|
|
21
|
+
case "help":
|
|
22
|
+
default: {
|
|
23
|
+
console.log(`
|
|
24
|
+
ZaloHub CLI - SDK & Bot Manager
|
|
25
|
+
|
|
26
|
+
Usage:
|
|
27
|
+
zalohub <command>
|
|
28
|
+
|
|
29
|
+
Commands:
|
|
30
|
+
login Quet ma QR dang nhap tai khoan ca nhan
|
|
31
|
+
start Khoi dong Bot service
|
|
32
|
+
help Xem huong dan
|
|
33
|
+
`);
|
|
34
|
+
break;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { ChannelHub } from "../../core/hub";
|
|
2
|
+
export interface McpToolDefinition {
|
|
3
|
+
name: string;
|
|
4
|
+
description: string;
|
|
5
|
+
parameters: Record<string, unknown>;
|
|
6
|
+
}
|
|
7
|
+
export declare function getChannelHubMcpTools(): McpToolDefinition[];
|
|
8
|
+
export declare function handleChannelHubMcpCall(hub: ChannelHub, toolName: string, args: Record<string, any>): Promise<{
|
|
9
|
+
content: Array<{
|
|
10
|
+
type: "text";
|
|
11
|
+
text: string;
|
|
12
|
+
}>;
|
|
13
|
+
isError?: boolean;
|
|
14
|
+
}>;
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// src/bridges/mcp/index.ts
|
|
2
|
+
function getChannelHubMcpTools() {
|
|
3
|
+
return [
|
|
4
|
+
{
|
|
5
|
+
name: "channelhub_list_channels",
|
|
6
|
+
description: "List all active channels registered in ChannelHub (e.g. zalo, telegram, discord, slack).",
|
|
7
|
+
parameters: {
|
|
8
|
+
type: "object",
|
|
9
|
+
properties: {}
|
|
10
|
+
}
|
|
11
|
+
},
|
|
12
|
+
{
|
|
13
|
+
name: "channelhub_send_message",
|
|
14
|
+
description: "Send a text message or reply to a specific chat on a registered channel.",
|
|
15
|
+
parameters: {
|
|
16
|
+
type: "object",
|
|
17
|
+
required: ["channel", "chatId", "text"],
|
|
18
|
+
properties: {
|
|
19
|
+
channel: {
|
|
20
|
+
type: "string",
|
|
21
|
+
description: "Channel name (e.g. 'zalo', 'telegram', 'discord', 'slack')"
|
|
22
|
+
},
|
|
23
|
+
chatId: {
|
|
24
|
+
type: "string",
|
|
25
|
+
description: "Target chat/thread/channel ID"
|
|
26
|
+
},
|
|
27
|
+
text: {
|
|
28
|
+
type: "string",
|
|
29
|
+
description: "Message body text"
|
|
30
|
+
},
|
|
31
|
+
replyToId: {
|
|
32
|
+
type: "string",
|
|
33
|
+
description: "Optional message ID to reply to"
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
{
|
|
39
|
+
name: "channelhub_add_reaction",
|
|
40
|
+
description: "React to a message with an emoji.",
|
|
41
|
+
parameters: {
|
|
42
|
+
type: "object",
|
|
43
|
+
required: ["channel", "chatId", "messageId", "emoji"],
|
|
44
|
+
properties: {
|
|
45
|
+
channel: { type: "string" },
|
|
46
|
+
chatId: { type: "string" },
|
|
47
|
+
messageId: { type: "string" },
|
|
48
|
+
emoji: { type: "string" }
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
];
|
|
53
|
+
}
|
|
54
|
+
async function handleChannelHubMcpCall(hub, toolName, args) {
|
|
55
|
+
try {
|
|
56
|
+
switch (toolName) {
|
|
57
|
+
case "channelhub_list_channels": {
|
|
58
|
+
const channels = hub.listChannels();
|
|
59
|
+
return {
|
|
60
|
+
content: [{ type: "text", text: JSON.stringify({ channels }, null, 2) }]
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
case "channelhub_send_message": {
|
|
64
|
+
const ch = hub.getChannel(args.channel);
|
|
65
|
+
if (!ch)
|
|
66
|
+
throw new Error(`Channel '${args.channel}' not found or not active.`);
|
|
67
|
+
const res = await ch.sendText(args.chatId, args.text, { replyToId: args.replyToId });
|
|
68
|
+
return {
|
|
69
|
+
content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
case "channelhub_add_reaction": {
|
|
73
|
+
const ch = hub.getChannel(args.channel);
|
|
74
|
+
if (!ch)
|
|
75
|
+
throw new Error(`Channel '${args.channel}' not found.`);
|
|
76
|
+
if (!ch.addReaction)
|
|
77
|
+
throw new Error(`Channel '${args.channel}' does not support reactions.`);
|
|
78
|
+
await ch.addReaction(args.chatId, args.messageId, args.emoji);
|
|
79
|
+
return {
|
|
80
|
+
content: [{ type: "text", text: JSON.stringify({ success: true }) }]
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
default:
|
|
84
|
+
throw new Error(`Unknown tool: ${toolName}`);
|
|
85
|
+
}
|
|
86
|
+
} catch (err) {
|
|
87
|
+
return {
|
|
88
|
+
isError: true,
|
|
89
|
+
content: [{ type: "text", text: err.message || String(err) }]
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
export {
|
|
94
|
+
getChannelHubMcpTools,
|
|
95
|
+
handleChannelHubMcpCall
|
|
96
|
+
};
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { ChannelHub } from "../../core/hub";
|
|
2
|
+
export interface WebhookBridgeConfig {
|
|
3
|
+
port?: number;
|
|
4
|
+
host?: string;
|
|
5
|
+
pathPrefix?: string;
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* HTTP / SSE bridge exposing ChannelHub over REST.
|
|
9
|
+
* Compatible with n8n, Dify, Flowise, LangChain custom tools, and plain curl.
|
|
10
|
+
*
|
|
11
|
+
* Endpoints:
|
|
12
|
+
* GET /health
|
|
13
|
+
* GET /channels
|
|
14
|
+
* POST /send { channel, chatId, text, replyToId? }
|
|
15
|
+
* POST /react { channel, chatId, messageId, emoji }
|
|
16
|
+
* GET /events Server-Sent Events stream of inbound UnifiedMessages
|
|
17
|
+
*/
|
|
18
|
+
export declare class WebhookBridge {
|
|
19
|
+
private hub;
|
|
20
|
+
private config;
|
|
21
|
+
private server;
|
|
22
|
+
private sseClients;
|
|
23
|
+
constructor(hub: ChannelHub, config?: WebhookBridgeConfig);
|
|
24
|
+
start(): Promise<void>;
|
|
25
|
+
stop(): Promise<void>;
|
|
26
|
+
private path;
|
|
27
|
+
private handle;
|
|
28
|
+
private handleSse;
|
|
29
|
+
private broadcastSse;
|
|
30
|
+
private json;
|
|
31
|
+
private readJson;
|
|
32
|
+
}
|
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
// src/bridges/webhook/index.ts
|
|
2
|
+
import { createServer } from "node:http";
|
|
3
|
+
|
|
4
|
+
class WebhookBridge {
|
|
5
|
+
hub;
|
|
6
|
+
config;
|
|
7
|
+
server = null;
|
|
8
|
+
sseClients = new Set;
|
|
9
|
+
constructor(hub, config = {}) {
|
|
10
|
+
this.hub = hub;
|
|
11
|
+
this.config = {
|
|
12
|
+
port: config.port ?? 8788,
|
|
13
|
+
host: config.host ?? "0.0.0.0",
|
|
14
|
+
pathPrefix: config.pathPrefix ?? ""
|
|
15
|
+
};
|
|
16
|
+
hub.onMessage(async (ctx) => {
|
|
17
|
+
this.broadcastSse(ctx.message);
|
|
18
|
+
});
|
|
19
|
+
}
|
|
20
|
+
async start() {
|
|
21
|
+
this.server = createServer((req, res) => this.handle(req, res));
|
|
22
|
+
await new Promise((resolve) => {
|
|
23
|
+
this.server.listen(this.config.port, this.config.host, () => resolve());
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
async stop() {
|
|
27
|
+
for (const client of this.sseClients) {
|
|
28
|
+
client.end();
|
|
29
|
+
}
|
|
30
|
+
this.sseClients.clear();
|
|
31
|
+
if (this.server) {
|
|
32
|
+
await new Promise((resolve, reject) => {
|
|
33
|
+
this.server.close((err) => err ? reject(err) : resolve());
|
|
34
|
+
});
|
|
35
|
+
this.server = null;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
path(req) {
|
|
39
|
+
const url = req.url || "/";
|
|
40
|
+
const bare = url.split("?")[0];
|
|
41
|
+
return bare.startsWith(this.config.pathPrefix) ? bare.slice(this.config.pathPrefix.length) || "/" : bare;
|
|
42
|
+
}
|
|
43
|
+
async handle(req, res) {
|
|
44
|
+
const p = this.path(req);
|
|
45
|
+
try {
|
|
46
|
+
if (req.method === "GET" && p === "/health") {
|
|
47
|
+
return this.json(res, 200, { ok: true });
|
|
48
|
+
}
|
|
49
|
+
if (req.method === "GET" && p === "/channels") {
|
|
50
|
+
return this.json(res, 200, { channels: this.hub.listChannels() });
|
|
51
|
+
}
|
|
52
|
+
if (req.method === "POST" && p === "/send") {
|
|
53
|
+
const body = await this.readJson(req);
|
|
54
|
+
const ch = this.hub.getChannel(body.channel);
|
|
55
|
+
if (!ch)
|
|
56
|
+
return this.json(res, 404, { error: `Channel '${body.channel}' not found` });
|
|
57
|
+
const result = await ch.sendText(body.chatId, body.text, { replyToId: body.replyToId });
|
|
58
|
+
return this.json(res, 200, result);
|
|
59
|
+
}
|
|
60
|
+
if (req.method === "POST" && p === "/react") {
|
|
61
|
+
const body = await this.readJson(req);
|
|
62
|
+
const ch = this.hub.getChannel(body.channel);
|
|
63
|
+
if (!ch)
|
|
64
|
+
return this.json(res, 404, { error: `Channel '${body.channel}' not found` });
|
|
65
|
+
if (!ch.addReaction)
|
|
66
|
+
return this.json(res, 400, { error: "Channel does not support reactions" });
|
|
67
|
+
await ch.addReaction(body.chatId, body.messageId, body.emoji);
|
|
68
|
+
return this.json(res, 200, { success: true });
|
|
69
|
+
}
|
|
70
|
+
if (req.method === "GET" && p === "/events") {
|
|
71
|
+
return this.handleSse(res);
|
|
72
|
+
}
|
|
73
|
+
this.json(res, 404, { error: "Not found" });
|
|
74
|
+
} catch (err) {
|
|
75
|
+
this.json(res, 500, { error: err.message || String(err) });
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
handleSse(res) {
|
|
79
|
+
res.writeHead(200, {
|
|
80
|
+
"Content-Type": "text/event-stream",
|
|
81
|
+
"Cache-Control": "no-cache",
|
|
82
|
+
Connection: "keep-alive"
|
|
83
|
+
});
|
|
84
|
+
res.write(`data: ${JSON.stringify({ type: "connected" })}
|
|
85
|
+
|
|
86
|
+
`);
|
|
87
|
+
this.sseClients.add(res);
|
|
88
|
+
res.on("close", () => this.sseClients.delete(res));
|
|
89
|
+
}
|
|
90
|
+
broadcastSse(msg) {
|
|
91
|
+
const payload = `data: ${JSON.stringify(msg)}
|
|
92
|
+
|
|
93
|
+
`;
|
|
94
|
+
for (const client of this.sseClients) {
|
|
95
|
+
client.write(payload);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
json(res, status, body) {
|
|
99
|
+
const data = JSON.stringify(body);
|
|
100
|
+
res.writeHead(status, {
|
|
101
|
+
"Content-Type": "application/json",
|
|
102
|
+
"Content-Length": Buffer.byteLength(data)
|
|
103
|
+
});
|
|
104
|
+
res.end(data);
|
|
105
|
+
}
|
|
106
|
+
readJson(req) {
|
|
107
|
+
return new Promise((resolve, reject) => {
|
|
108
|
+
const chunks = [];
|
|
109
|
+
req.on("data", (c) => chunks.push(c));
|
|
110
|
+
req.on("end", () => {
|
|
111
|
+
try {
|
|
112
|
+
resolve(JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}"));
|
|
113
|
+
} catch (err) {
|
|
114
|
+
reject(err);
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
req.on("error", reject);
|
|
118
|
+
});
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
export {
|
|
122
|
+
WebhookBridge
|
|
123
|
+
};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { BaseChannel } from "../../core/adapter";
|
|
2
|
+
import type { ChannelType, MediaPayload, SendOptions, SentMessageResult, UnifiedMessage } from "../../core/types";
|
|
3
|
+
export interface DiscordAdapterConfig {
|
|
4
|
+
botToken: string;
|
|
5
|
+
intents?: number;
|
|
6
|
+
autoStart?: boolean;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Lightweight Discord adapter using Discord HTTP REST API.
|
|
10
|
+
* Gateway WS is optional — messages can be pushed via normalizeEvent() for webhook/gateway bridges.
|
|
11
|
+
*/
|
|
12
|
+
export declare class DiscordChannelAdapter extends BaseChannel {
|
|
13
|
+
readonly name: ChannelType;
|
|
14
|
+
private config;
|
|
15
|
+
private apiBase;
|
|
16
|
+
constructor(config: DiscordAdapterConfig);
|
|
17
|
+
connect(): Promise<void>;
|
|
18
|
+
disconnect(): Promise<void>;
|
|
19
|
+
normalizeEvent(event: any): UnifiedMessage | null;
|
|
20
|
+
private callApi;
|
|
21
|
+
sendText(chatId: string, text: string, options?: SendOptions): Promise<SentMessageResult>;
|
|
22
|
+
sendMedia(chatId: string, media: MediaPayload, options?: SendOptions): Promise<SentMessageResult>;
|
|
23
|
+
addReaction(chatId: string, messageId: string, emoji: string): Promise<void>;
|
|
24
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./adapter";
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
// src/core/adapter.ts
|
|
2
|
+
import { EventEmitter } from "node:events";
|
|
3
|
+
|
|
4
|
+
class BaseChannel extends EventEmitter {
|
|
5
|
+
_connected = false;
|
|
6
|
+
isConnected() {
|
|
7
|
+
return this._connected;
|
|
8
|
+
}
|
|
9
|
+
setConnected(value) {
|
|
10
|
+
const changed = this._connected !== value;
|
|
11
|
+
this._connected = value;
|
|
12
|
+
if (changed) {
|
|
13
|
+
this.emit("status", value ? "connected" : "disconnected");
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// src/channels/discord/adapter.ts
|
|
19
|
+
class DiscordChannelAdapter extends BaseChannel {
|
|
20
|
+
name = "discord";
|
|
21
|
+
config;
|
|
22
|
+
apiBase = "https://discord.com/api/v10";
|
|
23
|
+
constructor(config) {
|
|
24
|
+
super();
|
|
25
|
+
this.config = config;
|
|
26
|
+
}
|
|
27
|
+
async connect() {
|
|
28
|
+
if (!this.config.botToken)
|
|
29
|
+
throw new Error("Discord botToken is required.");
|
|
30
|
+
await this.callApi("GET", "/users/@me");
|
|
31
|
+
this.setConnected(true);
|
|
32
|
+
}
|
|
33
|
+
async disconnect() {
|
|
34
|
+
this.setConnected(false);
|
|
35
|
+
}
|
|
36
|
+
normalizeEvent(event) {
|
|
37
|
+
if (!event || event.type !== 0 && !event.content && !event.author) {
|
|
38
|
+
if (!event?.content && !event?.d?.content)
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
const msg = event.d || event;
|
|
42
|
+
if (!msg.content && !msg.attachments?.length)
|
|
43
|
+
return null;
|
|
44
|
+
if (msg.author?.bot)
|
|
45
|
+
return null;
|
|
46
|
+
const isDm = !msg.guild_id;
|
|
47
|
+
return {
|
|
48
|
+
id: String(msg.id),
|
|
49
|
+
channel: "discord",
|
|
50
|
+
sender: {
|
|
51
|
+
id: String(msg.author?.id ?? ""),
|
|
52
|
+
name: msg.author?.global_name || msg.author?.username,
|
|
53
|
+
username: msg.author?.username,
|
|
54
|
+
isBot: Boolean(msg.author?.bot),
|
|
55
|
+
avatarUrl: msg.author?.avatar ? `https://cdn.discordapp.com/avatars/${msg.author.id}/${msg.author.avatar}.png` : undefined
|
|
56
|
+
},
|
|
57
|
+
chat: {
|
|
58
|
+
id: String(msg.channel_id),
|
|
59
|
+
type: isDm ? "dm" : "channel",
|
|
60
|
+
title: undefined
|
|
61
|
+
},
|
|
62
|
+
content: {
|
|
63
|
+
text: msg.content || "",
|
|
64
|
+
attachments: (msg.attachments || []).map((a) => ({
|
|
65
|
+
type: a.content_type?.startsWith("image/") ? "image" : a.content_type?.startsWith("video/") ? "video" : "file",
|
|
66
|
+
url: a.url,
|
|
67
|
+
filename: a.filename,
|
|
68
|
+
mimeType: a.content_type,
|
|
69
|
+
size: a.size
|
|
70
|
+
})),
|
|
71
|
+
replyToId: msg.message_reference?.message_id ? String(msg.message_reference.message_id) : undefined
|
|
72
|
+
},
|
|
73
|
+
raw: event,
|
|
74
|
+
timestamp: msg.timestamp ? Date.parse(msg.timestamp) : Date.now()
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
async callApi(method, path, body) {
|
|
78
|
+
const res = await fetch(`${this.apiBase}${path}`, {
|
|
79
|
+
method,
|
|
80
|
+
headers: {
|
|
81
|
+
Authorization: `Bot ${this.config.botToken}`,
|
|
82
|
+
"Content-Type": "application/json"
|
|
83
|
+
},
|
|
84
|
+
body: body ? JSON.stringify(body) : undefined
|
|
85
|
+
});
|
|
86
|
+
if (!res.ok) {
|
|
87
|
+
const errText = await res.text();
|
|
88
|
+
throw new Error(`Discord API ${method} ${path} failed: ${res.status} ${errText}`);
|
|
89
|
+
}
|
|
90
|
+
if (res.status === 204)
|
|
91
|
+
return null;
|
|
92
|
+
return res.json();
|
|
93
|
+
}
|
|
94
|
+
async sendText(chatId, text, options) {
|
|
95
|
+
const payload = { content: text };
|
|
96
|
+
if (options?.replyToId) {
|
|
97
|
+
payload.message_reference = { message_id: options.replyToId };
|
|
98
|
+
}
|
|
99
|
+
const res = await this.callApi("POST", `/channels/${chatId}/messages`, payload);
|
|
100
|
+
return {
|
|
101
|
+
messageId: String(res.id),
|
|
102
|
+
chatId,
|
|
103
|
+
timestamp: Date.parse(res.timestamp) || Date.now()
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
async sendMedia(chatId, media, options) {
|
|
107
|
+
const payload = {
|
|
108
|
+
content: media.caption || ""
|
|
109
|
+
};
|
|
110
|
+
if (typeof media.source === "string") {
|
|
111
|
+
payload.embeds = [{ image: { url: media.source } }];
|
|
112
|
+
}
|
|
113
|
+
if (options?.replyToId) {
|
|
114
|
+
payload.message_reference = { message_id: options.replyToId };
|
|
115
|
+
}
|
|
116
|
+
const res = await this.callApi("POST", `/channels/${chatId}/messages`, payload);
|
|
117
|
+
return {
|
|
118
|
+
messageId: String(res.id),
|
|
119
|
+
chatId,
|
|
120
|
+
timestamp: Date.parse(res.timestamp) || Date.now()
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
async addReaction(chatId, messageId, emoji) {
|
|
124
|
+
const encoded = encodeURIComponent(emoji);
|
|
125
|
+
await this.callApi("PUT", `/channels/${chatId}/messages/${messageId}/reactions/${encoded}/@me`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
export {
|
|
129
|
+
DiscordChannelAdapter
|
|
130
|
+
};
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { BaseChannel } from "../../core/adapter";
|
|
2
|
+
import type { ChannelType, MediaPayload, SendOptions, SentMessageResult, UnifiedMessage } from "../../core/types";
|
|
3
|
+
export interface SlackAdapterConfig {
|
|
4
|
+
botToken: string;
|
|
5
|
+
appToken?: string;
|
|
6
|
+
signingSecret?: string;
|
|
7
|
+
}
|
|
8
|
+
export declare class SlackChannelAdapter extends BaseChannel {
|
|
9
|
+
readonly name: ChannelType;
|
|
10
|
+
private config;
|
|
11
|
+
private apiBase;
|
|
12
|
+
constructor(config: SlackAdapterConfig);
|
|
13
|
+
connect(): Promise<void>;
|
|
14
|
+
disconnect(): Promise<void>;
|
|
15
|
+
normalizeEvent(event: any): UnifiedMessage | null;
|
|
16
|
+
private callApi;
|
|
17
|
+
sendText(chatId: string, text: string, options?: SendOptions): Promise<SentMessageResult>;
|
|
18
|
+
sendMedia(chatId: string, media: MediaPayload, options?: SendOptions): Promise<SentMessageResult>;
|
|
19
|
+
addReaction(chatId: string, messageId: string, emoji: string): Promise<void>;
|
|
20
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from "./adapter";
|