使用ctx.database.extend报错

2024-10-07 16:31:42 [I] j-integral 欢迎使用积分系统
2024-10-07 16:31:42 [I] j-integral 开始初始化
2024-10-07 16:31:42 [I] j-integral 开始初始化数据库
2024-10-07 16:31:42 [W] app Error: property database is not registered, declare it as `inject` to suppress this warning
                            at Object.apply (D:\bot\koishi\koishi-app\external\j-integral\src\index.ts:32:9)
                            at MainScope.apply (D:\bot\koishi\koishi-app\node_modules\@cordisjs\core\src\scope.ts:362:26)
                            at <anonymous> (D:\bot\koishi\koishi-app\node_modules\@cordisjs\core\src\scope.ts:389:49)
                            at MainScope.ensure (D:\bot\koishi\koishi-app\node_modules\@cordisjs\core\src\scope.ts:150:18)
                            at MainScope.start (D:\bot\koishi\koishi-app\node_modules\@cordisjs\core\src\scope.ts:389:12)
                            at MainScope.init (D:\bot\koishi\koishi-app\node_modules\@cordisjs\core\src\scope.ts:189:12)
                            at new MainScope (D:\bot\koishi\koishi-app\node_modules\@cordisjs\core\src\scope.ts:327:12)
                            at Proxy.plugin (D:\bot\koishi\koishi-app\node_modules\@cordisjs\core\src\registry.ts:207:15)
                            at Proxy.forkPlugin (D:\bot\koishi\koishi-app\node_modules\@koishijs\loader\src\shared.ts:313:19)
2024-10-07 16:31:43 [E] app TypeError: Cannot read properties of undefined (reading 'extend')
                            at Object.apply (D:\bot\koishi\koishi-app\external\j-integral\src\index.ts:32:18)
                            at MainScope.apply (D:\bot\koishi\koishi-app\node_modules\@cordisjs\core\src\scope.ts:362:26)
                            at <anonymous> (D:\bot\koishi\koishi-app\node_modules\@cordisjs\core\src\scope.ts:389:49)
                            at MainScope.ensure (D:\bot\koishi\koishi-app\node_modules\@cordisjs\core\src\scope.ts:150:18)
                            at MainScope.start (D:\bot\koishi\koishi-app\node_modules\@cordisjs\core\src\scope.ts:389:12)
                            at MainScope.init (D:\bot\koishi\koishi-app\node_modules\@cordisjs\core\src\scope.ts:189:12)
                            at new MainScope (D:\bot\koishi\koishi-app\node_modules\@cordisjs\core\src\scope.ts:327:12)
                            at Proxy.plugin (D:\bot\koishi\koishi-app\node_modules\@cordisjs\core\src\registry.ts:207:15)
                            at Proxy.forkPlugin (D:\bot\koishi\koishi-app\node_modules\@koishijs\loader\src\shared.ts:313:19)
                            at async Proxy.reload (D:\bot\koishi\koishi-app\node_modules\@koishijs\loader\src\shared.ts:343:16)

可能出现错误的代码:

    logger.info('欢迎使用积分系统');
    logger.info('开始初始化');
    logger.info('开始初始化数据库');
    ctx.database.extend("users",{ID: "string", integral: "string", grade: "string", FinalSignin: "string"},{primary: "ID"   });
    logger.info('初始化users数据库成功');
    ctx.database.extend("config",{name: "string",  value: "string",},{primary: "name"   });
    logger.info('初始化config数据库成功');

系统信息
image

数据库可以正常创建
就是不知道为啥报错

2 个赞
完整代码
import { Schema } from 'koishi'
import { Time, h } from "koishi"

export const name = "j-integral"

export interface Config {
  SignInMax: number
  SignInMin: number
}

