Skip to content

Commit

Permalink
fix: qa detail run error
Browse files Browse the repository at this point in the history
  • Loading branch information
class-liu-fullstack committed Feb 2, 2025
1 parent 72bc8ca commit 3d12cff
Show file tree
Hide file tree
Showing 16 changed files with 83 additions and 92 deletions.
4 changes: 2 additions & 2 deletions core/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,9 +135,9 @@ export class App extends EventEmitter {
);
}

getSupportCommands<A extends Adapter>(adapter: A, bot: Bot<A>, event: Message<A>) {
getSupportCommands(adapter: string) {
return this.pluginList
.filter(plugin => !plugin.adapters || plugin.adapters.includes(adapter.name))
.filter(plugin => !plugin.adapters || plugin.adapters.includes(adapter))
.flatMap(plugin => plugin.commandList);
}

Expand Down
32 changes: 11 additions & 21 deletions core/src/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Bot } from './types';
import { Adapter } from './adapter';
import { Message, segment } from './message';
import { Prompt } from './prompt';
import { App } from './app';

type Argv = {
name: string;
Expand Down Expand Up @@ -249,14 +250,12 @@ export class Command<A extends any[] = [], O = {}> {
}

async execute<AD extends Adapter>(
adapter: AD,
bot: Bot<AD>,
message: Message<AD>,
template = message.raw_message,
): Promise<Message.Segment | void> {
let runtime: Command.RunTime<AD, A, O> | void;
try {
runtime = this.parse(adapter, bot, message, template);
runtime = this.parse(template, message);
} catch (e: any) {
return segment.text(e.message);
}
Expand Down Expand Up @@ -383,26 +382,17 @@ export class Command<A extends any[] = [], O = {}> {
return argv;
}

match<AD extends Adapter>(adapter: AD, bot: Bot<AD>, message: Message<AD>, template: string): boolean {
match<AD extends Adapter>(template: string, message: Message<AD>, app: App): boolean {
try {
return !!this.parse(adapter, bot, message, template);
return !!this.parse(template, message);
} catch {
return false;
}
}

parse<AD extends Adapter>(
adapter: AD,
bot: Bot<AD>,
message: Message<AD>,
template: string,
): Command.RunTime<AD, A, O> | void {
parse<AD extends Adapter>(template: string, message: Message<AD>): Command.RunTime<AD, A, O> | void {
let argv = this.parseSugar(template);
if (!argv.name) {
if (bot.command_prefix) {
if (!template.startsWith(bot.command_prefix)) return;
template = template.replace(bot.command_prefix, '');
}
argv = this.parseArgv(template);
}
if (argv.name !== this.name) {
Expand All @@ -412,10 +402,10 @@ export class Command<A extends any[] = [], O = {}> {
Command.checkArgv(argv, this.argsConfig, this.optionsConfig);
return {
args: argv.args as A,
adapter: message.adapter,
bot: message.bot,
options: argv.options as O,
adapter,
bot,
prompt: new Prompt(adapter, bot, message),
prompt: new Prompt(message),
command: this,
message,
};
Expand All @@ -434,10 +424,10 @@ export function defineCommand<S extends string>(
): Command<ArgsType<S>>;
export function defineCommand<S extends string>(
decl: S,
...args: (ArgsType<S> | Command.Config)[]
...args: [ArgsType<S> | Command.Config, Command.Config?]
): Command<ArgsType<S>> {
const initialValue: ArgsType<S> | undefined = Array.isArray(args[0]) ? undefined : (args.shift() as ArgsType<S>);
const command = new Command<ArgsType<S>>(...(args as [Command.Config?]));
const command = new Command<ArgsType<S>>(...(args as [Command.Config]));
const argDeclArr = decl.split(' ').filter(Boolean);
for (let i = 0; i < argDeclArr.length; i++) {
const argDecl = argDeclArr[i];
Expand Down Expand Up @@ -527,8 +517,8 @@ export namespace Command {

export type RunTime<AD extends Adapter, A extends any[] = [], O = {}> = {
args: A;
adapter: AD;
options: O;
adapter: AD;
bot: Bot<AD>;
prompt: Prompt<AD>;
message: Message<AD>;
Expand Down
6 changes: 3 additions & 3 deletions core/src/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export function parseFromTemplate(template: string | MessageElem): MessageElem[]
);
if (child) {
// TODO temporarily use 'message' as the key of the child MessageElem
data.message = parseFromTemplate(child).map(({ type, data }) => ({ type, ...data }))
data.message = parseFromTemplate(child).map(({ type, data }) => ({ type, ...data }));
}
result.push({
type: type,
Expand Down Expand Up @@ -108,7 +108,7 @@ export namespace Message {
export type Type = 'private' | 'group' | 'guild' | 'direct';
export function fromEvent<AD extends Adapter>(adapter: AD, bot: Bot<AD>, message: AdapterReceive<AD>) {
const result = new Message(adapter, bot, message);
result.prompt = new Prompt(adapter, bot, result);
result.prompt = new Prompt(result);
return result;
}
export function fromJSON<AD extends Adapter>(adapter: AD, bot: Bot<AD>, json: MessageBase) {
Expand All @@ -117,7 +117,7 @@ export namespace Message {
result.sender = json.sender;
result.message_type = json.message_type;
result.raw_message = json.raw_message;
result.prompt = new Prompt(adapter, bot, result);
result.prompt = new Prompt(result);
return result;
}
}
Expand Down
19 changes: 9 additions & 10 deletions core/src/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ import { Middleware } from './middleware';
import { Bot } from './types';
import { Message } from './message';
import { Schema } from './schema';
import { App } from './app';

export class Prompt<T extends Adapter = Adapter> {
constructor(
private adapter: T,
private bot: Bot<T>,
private event: Message<T>,
) {}
private getChannelAddress<AD extends Adapter>(adapter: AD, bot: Bot<AD>, event: Message<AD>) {
return `${adapter.name}-${bot.unique_id}-${event.message_type}:${event.sender!.user_id}`;
constructor(private event: Message<T>) {}
get app() {
return this.event.adapter.app;
}
private getChannelAddress<AD extends Adapter>(event: Message<AD>) {
return `${event.adapter}-${event.bot.unique_id}-${event.message_type}:${event.sender!.user_id}`;
}
private prompt<T = any>(config: Prompt.Config<T>) {
return new Promise<T>((resolve, reject) => {
Expand All @@ -34,13 +34,12 @@ export class Prompt<T extends Adapter = Adapter> {
}
middleware(callback: (input: string | Error) => any, timeout: number = 3 * 60 * 1000, timeoutText = '输入超时') {
const middleware: Middleware = (adapter, bot, event, next) => {
if (this.getChannelAddress(adapter, bot, event) !== this.getChannelAddress(this.adapter, this.bot, this.event))
return next();
if (this.getChannelAddress(event) !== this.getChannelAddress(this.event)) return next();
callback(event.raw_message);
dispose();
clearTimeout(timer);
};
const dispose = this.adapter.app!.middleware(middleware);
const dispose = this.app!.middleware(middleware);
const timer = setTimeout(() => {
dispose();
callback(new Error(timeoutText));
Expand Down
22 changes: 10 additions & 12 deletions packages/plugins/client/app/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import '@ionic/vue/css/text-alignment.css';
import '@ionic/vue/css/text-transformation.css';
import '@ionic/vue/css/flex-utils.css';
import '@ionic/vue/css/display.css';
import { router, useCommonStore } from '@zhinjs/client';
import { addPage, router, useCommonStore } from '@zhinjs/client';
import App from './App.vue';
const pinia = createPinia();
const wsUrl = `${window.location.protocol.replace(/^http?/, 'ws')}${window.location.host}/server`;
Expand All @@ -41,20 +41,18 @@ ws.onmessage = message => {
ws.onclose = () => {
console.log('connection closed');
};

const app = createApp(App);
app.use(pinia).use(router).use(IonicVue);
app.config.globalProperties.$ws = ws;
router.addRoute({
path: '/',
name: 'Zhin',
component: () => import('./pages/$.vue'),
children: [
{
path: '',
name: '首页',
component: () => import('./pages/dashboard.vue'),
},
],
});
const app = createApp(App);
app.use(pinia).use(router).use(IonicVue);
app.config.globalProperties.$ws = ws;
addPage({
parentName: 'Zhin',
path: '/',
name: 'Dashboard',
component: () => import('./pages/dashboard.vue'),
});
app.mount('#app');
17 changes: 8 additions & 9 deletions packages/plugins/client/app/src/pages/$.vue
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
<ion-menu content-id="main-content">
<ion-header>
<ion-toolbar>
<ion-title>菜单</ion-title>
<ion-title>Menus</ion-title>
</ion-toolbar>
</ion-header>
<ion-content class="ion-padding">
Expand Down Expand Up @@ -31,13 +31,9 @@
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router';
const menus = computed(() => {
return useRouter()
.getRoutes()
.filter(item => !item.children?.length);
});
console.log(useRouter().getRoutes());
import { useCommonStore } from '@zhinjs/client';
import { computed } from 'vue';
import {
IonContent,
IonMenu,
Expand All @@ -52,5 +48,8 @@ import {
IonTitle,
IonToolbar,
} from '@ionic/vue';
import { computed } from 'vue';
const menus = computed(() => {
return useCommonStore().store.menus || [];
});
console.log(menus);
</script>
3 changes: 2 additions & 1 deletion packages/services/http-server/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,8 @@ server.listen(
() => {
const address = server.address();
if (!address) return;
httpServer.app?.logger.mark('server start at', address);
const visitAddress = typeof address === 'string' ? address : `${address.address}:${address.port}`;
httpServer.app?.logger.mark(`server is running at http://${visitAddress}`);
httpServer.app?.logger.info('your username is:', username);
httpServer.app?.logger.info('your password is:', password);
},
Expand Down
4 changes: 2 additions & 2 deletions packages/services/sandbox/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,9 +102,9 @@ sandbox.mounted(() => {
if (!context.children) return '';
const result = await renderWithRuntime(context.children, {}, context.$root);
const { adapter, bot } = context.$message;
const commands = sandbox.app!.getSupportCommands(adapter, bot, context.$message);
const commands = sandbox.app!.getSupportCommands(adapter.name);
for (const command of commands) {
const res = await command.execute(adapter, bot, context.$message, `${bot.command_prefix}${result}`);
const res = await command.execute(context.$message, result);
if (res) return res;
}
throw new Error(`执行${context.children}失败,未找到合适的指令`);
Expand Down
5 changes: 2 additions & 3 deletions test/plugins/foo.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { context, setOptions } from 'zhin';
import { useMiddleware, useCommand, setOptions } from 'zhin';
setOptions({
name: 'foo',
});
const { useMiddleware, useCommand } = context;
useCommand('foo')
.hidden()
.action(({ bot }) => {
return 'bar';
return 'bar1';
});

useCommand('bar')
Expand Down
16 changes: 8 additions & 8 deletions test/plugins/forwardForum.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,21 +84,21 @@ forwardForum.middleware<OneBotV12Adapter>(async (adapter, bot, event, next) => {
const [textSeg, forumSeg] = message;
if (!forumSeg || typeof forumSeg !== 'object' || forumSeg.type !== 'forum') return;
const { user_id, user_name } = event.sender || {};
const { guild_id, guild_name, channel_id, channel_name } = event.original;
const { guild_id, guild_name, channel_id, channel_name } = event.original!;
const configs = configList.filter(config => {
return config.guild_id === String(guild_id) && config.channel_id === String(channel_id);
});
if (!configs.length) return;
const forumUrl = await bot.getForumUrl(guild_id, channel_id, forumSeg.data.id);
const forumUrl = await bot.getForumUrl(guild_id!, channel_id!, forumSeg.data.id);
for (const config of configs) {
const { group_id, template } = config;
const message = template
.replace('{guild_name}', guild_name)
.replace('{guild_id}', guild_id)
.replace('{channel_name}', channel_name)
.replace('{channel_id}', channel_id)
.replace('{user_name}', user_name)
.replace('{user_id}', user_id)
.replace('{guild_name}', guild_name!)
.replace('{guild_id}', guild_id!)
.replace('{channel_name}', channel_name!)
.replace('{channel_id}', channel_id!)
.replace('{user_name}', user_name!)
.replace('{user_id}', `${user_id}`)
.replace('{title}', typeof textSeg === 'string' ? textSeg : textSeg.data.text)
.replace('{url}', forumUrl);
await bot.sendGroupMsg(group_id, message);
Expand Down
2 changes: 1 addition & 1 deletion zhin/src/adapters/processAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ const messageHandler = (bot: Adapter.Bot<NodeJS.Process>, event: Buffer) => {
user_name: bot.title,
permissions: ['admin', 'master', 'normal'],
};
const commands = processAdapter.app!.getSupportCommands(processAdapter, bot, message);
const commands = processAdapter.app!.getSupportCommands(processAdapter.name);
const matchReg = new RegExp(`^/(${commands.map(c => c.name).join('|')})`);
if (message.raw_message.match(matchReg)) message.raw_message = message.raw_message.slice(1);
processAdapter.logger.info(`recv [${message.message_type} ${message.from_id}]: ${message.raw_message}`);
Expand Down
13 changes: 9 additions & 4 deletions zhin/src/plugins/commandParser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,14 @@ declare module '@zhinjs/core' {
}
}
const executeCommand = async (message: Message) => {
const commands = commandParser.app!.getSupportCommands(message.adapter, message.bot, message);
let template = message.raw_message;
if (message.bot.command_prefix) {
if (!template.startsWith(message.bot.command_prefix)) return;
template = template.replace(message.bot.command_prefix, '');
}
const commands = commandParser.app!.getSupportCommands(message.adapter.name);
for (const command of commands) {
const result = await command.execute(message.adapter, message.bot, message, message.raw_message);
const result = await command.execute(message, template);
if (result) {
await message.reply(result);
return true;
Expand All @@ -28,8 +33,8 @@ commandParser
.desc('输出指令提示文本')
.alias('tip')
.option('-H [showHidden:boolean] 显示隐藏指令')
.action(({ options, adapter, bot, message }, target) => {
const supportCommands = commandParser.app!.getSupportCommands(adapter, bot, message);
.action(({ options, message }, target) => {
const supportCommands = commandParser.app!.getSupportCommands(message.adapter.name);
if (!target) {
const commands = supportCommands.filter(cmd => {
if (options.showHidden) return cmd.parent === null;
Expand Down
8 changes: 4 additions & 4 deletions zhin/src/plugins/hmr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,13 +90,13 @@ hmr
.command('zhin.restart')
.desc('重启项目')
.permission('master')
.action(async ({ bot, adapter, message }) => {
.action(async ({ message }) => {
await message.reply('正在重启');
process.send?.({
type: 'queue',
body: {
adapter: adapter.name,
bot: bot.unique_id,
adapter: message.adapter.name,
bot: message.bot.unique_id,
target_id: message.from_id,
target_type: message.message_type,
message: `已完成重启`,
Expand All @@ -108,7 +108,7 @@ hmr
.command('zhin.exit')
.desc('退出zhin')
.permission('master')
.action(async ({ bot, adapter, message }) => {
.action(async ({ message }) => {
await message.reply('正在退出');
process.exit();
});
Expand Down
Loading

0 comments on commit 3d12cff

Please sign in to comment.