-
Notifications
You must be signed in to change notification settings - Fork 39
/
ws.ts
55 lines (51 loc) · 1.65 KB
/
ws.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { Adapter, Context, Schema } from '@satorijs/satori'
import { DingtalkBot } from './bot'
import { decodeMessage } from './utils'
export class WsClient<C extends Context = Context> extends Adapter.WsClient<C, DingtalkBot<C>> {
async prepare() {
await this.bot.refreshToken()
await this.bot.getLogin()
const { endpoint, ticket } = await this.bot.http.post<{
endpoint: string
ticket: string
}>('/gateway/connections/open', {
clientId: this.bot.config.appkey,
clientSecret: this.bot.config.secret,
subscriptions: [
{
type: 'CALLBACK',
topic: '/v1.0/im/bot/messages/get',
},
],
})
return this.bot.http.ws(`${endpoint}?ticket=${ticket}`)
}
accept() {
this.bot.online()
this.socket.addEventListener('message', async ({ data }) => {
const parsed = JSON.parse(data.toString())
this.bot.logger.debug(parsed)
if (parsed.type === 'SYSTEM') {
if (parsed.headers.topic === 'ping') {
this.socket.send(JSON.stringify({
code: 200,
headers: parsed.headers,
message: 'OK',
data: parsed.data,
}))
}
} else if (parsed.type === 'CALLBACK') {
this.bot.logger.debug(JSON.parse(parsed.data))
const session = await decodeMessage(this.bot, JSON.parse(parsed.data))
if (session) this.bot.dispatch(session)
this.bot.logger.debug(session)
}
})
}
}
export namespace WsClient {
export interface Options extends Adapter.WsClientConfig {}
export const Options: Schema<Options> = Schema.intersect([
Adapter.WsClientConfig,
] as const)
}