Skip to content

Commit

Permalink
refactor: let bot handle session
Browse files Browse the repository at this point in the history
  • Loading branch information
bytemain committed Oct 9, 2024
1 parent 482eac4 commit 3ff2af0
Show file tree
Hide file tree
Showing 13 changed files with 197 additions and 134 deletions.
37 changes: 37 additions & 0 deletions libs/dingtalk-bot/__tests__/ding-bot.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { DingBotAdapter as BaseDingBotAdapter, Session } from '../src';

describe('bot-commander', () => {
it('should work', () => {
const example = {
chatbotCorpId: 'corp1',
chatbotUserId: 'user1',
conversationId: 'conv1',
conversationType: 'convType1',
createAt: 1,
isAdmin: true,
msgId: 'msg1',
msgtype: 'text' as const,
robotCode: 'code1',
senderCorpId: 'corp1',
senderId: 'sender1',
senderNick: 'nick1',
senderStaffId: 'staff1',
sessionWebhook: 'webhook1',
sessionWebhookExpiredTime: 1,
text: {
content: '/hello',
},
};

const session = new Session(example);
const adapter = new BaseDingBotAdapter('bot1');

adapter.cc.on('hello', async (ctx) => {
const { session } = ctx;
console.log(`===== ~ adapter.cc.on ~ ctx:`, ctx);
await session.replyText('world');
});

adapter.handle(session);
});
});
11 changes: 0 additions & 11 deletions libs/dingtalk-bot/src/bot/base-adapter.ts

This file was deleted.

60 changes: 32 additions & 28 deletions libs/dingtalk-bot/src/bot/dingtalk-adapter.ts
Original file line number Diff line number Diff line change
@@ -1,53 +1,57 @@
import { CommandCenter, ICommandCenterOptions } from '@opensumi/bot-commander';
import * as types from '../types';
import { send } from '../utils';
import { IBotAdapter } from './base-adapter';
import { Session } from './session';

function prepare(s: string) {
return s.toString().trim();
}

export class DingBotAdapter<CommandCenterContext extends Record<string, any>>
implements IBotAdapter
{
export class DingBotAdapter<
CommandCenterContext extends {
session: Session;
},
> {
public cc: CommandCenter<CommandCenterContext>;

constructor(
public id: string,
public msg: types.Message,
public commandOptions?: ICommandCenterOptions<CommandCenterContext>,
) {
this.cc = new CommandCenter(commandOptions);
}

public async getContext(): Promise<CommandCenterContext> {
return {} as CommandCenterContext;
public async constructContext(
session: Session,
): Promise<CommandCenterContext> {
return {
session,
} as CommandCenterContext;
}

async handle(options?: {
timeout?: number | null;
}) {
const msg = this.msg;
async handle(
session: Session,
options?: {
timeout?: number | null;
},
) {
const msg = session.msg;
console.log(
`${this.id} receive dingtalk msg: `,
JSON.stringify(msg, null, 2),
);

// 其实目前钉钉机器人也就支持这一种消息类型
if (msg.msgtype === 'text') {
const text = prepare(msg.text.content);
const text = session.text;
console.log(`DingBot ~ handle ~ text`, text);

await this.cc.tryHandle(text, await this.getContext(), options);
try {
await this.cc.tryHandle(
text,
await this.constructContext(session),
options,
);
} catch (err) {
await session.replyText(
`处理消息出错: ${(err as Error).message} ${(err as Error).stack}`,
);
throw err;
}
}
}

async replyText(text: string, contentExtra: Record<string, any> = {}) {
await this.reply(types.compose(types.text(text), contentExtra));
}

async reply(content: types.SendMessage) {
console.log(`DingBot ~ reply:`, JSON.stringify(content));
await send(content, this.msg.sessionWebhook);
}
}
29 changes: 19 additions & 10 deletions libs/dingtalk-bot/src/bot/session.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,23 @@
import { IBotAdapter } from './base-adapter';
import { Message, SendMessage, compose, text as textFn } from '../types';
import { send } from '../utils';

function prepare(s: string) {
return s.toString().trim();
}

export class Session {
constructor(public impl: IBotAdapter) {}

async run() {
await this.impl.handle().catch(async (err: Error) => {
await this.impl.replyText(
`处理消息出错: ${(err as Error).message} ${(err as Error).stack}`,
);
throw err;
});
constructor(public msg: Message) {}

async replyText(text: string, contentExtra: Record<string, any> = {}) {
await this.reply(compose(textFn(text), contentExtra));
}

async reply(content: SendMessage) {
console.log(`DingBot ~ reply:`, JSON.stringify(content));
await send(content, this.msg.sessionWebhook);
}

get text() {
return prepare(this.msg.text.content);
}
}
1 change: 0 additions & 1 deletion libs/dingtalk-bot/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,5 @@ export async function verifyMessage(headers: Headers, token: string) {
}
}

export { IBotAdapter } from './bot/base-adapter';
export { DingBotAdapter } from './bot/dingtalk-adapter';
export { Session } from './bot/session';
14 changes: 3 additions & 11 deletions src/api/controllers/ding.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,10 @@ export function route(hono: THono) {
return c.send.error(403, errMessage);
}

const session = new Session(
new DingBotAdapter(
id,
c,
await c.req.json(),
kvManager,
c.executionCtx,
setting,
),
);
const bot = new DingBotAdapter(id, c, kvManager, c.executionCtx, setting);
const session = new Session(await c.req.json());

c.executionCtx.waitUntil(session.run());
c.executionCtx.waitUntil(bot.handle(session));

return c.send.message('ok');
});
Expand Down
8 changes: 4 additions & 4 deletions src/im/commands/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,19 @@ import { IMCommandCenter } from './types';
export function registerCommonCommand(it: IMCommandCenter) {
it.on(
'putData',
async ({ bot }, command) => {
async ({ bot, session }, command) => {
const info = {} as IDingInfo;
if (command.args['defaultRepo']) {
info['defaultRepo'] = command.args['defaultRepo'];
}
await bot.kvManager.updateGroupInfo(bot.id, info);
await bot.replyText('更新信息成功');
await session.replyText('更新信息成功');
},
undefined,
);

it.on('getGroupInfo', async ({ bot, ctx }) => {
await bot.reply(
it.on('getGroupInfo', async ({ session, ctx }) => {
await session.reply(
code(
'json',
JSON.stringify({
Expand Down
Loading

0 comments on commit 3ff2af0

Please sign in to comment.