heybox-bot
Version:
A heybox chat bot frame
289 lines • 9.64 kB
JavaScript
;
// noinspection JSUnusedGlobalSymbols
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SeededRandom = exports.Request = exports.Util = exports.HeyboxBotRuntimeContext = void 0;
/**
* 导入常量和必要模块
*/
const constants_1 = __importDefault(require("../constants"));
const axios_1 = __importDefault(require("axios"));
const fs = __importStar(require("node:fs"));
const form_data_1 = __importDefault(require("form-data"));
const path = __importStar(require("path"));
const mime_types_1 = __importDefault(require("mime-types"));
const deasync_1 = __importDefault(require("deasync"));
/**
* HeyboxBot运行时上下文类,用于存储和提供全局的Bot实例和Logger实例
*/
class HeyboxBotRuntimeContext {
/**
* 获取Bot实例
* @returns {HeyBoxBot} Bot实例
* @throws {Error} 如果Bot未初始化
*/
static getBot() {
if (HeyboxBotRuntimeContext.bot === undefined) {
throw new Error('Bot not initialized');
}
return HeyboxBotRuntimeContext.bot;
}
/**
* 设置Bot实例
* @param {HeyBoxBot} bot Bot实例
*/
static setBot(bot) {
HeyboxBotRuntimeContext.bot = bot;
}
/**
* 获取Logger实例
* @returns {Logger} Logger实例
* @throws {Error} 如果Logger未初始化
*/
static getLogger() {
if (HeyboxBotRuntimeContext.logger === undefined) {
throw new Error('Logger not initialized');
}
return HeyboxBotRuntimeContext.logger;
}
/**
* 设置Logger实例
* @param {Logger} logger Logger实例
*/
static setLogger(logger) {
HeyboxBotRuntimeContext.logger = logger;
}
}
exports.HeyboxBotRuntimeContext = HeyboxBotRuntimeContext;
HeyboxBotRuntimeContext.bot = undefined;
HeyboxBotRuntimeContext.logger = undefined;
/**
* 工具类,提供日志记录、获取确认ID、获取代理配置和字符串哈希功能
*/
class Util {
/**
* 获取确认ID
* @returns {number} 确认ID
*/
static getAckId() {
return Util.ackID++;
}
/**
* 获取代理配置
* @returns 代理配置对象或未定义
*/
static getProxy() {
return HeyboxBotRuntimeContext.getBot().getConfig().proxy;
}
/**
* 使用DJB2算法计算字符串哈希值
* @param {string} str 输入字符串
* @returns {number} 哈希值
*/
static hashDJB2(str) {
let hash = 5381;
for (let i = 0; i < str.length; i++) {
hash = (hash * 33) ^ str.charCodeAt(i);
}
return hash >>> 0; // 确保结果为非负整数
}
}
exports.Util = Util;
Util.ackID = Number.parseInt(Math.floor(Math.random() * 1000000).toString(10));
Util.log = {
debug: msg => {
HeyboxBotRuntimeContext.getLogger().debug(msg);
},
error: msg => {
HeyboxBotRuntimeContext.getLogger().error(msg);
},
info: msg => {
HeyboxBotRuntimeContext.getLogger().info(msg);
},
warning: msg => {
HeyboxBotRuntimeContext.getLogger().warning(msg);
}
};
/**
* 请求类,处理与服务器的HTTP交互
*/
class Request {
static getInstance() {
return (this.instance ||
(this.instance = axios_1.default.create({
baseURL: Request.BASE_URL,
timeout: 15000,
headers: {
'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Cache-Control': 'no-cache',
'Pragma': 'no-cache',
'Content-Type': 'application/json;charset=UTF-8',
'token': HeyboxBotRuntimeContext.getBot().getConfig().token
},
proxy: Util.getProxy()
})));
}
/**
* 发送消息
* @param {Message} payload 消息负载
*/
static async sendMessage(payload) {
const url = `${constants_1.default.SEND_MSG_URL}${constants_1.default.COMMON_PARAMS}`;
Util.log.debug(`send message: ${JSON.stringify(payload)}`);
Request.getInstance().post(url, payload).then();
}
/**
* 发送用户消息
* @param {UserMessage} payload 用户消息负载
*/
static async sendUserMessage(payload) {
const url = `${constants_1.default.SEND_USER_MSG_URL}${constants_1.default.COMMON_PARAMS}`;
Util.log.debug(`send user message: ${JSON.stringify(payload)}`);
Request.getInstance().post(url, payload).then();
}
/**
* 上传文件
* @param {BufferSource | string} file 文件内容或文件路径
* @returns {Promise<string>} 上传后的文件URL
*/
static async uploadFile(file) {
if (typeof file === 'string' && file.includes(constants_1.default.CDN_URL))
return Promise.resolve(file);
let fileName = '';
if (typeof file === 'string') {
if (file.startsWith('http')) {
let response = await axios_1.default.get(file, {
responseType: 'arraybuffer',
proxy: Util.getProxy()
});
file = Buffer.from(response.data, 'binary');
const mimeType = response.headers['Content-Type'] ||
response.headers['content-type'] ||
'application/octet-stream';
fileName = `file.${mime_types_1.default.extension(mimeType)}`;
}
else {
fileName = path.parse(file).name;
file = fs.readFileSync(file);
}
}
const url = `${constants_1.default.UPLOAD_URL}${constants_1.default.COMMON_PARAMS}`;
const payload = new form_data_1.default();
payload.append('file', file, fileName);
Util.log.debug(`upload file: <${fileName}>`);
return new Promise((resolve, reject) => {
Request.getInstance().post(url, payload, {
transformRequest: [
(data, headers) => {
delete headers['Content-Type']; // 让 axios 自动设置 Content-Type
return data;
}
]
})
.then(value => {
const data = value.data;
if (data.status == 'ok') {
resolve(data.result.url);
}
else {
reject(data);
}
})
.catch(reject);
});
}
/**
* 同步方式上传文件
* @param {BufferSource | string} file 文件内容或文件路径
* @returns {string} 上传后的文件URL
*/
static uploadFileSync(file) {
let cdnUrl = '';
let done = false;
Request.uploadFile(file)
.then(res => {
done = true;
cdnUrl = res;
})
.catch(err => {
Util.log.error(JSON.stringify(err));
done = true;
});
deasync_1.default.loopWhile(() => !done);
return cdnUrl;
}
}
exports.Request = Request;
Request.BASE_URL = `${constants_1.default.BASE_URL}`;
Request.instance = undefined;
/**
* 基于种子的随机数生成器类
*/
class SeededRandom {
/**
* 构造函数
* @param {number} seed 种子
*/
constructor(seed) {
this.seed = seed;
this.m = 0x80000000; // 2^31
this.a = 1103515245;
this.c = 12345;
this.state = ((seed % this.m) + this.m) % this.m;
}
/**
* 生成下一个随机数
* @returns {number} 随机数
*/
next() {
this.state = (this.a * this.state + this.c) % this.m;
return this.state / this.m;
}
/**
* 生成下一个整数
* @param {number} min 最小值
* @param {number} max 最大值
* @returns {number} 随机整数
*/
nextInt(min, max) {
return Math.floor(this.next() * (max - min + 1)) + min;
}
}
exports.SeededRandom = SeededRandom;
//# sourceMappingURL=index.js.map