码桶
发现社区成员的开源项目
bot.js2 KB
/**
* 机器人模型 — 对应 PHP lib/bot.php
*/
const crypto = require('crypto');
const db = require('./db');
const config = require('../config');
class Bot {
/** 生成不重复的机器人码(去除了易混字符) */
static async genCode() {
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
const len = config.botcode_len;
let code;
do {
code = '';
const bytes = crypto.randomBytes(len);
for (let i = 0; i < len; i++) {
code += chars[bytes[i] % chars.length];
}
} while (await db.row('SELECT id FROM bots WHERE bot_code = ?', [code]));
return code;
}
/** 生成默认机器人名称:奶狗bot_ + 6位随机字母数字 */
static genName() {
const chars = 'abcdefghijklmnopqrstuvwxyz0123456789';
const bytes = crypto.randomBytes(6);
let s = '';
for (let i = 0; i < 6; i++) s += chars[bytes[i] % chars.length];
return '奶狗bot_' + s;
}
/** 创建一台新机器人 */
static async create(userId) {
const code = await Bot.genCode();
const name = Bot.genName();
const now = Math.floor(Date.now() / 1000);
await db.exec(
'INSERT INTO bots (user_id, bot_code, name, login_status, updated_at) VALUES (?, ?, ?, ?, ?)',
[userId, code, name, 'none', now]
);
const id = await db.lastInsertId();
// 智能助手已是内置核心功能(固定设置、强制运行),无需在 plugins 表登记,故不再自动安装。
return db.row('SELECT * FROM bots WHERE id = ?', [id]);
}
/** 列出某用户的全部机器人 */
static async list(userId) {
return db.rows(
'SELECT id, bot_code, name, login_status, wechat_uin, bind_at FROM bots WHERE user_id = ? ORDER BY id',
[userId]
);
}
/** 取某机器人并校验归属 */
static async owned(botId, userId) {
return db.row('SELECT * FROM bots WHERE id = ? AND user_id = ?', [botId, userId]);
}
}
module.exports = Bot;