UNPKG

amesu

Version:
64 lines (63 loc) 1.89 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Token = void 0; const common_1 = require("../utils/common"); const logger_1 = require("../utils/logger"); /** * 获取接口凭证 * * @param appId - 在开放平台管理端上获得。 * @param clientSecret - 在开放平台管理端上获得。 */ async function getAppAccessToken(appId, clientSecret) { const response = await fetch('https://bots.qq.com/app/getAppAccessToken', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ appId, clientSecret, }), }); return response.json(); } class Token { config; value; /** 有效期 */ lifespan; /** 记录器 */ logger; constructor(config) { this.config = config; this.value = ''; this.lifespan = 0; this.logger = (0, logger_1.getLogger)(config.appid); } get authorization() { return `QQBot ${this.value}`; } get is_expires() { return this.lifespan - Date.now() < 6000; } async renew() { if (!this.is_expires) { return; } const { appid, secret } = this.config; try { this.logger.trace('开始获取 token 令牌...'); const data = await getAppAccessToken(appid, secret); const timestamp = Date.now(); this.value = data.access_token; this.lifespan = timestamp + data.expires_in * 1000; this.logger.debug(`Token: ${(0, common_1.objectToString)(data)}`); } catch (error) { this.logger.error('获取 token 失败,请检查网络以及 appid 等参数是否有效'); throw new Error('Please check the config parameter is correct'); } } } exports.Token = Token;