Skip to content

Commit

Permalink
feat(dingtalk): delete message, fix oapi
Browse files Browse the repository at this point in the history
  • Loading branch information
XxLittleCxX committed Jul 25, 2023
1 parent 2075f73 commit 2d8d501
Show file tree
Hide file tree
Showing 5 changed files with 45 additions and 11 deletions.
43 changes: 35 additions & 8 deletions adapters/dingtalk/src/bot.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Bot, Context, Logger, Quester, Schema } from '@satorijs/satori'
import { Bot, Context, Logger, Quester, Schema, Universal } from '@satorijs/satori'
import { HttpServer } from './http'
import { DingtalkMessageEncoder } from './message'
import { WsClient } from './ws'
Expand All @@ -15,10 +15,8 @@ export class DingtalkBot extends Bot<DingtalkBot.Config> {
public internal: Internal
constructor(ctx: Context, config: DingtalkBot.Config) {
super(ctx, config)
this.http = ctx.http.extend(config)
this.oldHttp = ctx.http.extend({
endpoint: 'https://oapi.dingtalk.com/',
})
this.http = ctx.http.extend(config.api)
this.oldHttp = ctx.http.extend(config.oldApi)
this.internal = new Internal(this)

if (config.protocol === 'http') {
Expand All @@ -28,6 +26,13 @@ export class DingtalkBot extends Bot<DingtalkBot.Config> {
}
}

async initialize() {
const { appList } = await this.internal.OapiMicroappList()
const self = appList.find(v => v.agentId === this.config.agentId)
this.username = self.name
this.avatar = self.appIcon
}

// @ts-ignore
stop(): Promise<void> {
clearTimeout(this.refreshTokenTimer)
Expand All @@ -47,7 +52,7 @@ export class DingtalkBot extends Bot<DingtalkBot.Config> {
headers: {
'x-acs-dingtalk-access-token': data.accessToken,
},
}).extend(this.config)
}).extend(this.config.api)
this.refreshTokenTimer = setTimeout(this.refreshToken.bind(this), (data.expireIn - 10) * 1000)
}

Expand All @@ -58,13 +63,33 @@ export class DingtalkBot extends Bot<DingtalkBot.Config> {
})
return downloadUrl
}

async deleteMessage(channelId: string, messageId: string): Promise<void> {
if (channelId.startsWith("cid")) {
await this.internal.orgGroupRecall({
robotCode: this.selfId,
processQueryKeys: [messageId],
openConversationId: channelId
})
} else {
await this.internal.batchRecallOTO({
robotCode: this.selfId,
processQueryKeys: [messageId]
})
}

}

}

export namespace DingtalkBot {
export interface Config extends Bot.Config, Quester.Config, WsClient.Config {
export interface Config extends Bot.Config, WsClient.Config {
secret: string
protocol: string
appkey: string
agentId: number
api: Quester.Config,
oldApi: Quester.Config
}

export const Config: Schema<Config> = Schema.intersect([
Expand All @@ -75,10 +100,12 @@ export namespace DingtalkBot {
}),
Schema.object({
secret: Schema.string().required().description('机器人密钥。'),
agentId: Schema.number().required().description('AgentId'),
appkey: Schema.string().required(),
api: Quester.createConfig('https://api.dingtalk.com/v1.0/'),
oldApi: Quester.createConfig('https://oapi.dingtalk.com/')
}),
WsClient.Config,
Quester.createConfig('https://api.dingtalk.com/v1.0/'),
])
}

Expand Down
1 change: 1 addition & 0 deletions adapters/dingtalk/src/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export class HttpServer extends Adapter.Server<DingtalkBot> {
async start(bot: DingtalkBot) {
await bot.refreshToken()
bot.selfId = bot.config.appkey
await bot.initialize()
// https://open.dingtalk.com/document/orgapp/receive-message
bot.ctx.router.post('/dingtalk', async (ctx) => {
const timestamp = ctx.get('timestamp')
Expand Down
3 changes: 3 additions & 0 deletions adapters/dingtalk/src/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ export class Internal {
throw new Error(`too many arguments for ${path}, received ${raw}`)
}
const quester = isOldApi ? this.bot.oldHttp : this.bot.http
if (isOldApi) {
config.params = { ...config.params, access_token: this.bot.token }
}
try {
return await quester(method, url, config)
} catch (error) {
Expand Down
7 changes: 4 additions & 3 deletions adapters/dingtalk/src/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@ export class DingtalkMessageEncoder extends MessageEncoder<DingtalkBot> {

// https://open.dingtalk.com/document/orgapp/the-robot-sends-a-group-message
async sendMessage<T extends keyof SendMessageData>(msgType: T, msgParam: SendMessageData[T]) {
console.log(this.session)
const { processQueryKey } = this.session.isDirect ? await this.bot.internal.batchSendOTO({
msgKey: msgType,
msgParam: JSON.stringify(msgParam),
Expand All @@ -51,6 +50,10 @@ export class DingtalkMessageEncoder extends MessageEncoder<DingtalkBot> {
})
const session = this.bot.session()
session.messageId = processQueryKey
session.channelId = this.session.channelId
session.guildId = this.session.guildId
console.log(session, processQueryKey)
session.app.emit(session, 'send', session)
this.results.push(session)
}

Expand Down Expand Up @@ -109,7 +112,6 @@ export class DingtalkMessageEncoder extends MessageEncoder<DingtalkBot> {
this.buffer += `* `
} else if (type === 'a' && attrs.href) {
this.buffer += `[`
console.log(children)
await this.render(children)
this.buffer += `](${encodeURI(attrs.href)})`
} else if (type === 'ul' || type === 'ol') {
Expand All @@ -126,7 +128,6 @@ export class DingtalkMessageEncoder extends MessageEncoder<DingtalkBot> {
this.render(children)
this.buffer += '\n'
} else if (type === 'blockquote') {
console.log(children)
if (!this.buffer.endsWith('\n')) this.buffer += '\n'
this.buffer += '> '
await this.render(children)
Expand Down
2 changes: 2 additions & 0 deletions adapters/dingtalk/src/ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ export class WsClient extends Adapter.WsClient<DingtalkBot> {
async prepare() {
await this.bot.refreshToken()
this.bot.selfId = this.bot.config.appkey
await this.bot.initialize()
const { endpoint, ticket } = await this.bot.http.post<{
endpoint: string
ticket: string
Expand All @@ -23,6 +24,7 @@ export class WsClient extends Adapter.WsClient<DingtalkBot> {
}

accept() {
this.bot.online()
this.bot.socket.addEventListener('message', async ({ data }) => {
const parsed = JSON.parse(data.toString())
this.ctx.logger('dingtalk').debug(require('util').inspect(parsed, false, null, true))
Expand Down

0 comments on commit 2d8d501

Please sign in to comment.