Skip to content

Commit

Permalink
refa: use message encoder for mock bots
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Jul 17, 2024
1 parent 10e359a commit e97a631
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 13 deletions.
11 changes: 4 additions & 7 deletions plugins/mock/src/adapter.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { Adapter, Bot, Channel, Context, Fragment, Universal, User } from 'koishi'
import { MessageClient, MockMessenger } from './client'
import { Adapter, Bot, Channel, Context, Universal, User } from 'koishi'
import { MessageClient, MockMessageEncoder } from './client'
import { Webhook } from './webhook'

declare module 'koishi' {
Expand All @@ -21,6 +21,8 @@ export namespace MockBot {
}

export class MockBot<C extends Context = Context> extends Bot<C> {
static MessageEncoder = MockMessageEncoder

constructor(ctx: C, config: MockBot.Config) {
super(ctx, config)
this.platform = 'mock'
Expand Down Expand Up @@ -51,11 +53,6 @@ export class MockBot<C extends Context = Context> extends Bot<C> {
user: { id: this.selfId },
}
}

async sendMessage(channelId: string, fragment: Fragment, guildId?: string, options?: Universal.SendOptions) {
const messages = await new MockMessenger(options!.session['client'], options).send(fragment)
return messages.map(messages => messages.id)
}
}

export class MockAdapter<C extends Context = Context> extends Adapter<C, MockBot<C>> {
Expand Down
8 changes: 2 additions & 6 deletions plugins/mock/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,13 @@ const RECEIVED_OTHERWISE = 'expected "%s" to be replied with %s but received "%s
const RECEIVED_NTH_NOTHING = 'expected "%s" to be replied at index %s but received nothing'
const RECEIVED_NTH_OTHERWISE = 'expected "%s" to be replied with %s at index %s but received "%s"'

export class MockMessenger extends MessageEncoder<Context, MockBot> {
export class MockMessageEncoder extends MessageEncoder<Context, MockBot> {
private buffer = ''

constructor(private client: MessageClient, options?: Universal.SendOptions) {
super(client.bot, client.event.channel.id, client.event.guild?.id, options)
}

async flush() {
this.buffer = this.buffer.trim()
if (!this.buffer) return
this.client.flush(this.buffer)
this.options.session?.['client']?.flush(this.buffer)
this.buffer = ''
}

Expand Down

0 comments on commit e97a631

Please sign in to comment.