|
| 1 | +import { Context, Schema, Logger } from 'koishi' |
| 2 | + |
| 3 | +export const usage = ` |
| 4 | +## koishi-plugin-api-handler v1.0 |
| 5 | +
|
| 6 | +1. 配置API地址。 |
| 7 | +
|
| 8 | +2. 设置消息前缀,例如:tx。 |
| 9 | +
|
| 10 | +3. 当用户发送的消息以该前缀开头(如tx1234或Tx1234)时,系统将通过POST方式向API发送请求,包括参数:token、message、session。 |
| 11 | +
|
| 12 | +4. 服务器需返回一个字符串,该字符串将作为机器人的回复消息。 |
| 13 | +
|
| 14 | +` |
| 15 | + |
| 16 | +export const name = 'koishi-plugin-api-handler' |
| 17 | + |
| 18 | +export const logger = new Logger('koishi-plugin-api-handler') |
| 19 | + |
| 20 | +export interface Config { |
| 21 | + api: string, |
| 22 | + token: string, |
| 23 | + prefix_1: string, |
| 24 | + prefix_2: string, |
| 25 | + prefix_3?: string, |
| 26 | + prefix_4?: string, |
| 27 | +} |
| 28 | + |
| 29 | +export const Config: Schema<Config> = Schema.object({ |
| 30 | + api: Schema.string().required(true).description('API地址'), |
| 31 | + token: Schema.string().required(true).description('API接收的token,以POST传递,参数名为token'), |
| 32 | + prefix_1: Schema.string().required(true).description('消息开头匹配字符串,不区分大小写,完全包含则将用户消息发送到API,由API返回回复内容字符串'), |
| 33 | + prefix_2: Schema.string().description('匹配消息前缀2'), |
| 34 | + prefix_3: Schema.string().description('匹配消息前缀3'), |
| 35 | + prefix_4: Schema.string().description('匹配消息前缀4'), |
| 36 | +}) |
| 37 | + |
| 38 | +export function startsWithPrefix(str: string, prefix: string) { |
| 39 | + // 首先去掉字符串前后的空格 |
| 40 | + str = str.trim(); |
| 41 | + |
| 42 | + // 构建正则表达式,不区分大小写 |
| 43 | + const regex = new RegExp('^' + prefix, 'i'); |
| 44 | + |
| 45 | + // 使用正则表达式判断是否以指定前缀开头 |
| 46 | + return regex.test(str); |
| 47 | +} |
| 48 | + |
| 49 | +export function handlePrefixes(sessionContent: string, config: Config) { |
| 50 | + for (let i = 1; i <= 4; i++) { // 假设有四个前缀 |
| 51 | + let prefixKey = `prefix_${i}`; |
| 52 | + if (config[prefixKey]) { |
| 53 | + if (startsWithPrefix(sessionContent, config[prefixKey])) { |
| 54 | + // 这里可以根据前缀执行不同的逻辑 |
| 55 | + return `匹配前缀${i}`; |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | +} |
| 60 | + |
| 61 | +export function apply(ctx: Context, config: Config) { |
| 62 | + ctx.middleware(async (session, next) => { |
| 63 | + // console.log(config); |
| 64 | + // console.log(session); |
| 65 | + // console.log(session.content); |
| 66 | + let match_prefix = handlePrefixes(session.content, config) |
| 67 | + let error = null; |
| 68 | + if (match_prefix) { |
| 69 | + logger.info(match_prefix + ':' + session.content) |
| 70 | + const res = await ctx.http.post(config.api, { |
| 71 | + token: config.token, |
| 72 | + message: session.content, |
| 73 | + session: session, |
| 74 | + }) |
| 75 | + .catch((err) => { |
| 76 | + return { error: err.message } |
| 77 | + }) |
| 78 | + if (res !== undefined) { |
| 79 | + // console.log(res); |
| 80 | + return res; |
| 81 | + } |
| 82 | + |
| 83 | + return 'Error'; |
| 84 | + } |
| 85 | + return next() |
| 86 | + }, true) |
| 87 | +} |
0 commit comments