export const Config: Schema<Config> = Schema.object({
  SignInMax: Schema.number().default(1),
  SignInMin: Schema.number().default(10),
})
export async function apply(ctx,config){
  const logger = ctx.logger("j-integral")
  
  function mathRandomInt(a, b) {
    if (a > b) {
      // Swap a and b to ensure a is smaller.
      var c = a;
      a = b;
      b = c;
    }
    return Math.floor(Math.random() * (b - a + 1) + a);
  }
  
  
    logger.info('欢迎使用积分系统');
    logger.info('开始初始化');
    logger.info('开始初始化数据库');
    ctx.database.extend("users",{ID: "string", integral: "string", grade: "string", FinalSignin: "string"},{primary: "ID"   });
    logger.info('初始化users数据库成功');
    ctx.database.extend("config",{name: "string",  value: "string",},{primary: "name"   });
    logger.info('初始化config数据库成功');
  
  ctx.middleware(async (session,next)=>{
    if ((((await ctx.database.get('users',{ID:([session.bot.sid,'.',session.userId].join(''))}))[0]?.ID)) == null) {
      ctx.database.upsert('users',[{ID: ([session.bot.sid,'.',session.userId].join('')), integral: "0", grade: "0",}],['ID']);
      logger.info((['用户',[session.bot.sid,'.',session.userId].join(''),'注册成功'].join('')));
    }
    return next();
  })
  ctx.command('我是主人').action(async ({session},...args)=>{
    if ((((await ctx.database.get('config',{name: "owner"}))[0]?.value)) == null) {
      ctx.database.upsert('users',[{ID: ([session.bot.sid,'.',session.userId].join('')), grade: "10",}],['ID']);
      ctx.database.upsert('config',[{name: "owner", value: "True",}],['name']);
      return (String(h('at',{ id: (session.userId) })) + '主人你好,欢迎使用积分系统');
    }
    return '权限不足';
  
  });
  
  ctx.command('我的信息').action(async ({session},...args)=>{
    await session.send(('ID:' + String(([session.bot.sid,'.',session.userId].join('')))));
    await session.send(('积分:' + String(((await ctx.database.get('users',{ID: ([session.bot.sid,'.',session.userId].join(''))}))[0]?.integral))));
    return ('权限等级:' + String(((await ctx.database.get('users',{ID: ([session.bot.sid,'.',session.userId].join(''))}))[0]?.grade)));
  
  });
  
  ctx.command('签到').action(async ({session},...args)=>{
    // 判断日期
    if (Number((Time.template('yyyy',new Date((Math.round(Number(new Date()) )))))) >= Number(((((await ctx.database.get('users',{ID: ([session.bot.sid,'.',session.userId].join(''))}))[0]?.FinalSignin)).slice(0, 4))) && Number((Time.template('MM',new Date((Math.round(Number(new Date()) )))))) >= Number(((((await ctx.database.get('users',{ID: ([session.bot.sid,'.',session.userId].join(''))}))[0]?.FinalSignin)).slice(5, 7))) && Number((Time.template('dd',new Date((Math.round(Number(new Date()) )))))) > Number(((((await ctx.database.get('users',{ID: ([session.bot.sid,'.',session.userId].join(''))}))[0]?.FinalSignin)).slice(8, 10)))) {
      {
        let x = mathRandomInt(Number(config.SignInMax), Number(config.SignInMin));
        ctx.database.upsert('users',[{ID: ([session.bot.sid,'.',session.userId].join('')), integral: String(Number(x)+Number(((await ctx.database.get('users',{ID: ([session.bot.sid,'.',session.userId].join(''))}))[0]?.integral))),}],['ID']);
        ctx.database.upsert('users',[{ID: ([session.bot.sid,'.',session.userId].join('')), FinalSignin: (Time.template('yyyy-MM-dd',new Date((Math.round(Number(new Date()) ))))),}],['ID']);
        return (['签到成功,获得',x,'积分'].join(''));
      }
    } else {
      return '今天你已经签到过了!';
    }
  
  });
  
  ctx.command('管理.添加管理 <id>').action(async ({session},...args)=>{
    if ((((await ctx.database.get('users',{ID: ([session.bot.sid,'.',session.userId].join(''))}))[0]?.grade)) >= 10) {
      ctx.database.upsert('users',[{ID: ([session.bot.sid,'.',((args[0])).match(new RegExp("[1-9]([0-9]{5,11})", "g"))].join('')), grade: "10",}],['ID']);
      return '提交成功';
    }
    return '权限不足';
  
  });
  
  ctx.command('管理.给予积分 <id> <积分:number>').action(async ({session},...args)=>{
    if ((((await ctx.database.get('users',{ID: ([session.bot.sid,'.',session.userId].join(''))}))[0]?.grade)) >= 10) {
      ctx.database.upsert('users',[{ID: ([session.bot.sid,'.',((args[0])).match(new RegExp("[1-9]([0-9]{5,11})", "g"))].join('')), integral: String(args[1]+Number(((await ctx.database.get('users',{ID: ([session.bot.sid,'.',((args[0])).match(new RegExp("[1-9]([0-9]{5,11})", "g"))].join(''))}))[0]?.integral))),}],['ID']);
      return '添加成功';
    }
    return '权限不足';
  
  });
  
  ctx.command('管理.扣除积分 <id> <积分:number>').action(async ({session},...args)=>{
    if ((((await ctx.database.get('users',{ID: ([session.bot.sid,'.',session.userId].join(''))}))[0]?.grade)) >= 10) {
      ctx.database.upsert('users',[{ID: ([session.bot.sid,'.',session.userId].join('')), integral: String(Number(((await ctx.database.get('users',{ID: ([session.bot.sid,'.',session.userId].join(''))}))[0]?.integral))-Number(args[1])),}],['ID']);
      return '扣除成功';
    }
    return '权限不足';
  
  });
  
  ctx.command('管理 <参数名称>').action(async ({session},...args)=>{
    return null;
  
  });
  
}
1 个赞

