Skip to content

Commit

Permalink
feat(plugin-nlp): cmd.intend() should return this
Browse files Browse the repository at this point in the history
  • Loading branch information
shigma committed Jan 27, 2020
1 parent c8b8d0d commit 8036e02
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 3 deletions.
7 changes: 4 additions & 3 deletions packages/plugin-nlp/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Command, Meta, Context, ParsedLine, ParsedCommandLine } from 'koishi-core'
import { Command, Meta, Context, ParsedLine, ParsedCommandLine, App } from 'koishi-core'
import { tag, load } from 'nodejieba'
import { resolve } from 'path'

declare module 'koishi-core/dist/command' {
interface Command {
intend (keyword: string, callback: IntenderCallback): void
intend (keywords: string[], callback: IntenderCallback): void
intend (keyword: string, callback: IntenderCallback): this
intend (keywords: string[], callback: IntenderCallback): this
}
}

Expand Down Expand Up @@ -48,6 +48,7 @@ const intenders: Intender[] = []
Command.prototype.intend = function (this: Command, arg0: string | string[], callback: IntenderCallback) {
const keywords = typeof arg0 === 'string' ? [arg0] : arg0
intenders.push({ command: this, keywords, callback })
return this
}

export const name = 'nlp'
Expand Down
42 changes: 42 additions & 0 deletions packages/plugin-nlp/tests/index.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { App } from 'koishi-test-utils'
import { resolve } from 'path'
import * as nlp from '../src'

test('basic support', async () => {
const app = new App()
const session = app.createSession('user', 123)
app.plugin(nlp)

app.command('weather <location>')
.intend('天气', (meta) => {
const tag = meta.$parsed.tags.find(({ tag }) => tag === 'ns')
if (tag) return { args: [tag.word] }
})
.action(({ meta }, location) => meta.$send(location))

await session.shouldHaveNoReply('今天的天气')
await session.shouldHaveNoReply('今天的北京')
await session.shouldHaveNoReply('幻想乡今天的天气')
await session.shouldHaveReply('北京今天的天气', '北京')
})

test('user dict', async () => {
const app = new App()
const session = app.createSession('user', 123)
app.plugin(nlp, {
userDict: resolve(__dirname, 'user.dict.utf8'),
})

app.command('weather <location>')
.intend(['天气'], (meta) => {
const tag = meta.$parsed.tags.find(({ tag }) => tag === 'ns')
if (tag) return { confidence: 0.9, args: [tag.word] }
return { confidence: 0.5 }
})
.action(({ meta }, location) => meta.$send(location))

await session.shouldHaveNoReply('今天的天气')
await session.shouldHaveNoReply('今天的北京')
await session.shouldHaveReply('北京今天的天气', '北京')
await session.shouldHaveReply('幻想乡今天的天气', '幻想乡')
})
1 change: 1 addition & 0 deletions packages/plugin-nlp/tests/user.dict.utf8
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
幻想乡 ns

0 comments on commit 8036e02

Please sign in to comment.