node-napcat-ts
Version:
napcat SDK for Node
66 lines (65 loc) • 1.88 kB
JavaScript
const getTime = () => new Date().toLocaleString();
export const logger = {
warn: (...args) => {
console.warn(`[${getTime()}]`, ...args);
},
debug: (...args) => {
console.debug(`[${getTime()}]`, ...args);
},
dir: (json) => {
console.dir(json, { depth: null });
},
};
export const SPLIT = /(?=\[CQ:)|(?<=])/;
export const CQ_TAG_REGEXP = /^\[CQ:([a-z]+)(?:,([^\]]+))?]$/;
/**
* CQ码转JSON
*/
export function convertCQCodeToJSON(msg) {
return CQCodeDecode(msg)
.split(SPLIT)
.map((tagStr) => {
const match = CQ_TAG_REGEXP.exec(tagStr);
if (match === null)
return { type: 'text', data: { text: tagStr } };
const [, tagName, value] = match;
if (value === undefined)
return { type: tagName, data: {} };
const data = Object.fromEntries(value.split(',').map((item) => item.split('=')));
return { type: tagName, data };
});
}
const _conver = (json) => {
if (json.type === 'text')
return json.data.text;
return `[CQ:${json.type}${Object.entries(json.data)
.map(([k, v]) => (v ? `,${k}=${v}` : ''))
.join('')}]`;
};
/**
* JSON转CQ码
*/
export function convertJSONToCQCode(json) {
if (Array.isArray(json)) {
return json.map((item) => _conver(item)).join('');
}
else {
return _conver(json);
}
}
export function CQCodeDecode(str) {
if (typeof str !== 'string')
return String(str || ''); // 尝试转换为字符串,或返回空字符串
return str
.replace(/,/g, ',')
.replace(/[/g, '[')
.replace(/]/g, ']')
.replace(/&/g, '&');
}
export function CQCodeEncode(str) {
return str
.replace(/,/g, ',')
.replace(/\[/g, '[')
.replace(/]/g, ']')
.replace(/&/g, '&');
}