ctx.model.extend 而不是 ctx.database.extend

2 个赞

哦,谢谢
(blockly中抄的)

2 个赞

对了,这两个有啥区别吗

以及我下面的代码是否也要修改

2 个赞

一个是错的,一个是对的

看上去没什么问题

2 个赞

en
改完了,在加载到时候不会报错了,但是一用数据库就error

2024-10-08 18:07:42 [W] app Error: property database is not registered, declare it as `inject` to suppress this warning
                            at _Command.<anonymous> (D:\bot\koishi\koishi-app\external\j-integral\src\index.ts:66:109)
                            at Array.<anonymous> (D:\bot\koishi\koishi-app\node_modules\@koishijs\core\src\command\command.ts:291:27)
                            at Object.argv.next (D:\bot\koishi\koishi-app\node_modules\@koishijs\core\src\command\command.ts:303:27)
                            at _Command.execute (D:\bot\koishi\koishi-app\node_modules\@koishijs\core\src\command\command.ts:307:33)
                            at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
                            at async <anonymous> (D:\bot\koishi\koishi-app\node_modules\@koishijs\core\src\session.ts:443:22)
                            at async Proxy.withScope (D:\bot\koishi\koishi-app\node_modules\@koishijs\core\src\session.ts:342:22)
                            at async next (D:\bot\koishi\koishi-app\node_modules\@koishijs\core\src\middleware.ts:258:16)
                            at async next (D:\bot\koishi\koishi-app\node_modules\@koishijs\core\src\middleware.ts:258:16)
2024-10-08 18:07:42 [W] command 签到 
                        TypeError: Cannot read properties of undefined (reading 'slice')
                            at _Command.<anonymous> (D:\bot\koishi\koishi-app\external\j-integral\src\index.ts:66:204)
                            at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
                            at async Array.<anonymous> (D:\bot\koishi\koishi-app\node_modules\@koishijs\core\src\command\command.ts:291:14)
                            at async _Command.execute (D:\bot\koishi\koishi-app\node_modules\@koishijs\core\src\command\command.ts:307:22)
                            at async <anonymous> (D:\bot\koishi\koishi-app\node_modules\@koishijs\core\src\session.ts:443:22)
                            at async Proxy.withScope (D:\bot\koishi\koishi-app\node_modules\@koishijs\core\src\session.ts:342:22)
                            at async next (D:\bot\koishi\koishi-app\node_modules\@koishijs\core\src\middleware.ts:258:16)
                            at async next (D:\bot\koishi\koishi-app\node_modules\@koishijs\core\src\middleware.ts:258:16)
                            at async Processor._handleMessage (D:\bot\koishi\koishi-app\node_modules\@koishijs\core\src\middleware.ts:269:22)
2 个赞

哥们你这行有问题,是不是 await 括号没套好套到 Promise 上了
还有请你能别塞到一行里吗谢谢
展开一下,写几个 const 声明变量()
@jandy

2 个赞

这个,在代码 export const name = 下一行写一个

export const inject = ['database'];
2 个赞

把报错的部分贴出来

2 个赞

还是 Number ... Time.template 这一行
我记得 Time 有一个时间戳,对比那个就行

2 个赞

仍然这一行,他的下面,你为什么写两层 {}
而且两层中间没有内容,多废一层缩进(

2 个赞

知道bug了,数据库问题(这个沙盒没初始化用户)

2 个赞

对。。。
也有可能是没初始化
他没返回数据你最好加个处理 :slight_smile:

2 个赞