Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
93efce86ca | ||
|
|
091c012427 | ||
|
|
8a3faf64f9 | ||
|
|
fbd70bbb04 | ||
|
|
c405b6d0a4 | ||
|
|
3a4b335062 | ||
|
|
9aa11fd7c4 | ||
|
|
8ae11bfdca | ||
|
|
6acf350613 | ||
|
|
0af6445d5a | ||
|
|
a716a1a185 | ||
|
|
8c9fc7edf4 | ||
|
|
1abad76ac9 | ||
|
|
484c181050 | ||
|
|
9d652be35d | ||
|
|
f226c83595 | ||
|
|
b565f876c5 | ||
|
|
19a5febb1a | ||
|
|
bbf822035f | ||
|
|
a2b0ac10a0 | ||
|
|
279b3ea4eb | ||
|
|
33cc11ba84 | ||
|
|
b058604077 | ||
|
|
1c703a60ed | ||
|
|
285ba9cf2d | ||
|
|
b253fd82c4 | ||
|
|
8996b35dd1 | ||
|
|
25db6f0835 | ||
|
|
2c8f9743da | ||
|
|
fc26077283 | ||
|
|
e9bbc82f37 | ||
|
|
600f2a4518 | ||
|
|
abf57e688c | ||
|
|
d92a4cff8d | ||
|
|
e195aee5d2 | ||
|
|
014a32533d | ||
|
|
fa97d15c66 | ||
|
|
285632f463 | ||
|
|
6d63da4fa0 | ||
|
|
d849188ef2 | ||
|
|
45966f072e | ||
|
|
c235c92ce9 | ||
|
|
a62c9298ac | ||
|
|
c5bc48da1f | ||
|
|
4edb3385e4 | ||
|
|
10f961c552 | ||
|
|
0baf800d21 | ||
|
|
5c0fac7de6 | ||
|
|
c7109e20ad | ||
|
|
d61433f2a4 | ||
|
|
0ae05ccb8d | ||
|
|
973ccaebed | ||
|
|
59bd457a97 | ||
|
|
d70e06a4f5 | ||
|
|
e6f6468377 | ||
|
|
9d5f0ee604 | ||
|
|
07d4d80ab7 | ||
|
|
7a974d38d4 | ||
|
|
e9b74138d1 | ||
|
|
df0795f2c5 | ||
|
|
85b56e52ac | ||
|
|
77c89d0923 | ||
|
|
58b36cd331 | ||
|
|
deae7fd467 | ||
|
|
8b2207e109 | ||
|
|
f3b76e8b3a | ||
|
|
466d9a3c4f | ||
|
|
4af49c5761 | ||
|
|
442ad4f9a3 | ||
|
|
7ee2f1c40d | ||
|
|
7380665cc2 | ||
|
|
2c57faf117 | ||
|
|
8b0d186625 |
No files matched your search
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Bash(tasklist)",
|
||||
"Bash(sort -rk5)",
|
||||
"Bash(powershell \"Get-Process | Sort-Object CPU -Descending | Select-Object -First 15 Name,CPU,Id,WorkingSet | Format-Table -AutoSize\")",
|
||||
"Bash(powershell *)",
|
||||
"Bash(where ssh *)",
|
||||
"Bash(where plink *)",
|
||||
"Bash(where sshpass *)",
|
||||
"Bash(echo \"exit=$?\")",
|
||||
"Bash(python -c \"import paramiko; print\\('paramiko OK'\\)\")",
|
||||
"Bash(pnpm --filter napcat-common run typecheck)",
|
||||
"Bash(pnpm --filter napcat-core run typecheck)",
|
||||
"Bash(pnpm --filter napcat-onebot run typecheck)",
|
||||
"Bash(git *)"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,16 @@
|
||||
*/
|
||||
|
||||
export const COMMENT_MARKER = '<!-- napcat-pr-build -->';
|
||||
export const DOCKER_COMMENT_MARKER = '<!-- napcat-pr-docker -->';
|
||||
|
||||
// 默认代理前缀(加速中国大陆访问 GitHub Release)
|
||||
// 格式:https://ghfast.top/{full-github-url}
|
||||
export const PROXY_BASE = 'https://gh.llkk.cc';
|
||||
|
||||
/** 将 GitHub 直链转换为 ghfast.top 加速链接 */
|
||||
export function toProxyUrl (directUrl: string): string {
|
||||
return `${PROXY_BASE}/${directUrl}`;
|
||||
}
|
||||
|
||||
export type BuildStatus = 'success' | 'failure' | 'cancelled' | 'pending' | 'unknown';
|
||||
|
||||
@@ -105,12 +115,19 @@ export function generateBuildingComment (prSha: string, targets: string[]): stri
|
||||
|
||||
// ============== 构建结果评论 ==============
|
||||
|
||||
export interface InstallInfo {
|
||||
installUrl: string;
|
||||
releaseUrl: string;
|
||||
}
|
||||
|
||||
export function generateResultComment (
|
||||
targets: BuildTarget[],
|
||||
prSha: string,
|
||||
runId: string,
|
||||
repository: string,
|
||||
version?: string
|
||||
version?: string,
|
||||
installInfo?: InstallInfo,
|
||||
publishFailed?: boolean
|
||||
): string {
|
||||
const runUrl = `https://github.com/${repository}/actions/runs/${runId}`;
|
||||
const shortSha = formatSha(prSha);
|
||||
@@ -173,6 +190,41 @@ export function generateResultComment (
|
||||
`| 🕐 完成时间 | ${time} |`,
|
||||
];
|
||||
|
||||
// 添加快速安装命令
|
||||
if (installInfo) {
|
||||
const directUrl = installInfo.installUrl;
|
||||
const proxyInstallUrl = toProxyUrl(directUrl);
|
||||
lines.push(
|
||||
'',
|
||||
'---',
|
||||
'',
|
||||
'## 🚀 快速安装 (Linux)',
|
||||
'',
|
||||
'**直连(需要能访问 GitHub)**',
|
||||
'```bash',
|
||||
`curl -sSL ${directUrl} | bash`,
|
||||
'```',
|
||||
'',
|
||||
'**加速(国内推荐,ghfast.top)**',
|
||||
'```bash',
|
||||
`curl -sSL ${proxyInstallUrl} | bash`,
|
||||
'```',
|
||||
'',
|
||||
`> 📦 [查看 Release 页面](${installInfo.releaseUrl})`,
|
||||
'> ⚠️ 此为 PR 测试版本,约 5 天后会被自动清理。'
|
||||
);
|
||||
} else if (publishFailed) {
|
||||
lines.push(
|
||||
'',
|
||||
'---',
|
||||
'',
|
||||
'## ⚠️ Release 发布失败',
|
||||
'',
|
||||
'> ❌ PR Release 发布过程中出现错误,无法提供快速安装命令。',
|
||||
`> 🔗 [查看构建日志](${runUrl}) 了解详情。`
|
||||
);
|
||||
}
|
||||
|
||||
// 添加错误详情
|
||||
const failedTargets = targets.filter(t => t.status === 'failure' && t.error);
|
||||
if (failedTargets.length > 0) {
|
||||
@@ -228,3 +280,138 @@ export function generateResultComment (
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
// ============== Docker 构建评论 ==============
|
||||
|
||||
export function generateDockerBuildingComment (prNumber: string, prSha: string): string {
|
||||
const time = getTimeString();
|
||||
const shortSha = formatSha(prSha);
|
||||
|
||||
const lines: string[] = [
|
||||
DOCKER_COMMENT_MARKER,
|
||||
'',
|
||||
'<div align="center">',
|
||||
'',
|
||||
'# 🐳 Docker 测试镜像构建中',
|
||||
'',
|
||||
'',
|
||||
'',
|
||||
'</div>',
|
||||
'',
|
||||
'---',
|
||||
'',
|
||||
'## 📋 构建信息',
|
||||
'',
|
||||
'| 项目 | 值 |',
|
||||
'| :--- | :--- |',
|
||||
`| 📝 提交 | \`${shortSha}\` |`,
|
||||
`| 🔗 PR | #${prNumber} |`,
|
||||
`| 🕐 触发时间 | ${time} |`,
|
||||
'',
|
||||
'---',
|
||||
'',
|
||||
'<div align="center">',
|
||||
'',
|
||||
'> ⏳ **Docker 镜像正在构建中,请稍候...**',
|
||||
'>',
|
||||
'> 构建完成后将自动更新此评论',
|
||||
'',
|
||||
'</div>',
|
||||
];
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
export function generateDockerResultComment (
|
||||
prNumber: string,
|
||||
prSha: string,
|
||||
success: boolean,
|
||||
dockerImage?: string,
|
||||
error?: string
|
||||
): string {
|
||||
const time = getTimeString();
|
||||
const shortSha = formatSha(prSha);
|
||||
|
||||
const statusBadge = success
|
||||
? ''
|
||||
: '';
|
||||
const headerTitle = success ? '# ✅ Docker 测试镜像就绪' : '# ❌ Docker 测试镜像构建失败';
|
||||
|
||||
const lines: string[] = [
|
||||
DOCKER_COMMENT_MARKER,
|
||||
'',
|
||||
'<div align="center">',
|
||||
'',
|
||||
headerTitle,
|
||||
'',
|
||||
statusBadge,
|
||||
'',
|
||||
'</div>',
|
||||
'',
|
||||
'---',
|
||||
'',
|
||||
'## 📋 构建信息',
|
||||
'',
|
||||
'| 项目 | 值 |',
|
||||
'| :--- | :--- |',
|
||||
`| 📝 提交 | \`${shortSha}\` |`,
|
||||
`| 🔗 PR | #${prNumber} |`,
|
||||
`| 🕐 完成时间 | ${time} |`,
|
||||
];
|
||||
|
||||
if (success && dockerImage) {
|
||||
lines.push(
|
||||
'',
|
||||
'---',
|
||||
'',
|
||||
'## 🚀 快速使用',
|
||||
'',
|
||||
'```bash',
|
||||
`docker pull ${dockerImage}`,
|
||||
'```',
|
||||
'',
|
||||
'> ⚠️ 此为 PR 测试镜像,保留 5 天后自动清理。'
|
||||
);
|
||||
}
|
||||
|
||||
if (!success && error) {
|
||||
lines.push(
|
||||
'',
|
||||
'---',
|
||||
'',
|
||||
'<details>',
|
||||
'<summary>🔴 <b>错误详情</b></summary>',
|
||||
'',
|
||||
'```',
|
||||
escapeCodeBlock(error),
|
||||
'```',
|
||||
'',
|
||||
'</details>'
|
||||
);
|
||||
}
|
||||
|
||||
lines.push('', '---', '');
|
||||
if (success) {
|
||||
lines.push(
|
||||
'<div align="center">',
|
||||
'',
|
||||
'> 🎉 **Docker 测试镜像已就绪!**',
|
||||
'>',
|
||||
'> 使用上方命令拉取镜像进行测试',
|
||||
'',
|
||||
'</div>'
|
||||
);
|
||||
} else {
|
||||
lines.push(
|
||||
'<div align="center">',
|
||||
'',
|
||||
'> ⚠️ **Docker 镜像构建失败**',
|
||||
'>',
|
||||
'> 请检查错误详情',
|
||||
'',
|
||||
'</div>'
|
||||
);
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
@@ -31,6 +31,21 @@ export interface Artifact {
|
||||
archive_download_url: string;
|
||||
}
|
||||
|
||||
export interface Release {
|
||||
id: number;
|
||||
tag_name: string;
|
||||
name: string;
|
||||
upload_url: string;
|
||||
html_url: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface ReleaseAsset {
|
||||
id: number;
|
||||
name: string;
|
||||
browser_download_url: string;
|
||||
}
|
||||
|
||||
// ============== GitHub API Client ==========================
|
||||
|
||||
export class GitHubAPI {
|
||||
@@ -56,6 +71,11 @@ export class GitHubAPI {
|
||||
throw new Error(`GitHub API error: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
// 204 No Content(DELETE 等)不解析 body
|
||||
if (response.status === 204) {
|
||||
return undefined as T;
|
||||
}
|
||||
|
||||
return response.json() as Promise<T>;
|
||||
}
|
||||
|
||||
@@ -150,6 +170,119 @@ export class GitHubAPI {
|
||||
console.log('✓ Created new comment');
|
||||
}
|
||||
}
|
||||
|
||||
// ============== Release API ==============
|
||||
|
||||
async getReleaseByTag (owner: string, repo: string, tag: string): Promise<Release | null> {
|
||||
try {
|
||||
return await this.request<Release>(`/repos/${owner}/${repo}/releases/tags/${tag}`);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async deleteRelease (owner: string, repo: string, releaseId: number): Promise<void> {
|
||||
await this.request(`/repos/${owner}/${repo}/releases/${releaseId}`, { method: 'DELETE' });
|
||||
}
|
||||
|
||||
async deleteRef (owner: string, repo: string, ref: string): Promise<void> {
|
||||
try {
|
||||
await this.request(`/repos/${owner}/${repo}/git/refs/${ref}`, { method: 'DELETE' });
|
||||
} catch {
|
||||
// ref may not exist, ignore
|
||||
}
|
||||
}
|
||||
|
||||
async createRelease (
|
||||
owner: string,
|
||||
repo: string,
|
||||
tag: string,
|
||||
name: string,
|
||||
body: string,
|
||||
prerelease = true
|
||||
): Promise<Release> {
|
||||
return this.request<Release>(`/repos/${owner}/${repo}/releases`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ tag_name: tag, name, body, prerelease }),
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
|
||||
async uploadReleaseAsset (
|
||||
uploadUrl: string,
|
||||
fileName: string,
|
||||
data: Buffer,
|
||||
contentType = 'application/octet-stream'
|
||||
): Promise<ReleaseAsset> {
|
||||
const url = uploadUrl.replace(/\{[^}]*\}/g, '') + `?name=${encodeURIComponent(fileName)}`;
|
||||
const response = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.token}`,
|
||||
Accept: 'application/vnd.github+json',
|
||||
'Content-Type': contentType,
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
},
|
||||
body: data,
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(`Upload ${fileName} failed: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
return response.json() as Promise<ReleaseAsset>;
|
||||
}
|
||||
|
||||
// ============== Dispatch API ==============
|
||||
|
||||
async repositoryDispatch (
|
||||
owner: string,
|
||||
repo: string,
|
||||
eventType: string,
|
||||
clientPayload: Record<string, string>
|
||||
): Promise<void> {
|
||||
const response = await fetch(`${this.baseUrl}/repos/${owner}/${repo}/dispatches`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.token}`,
|
||||
Accept: 'application/vnd.github+json',
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ event_type: eventType, client_payload: clientPayload }),
|
||||
});
|
||||
if (!response.ok && response.status !== 204) {
|
||||
throw new Error(`Dispatch failed: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
}
|
||||
|
||||
async createWorkflowDispatch (
|
||||
owner: string,
|
||||
repo: string,
|
||||
workflowFile: string,
|
||||
ref: string,
|
||||
inputs: Record<string, string>
|
||||
): Promise<void> {
|
||||
const response = await fetch(`${this.baseUrl}/repos/${owner}/${repo}/actions/workflows/${workflowFile}/dispatches`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${this.token}`,
|
||||
Accept: 'application/vnd.github+json',
|
||||
'X-GitHub-Api-Version': '2022-11-28',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ ref, inputs }),
|
||||
});
|
||||
if (!response.ok && response.status !== 204) {
|
||||
throw new Error(`Workflow dispatch failed: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
}
|
||||
|
||||
// ============== Release Cleanup API ==============
|
||||
|
||||
async listReleases (owner: string, repo: string, perPage = 100, page = 1): Promise<Release[]> {
|
||||
return this.request<Release[]>(
|
||||
`/repos/${owner}/${repo}/releases?per_page=${perPage}&page=${page}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ============== Output 工具 ==============
|
||||
@@ -172,8 +305,7 @@ export function setMultilineOutput (name: string, value: string): void {
|
||||
|
||||
// ============== 环境变量工具 ==============
|
||||
|
||||
export function getEnv (name: string, required: true): string;
|
||||
export function getEnv (name: string, required?: false): string | undefined;
|
||||
// Note: 不使用函数重载——Node.js --experimental-strip-types 不支持 TS overload signatures
|
||||
export function getEnv (name: string, required = false): string | undefined {
|
||||
const value = process.env[name];
|
||||
if (required && !value) {
|
||||
@@ -183,7 +315,7 @@ export function getEnv (name: string, required = false): string | undefined {
|
||||
}
|
||||
|
||||
export function getRepository (): { owner: string, repo: string; } {
|
||||
const repository = getEnv('GITHUB_REPOSITORY', true);
|
||||
const repository = getEnv('GITHUB_REPOSITORY', true)!;
|
||||
const [owner, repo] = repository.split('/');
|
||||
return { owner, repo };
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* PR Build - Dispatch untrusted build workflow
|
||||
*
|
||||
* 环境变量:
|
||||
* - GITHUB_TOKEN: GitHub API Token
|
||||
* - PR_NUMBER: PR 编号
|
||||
* - PR_SHA: PR HEAD SHA
|
||||
* - PR_HEAD_REPO: PR 源仓库
|
||||
* - PR_HEAD_REF: PR 源分支
|
||||
* - WORKFLOW_FILE: 工作流文件名,默认 build-pr.yml
|
||||
* - DISPATCH_REF: 触发分支,默认当前分支
|
||||
*/
|
||||
|
||||
import { GitHubAPI, getEnv, getRepository } from './lib/github.ts';
|
||||
|
||||
declare const process: { exit(code?: number): never; };
|
||||
|
||||
async function main (): Promise<void> {
|
||||
console.log('🚀 Dispatching PR build workflow\n');
|
||||
|
||||
const token = getEnv('GITHUB_TOKEN', true)!;
|
||||
const prNumber = getEnv('PR_NUMBER', true)!;
|
||||
const prSha = getEnv('PR_SHA', true)!;
|
||||
const prHeadRepo = getEnv('PR_HEAD_REPO', true)!;
|
||||
const prHeadRef = getEnv('PR_HEAD_REF') || '';
|
||||
const workflowFile = getEnv('WORKFLOW_FILE') || 'build-pr.yml';
|
||||
const dispatchRef = getEnv('DISPATCH_REF') || getEnv('GITHUB_REF_NAME') || 'main';
|
||||
const { owner, repo } = getRepository();
|
||||
|
||||
console.log(`PR: #${prNumber}`);
|
||||
console.log(`SHA: ${prSha}`);
|
||||
console.log(`Head repo: ${prHeadRepo}`);
|
||||
console.log(`Workflow: ${workflowFile}`);
|
||||
console.log(`Ref: ${dispatchRef}\n`);
|
||||
|
||||
const github = new GitHubAPI(token);
|
||||
await github.createWorkflowDispatch(owner, repo, workflowFile, dispatchRef, {
|
||||
pr_number: prNumber,
|
||||
pr_sha: prSha,
|
||||
pr_head_repo: prHeadRepo,
|
||||
pr_head_ref: prHeadRef,
|
||||
});
|
||||
|
||||
console.log('✅ Dispatch created');
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error('❌ Error:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -11,11 +11,13 @@
|
||||
* - FRAMEWORK_ERROR: Framework 构建错误信息
|
||||
* - SHELL_STATUS: Shell 构建状态
|
||||
* - SHELL_ERROR: Shell 构建错误信息
|
||||
* - INSTALL_URL: PR Release 安装脚本 URL (可选)
|
||||
* - RELEASE_URL: PR Release 页面 URL (可选)
|
||||
*/
|
||||
|
||||
import { GitHubAPI, getEnv, getRepository } from './lib/github.ts';
|
||||
import { generateResultComment, COMMENT_MARKER } from './lib/comment.ts';
|
||||
import type { BuildTarget, BuildStatus } from './lib/comment.ts';
|
||||
import type { BuildTarget, BuildStatus, InstallInfo } from './lib/comment.ts';
|
||||
|
||||
function parseStatus (value: string | undefined): BuildStatus {
|
||||
if (value === 'success' || value === 'failure' || value === 'cancelled') {
|
||||
@@ -46,6 +48,21 @@ async function main (): Promise<void> {
|
||||
console.log(`Framework: ${frameworkStatus}${frameworkError ? ` (${frameworkError})` : ''}`);
|
||||
console.log(`Shell: ${shellStatus}${shellError ? ` (${shellError})` : ''}\n`);
|
||||
|
||||
// PR Release 信息(由 publish-pr-release job 传入)
|
||||
const installUrl = getEnv('INSTALL_URL');
|
||||
const releaseUrl = getEnv('RELEASE_URL');
|
||||
const publishStatus = getEnv('PUBLISH_STATUS'); // 'success' | 'failure' | 'skipped' | ''
|
||||
const installInfo: InstallInfo | undefined =
|
||||
installUrl && releaseUrl ? { installUrl, releaseUrl } : undefined;
|
||||
const publishFailed = publishStatus === 'failure';
|
||||
|
||||
if (installInfo) {
|
||||
console.log(`Install URL: ${installUrl}`);
|
||||
console.log(`Release URL: ${releaseUrl}\n`);
|
||||
} else if (publishFailed) {
|
||||
console.log('Publish status: FAILED\n');
|
||||
}
|
||||
|
||||
const github = new GitHubAPI(token);
|
||||
const repository = `${owner}/${repo}`;
|
||||
|
||||
@@ -79,7 +96,7 @@ async function main (): Promise<void> {
|
||||
},
|
||||
];
|
||||
|
||||
const comment = generateResultComment(targets, prSha, runId, repository, version);
|
||||
const comment = generateResultComment(targets, prSha, runId, repository, version, installInfo, publishFailed);
|
||||
|
||||
await github.createOrUpdateComment(owner, repo, prNumber, comment, COMMENT_MARKER);
|
||||
}
|
||||
|
||||
@@ -22,11 +22,7 @@ interface BuildStep {
|
||||
|
||||
function getCommonSteps (): BuildStep[] {
|
||||
return [
|
||||
{
|
||||
name: 'Install pnpm',
|
||||
command: 'npm i -g pnpm',
|
||||
errorMessage: 'Failed to install pnpm',
|
||||
},
|
||||
// pnpm 已通过 GitHub Action (pnpm/action-setup) 预安装并固定 v9, 此处无需再次安装
|
||||
{
|
||||
name: 'Install dependencies',
|
||||
command: 'pnpm i',
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* PR Build - 触发 NapCat-Docker 仓库构建 PR 测试镜像
|
||||
*
|
||||
* 功能:
|
||||
* 1. 在 PR 中创建 Docker 构建中评论
|
||||
* 2. 触发 NapCat-Docker 仓库的 repository_dispatch 事件
|
||||
*
|
||||
* 环境变量:
|
||||
* DISPATCH_PAT - 具备目标仓库 dispatch 权限的 PAT
|
||||
* GITHUB_TOKEN - GitHub API Token (用于写 PR 评论)
|
||||
* PR_NUMBER - PR 编号
|
||||
* PR_SHA - PR HEAD 提交 SHA
|
||||
* PR_HEAD_REPO - PR 源仓库 (owner/repo)
|
||||
* SOURCE_REPO - 当前仓库 (默认 NapNeko/NapCatQQ)
|
||||
* RELEASE_REPO - PR release 仓库 (默认 NapNeko/napcat-pr-release)
|
||||
* TARGET_REPO - Docker 仓库 (默认 NapNeko/NapCat-Docker)
|
||||
*/
|
||||
|
||||
import { GitHubAPI, getEnv } from './lib/github.ts';
|
||||
import { generateDockerBuildingComment, DOCKER_COMMENT_MARKER } from './lib/comment.ts';
|
||||
|
||||
async function main (): Promise<void> {
|
||||
console.log('🐳 Dispatching Docker build\n');
|
||||
|
||||
const token = getEnv('DISPATCH_PAT', true);
|
||||
const githubToken = getEnv('GITHUB_TOKEN', true);
|
||||
const prNumber = getEnv('PR_NUMBER', true);
|
||||
const prSha = getEnv('PR_SHA', true);
|
||||
const prHeadRepo = getEnv('PR_HEAD_REPO') || '';
|
||||
const sourceRepo = getEnv('SOURCE_REPO') || 'NapNeko/NapCatQQ';
|
||||
const releaseRepo = getEnv('RELEASE_REPO') || 'NapNeko/napcat-pr-release';
|
||||
const targetRepo = getEnv('TARGET_REPO') || 'NapNeko/NapCat-Docker';
|
||||
|
||||
const [targetOwner, targetRepoName] = targetRepo.split('/');
|
||||
const [sourceOwner, sourceRepoName] = sourceRepo.split('/');
|
||||
const shortSha = prSha.substring(0, 7);
|
||||
|
||||
console.log(` PR: #${prNumber}`);
|
||||
console.log(` SHA: ${shortSha}`);
|
||||
console.log(` Target: ${targetRepo}`);
|
||||
console.log(` Release: ${releaseRepo}\n`);
|
||||
|
||||
// 在 PR 中创建 Docker 构建中评论
|
||||
console.log('💬 Creating Docker building comment...');
|
||||
const prGithub = new GitHubAPI(githubToken);
|
||||
const dockerComment = generateDockerBuildingComment(prNumber, prSha);
|
||||
await prGithub.createOrUpdateComment(
|
||||
sourceOwner, sourceRepoName, parseInt(prNumber, 10), dockerComment, DOCKER_COMMENT_MARKER
|
||||
);
|
||||
|
||||
// 触发 Docker 仓库构建
|
||||
const github = new GitHubAPI(token);
|
||||
|
||||
await github.repositoryDispatch(targetOwner, targetRepoName, 'napcatqq-pr-build', {
|
||||
pr_number: prNumber,
|
||||
pr_sha: prSha,
|
||||
pr_short_sha: shortSha,
|
||||
pr_head_repo: prHeadRepo,
|
||||
source_repo: sourceRepo,
|
||||
release_repo: releaseRepo,
|
||||
});
|
||||
|
||||
console.log('✅ Dispatch succeeded');
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error('❌ Error:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* PR Build - 发布构建产物到 napcat-pr-release 仓库
|
||||
*
|
||||
* 功能:
|
||||
* 1. 将 CI 构建产物(Framework / Shell)打包为 zip
|
||||
* 2. 从 NapCat-Installer 仓库拉取 install.sh 并替换下载链接
|
||||
* 3. 发布到 napcat-pr-release 仓库的 GitHub Release
|
||||
*
|
||||
* 环境变量:
|
||||
* RELEASE_PAT - 具备目标仓库 release 写权限的 PAT
|
||||
* PR_NUMBER - PR 编号
|
||||
* PR_SHA - PR HEAD 提交 SHA
|
||||
* NAPCAT_VERSION - 构建版本号
|
||||
* ARTIFACTS_DIR - 构建产物目录 (默认 ./artifacts)
|
||||
* RELEASE_REPO - 发布仓库 (默认 NapNeko/napcat-pr-release)
|
||||
* INSTALLER_REPO - 安装脚本仓库 (默认 NapNeko/NapCat-Installer)
|
||||
* INSTALLER_BRANCH - 安装脚本分支 (默认 main)
|
||||
*/
|
||||
|
||||
import { execSync } from 'node:child_process';
|
||||
import { existsSync, readFileSync, writeFileSync, mkdirSync, readdirSync } from 'node:fs';
|
||||
import { join, resolve } from 'node:path';
|
||||
import { GitHubAPI, getEnv, setOutput } from './lib/github.ts';
|
||||
import { toProxyUrl } from './lib/comment.ts';
|
||||
|
||||
interface AssetEntry {
|
||||
name: string;
|
||||
path: string;
|
||||
contentType: string;
|
||||
}
|
||||
|
||||
async function main (): Promise<void> {
|
||||
console.log('📦 PR Release Publisher\n');
|
||||
|
||||
const token = getEnv('RELEASE_PAT', true);
|
||||
const prNumber = getEnv('PR_NUMBER', true);
|
||||
const prSha = getEnv('PR_SHA', true);
|
||||
const version = getEnv('NAPCAT_VERSION') || 'unknown';
|
||||
const artifactsDir = getEnv('ARTIFACTS_DIR') || './artifacts';
|
||||
const releaseRepo = getEnv('RELEASE_REPO') || 'NapNeko/napcat-pr-release';
|
||||
const installerRepo = getEnv('INSTALLER_REPO') || 'NapNeko/NapCat-Installer';
|
||||
const installerBranch = getEnv('INSTALLER_BRANCH') || 'main';
|
||||
|
||||
const [releaseOwner, releaseRepoName] = releaseRepo.split('/');
|
||||
const shortSha = prSha.substring(0, 7);
|
||||
const tag = `pr-${prNumber}-${shortSha}`;
|
||||
const releaseName = `PR #${prNumber} (${shortSha})`;
|
||||
const downloadBase = `https://github.com/${releaseRepo}/releases/download/${tag}`;
|
||||
|
||||
console.log(` Tag: ${tag}`);
|
||||
console.log(` Repo: ${releaseRepo}`);
|
||||
console.log(` Version: ${version}`);
|
||||
console.log(` SHA: ${shortSha}\n`);
|
||||
|
||||
const github = new GitHubAPI(token);
|
||||
const releaseDir = resolve('./release-assets'); // 使用绝对路径,避免 zip cwd 切换后相对路径解析错误
|
||||
mkdirSync(releaseDir, { recursive: true });
|
||||
|
||||
// ---- 打包构建产物 ----
|
||||
const artifacts = ['NapCat.Framework', 'NapCat.Shell'];
|
||||
for (const name of artifacts) {
|
||||
const dir = join(artifactsDir, name);
|
||||
if (existsSync(dir)) {
|
||||
const zipPath = join(releaseDir, `${name}.zip`);
|
||||
console.log(`📦 Packing ${name}...`);
|
||||
execSync(`zip -qr "${zipPath}" .`, { cwd: dir, stdio: 'inherit' });
|
||||
console.log(` ✓ ${name}.zip\n`);
|
||||
} else {
|
||||
console.log(` ⚠ ${name} 目录不存在,跳过\n`);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 拉取并修改安装脚本 ----
|
||||
console.log('📜 Fetching install.sh...');
|
||||
const scriptUrl = `https://raw.githubusercontent.com/${installerRepo}/${installerBranch}/script/install.sh`;
|
||||
try {
|
||||
const response = await fetch(scriptUrl);
|
||||
if (response.ok) {
|
||||
let script = await response.text();
|
||||
// 替换下载链接(保留代理前缀 ${target_proxy:+${target_proxy}/})
|
||||
const shellUrl = `${downloadBase}/NapCat.Shell.zip`;
|
||||
const originalScript = script;
|
||||
script = script.replace(
|
||||
/napcat_download_url="\$\{target_proxy:\+\$\{target_proxy\}\/\}https:\/\/github\.com\/NapNeko\/NapCatQQ\/releases\/latest\/download\/NapCat\.Shell\.zip"/g,
|
||||
`napcat_download_url="\${target_proxy:+\${target_proxy}/}${shellUrl}"`
|
||||
);
|
||||
if (script === originalScript) {
|
||||
console.log(' ⚠ Warning: URL replacement did not match - install.sh format may have changed');
|
||||
}
|
||||
const scriptPath = join(releaseDir, 'install.sh');
|
||||
writeFileSync(scriptPath, script, { mode: 0o755 });
|
||||
console.log(` ✓ Patched download URL -> ${shellUrl}\n`);
|
||||
} else {
|
||||
console.log(` ⚠ Failed to fetch install.sh: ${response.status}\n`);
|
||||
}
|
||||
} catch (e) {
|
||||
console.log(` ⚠ Failed to fetch install.sh: ${(e as Error).message}\n`);
|
||||
}
|
||||
|
||||
// ---- 收集所有要上传的文件 ----
|
||||
const assets: AssetEntry[] = [];
|
||||
for (const file of readdirSync(releaseDir)) {
|
||||
const ext = file.split('.').pop()?.toLowerCase();
|
||||
const contentType = ext === 'zip' ? 'application/zip' : ext === 'sh' ? 'application/x-sh' : 'application/octet-stream';
|
||||
assets.push({ name: file, path: join(releaseDir, file), contentType });
|
||||
}
|
||||
console.log(`📋 Assets to upload: ${assets.map(a => a.name).join(', ')}\n`);
|
||||
|
||||
// ---- 删除旧 release ----
|
||||
console.log('🗑️ Checking for existing release...');
|
||||
const existing = await github.getReleaseByTag(releaseOwner, releaseRepoName, tag);
|
||||
if (existing) {
|
||||
console.log(` Deleting existing release (id=${existing.id})...`);
|
||||
await github.deleteRelease(releaseOwner, releaseRepoName, existing.id);
|
||||
await github.deleteRef(releaseOwner, releaseRepoName, `tags/${tag}`);
|
||||
console.log(' ✓ Deleted\n');
|
||||
} else {
|
||||
console.log(' No existing release\n');
|
||||
}
|
||||
|
||||
// ---- 创建 Release ----
|
||||
const directInstallUrl = `${downloadBase}/install.sh`;
|
||||
const proxyInstallUrl = toProxyUrl(directInstallUrl);
|
||||
const releaseBody = [
|
||||
`## NapCat PR #${prNumber} 测试版本`,
|
||||
'',
|
||||
`- **版本**: \`${version}\``,
|
||||
`- **提交**: \`${prSha}\``,
|
||||
`- **来源**: [NapCatQQ PR #${prNumber}](https://github.com/NapNeko/NapCatQQ/pull/${prNumber})`,
|
||||
'',
|
||||
'### 快速安装 (Linux)',
|
||||
'',
|
||||
'**直连(需要能访问 GitHub)**',
|
||||
'```bash',
|
||||
`curl -sSL ${directInstallUrl} | bash`,
|
||||
'```',
|
||||
'',
|
||||
'**加速(国内推荐,ghfast.top)**',
|
||||
'```bash',
|
||||
`curl -sSL ${proxyInstallUrl} | bash`,
|
||||
'```',
|
||||
'',
|
||||
'> ⚠️ 此为 PR 测试版本,约 5 天后会被自动清理。',
|
||||
].join('\n');
|
||||
|
||||
console.log('🚀 Creating release...');
|
||||
const release = await github.createRelease(
|
||||
releaseOwner, releaseRepoName, tag, releaseName, releaseBody, true
|
||||
);
|
||||
console.log(` ✓ Release created: ${release.html_url}\n`);
|
||||
|
||||
// ---- 上传资产 ----
|
||||
console.log('📤 Uploading assets...');
|
||||
for (const asset of assets) {
|
||||
const data = readFileSync(asset.path);
|
||||
const uploaded = await github.uploadReleaseAsset(
|
||||
release.upload_url, asset.name, data, asset.contentType
|
||||
);
|
||||
console.log(` ✓ ${asset.name} -> ${uploaded.browser_download_url}`);
|
||||
}
|
||||
|
||||
console.log(`\n✅ Release published: ${release.html_url}`);
|
||||
|
||||
// 输出供后续 job 使用
|
||||
setOutput('release_url', release.html_url);
|
||||
setOutput('release_tag', tag);
|
||||
setOutput('install_url', `${downloadBase}/install.sh`);
|
||||
}
|
||||
|
||||
main().catch((error) => {
|
||||
console.error('❌ Error:', error);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -1,153 +0,0 @@
|
||||
name: Auto Release Docker
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
|
||||
jobs:
|
||||
publish-schema:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
|
||||
- name: Get Version
|
||||
id: get_version
|
||||
run: |
|
||||
latest_tag=$(git describe --tags $(git rev-list --tags --max-count=1))
|
||||
version=${latest_tag#v}
|
||||
echo "version=${version}" >> $GITHUB_ENV
|
||||
echo "latest_tag=${latest_tag}" >> $GITHUB_ENV
|
||||
echo "Debug: Version is ${version}"
|
||||
|
||||
- name: Install Dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build napcat-schema
|
||||
run: |
|
||||
cd packages/napcat-schema
|
||||
pnpm run build:openapi
|
||||
|
||||
- name: Checkout NapCatDocs
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: NapNeko/NapCatDocs
|
||||
token: ${{ secrets.NAPCAT_BUILD }}
|
||||
path: napcat-docs
|
||||
|
||||
- name: Copy OpenAPI Schema
|
||||
run: |
|
||||
mkdir -p napcat-docs/src/api/${{ env.version }}
|
||||
cp packages/napcat-schema/dist/openapi.json napcat-docs/src/api/${{ env.version }}/openapi.json
|
||||
echo "OpenAPI schema copied to napcat-docs/src/api/${{ env.version }}/openapi.json"
|
||||
|
||||
- name: Commit and Push
|
||||
run: |
|
||||
cd napcat-docs
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git add src/api/${{ env.version }}/openapi.json
|
||||
git commit -m "chore: update OpenAPI schema for version ${{ env.version }}" || echo "No changes to commit"
|
||||
git push
|
||||
|
||||
shell-docker:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Trigger NapCat-Docker docker-publish workflow
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
|
||||
run: |
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/NapNeko/NapCat-Docker/actions/workflows/docker-publish.yml/dispatches \
|
||||
-d '{"ref":"main"}'
|
||||
framework-docker:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Trigger NapCat-Framework-Docker docker-publish workflow
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
|
||||
run: |
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/NapNeko/NapCat.Docker.Framework/actions/workflows/docker-image.yml/dispatches \
|
||||
-d '{"ref":"main"}'
|
||||
appimage-shell-docker:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v4
|
||||
- name: Get Latest NapCat Version
|
||||
id: get_version
|
||||
run: |
|
||||
# 获取当前仓库的最新 tag
|
||||
latest_tag=$(git describe --tags $(git rev-list --tags --max-count=1))
|
||||
# 输出调试信息
|
||||
echo "Debug: Latest NapCat Version is ${latest_tag}"
|
||||
echo "latest_tag=${latest_tag}" >> $GITHUB_ENV
|
||||
- name: Trigger Release NapCat AppImage Workflow
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
|
||||
NAPCAT_VERSION: ${{ env.latest_tag }}
|
||||
QQ_VERSION_X86_64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.AppImage' # 写死 QQ 版本
|
||||
QQ_VERSION_ARM64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.AppImage' # 写死 QQ 版本
|
||||
run: |
|
||||
echo "Debug: Triggering Release NapCat AppImage with napcat_version=${NAPCAT_VERSION}, qq_version_x86_64=${QQ_VERSION_X86_64}, qq_version_arm64=${QQ_VERSION_ARM64}"
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/NapNeko/NapCatAppImageBuild/actions/workflows/release.yml/dispatches \
|
||||
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_version_x86_64\":\"${QQ_VERSION_X86_64}\",\"qq_version_arm64\":\"${QQ_VERSION_ARM64}\"}}"
|
||||
node-shell-docker:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v4
|
||||
- name: Get Latest NapCat Version
|
||||
id: get_version
|
||||
run: |
|
||||
# 获取当前仓库的最新 tag
|
||||
latest_tag=$(git describe --tags $(git rev-list --tags --max-count=1))
|
||||
# 输出调试信息
|
||||
echo "Debug: Latest NapCat Version is ${latest_tag}"
|
||||
echo "latest_tag=${latest_tag}" >> $GITHUB_ENV
|
||||
- name: Trigger Release NapCat AppImage Workflow
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
|
||||
NAPCAT_VERSION: ${{ env.latest_tag }}
|
||||
QQ_VERSION_X86_64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.AppImage' # 写死 QQ 版本
|
||||
QQ_VERSION_ARM64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.AppImage' # 写死 QQ 版本
|
||||
run: |
|
||||
echo "Debug: Triggering Release NapCat AppImage with napcat_version=${NAPCAT_VERSION}, qq_url_amd64=${QQ_VERSION_X86_64}, qq_url_arm64=${QQ_VERSION_ARM64}"
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/NapNeko/NapCatLinuxNodeLoader/actions/workflows/release.yml/dispatches \
|
||||
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_url_amd64\":\"${QQ_VERSION_X86_64}\",\"qq_url_arm64\":\"${QQ_VERSION_ARM64}\"}}"
|
||||
- name: Trigger Release NapCat AppImage Workflow
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
|
||||
NAPCAT_VERSION: ${{ env.latest_tag }}
|
||||
QQ_VERSION_X86_64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.AppImage' # 写死 QQ 版本
|
||||
QQ_VERSION_ARM64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.AppImage' # 写死 QQ 版本
|
||||
run: |
|
||||
echo "Debug: Triggering Release NapCat AppImage with napcat_version=${NAPCAT_VERSION}, qq_url_amd64=${QQ_VERSION_X86_64}, qq_url_arm64=${QQ_VERSION_ARM64}"
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/NapNeko/NapCatLinuxNodeLoader/actions/workflows/docker-publish.yml/dispatches \
|
||||
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_url_amd64\":\"${QQ_VERSION_X86_64}\",\"qq_url_arm64\":\"${QQ_VERSION_ARM64}\"}}"
|
||||
@@ -0,0 +1,91 @@
|
||||
name: Build NapCat Artifacts
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
permissions: write-all
|
||||
|
||||
jobs:
|
||||
typecheck-and-test:
|
||||
name: Type Check & Test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Clone Main Repository
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
run_install: false
|
||||
- name: Use Node.js 20.x
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 20.x
|
||||
- name: Install Dependencies
|
||||
run: pnpm i
|
||||
- name: Type Check
|
||||
run: pnpm run typecheck
|
||||
- name: Run Tests
|
||||
run: pnpm test
|
||||
|
||||
build:
|
||||
name: Build NapCat.${{ matrix.target.name }}
|
||||
needs: typecheck-and-test
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
target:
|
||||
- name: Framework
|
||||
build_cmd: build:framework
|
||||
src_dir: packages/napcat-framework/dist
|
||||
dist_dir: framework-dist
|
||||
- name: Shell
|
||||
build_cmd: build:shell
|
||||
src_dir: packages/napcat-shell/dist
|
||||
dist_dir: shell-dist
|
||||
steps:
|
||||
- name: Clone Main Repository
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
run_install: false
|
||||
- name: Use Node.js 20.x
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 20.x
|
||||
- name: Generate Version
|
||||
run: |
|
||||
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
|
||||
BASE_VERSION="${LATEST_TAG#v}"
|
||||
SHORT_SHA="${GITHUB_SHA::7}"
|
||||
VERSION="${BASE_VERSION}-main.${{ github.run_number }}+${SHORT_SHA}"
|
||||
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
|
||||
echo "Latest tag: ${LATEST_TAG}"
|
||||
echo "Build version: ${VERSION}"
|
||||
- name: Build NapCat.${{ matrix.target.name }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
|
||||
run: |
|
||||
pnpm i
|
||||
pnpm --filter napcat-webui-frontend run build || exit 1
|
||||
pnpm run ${{ matrix.target.build_cmd }}
|
||||
pnpm --filter napcat-plugin-builtin run build || exit 1
|
||||
mv ${{ matrix.target.src_dir }} ${{ matrix.target.dist_dir }}
|
||||
cd ${{ matrix.target.dist_dir }}
|
||||
npm install --omit=dev
|
||||
rm ./package-lock.json || exit 0
|
||||
- name: Upload Artifact
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: NapCat.${{ matrix.target.name }}
|
||||
path: ${{ matrix.target.dist_dir }}
|
||||
@@ -0,0 +1,424 @@
|
||||
# =============================================================================
|
||||
# PR 构建工作流
|
||||
# =============================================================================
|
||||
# 安全模型:
|
||||
# 1. pull_request_target / issue_comment 入口只读取元数据、检查权限、更新评论并触发构建。
|
||||
# 2. 真正执行 PR 代码的构建流程只在 workflow_dispatch 中运行。
|
||||
# 3. 构建流程不具备写仓库/写评论/读 secrets 权限,显式清空 GITHUB_TOKEN,不持久化 checkout 凭据。
|
||||
# 4. 版本号在 Action 中提前生成,通过 NAPCAT_VERSION 传给 Vite 插件,插件无需 GitHub token。
|
||||
# 5. 发布 Release、触发 Docker 等可信操作只消费构建 artifact,不执行 PR artifact 中的代码。
|
||||
# =============================================================================
|
||||
|
||||
name: Build PR
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened, synchronize, reopened]
|
||||
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
pr_number:
|
||||
description: PR 编号
|
||||
required: true
|
||||
type: string
|
||||
pr_sha:
|
||||
description: PR HEAD SHA
|
||||
required: true
|
||||
type: string
|
||||
pr_head_repo:
|
||||
description: PR 源仓库
|
||||
required: true
|
||||
type: string
|
||||
pr_head_ref:
|
||||
description: PR 源分支
|
||||
required: false
|
||||
type: string
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: pr-build-${{ github.event_name == 'workflow_dispatch' && inputs.pr_number || github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event_name == 'issue_comment' && github.event.issue.pull_request && contains(github.event.comment.body, '/build') && github.event.issue.number || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
# ---------------------------------------------------------------------------
|
||||
# 特权入口:只检查条件、写入“构建中”评论、触发无权限构建
|
||||
# ---------------------------------------------------------------------------
|
||||
check-build:
|
||||
if: github.event_name != 'workflow_dispatch'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: read
|
||||
issues: write
|
||||
outputs:
|
||||
should_build: ${{ steps.check.outputs.should_build }}
|
||||
pr_number: ${{ steps.check.outputs.pr_number }}
|
||||
pr_sha: ${{ steps.check.outputs.pr_sha }}
|
||||
pr_head_repo: ${{ steps.check.outputs.pr_head_repo }}
|
||||
pr_head_ref: ${{ steps.check.outputs.pr_head_ref }}
|
||||
steps:
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
- name: Check trigger condition
|
||||
id: check
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: node --experimental-strip-types .github/scripts/pr-build-check.ts
|
||||
|
||||
update-comment-building:
|
||||
needs: check-build
|
||||
if: needs.check-build.outputs.should_build == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
issues: write
|
||||
steps:
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
- name: Update building comment
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
PR_NUMBER: ${{ needs.check-build.outputs.pr_number }}
|
||||
PR_SHA: ${{ needs.check-build.outputs.pr_sha }}
|
||||
run: node --experimental-strip-types .github/scripts/pr-build-building.ts
|
||||
|
||||
dispatch-build:
|
||||
needs: [check-build, update-comment-building]
|
||||
if: needs.check-build.outputs.should_build == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
actions: write
|
||||
steps:
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
- name: Dispatch untrusted build
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
PR_NUMBER: ${{ needs.check-build.outputs.pr_number }}
|
||||
PR_SHA: ${{ needs.check-build.outputs.pr_sha }}
|
||||
PR_HEAD_REPO: ${{ needs.check-build.outputs.pr_head_repo }}
|
||||
PR_HEAD_REF: ${{ needs.check-build.outputs.pr_head_ref }}
|
||||
WORKFLOW_FILE: build-pr.yml
|
||||
DISPATCH_REF: ${{ github.event.repository.default_branch }}
|
||||
run: node --experimental-strip-types .github/scripts/pr-build-dispatch.ts
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 无权限构建:只由 workflow_dispatch 执行 PR 代码
|
||||
# ---------------------------------------------------------------------------
|
||||
build-framework:
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
outputs:
|
||||
status: ${{ steps.build.outcome }}
|
||||
error: ${{ steps.build.outputs.error }}
|
||||
version: ${{ steps.version.outputs.version }}
|
||||
steps:
|
||||
- name: Checkout scripts from base
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
path: _scripts
|
||||
persist-credentials: false
|
||||
|
||||
- name: Checkout PR code
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
repository: ${{ inputs.pr_head_repo }}
|
||||
ref: ${{ inputs.pr_sha }}
|
||||
path: workspace
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
run_install: false
|
||||
|
||||
- name: Generate Version
|
||||
id: version
|
||||
working-directory: workspace
|
||||
run: |
|
||||
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
|
||||
BASE_VERSION="${LATEST_TAG#v}"
|
||||
SHORT_SHA="${{ inputs.pr_sha }}"
|
||||
SHORT_SHA="${SHORT_SHA::7}"
|
||||
VERSION="${BASE_VERSION}-pr.${{ inputs.pr_number }}.${{ github.run_number }}+${SHORT_SHA}"
|
||||
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
|
||||
echo "version=${VERSION}" >> $GITHUB_OUTPUT
|
||||
echo "Latest tag: ${LATEST_TAG}"
|
||||
echo "Build version: ${VERSION}"
|
||||
|
||||
- name: Build
|
||||
id: build
|
||||
working-directory: workspace
|
||||
env:
|
||||
GITHUB_TOKEN: ''
|
||||
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
|
||||
run: node --experimental-strip-types ../_scripts/.github/scripts/pr-build-run.ts framework
|
||||
continue-on-error: true
|
||||
|
||||
- name: Upload Artifact
|
||||
if: steps.build.outcome == 'success'
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: NapCat.Framework
|
||||
path: workspace/framework-dist
|
||||
retention-days: 5
|
||||
|
||||
build-shell:
|
||||
if: github.event_name == 'workflow_dispatch'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
outputs:
|
||||
status: ${{ steps.build.outcome }}
|
||||
error: ${{ steps.build.outputs.error }}
|
||||
version: ${{ steps.version.outputs.version }}
|
||||
steps:
|
||||
- name: Checkout scripts from base
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
path: _scripts
|
||||
persist-credentials: false
|
||||
|
||||
- name: Checkout PR code
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
repository: ${{ inputs.pr_head_repo }}
|
||||
ref: ${{ inputs.pr_sha }}
|
||||
path: workspace
|
||||
fetch-depth: 0
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
run_install: false
|
||||
|
||||
- name: Generate Version
|
||||
id: version
|
||||
working-directory: workspace
|
||||
run: |
|
||||
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
|
||||
BASE_VERSION="${LATEST_TAG#v}"
|
||||
SHORT_SHA="${{ inputs.pr_sha }}"
|
||||
SHORT_SHA="${SHORT_SHA::7}"
|
||||
VERSION="${BASE_VERSION}-pr.${{ inputs.pr_number }}.${{ github.run_number }}+${SHORT_SHA}"
|
||||
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
|
||||
echo "version=${VERSION}" >> $GITHUB_OUTPUT
|
||||
echo "Latest tag: ${LATEST_TAG}"
|
||||
echo "Build version: ${VERSION}"
|
||||
|
||||
- name: Build
|
||||
id: build
|
||||
working-directory: workspace
|
||||
env:
|
||||
GITHUB_TOKEN: ''
|
||||
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
|
||||
run: node --experimental-strip-types ../_scripts/.github/scripts/pr-build-run.ts shell
|
||||
continue-on-error: true
|
||||
|
||||
- name: Upload Artifact
|
||||
if: steps.build.outcome == 'success'
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: NapCat.Shell
|
||||
path: workspace/shell-dist
|
||||
retention-days: 5
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 可信后处理:只下载/打包/发布 artifact,不执行 artifact 中的代码
|
||||
# ---------------------------------------------------------------------------
|
||||
publish-pr-release:
|
||||
needs: [build-framework, build-shell]
|
||||
if: always() && github.event_name == 'workflow_dispatch' && (needs.build-framework.outputs.status == 'success' || needs.build-shell.outputs.status == 'success')
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
outputs:
|
||||
release_url: ${{ steps.publish.outputs.release_url }}
|
||||
release_tag: ${{ steps.publish.outputs.release_tag }}
|
||||
install_url: ${{ steps.publish.outputs.install_url }}
|
||||
publish_status: ${{ steps.publish.outcome }}
|
||||
steps:
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
- name: Download Framework artifact
|
||||
if: needs.build-framework.outputs.status == 'success'
|
||||
uses: actions/download-artifact@v6
|
||||
with:
|
||||
name: NapCat.Framework
|
||||
path: ./artifacts/NapCat.Framework
|
||||
|
||||
- name: Download Shell artifact
|
||||
if: needs.build-shell.outputs.status == 'success'
|
||||
uses: actions/download-artifact@v6
|
||||
with:
|
||||
name: NapCat.Shell
|
||||
path: ./artifacts/NapCat.Shell
|
||||
|
||||
- name: Publish release
|
||||
id: publish
|
||||
continue-on-error: true
|
||||
env:
|
||||
RELEASE_PAT: ${{ secrets.PR_RELEASE_PAT }}
|
||||
PR_NUMBER: ${{ inputs.pr_number }}
|
||||
PR_SHA: ${{ inputs.pr_sha }}
|
||||
NAPCAT_VERSION: ${{ needs.build-framework.outputs.version || needs.build-shell.outputs.version || '' }}
|
||||
ARTIFACTS_DIR: ./artifacts
|
||||
run: |
|
||||
if [ -z "${RELEASE_PAT}" ]; then
|
||||
echo "::warning::PR_RELEASE_PAT secret 未配置,跳过 PR Release 发布"
|
||||
exit 0
|
||||
fi
|
||||
node --experimental-strip-types .github/scripts/pr-publish-release.ts
|
||||
|
||||
- name: Upload install script as artifact
|
||||
if: steps.publish.outcome == 'success'
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: install-script
|
||||
path: ./release-assets/install.sh
|
||||
retention-days: 5
|
||||
if-no-files-found: ignore
|
||||
|
||||
update-comment-result:
|
||||
needs: [build-framework, build-shell, publish-pr-release]
|
||||
if: always() && github.event_name == 'workflow_dispatch'
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
actions: read
|
||||
pull-requests: write
|
||||
issues: write
|
||||
steps:
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
- name: Update result comment
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
PR_NUMBER: ${{ inputs.pr_number }}
|
||||
PR_SHA: ${{ inputs.pr_sha }}
|
||||
RUN_ID: ${{ github.run_id }}
|
||||
NAPCAT_VERSION: ${{ needs.build-framework.outputs.version || needs.build-shell.outputs.version || '' }}
|
||||
FRAMEWORK_STATUS: ${{ needs.build-framework.outputs.status || 'cancelled' }}
|
||||
FRAMEWORK_ERROR: ${{ needs.build-framework.outputs.error }}
|
||||
SHELL_STATUS: ${{ needs.build-shell.outputs.status || 'cancelled' }}
|
||||
SHELL_ERROR: ${{ needs.build-shell.outputs.error }}
|
||||
INSTALL_URL: ${{ needs.publish-pr-release.outputs.install_url || '' }}
|
||||
RELEASE_URL: ${{ needs.publish-pr-release.outputs.release_url || '' }}
|
||||
PUBLISH_STATUS: ${{ needs.publish-pr-release.outputs.publish_status || '' }}
|
||||
run: node --experimental-strip-types .github/scripts/pr-build-result.ts
|
||||
|
||||
trigger-docker:
|
||||
needs: [build-shell, publish-pr-release]
|
||||
if: github.event_name == 'workflow_dispatch' && needs.build-shell.outputs.status == 'success' && needs.publish-pr-release.outputs.release_tag != ''
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
issues: write
|
||||
steps:
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
persist-credentials: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
- name: Dispatch docker build
|
||||
continue-on-error: true
|
||||
env:
|
||||
DISPATCH_PAT: ${{ secrets.PR_RELEASE_PAT }}
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
PR_NUMBER: ${{ inputs.pr_number }}
|
||||
PR_SHA: ${{ inputs.pr_sha }}
|
||||
PR_HEAD_REPO: ${{ inputs.pr_head_repo }}
|
||||
SOURCE_REPO: ${{ github.repository }}
|
||||
RELEASE_REPO: NapNeko/napcat-pr-release
|
||||
run: |
|
||||
if [ -z "${DISPATCH_PAT}" ]; then
|
||||
echo "::warning::PR_RELEASE_PAT secret 未配置,跳过 Docker 测试镜像构建"
|
||||
exit 0
|
||||
fi
|
||||
node --experimental-strip-types .github/scripts/pr-docker-dispatch.ts
|
||||
@@ -1,96 +0,0 @@
|
||||
name: Build NapCat Artifacts
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
permissions: write-all
|
||||
|
||||
jobs:
|
||||
Build-Framework:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Clone Main Repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # 需要完整历史来获取 tags
|
||||
- name: Use Node.js 20.X
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20.x
|
||||
- name: Generate Version
|
||||
run: |
|
||||
# 获取最近的 release tag (格式: vX.X.X)
|
||||
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
|
||||
# 去掉 v 前缀
|
||||
BASE_VERSION="${LATEST_TAG#v}"
|
||||
SHORT_SHA="${GITHUB_SHA::7}"
|
||||
VERSION="${BASE_VERSION}-main.${{ github.run_number }}+${SHORT_SHA}"
|
||||
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
|
||||
echo "Latest tag: ${LATEST_TAG}"
|
||||
echo "Build version: ${VERSION}"
|
||||
- name: Build NapCat.Framework
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
|
||||
run: |
|
||||
npm i -g pnpm
|
||||
pnpm i
|
||||
pnpm run typecheck || exit 1
|
||||
pnpm test || exit 1
|
||||
pnpm --filter napcat-webui-frontend run build || exit 1
|
||||
pnpm run build:framework
|
||||
pnpm --filter napcat-plugin-builtin run build || exit 1
|
||||
mv packages/napcat-framework/dist framework-dist
|
||||
cd framework-dist
|
||||
npm install --omit=dev
|
||||
rm ./package-lock.json || exit 0
|
||||
- name: Upload Artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: NapCat.Framework
|
||||
path: framework-dist
|
||||
Build-Shell:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Clone Main Repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 0 # 需要完整历史来获取 tags
|
||||
- name: Use Node.js 20.X
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 20.x
|
||||
- name: Generate Version
|
||||
run: |
|
||||
# 获取最近的 release tag (格式: vX.X.X)
|
||||
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
|
||||
# 去掉 v 前缀
|
||||
BASE_VERSION="${LATEST_TAG#v}"
|
||||
SHORT_SHA="${GITHUB_SHA::7}"
|
||||
VERSION="${BASE_VERSION}-main.${{ github.run_number }}+${SHORT_SHA}"
|
||||
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
|
||||
echo "Latest tag: ${LATEST_TAG}"
|
||||
echo "Build version: ${VERSION}"
|
||||
- name: Build NapCat.Shell
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
|
||||
run: |
|
||||
npm i -g pnpm
|
||||
pnpm i
|
||||
pnpm run typecheck || exit 1
|
||||
pnpm test || exit 1
|
||||
pnpm --filter napcat-webui-frontend run build || exit 1
|
||||
pnpm run build:shell
|
||||
pnpm --filter napcat-plugin-builtin run build || exit 1
|
||||
mv packages/napcat-shell/dist shell-dist
|
||||
cd shell-dist
|
||||
npm install --omit=dev
|
||||
rm ./package-lock.json || exit 0
|
||||
- name: Upload Artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: NapCat.Shell
|
||||
path: shell-dist
|
||||
@@ -1,303 +0,0 @@
|
||||
# =============================================================================
|
||||
# PR 构建工作流
|
||||
# =============================================================================
|
||||
# 功能:
|
||||
# 1. 在 PR 提交时自动构建 Framework 和 Shell 包
|
||||
# 2. 支持通过 /build 命令手动触发构建(仅协作者/组织成员)
|
||||
# 3. 在 PR 中发布构建状态评论,并持续更新(不会重复创建)
|
||||
# 4. 支持 Fork PR 的构建(使用 pull_request_target 获取写权限)
|
||||
#
|
||||
# 安全说明:
|
||||
# - 使用 pull_request_target 事件,在 base 分支上下文运行
|
||||
# - 构建脚本始终从 base 分支 checkout,避免恶意 PR 篡改脚本
|
||||
# - PR 代码单独 checkout 到 workspace 目录
|
||||
# =============================================================================
|
||||
|
||||
name: PR Build
|
||||
|
||||
# =============================================================================
|
||||
# 触发条件
|
||||
# =============================================================================
|
||||
on:
|
||||
# PR 事件:打开、同步(新推送)、重新打开时触发
|
||||
# 注意:使用 pull_request_target 而非 pull_request,以便对 Fork PR 有写权限
|
||||
pull_request_target:
|
||||
types: [opened, synchronize, reopened]
|
||||
|
||||
# Issue 评论事件:用于响应 /build 命令
|
||||
issue_comment:
|
||||
types: [created]
|
||||
|
||||
# =============================================================================
|
||||
# 权限配置
|
||||
# =============================================================================
|
||||
permissions:
|
||||
contents: read # 读取仓库内容
|
||||
pull-requests: write # 写入 PR 评论
|
||||
issues: write # 写入 Issue 评论(/build 命令响应)
|
||||
actions: read # 读取 Actions 信息(获取构建日志链接)
|
||||
|
||||
# =============================================================================
|
||||
# 并发控制
|
||||
# =============================================================================
|
||||
# 同一 PR 的多次构建会取消之前未完成的构建,避免资源浪费
|
||||
# 注意:只有在 should_build=true 时才会进入实际构建流程,
|
||||
# issue_comment 事件如果不是 /build 命令,会在 check-build 阶段快速退出,
|
||||
# 不会取消正在进行的构建(因为 cancel-in-progress 只影响同 group 的后续任务)
|
||||
concurrency:
|
||||
# 使用不同的 group 策略:
|
||||
# - pull_request_target: 使用 PR 号
|
||||
# - issue_comment: 只有确认是 /build 命令时才使用 PR 号,否则使用 run_id(不冲突)
|
||||
group: pr-build-${{ github.event_name == 'pull_request_target' && github.event.pull_request.number || github.event_name == 'issue_comment' && github.event.issue.pull_request && contains(github.event.comment.body, '/build') && github.event.issue.number || github.run_id }}
|
||||
cancel-in-progress: true
|
||||
|
||||
# =============================================================================
|
||||
# 任务定义
|
||||
# =============================================================================
|
||||
jobs:
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 1: 检查构建条件
|
||||
# ---------------------------------------------------------------------------
|
||||
# 判断是否应该触发构建:
|
||||
# - pull_request_target 事件:总是触发
|
||||
# - issue_comment 事件:检查是否为 /build 命令,且用户有权限
|
||||
# ---------------------------------------------------------------------------
|
||||
check-build:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
should_build: ${{ steps.check.outputs.should_build }} # 是否应该构建
|
||||
pr_number: ${{ steps.check.outputs.pr_number }} # PR 编号
|
||||
pr_sha: ${{ steps.check.outputs.pr_sha }} # PR 最新提交 SHA
|
||||
pr_head_repo: ${{ steps.check.outputs.pr_head_repo }} # PR 源仓库(用于 Fork)
|
||||
pr_head_ref: ${{ steps.check.outputs.pr_head_ref }} # PR 源分支
|
||||
steps:
|
||||
# 仅 checkout 脚本目录,加快速度
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
# 使用 Node.js 24 以支持原生 TypeScript 执行
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
# 执行检查脚本,判断是否触发构建
|
||||
- name: Check trigger condition
|
||||
id: check
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: node --experimental-strip-types .github/scripts/pr-build-check.ts
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 2: 更新评论为"构建中"状态
|
||||
# ---------------------------------------------------------------------------
|
||||
# 在 PR 中创建或更新评论,显示构建正在进行中
|
||||
# ---------------------------------------------------------------------------
|
||||
update-comment-building:
|
||||
needs: check-build
|
||||
if: needs.check-build.outputs.should_build == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
# 更新 PR 评论,显示构建中状态
|
||||
- name: Update building comment
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
PR_NUMBER: ${{ needs.check-build.outputs.pr_number }}
|
||||
PR_SHA: ${{ needs.check-build.outputs.pr_sha }}
|
||||
run: node --experimental-strip-types .github/scripts/pr-build-building.ts
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 3: 构建 Framework 包
|
||||
# ---------------------------------------------------------------------------
|
||||
# 执行 napcat-framework 的构建流程
|
||||
# ---------------------------------------------------------------------------
|
||||
build-framework:
|
||||
needs: [check-build, update-comment-building]
|
||||
if: needs.check-build.outputs.should_build == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
status: ${{ steps.build.outcome }} # 构建结果:success/failure
|
||||
error: ${{ steps.build.outputs.error }} # 错误信息(如有)
|
||||
version: ${{ steps.version.outputs.version }} # 构建版本号
|
||||
steps:
|
||||
# 【安全】先从 base 分支 checkout 构建脚本
|
||||
# 这样即使 PR 中修改了脚本,也不会被执行
|
||||
- name: Checkout scripts from base
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
path: _scripts
|
||||
|
||||
# 将 PR 代码 checkout 到单独的 workspace 目录
|
||||
- name: Checkout PR code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: ${{ needs.check-build.outputs.pr_head_repo }}
|
||||
ref: ${{ needs.check-build.outputs.pr_sha }}
|
||||
path: workspace
|
||||
fetch-depth: 0 # 需要完整历史来获取 tags
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
# 获取最新 release tag 并生成版本号
|
||||
- name: Generate Version
|
||||
id: version
|
||||
working-directory: workspace
|
||||
run: |
|
||||
# 获取最近的 release tag (格式: vX.X.X)
|
||||
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
|
||||
# 去掉 v 前缀
|
||||
BASE_VERSION="${LATEST_TAG#v}"
|
||||
SHORT_SHA="${{ needs.check-build.outputs.pr_sha }}"
|
||||
SHORT_SHA="${SHORT_SHA::7}"
|
||||
VERSION="${BASE_VERSION}-pr.${{ needs.check-build.outputs.pr_number }}.${{ github.run_number }}+${SHORT_SHA}"
|
||||
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
|
||||
echo "Latest tag: ${LATEST_TAG}"
|
||||
echo "Build version: ${VERSION}"
|
||||
|
||||
# 执行构建,使用 base 分支的脚本处理 workspace 中的代码
|
||||
- name: Build
|
||||
id: build
|
||||
working-directory: workspace
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
|
||||
run: node --experimental-strip-types ../_scripts/.github/scripts/pr-build-run.ts framework
|
||||
continue-on-error: true # 允许失败,后续更新评论时处理
|
||||
|
||||
# 构建成功时上传产物
|
||||
- name: Upload Artifact
|
||||
if: steps.build.outcome == 'success'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: NapCat.Framework
|
||||
path: workspace/framework-dist
|
||||
retention-days: 7 # 保留 7 天
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 4: 构建 Shell 包
|
||||
# ---------------------------------------------------------------------------
|
||||
# 执行 napcat-shell 的构建流程(与 Framework 并行执行)
|
||||
# ---------------------------------------------------------------------------
|
||||
build-shell:
|
||||
needs: [check-build, update-comment-building]
|
||||
if: needs.check-build.outputs.should_build == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
status: ${{ steps.build.outcome }} # 构建结果:success/failure
|
||||
error: ${{ steps.build.outputs.error }} # 错误信息(如有)
|
||||
version: ${{ steps.version.outputs.version }} # 构建版本号
|
||||
steps:
|
||||
# 【安全】先从 base 分支 checkout 构建脚本
|
||||
- name: Checkout scripts from base
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
path: _scripts
|
||||
|
||||
# 将 PR 代码 checkout 到单独的 workspace 目录
|
||||
- name: Checkout PR code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
repository: ${{ needs.check-build.outputs.pr_head_repo }}
|
||||
ref: ${{ needs.check-build.outputs.pr_sha }}
|
||||
path: workspace
|
||||
fetch-depth: 0 # 需要完整历史来获取 tags
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
# 获取最新 release tag 并生成版本号
|
||||
- name: Generate Version
|
||||
id: version
|
||||
working-directory: workspace
|
||||
run: |
|
||||
# 获取最近的 release tag (格式: vX.X.X)
|
||||
LATEST_TAG=$(git describe --tags --abbrev=0 --match "v[0-9]*.[0-9]*.[0-9]*" 2>/dev/null || echo "v0.0.0")
|
||||
# 去掉 v 前缀
|
||||
BASE_VERSION="${LATEST_TAG#v}"
|
||||
SHORT_SHA="${{ needs.check-build.outputs.pr_sha }}"
|
||||
SHORT_SHA="${SHORT_SHA::7}"
|
||||
VERSION="${BASE_VERSION}-pr.${{ needs.check-build.outputs.pr_number }}.${{ github.run_number }}+${SHORT_SHA}"
|
||||
echo "NAPCAT_VERSION=${VERSION}" >> $GITHUB_ENV
|
||||
echo "version=${VERSION}" >> $GITHUB_OUTPUT
|
||||
echo "Latest tag: ${LATEST_TAG}"
|
||||
echo "Build version: ${VERSION}"
|
||||
|
||||
# 执行构建
|
||||
- name: Build
|
||||
id: build
|
||||
working-directory: workspace
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
NAPCAT_VERSION: ${{ env.NAPCAT_VERSION }}
|
||||
run: node --experimental-strip-types ../_scripts/.github/scripts/pr-build-run.ts shell
|
||||
continue-on-error: true
|
||||
|
||||
# 构建成功时上传产物
|
||||
- name: Upload Artifact
|
||||
if: steps.build.outcome == 'success'
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: NapCat.Shell
|
||||
path: workspace/shell-dist
|
||||
retention-days: 7 # 保留 7 天
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Job 5: 更新评论为构建结果
|
||||
# ---------------------------------------------------------------------------
|
||||
# 汇总所有构建结果,更新 PR 评论显示最终状态
|
||||
# 使用 always() 确保即使构建失败/取消也会执行
|
||||
# ---------------------------------------------------------------------------
|
||||
update-comment-result:
|
||||
needs: [check-build, update-comment-building, build-framework, build-shell]
|
||||
if: always() && needs.check-build.outputs.should_build == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout scripts
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
sparse-checkout: .github/scripts
|
||||
sparse-checkout-cone-mode: false
|
||||
|
||||
- name: Setup Node.js 24
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 24
|
||||
|
||||
# 更新评论,显示构建结果和下载链接
|
||||
- name: Update result comment
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
PR_NUMBER: ${{ needs.check-build.outputs.pr_number }}
|
||||
PR_SHA: ${{ needs.check-build.outputs.pr_sha }}
|
||||
RUN_ID: ${{ github.run_id }}
|
||||
# 构建版本号
|
||||
NAPCAT_VERSION: ${{ needs.build-framework.outputs.version || needs.build-shell.outputs.version || '' }}
|
||||
# 获取构建状态,如果 job 被跳过则标记为 cancelled
|
||||
FRAMEWORK_STATUS: ${{ needs.build-framework.outputs.status || 'cancelled' }}
|
||||
FRAMEWORK_ERROR: ${{ needs.build-framework.outputs.error }}
|
||||
SHELL_STATUS: ${{ needs.build-shell.outputs.status || 'cancelled' }}
|
||||
SHELL_ERROR: ${{ needs.build-shell.outputs.error }}
|
||||
run: node --experimental-strip-types .github/scripts/pr-build-result.ts
|
||||
@@ -0,0 +1,153 @@
|
||||
name: Release Downstream
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
inputs:
|
||||
tag_name:
|
||||
description: 'Release tag name (e.g., v4.10.7)'
|
||||
required: true
|
||||
type: string
|
||||
|
||||
env:
|
||||
QQ_URL_X86_64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_x86_64.AppImage'
|
||||
QQ_URL_ARM64: 'https://dldir1v6.qq.com/qqfile/qq/QQNT/94704804/linuxqq_3.2.23-44343_arm64.AppImage'
|
||||
|
||||
jobs:
|
||||
get-version:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
latest_tag: ${{ steps.get_version.outputs.latest_tag }}
|
||||
version: ${{ steps.get_version.outputs.version }}
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v5
|
||||
- name: Get Latest NapCat Version
|
||||
id: get_version
|
||||
run: |
|
||||
if [ -n "${{ inputs.tag_name }}" ]; then
|
||||
latest_tag="${{ inputs.tag_name }}"
|
||||
else
|
||||
latest_tag=$(git describe --tags $(git rev-list --tags --max-count=1))
|
||||
fi
|
||||
version=${latest_tag#v}
|
||||
echo "Debug: Latest NapCat Version is ${latest_tag}, version is ${version}"
|
||||
echo "latest_tag=${latest_tag}" >> $GITHUB_OUTPUT
|
||||
echo "version=${version}" >> $GITHUB_OUTPUT
|
||||
|
||||
publish-schema:
|
||||
needs: get-version
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Repository
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: '20'
|
||||
|
||||
- name: Setup pnpm
|
||||
uses: pnpm/action-setup@v4
|
||||
with:
|
||||
version: 9
|
||||
|
||||
- name: Install Dependencies
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Build napcat-schema
|
||||
run: |
|
||||
cd packages/napcat-schema
|
||||
pnpm run build:openapi
|
||||
|
||||
- name: Checkout NapCatDocs
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
repository: NapNeko/NapCatDocs
|
||||
token: ${{ secrets.NAPCAT_BUILD }}
|
||||
path: napcat-docs
|
||||
|
||||
- name: Copy OpenAPI Schema
|
||||
run: |
|
||||
VERSION="${{ needs.get-version.outputs.version }}"
|
||||
mkdir -p napcat-docs/src/api/${VERSION}
|
||||
cp packages/napcat-schema/dist/openapi.json napcat-docs/src/api/${VERSION}/openapi.json
|
||||
echo "OpenAPI schema copied to napcat-docs/src/api/${VERSION}/openapi.json"
|
||||
|
||||
- name: Commit and Push
|
||||
run: |
|
||||
VERSION="${{ needs.get-version.outputs.version }}"
|
||||
cd napcat-docs
|
||||
git config user.name "github-actions[bot]"
|
||||
git config user.email "github-actions[bot]@users.noreply.github.com"
|
||||
git add src/api/${VERSION}/openapi.json
|
||||
git commit -m "chore: update OpenAPI schema for version ${VERSION}" || echo "No changes to commit"
|
||||
git push
|
||||
|
||||
shell-docker:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Trigger NapCat-Docker docker-publish workflow
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
|
||||
run: |
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/NapNeko/NapCat-Docker/actions/workflows/docker-publish.yml/dispatches \
|
||||
-d '{"ref":"main"}'
|
||||
|
||||
framework-docker:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Trigger NapCat-Framework-Docker docker-publish workflow
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
|
||||
run: |
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/NapNeko/NapCat.Docker.Framework/actions/workflows/docker-image.yml/dispatches \
|
||||
-d '{"ref":"main"}'
|
||||
|
||||
appimage:
|
||||
needs: get-version
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Trigger NapCat AppImage build workflow
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
|
||||
NAPCAT_VERSION: ${{ needs.get-version.outputs.latest_tag }}
|
||||
run: |
|
||||
echo "Debug: Triggering NapCat AppImage with napcat_version=${NAPCAT_VERSION}"
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/NapNeko/NapCatAppImageBuild/actions/workflows/release.yml/dispatches \
|
||||
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_version_x86_64\":\"${{ env.QQ_URL_X86_64 }}\",\"qq_version_arm64\":\"${{ env.QQ_URL_ARM64 }}\"}}"
|
||||
|
||||
node-shell:
|
||||
needs: get-version
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
|
||||
NAPCAT_VERSION: ${{ needs.get-version.outputs.latest_tag }}
|
||||
steps:
|
||||
- name: Trigger NapCat NodeLoader release workflow
|
||||
run: |
|
||||
echo "Debug: Triggering NapCat NodeLoader release with napcat_version=${NAPCAT_VERSION}"
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/NapNeko/NapCatLinuxNodeLoader/actions/workflows/release.yml/dispatches \
|
||||
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_url_amd64\":\"${{ env.QQ_URL_X86_64 }}\",\"qq_url_arm64\":\"${{ env.QQ_URL_ARM64 }}\"}}"
|
||||
|
||||
- name: Trigger NapCat NodeLoader docker workflow
|
||||
run: |
|
||||
echo "Debug: Triggering NapCat NodeLoader docker with napcat_version=${NAPCAT_VERSION}"
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/NapNeko/NapCatLinuxNodeLoader/actions/workflows/docker-publish.yml/dispatches \
|
||||
-d "{\"ref\":\"main\",\"inputs\":{\"napcat_version\":\"${NAPCAT_VERSION}\",\"qq_url_amd64\":\"${{ env.QQ_URL_X86_64 }}\",\"qq_url_arm64\":\"${{ env.QQ_URL_ARM64 }}\"}}"
|
||||
@@ -1,115 +1,73 @@
|
||||
name: Release NapCat
|
||||
name: Release Publish
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
inputs:
|
||||
version:
|
||||
description: 'Release version tag (e.g., v4.10.7)'
|
||||
required: true
|
||||
type: string
|
||||
|
||||
permissions: write-all
|
||||
|
||||
env:
|
||||
OPENAI_API_URL: https://openrouter.ai/api/v1/chat/completions
|
||||
OPENAI_MODEL: "stepfun/step-3.5-flash:free"
|
||||
OPENAI_MODEL: "z-ai/glm-4.5-air:free"
|
||||
RELEASE_NAME: "NapCat"
|
||||
|
||||
jobs:
|
||||
# 验证版本号格式
|
||||
validate-version:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
valid: ${{ steps.check.outputs.valid }}
|
||||
version: ${{ steps.check.outputs.version }}
|
||||
steps:
|
||||
- name: Validate semantic version
|
||||
id: check
|
||||
run: |
|
||||
TAG="${GITHUB_REF#refs/tags/}"
|
||||
echo "Checking tag: $TAG"
|
||||
|
||||
# 语义化版本正则表达式
|
||||
# 支持: v1.0.0, v1.0.0-beta, v1.0.0-rc.1, v1.0.0-alpha.1+build.123
|
||||
SEMVER_REGEX="^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-((0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*))?$"
|
||||
|
||||
if [[ "$TAG" =~ $SEMVER_REGEX ]]; then
|
||||
echo "✅ Valid semantic version: $TAG"
|
||||
echo "valid=true" >> $GITHUB_OUTPUT
|
||||
echo "version=$TAG" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "❌ Invalid version format: $TAG"
|
||||
echo "Expected format: vX.Y.Z or vX.Y.Z-prerelease"
|
||||
echo "Examples: v1.0.0, v1.2.3-beta, v2.0.0-rc.1"
|
||||
echo "valid=false" >> $GITHUB_OUTPUT
|
||||
exit 1
|
||||
fi
|
||||
|
||||
Build-Framework:
|
||||
needs: validate-version
|
||||
if: needs.validate-version.outputs.valid == 'true'
|
||||
build:
|
||||
name: Build NapCat.${{ matrix.target.name }}
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
target:
|
||||
- name: Framework
|
||||
build_cmd: build:framework
|
||||
src_dir: packages/napcat-framework/dist
|
||||
dist_dir: framework-dist
|
||||
- name: Shell
|
||||
build_cmd: build:shell
|
||||
src_dir: packages/napcat-shell/dist
|
||||
dist_dir: shell-dist
|
||||
steps:
|
||||
- name: Clone Main Repository
|
||||
uses: actions/checkout@v4
|
||||
- name: Use Node.js 20.X
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
ref: ${{ inputs.version }}
|
||||
- name: Use Node.js 20.x
|
||||
uses: actions/setup-node@v6
|
||||
with:
|
||||
node-version: 20.x
|
||||
- name: Build NapCat.Framework
|
||||
- name: Build NapCat.${{ matrix.target.name }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
npm i -g pnpm
|
||||
pnpm i
|
||||
pnpm --filter napcat-webui-frontend run build || exit 1
|
||||
pnpm run build:framework
|
||||
pnpm run ${{ matrix.target.build_cmd }}
|
||||
pnpm --filter napcat-plugin-builtin run build || exit 1
|
||||
mv packages/napcat-framework/dist framework-dist
|
||||
cd framework-dist
|
||||
mv ${{ matrix.target.src_dir }} ${{ matrix.target.dist_dir }}
|
||||
cd ${{ matrix.target.dist_dir }}
|
||||
npm install --omit=dev
|
||||
rm ./package-lock.json || exit 0
|
||||
- name: Upload Artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: NapCat.Framework
|
||||
path: framework-dist
|
||||
name: NapCat.${{ matrix.target.name }}
|
||||
path: ${{ matrix.target.dist_dir }}
|
||||
|
||||
Build-Shell:
|
||||
needs: validate-version
|
||||
if: needs.validate-version.outputs.valid == 'true'
|
||||
assemble-windows-node:
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Clone Main Repository
|
||||
uses: actions/checkout@v4
|
||||
- name: Use Node.js 20.X
|
||||
uses: actions/setup-node@v4
|
||||
- uses: actions/checkout@v5
|
||||
with:
|
||||
node-version: 20.x
|
||||
- name: Build NapCat.Shell
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
npm i -g pnpm
|
||||
pnpm i
|
||||
pnpm --filter napcat-webui-frontend run build || exit 1
|
||||
pnpm run build:shell
|
||||
pnpm --filter napcat-plugin-builtin run build || exit 1
|
||||
mv packages/napcat-shell/dist shell-dist
|
||||
cd shell-dist
|
||||
npm install --omit=dev
|
||||
rm ./package-lock.json || exit 0
|
||||
- name: Upload Artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: NapCat.Shell
|
||||
path: shell-dist
|
||||
Download-QNX64:
|
||||
needs: Build-Shell
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
ref: ${{ inputs.version }}
|
||||
|
||||
- name: Download Artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
path: ./artifacts
|
||||
|
||||
@@ -118,35 +76,48 @@ jobs:
|
||||
sudo apt update
|
||||
sudo apt install -y aria2 unzip zip p7zip-full curl jq
|
||||
|
||||
- name: Download and Assemble NapCat.Shell.Windows.Node.zip
|
||||
- name: Cache QQ and Node.js downloads
|
||||
id: cache-downloads
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: /tmp/napcat-downloads
|
||||
key: napcat-downloads-qq9.9.27.45627-node22.11.0
|
||||
|
||||
- name: Download QQ and Node.js
|
||||
if: steps.cache-downloads.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir -p /tmp/napcat-downloads
|
||||
cd /tmp/napcat-downloads
|
||||
|
||||
NT_URL="https://dldir1v6.qq.com/qqfile/qq/QQNT/32876254/QQ9.9.27.45627_x64.exe"
|
||||
echo "Downloading QQ installer..."
|
||||
aria2c -x16 -s16 -k1M -o "QQ_x64.exe" "$NT_URL"
|
||||
|
||||
NODE_VER="22.11.0"
|
||||
NODE_URL="https://nodejs.org/dist/v$NODE_VER/node-v$NODE_VER-win-x64.zip"
|
||||
echo "Downloading Node.js $NODE_VER..."
|
||||
aria2c -x1 -s1 -k1M -o "node-win-x64.zip" "$NODE_URL"
|
||||
|
||||
- name: Assemble NapCat.Shell.Windows.Node.zip
|
||||
run: |
|
||||
set -euo pipefail
|
||||
TMPDIR=$(mktemp -d)
|
||||
cd "$TMPDIR"
|
||||
CACHE_DIR="/tmp/napcat-downloads"
|
||||
|
||||
# -----------------------------
|
||||
# 1) 下载 QQ x64
|
||||
# 1) 解压 QQ x64
|
||||
# -----------------------------
|
||||
NT_URL="https://dldir1v6.qq.com/qqfile/qq/QQNT/32876254/QQ9.9.27.45627_x64.exe"
|
||||
QQ_ZIP="$(basename "$NT_URL")"
|
||||
echo "Downloading QQ installer: $QQ_ZIP"
|
||||
aria2c -x16 -s16 -k1M -o "$QQ_ZIP" "$NT_URL"
|
||||
|
||||
QQ_EXTRACT="$TMPDIR/qq_extracted"
|
||||
mkdir -p "$QQ_EXTRACT"
|
||||
7z x -y -o"$QQ_EXTRACT" "$QQ_ZIP" >/dev/null
|
||||
7z x -y -o"$QQ_EXTRACT" "$CACHE_DIR/QQ_x64.exe" >/dev/null
|
||||
|
||||
# -----------------------------
|
||||
# 2) 下载 Node.js Windows x64 zip 22.11.0
|
||||
# 2) 解压 Node.js Windows x64
|
||||
# -----------------------------
|
||||
NODE_VER="22.11.0"
|
||||
NODE_URL="https://nodejs.org/dist/v$NODE_VER/node-v$NODE_VER-win-x64.zip"
|
||||
NODE_ZIP="node-v$NODE_VER-win-x64.zip"
|
||||
aria2c -x1 -s1 -k1M -o "$NODE_ZIP" "$NODE_URL"
|
||||
|
||||
NODE_EXTRACT="$TMPDIR/node_extracted"
|
||||
mkdir -p "$NODE_EXTRACT"
|
||||
unzip -q "$NODE_ZIP" -d "$NODE_EXTRACT"
|
||||
unzip -q "$CACHE_DIR/node-win-x64.zip" -d "$NODE_EXTRACT"
|
||||
|
||||
# -----------------------------
|
||||
# 3) 创建输出目录
|
||||
@@ -180,6 +151,7 @@ jobs:
|
||||
cp -a "$GITHUB_WORKSPACE/packages/napcat-develop/napcat.bat" "$OUT_DIR/" || true
|
||||
cp -a "$GITHUB_WORKSPACE/packages/napcat-develop/index.js" "$OUT_DIR/" || true
|
||||
cp -a "$GITHUB_WORKSPACE/packages/napcat-develop/QQNT.dll" "$OUT_DIR/" || true
|
||||
|
||||
# -----------------------------
|
||||
# 7) 拷贝 Node.exe 到 NapCat.Shell.Windows.Node
|
||||
# -----------------------------
|
||||
@@ -187,22 +159,22 @@ jobs:
|
||||
cp -a "$NODE_EXTRACT/node-v$NODE_VER-win-x64/node.exe" "$OUT_DIR/" || true
|
||||
|
||||
- name: Upload Artifact
|
||||
uses: actions/upload-artifact@v4
|
||||
uses: actions/upload-artifact@v6
|
||||
with:
|
||||
name: NapCat.Shell.Windows.Node
|
||||
path: NapCat.Shell.Windows.Node
|
||||
|
||||
release-napcat:
|
||||
needs: [Build-Framework, Build-Shell, Download-QNX64]
|
||||
needs: [build, assemble-windows-node]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v5
|
||||
with:
|
||||
fetch-depth: 0
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Download Artifacts
|
||||
uses: actions/download-artifact@v4
|
||||
uses: actions/download-artifact@v7
|
||||
with:
|
||||
path: ./artifacts
|
||||
|
||||
@@ -223,13 +195,13 @@ jobs:
|
||||
OPENAI_KEY: ${{ secrets.OPENAI_KEY }}
|
||||
OPENAI_API_URL: ${{ env.OPENAI_API_URL }}
|
||||
OPENAI_MODEL: ${{ env.OPENAI_MODEL }}
|
||||
GITHUB_OWNER: "NapNeko" # 替换成你的 repo owner
|
||||
GITHUB_REPO: "NapCatQQ" # 替换成你的 repo 名
|
||||
GITHUB_OWNER: "NapNeko"
|
||||
GITHUB_REPO: "NapCatQQ"
|
||||
run: |
|
||||
set -euo pipefail
|
||||
|
||||
# 当前 tag
|
||||
CURRENT_TAG="${GITHUB_REF#refs/tags/}"
|
||||
CURRENT_TAG="${{ inputs.version }}"
|
||||
echo "Current tag: $CURRENT_TAG"
|
||||
|
||||
# 从 GitHub API 获取 tag 列表
|
||||
@@ -248,7 +220,7 @@ jobs:
|
||||
done
|
||||
|
||||
if [ -z "$PREV_TAG" ]; then
|
||||
echo "⚠️ Could not find previous tag for $CURRENT_TAG, using first commit"
|
||||
echo "Could not find previous tag for $CURRENT_TAG, using first commit"
|
||||
PREV_TAG=$(git rev-list --max-parents=0 HEAD | head -1)
|
||||
fi
|
||||
|
||||
@@ -259,7 +231,6 @@ jobs:
|
||||
git fetch origin "refs/tags/$CURRENT_TAG:refs/tags/$CURRENT_TAG" --force || true
|
||||
|
||||
# 获取 commit,使用更清晰的格式
|
||||
# 格式: <type>: <subject> (<hash>)
|
||||
COMMITS=$(git log --pretty=format:'- %s (%h)' "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null || git log --pretty=format:'- %s (%h)' -20)
|
||||
|
||||
echo "Commit list from $PREV_TAG to $CURRENT_TAG:"
|
||||
@@ -268,15 +239,15 @@ jobs:
|
||||
# 获取文件变化统计
|
||||
echo "Getting file change statistics..."
|
||||
FILE_STATS=$(git diff --stat "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null || echo "")
|
||||
|
||||
|
||||
# 获取总体统计(最后一行)
|
||||
SUMMARY_LINE=$(echo "$FILE_STATS" | tail -1)
|
||||
echo "Summary: $SUMMARY_LINE"
|
||||
|
||||
|
||||
# 获取每个文件的变化(去掉最后一行汇总)
|
||||
# 截断过长的输出(最多50个文件,每行最多80字符)
|
||||
FILE_CHANGES=$(echo "$FILE_STATS" | head -n -1 | head -50 | cut -c1-80)
|
||||
|
||||
|
||||
# 如果文件变化太多,进一步精简:只保留主要目录的变化
|
||||
FILE_COUNT=$(echo "$FILE_STATS" | head -n -1 | wc -l)
|
||||
if [ "$FILE_COUNT" -gt 50 ]; then
|
||||
@@ -289,28 +260,27 @@ jobs:
|
||||
FILE_CHANGES="[按目录分组统计 - 共 $FILE_COUNT 个文件变更]
|
||||
$DIR_STATS"
|
||||
fi
|
||||
|
||||
|
||||
echo "File changes:"
|
||||
echo "$FILE_CHANGES"
|
||||
|
||||
# 获取具体代码变化(关键文件的diff)
|
||||
echo "Getting code diff for key files..."
|
||||
|
||||
|
||||
# 定义关键目录(优先展示这些目录的变化)
|
||||
KEY_DIRS="packages/napcat-core packages/napcat-onebot packages/napcat-webui-backend"
|
||||
|
||||
|
||||
# 获取变更的关键文件列表(排除测试、配置等)
|
||||
# 使用 || true 防止 grep 无匹配时返回非零退出码
|
||||
KEY_FILES=$(git diff --name-only "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null | \
|
||||
grep -E "^packages/napcat-(core|onebot|webui-backend|shell)/" || true | \
|
||||
grep -E "\.(ts|js)$" || true | \
|
||||
grep -v -E "(test|spec|\.d\.ts|config)" || true | \
|
||||
head -15) || true
|
||||
|
||||
|
||||
CODE_DIFF=""
|
||||
DIFF_CHAR_LIMIT=6000 # 总diff字符限制
|
||||
DIFF_CHAR_LIMIT=6000
|
||||
CURRENT_CHARS=0
|
||||
|
||||
|
||||
if [ -n "$KEY_FILES" ]; then
|
||||
for file in $KEY_FILES; do
|
||||
if [ "$CURRENT_CHARS" -ge "$DIFF_CHAR_LIMIT" ]; then
|
||||
@@ -318,21 +288,19 @@ jobs:
|
||||
[... 更多文件变化已截断 ...]"
|
||||
break
|
||||
fi
|
||||
|
||||
# 获取单个文件的diff,限制每个文件最多50行
|
||||
|
||||
FILE_DIFF=$(git diff "$PREV_TAG".."$CURRENT_TAG" -- "$file" 2>/dev/null | head -50) || true
|
||||
FILE_DIFF_LEN=${#FILE_DIFF}
|
||||
|
||||
# 如果单个文件diff超过1500字符,截断
|
||||
|
||||
if [ "$FILE_DIFF_LEN" -gt 1500 ]; then
|
||||
FILE_DIFF=$(echo "$FILE_DIFF" | head -c 1500)
|
||||
FILE_DIFF="$FILE_DIFF
|
||||
[... 文件 $file 变化已截断 ...]"
|
||||
fi
|
||||
|
||||
|
||||
if [ -n "$FILE_DIFF" ]; then
|
||||
CODE_DIFF="$CODE_DIFF
|
||||
|
||||
|
||||
### $file
|
||||
\`\`\`diff
|
||||
$FILE_DIFF
|
||||
@@ -341,19 +309,19 @@ jobs:
|
||||
fi
|
||||
done
|
||||
fi
|
||||
|
||||
|
||||
# 如果没有关键文件变化,获取前5个变更文件的diff
|
||||
if [ -z "$CODE_DIFF" ]; then
|
||||
echo "No key files changed, getting top changed files..."
|
||||
TOP_FILES=$(git diff --name-only "$PREV_TAG".."$CURRENT_TAG" 2>/dev/null | \
|
||||
grep -E "\.(ts|js|yml|md)$" | head -5) || true
|
||||
|
||||
|
||||
if [ -n "$TOP_FILES" ]; then
|
||||
for file in $TOP_FILES; do
|
||||
FILE_DIFF=$(git diff "$PREV_TAG".."$CURRENT_TAG" -- "$file" 2>/dev/null | head -30) || true
|
||||
if [ -n "$FILE_DIFF" ] && [ ${#FILE_DIFF} -lt 1000 ]; then
|
||||
CODE_DIFF="$CODE_DIFF
|
||||
|
||||
|
||||
### $file
|
||||
\`\`\`diff
|
||||
$FILE_DIFF
|
||||
@@ -362,12 +330,12 @@ jobs:
|
||||
done
|
||||
fi
|
||||
fi
|
||||
|
||||
|
||||
# 如果仍然没有代码变化,添加说明
|
||||
if [ -z "$CODE_DIFF" ]; then
|
||||
CODE_DIFF="[本次更新主要涉及配置文件和文档变更,无核心代码变化]"
|
||||
fi
|
||||
|
||||
|
||||
echo "Code diff preview:"
|
||||
echo "$CODE_DIFF" | head -50
|
||||
|
||||
@@ -378,16 +346,16 @@ jobs:
|
||||
# 构建用户内容,传递更多上下文(包含文件变化和代码diff)
|
||||
USER_CONTENT="当前版本: $CURRENT_TAG
|
||||
上一版本: $PREV_TAG
|
||||
|
||||
|
||||
## 提交列表
|
||||
$COMMITS
|
||||
|
||||
|
||||
## 文件变化统计
|
||||
$SUMMARY_LINE
|
||||
|
||||
|
||||
## 变更文件列表
|
||||
$FILE_CHANGES
|
||||
|
||||
|
||||
## 关键代码变化
|
||||
$CODE_DIFF"
|
||||
|
||||
@@ -406,7 +374,7 @@ jobs:
|
||||
-H "Content-Type: application/json" \
|
||||
-d "$BODY"); then
|
||||
echo "=== raw response ==="
|
||||
echo "$RESPONSE"
|
||||
echo "$RESPONSE"
|
||||
echo "=== parsed response ==="
|
||||
if echo "$RESPONSE" | jq . >/dev/null 2>&1; then
|
||||
echo "$RESPONSE" | jq .
|
||||
@@ -418,18 +386,16 @@ jobs:
|
||||
RELEASE_BODY=$(echo "$RESPONSE" | jq -r '.choices[0].message.content // .choices[0].text // ""' 2>/dev/null || echo "")
|
||||
|
||||
if [ -z "$RELEASE_BODY" ]; then
|
||||
echo "❌ LLM failed to generate release note, using default.md"
|
||||
# 替换默认模板中的版本占位符
|
||||
echo "LLM failed to generate release note, using default.md"
|
||||
sed "s/{VERSION}/$CURRENT_TAG/g" .github/prompt/default.md > CHANGELOG.md
|
||||
else
|
||||
# 后处理:确保版本号正确,并添加比较链接
|
||||
echo -e "$RELEASE_BODY" > CHANGELOG.md
|
||||
# 替换可能的占位符
|
||||
sed -i "s/{VERSION}/$CURRENT_TAG/g" CHANGELOG.md
|
||||
sed -i "s/{PREV_VERSION}/$PREV_TAG/g" CHANGELOG.md
|
||||
fi
|
||||
else
|
||||
echo "❌ Curl failed, using default.md"
|
||||
echo "Curl failed, using default.md"
|
||||
sed "s/{VERSION}/$CURRENT_TAG/g" .github/prompt/default.md > CHANGELOG.md
|
||||
fi
|
||||
echo "=== generated release note ==="
|
||||
@@ -438,9 +404,8 @@ jobs:
|
||||
- name: Create Release and Upload Artifacts
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
tag_name: ${{ github.ref_name }}
|
||||
name: NapCat ${{ github.ref_name }}
|
||||
token: ${{ secrets.NAPCAT_BUILD }}
|
||||
tag_name: ${{ inputs.version }}
|
||||
name: NapCat ${{ inputs.version }}
|
||||
body_path: CHANGELOG.md
|
||||
files: |
|
||||
NapCat.Shell.Windows.Node.zip
|
||||
@@ -449,16 +414,14 @@ jobs:
|
||||
NapCat.Shell.Windows.OneKey.zip
|
||||
draft: false
|
||||
|
||||
|
||||
- name: Update apifox
|
||||
env:
|
||||
APIFOX_TOKEN: ${{ secrets.APIFOX_TOKEN }}
|
||||
run: |
|
||||
npm i -g pnpm
|
||||
pnpm i
|
||||
pnpm i --ignore-scripts
|
||||
pnpm run build:openapi
|
||||
|
||||
# 使用 jq 安全地构建大型 JSON 数据并保存到文件
|
||||
jq -n --rawfile input packages/napcat-schema/dist/openapi.json \
|
||||
'{
|
||||
input: $input,
|
||||
@@ -471,7 +434,6 @@ jobs:
|
||||
}
|
||||
}' > apifox_payload.json
|
||||
|
||||
# 通过文件形式发送数据,避免命令行长度限制
|
||||
curl --location -g --request POST 'https://api.apifox.com/v1/projects/5348325/import-openapi?locale=zh-CN' \
|
||||
--header 'X-Apifox-Api-Version: 2024-03-28' \
|
||||
--header "Authorization: Bearer $APIFOX_TOKEN" \
|
||||
@@ -483,7 +445,7 @@ jobs:
|
||||
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
VERSION="${GITHUB_REF#refs/tags/}"
|
||||
VERSION="${{ inputs.version }}"
|
||||
HASH_REPO="NapNeko/napcat-release-hash"
|
||||
|
||||
gh auth setup-git
|
||||
@@ -506,3 +468,14 @@ jobs:
|
||||
git push origin HEAD:main || git push origin HEAD:master
|
||||
fi
|
||||
|
||||
- name: Trigger downstream release workflows
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
VERSION: ${{ inputs.version }}
|
||||
run: |
|
||||
echo "Triggering release-downstream workflow with tag_name=${VERSION}"
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/${{ github.repository }}/actions/workflows/release-downstream.yml/dispatches \
|
||||
-d "{\"ref\":\"main\",\"inputs\":{\"tag_name\":\"${VERSION}\"}}"
|
||||
@@ -0,0 +1,53 @@
|
||||
name: Release Tag
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
permissions: write-all
|
||||
|
||||
jobs:
|
||||
validate-version:
|
||||
runs-on: ubuntu-latest
|
||||
outputs:
|
||||
valid: ${{ steps.check.outputs.valid }}
|
||||
version: ${{ steps.check.outputs.version }}
|
||||
steps:
|
||||
- name: Validate semantic version
|
||||
id: check
|
||||
run: |
|
||||
TAG="${GITHUB_REF#refs/tags/}"
|
||||
echo "Checking tag: $TAG"
|
||||
|
||||
SEMVER_REGEX="^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-((0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)(\.(0|[1-9][0-9]*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*))?$"
|
||||
|
||||
if [[ "$TAG" =~ $SEMVER_REGEX ]]; then
|
||||
echo "Valid semantic version: $TAG"
|
||||
echo "valid=true" >> $GITHUB_OUTPUT
|
||||
echo "version=$TAG" >> $GITHUB_OUTPUT
|
||||
else
|
||||
echo "Invalid version format: $TAG"
|
||||
echo "Expected format: vX.Y.Z or vX.Y.Z-prerelease"
|
||||
echo "Examples: v1.0.0, v1.2.3-beta, v2.0.0-rc.1"
|
||||
echo "valid=false" >> $GITHUB_OUTPUT
|
||||
exit 1
|
||||
fi
|
||||
|
||||
trigger-release:
|
||||
needs: [validate-version]
|
||||
if: needs.validate-version.outputs.valid == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Trigger release-publish workflow
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.NAPCAT_BUILD }}
|
||||
VERSION: ${{ needs.validate-version.outputs.version }}
|
||||
run: |
|
||||
echo "Triggering release-publish workflow with version=${VERSION}"
|
||||
curl -X POST \
|
||||
-H "Accept: application/vnd.github+json" \
|
||||
-H "Authorization: Bearer $GH_TOKEN" \
|
||||
https://api.github.com/repos/${{ github.repository }}/actions/workflows/release-publish.yml/dispatches \
|
||||
-d "{\"ref\":\"main\",\"inputs\":{\"version\":\"${VERSION}\"}}"
|
||||
Vendored
+1
-1
@@ -6,7 +6,7 @@
|
||||
"vite.config.ts": "vite*.ts",
|
||||
"README.md": "CODE_OF_CONDUCT.md, RELEASES.md, CONTRIBUTING.md, CHANGELOG.md, SECURITY.md",
|
||||
"tsconfig.json": "tsconfig.*.json, env.d.ts",
|
||||
"package.json": "package-lock.json, eslint*, .prettier*, .editorconfig, manifest.json, logo.png, .gitignore, LICENSE"
|
||||
"package.json": "package-lock.json, eslint*, .prettier*, .editorconfig, logo.png, .gitignore, LICENSE"
|
||||
},
|
||||
"css.customData": [
|
||||
".vscode/tailwindcss.json"
|
||||
|
||||
@@ -5,52 +5,41 @@
|
||||
|
||||
_Modern protocol-side framework implemented based on NTQQ._
|
||||
|
||||
> Where clouds rise and winds are born, the heart yearns for distant lands yet untraveled.
|
||||
|
||||
English | [简体中文](./docs/README_zh-CN.md) | [繁體中文](./docs/README_zh-TW.md) | [日本語](./docs/README_ja.md) | [한국어](./docs/README_ko.md) | [Русский](./docs/README_ru.md) | [العربية](./docs/README_ar.md)
|
||||
> 云起兮风生,心向远方兮路未曾至.
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## Notice
|
||||
NapCat is currently looking for a new primary maintainer. Please email nanaeonn@outlook.com if you are interested.
|
||||
## New Framework ?
|
||||
|
||||
### Community Groups
|
||||
|
||||
You can get the join password directly from the **About** page of the WebUI.
|
||||
|
||||
- [NapCat Family Group 1](https://qm.qq.com/q/VwpnklcXqo) Group ID(1090875633)
|
||||
- [NapCat Family Group 2](https://qm.qq.com/q/gq18RH7o7S) Group ID(1059714215)
|
||||
- [NapCat Family Group 3](https://qm.qq.com/q/XyiyGPqa42) Group ID(1085662710)
|
||||
- [NapCat Family Group 4](https://qm.qq.com/q/E4nfkGD6oK) Group ID(1085359803)
|
||||
|
||||
> Note: The join key is only valid for the latest 100 versions, and requires NapCat version >= 4.17.31. If it fails, please update.
|
||||
可以试试更新更好用的 [SnowLuma](https://github.com/SnowLuma/SnowLuma) 作为NapCat Gui替代品。
|
||||
|
||||
## Welcome
|
||||
|
||||
- NapCatQQ is a modern implementation of the Bot protocol based on NTQQ.
|
||||
- NapCatQQ 是现代化的基于 NTQQ 的 Bot 协议端实现
|
||||
|
||||
## Features
|
||||
## Feature
|
||||
|
||||
- **Easy to Use**
|
||||
- Beginners can get started effortlessly.
|
||||
- 作为初学者能够轻松使用.
|
||||
- **Quick and Efficient**
|
||||
- Runs for extended periods on low-memory systems.
|
||||
- 在低内存操作系统长时运行.
|
||||
- **Rich API Interface**
|
||||
- Fully implements most standard interfaces.
|
||||
- 完整实现了大部分标准接口.
|
||||
- **Stable and Reliable**
|
||||
- Continuous and stable development and maintenance.
|
||||
- 持续稳定的开发与维护.
|
||||
|
||||
## Quick Start
|
||||
|
||||
Download the latest version from the [Release](https://github.com/NapNeko/NapCatQQ/releases/) page.
|
||||
可前往 [Release](https://github.com/NapNeko/NapCatQQ/releases/) 页面下载最新版本
|
||||
|
||||
**First-time users** should make sure to read the documentation below for a usage guide.
|
||||
**首次使用**请务必查看如下文档看使用教程
|
||||
|
||||
> This is a non-profit project. For integration issues, basic questions, or underlying framework issues, please search for solutions on your own — this project's community does not provide such support.
|
||||
> 项目非盈利,涉及 对接问题/基础问题/下层框架问题 请自行搜索解决,本项目社区不提供此类解答。
|
||||
|
||||
## Links
|
||||
## Link
|
||||
|
||||
| Docs | [](https://napneko.github.io/) | [](https://doc.napneko.icu/) | [](https://napcat.napneko.icu/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
@@ -58,34 +47,41 @@ Download the latest version from the [Release](https://github.com/NapNeko/NapCat
|
||||
| Docs | [](https://napneko.pages.dev/) | [](https://napcat.top/) | [](https://napcat.top/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| QQ Group | [](https://qm.qq.com/q/E4nfkGD6oK) | [](https://qm.qq.com/q/XyiyGPqa42) | [](https://qm.qq.com/q/gq18RH7o7S) | [](https://qm.qq.com/q/VwpnklcXqo) |
|
||||
|:-:|:-:|:-:|:-:|:-:|
|
||||
|
||||
| Telegram | [](https://t.me/napcatqq) |
|
||||
|:-:|:-:|
|
||||
|
||||
| DeepWiki | [](https://deepwiki.com/NapNeko/NapCatQQ) |
|
||||
|:-:|:-:|
|
||||
|
||||
| QQ Groups | [Happy Family](https://qm.qq.com/q/VwpnklcXqo) | [Royal Relatives](https://qm.qq.com/q/gq18RH7o7S) | [Loving Family](https://qm.qq.com/q/XyiyGPqa42) | [Joyful Family](https://qm.qq.com/q/E4nfkGD6oK) |
|
||||
|:-:|:-:|:-:|:-:|:-:|
|
||||
> QQ群因为特殊原因需要入群密钥,请在webui关于页面获取,仅最新的100个版本以内有效。
|
||||
|
||||
> Please do not mention this project in other communities (including other protocol-side or related application-side projects) to avoid disputes. If you have suggestions, please discuss them in the official group or submit a PR.
|
||||
社区相关日后会进一步加强审核,并严格限制一定时间的入群人数,请具备一定编程基础和问题解决能力再申请入群。
|
||||
|
||||
[困困猫猫的高中](https://qm.qq.com/q/14aUVclRUA)
|
||||
|
||||
## Thanks
|
||||
|
||||
- [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) — Great support for this project; some code was referenced (with permission)
|
||||
- [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) 对本项目的大力支持 参考部分代码 已获授权
|
||||
|
||||
- [AstrBot](https://github.com/AstrBotDevs/AstrBot) — An LLM Bot framework that perfectly integrates with this project
|
||||
- [AstrBot](https://github.com/AstrBotDevs/AstrBot) 是完美适配本项目的LLM Bot框架 在此推荐一下
|
||||
|
||||
- [MaiBot](https://github.com/MaiM-with-u/MaiBot) — A cyber companion Bot framework
|
||||
- [MaiBot](https://github.com/MaiM-with-u/MaiBot) 一只赛博群友 麦麦 Bot框架 在此推荐一下
|
||||
|
||||
- [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) — A message export tool based on NapCat
|
||||
- [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) 基于NapCat的消息导出工具 在此推荐一下
|
||||
|
||||
- And most importantly, thank you — the person reading this right now~
|
||||
- 不过最最重要的 还是需要感谢屏幕前的你哦~
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
This project is open-sourced under a hybrid license. When using this project, please note the following:
|
||||
本项目采用 混合协议 开源,因此使用本项目时,你需要注意以下几点:
|
||||
|
||||
1. Third-party library code or modified portions follow their original open-source licenses.
|
||||
2. This project has obtained authorization from certain projects and is not subject to some restrictions.
|
||||
3. The remaining logic code of the project is governed by the [repository license](./LICENSE).
|
||||
1. 第三方库代码或修改部分遵循其原始开源许可.
|
||||
2. 本项目获取部分项目授权而不受部分约束
|
||||
2. 项目其余逻辑代码采用[本仓库开源许可](./LICENSE).
|
||||
|
||||
**This repository is solely intended to improve usability and implement message push features. Furthermore, developing any project based on NapCat code without prior authorization from the repository's main author is prohibited. Please comply with local laws and regulations when using this project. Any issues arising from misuse are the responsibility of the user and anyone providing tutorials for unauthorized use.**
|
||||
**本仓库仅用于提高易用性,实现消息推送类功能,此外,禁止任何项目未经仓库主作者授权基于 NapCat 代码开发。使用请遵守当地法律法规,由此造成的问题由使用者和提供违规使用教程者负责。**
|
||||
@@ -1,93 +0,0 @@
|
||||
<div dir="rtl">
|
||||
|
||||
<img src="https://napneko.github.io/assets/newnewlogo.png" width = "305" height = "411" alt="NapCat" align=left />
|
||||
<div align="center">
|
||||
|
||||
# NapCat
|
||||
|
||||
_إطار عمل حديث على جانب البروتوكول مبني على NTQQ._
|
||||
|
||||
> حيث تنهض السحب وتولد الرياح، يتوق القلب إلى أراضٍ بعيدة لم تُسلك بعد.
|
||||
|
||||
[English](../README.md) | [简体中文](./README_zh-CN.md) | [繁體中文](./README_zh-TW.md) | [日本語](./README_ja.md) | [한국어](./README_ko.md) | [Русский](./README_ru.md) | العربية
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## إعلان
|
||||
يبحث NapCat حالياً عن مشرف رئيسي جديد. يرجى التواصل عبر البريد الإلكتروني nanaeonn@outlook.com.
|
||||
|
||||
### مجموعات المجتمع
|
||||
|
||||
يمكنك الحصول على كلمة مرور الانضمام مباشرةً من **صفحة "حول" في WebUI**:
|
||||
|
||||
- [NapCat Family] Happy Family 1090875633:https://qm.qq.com/q/VwpnklcXqo
|
||||
- [NapCat Family] Royal Relatives 1059714215:https://qm.qq.com/q/gq18RH7o7S
|
||||
- [NapCat Family] Loving Family 1085662710:https://qm.qq.com/q/XyiyGPqa42
|
||||
- [NapCat Family] Joyful Family 1085359803:https://qm.qq.com/q/E4nfkGD6oK
|
||||
|
||||
## مرحباً
|
||||
|
||||
- NapCatQQ هو تطبيق حديث لبروتوكول Bot مبني على NTQQ
|
||||
|
||||
## المميزات
|
||||
|
||||
- **سهل الاستخدام**
|
||||
- يمكن للمبتدئين البدء بسهولة.
|
||||
- **سريع وفعال**
|
||||
- يعمل لفترات طويلة على أنظمة ذات ذاكرة منخفضة.
|
||||
- **واجهة API غنية**
|
||||
- تنفيذ كامل لمعظم الواجهات القياسية.
|
||||
- **مستقر وموثوق**
|
||||
- تطوير وصيانة مستمرة ومستقرة.
|
||||
|
||||
## البداية السريعة
|
||||
|
||||
قم بتنزيل أحدث إصدار من صفحة [Release](https://github.com/NapNeko/NapCatQQ/releases/)
|
||||
|
||||
**للمستخدمين لأول مرة** تأكد من قراءة الوثائق أدناه للحصول على دليل الاستخدام
|
||||
|
||||
> هذا مشروع غير ربحي. للمشاكل المتعلقة بالتكامل والأسئلة الأساسية ومشاكل إطار العمل الأساسي، يرجى البحث عن الحلول بنفسك — مجتمع هذا المشروع لا يقدم مثل هذا الدعم.
|
||||
|
||||
## الروابط
|
||||
|
||||
| الوثائق | [](https://napneko.github.io/) | [](https://doc.napneko.icu/) | [](https://napcat.napneko.icu/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| الوثائق | [](https://napneko.pages.dev/) | [](https://napcat.top/) | [](https://napcat.top/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| DeepWiki | [](https://deepwiki.com/NapNeko/NapCatQQ) |
|
||||
|:-:|:-:|
|
||||
|
||||
| مجموعات QQ | [Happy Family](https://qm.qq.com/q/VwpnklcXqo) | [Royal Relatives](https://qm.qq.com/q/gq18RH7o7S) | [Loving Family](https://qm.qq.com/q/XyiyGPqa42) | [Joyful Family](https://qm.qq.com/q/E4nfkGD6oK) |
|
||||
|:-:|:-:|:-:|:-:|:-:|
|
||||
|
||||
> يرجى عدم ذكر هذا المشروع في مجتمعات أخرى (بما في ذلك مشاريع البروتوكول الأخرى / مشاريع التطبيقات ذات الصلة) لتجنب الخلافات. إذا كانت لديك اقتراحات، يرجى مناقشتها في المجموعة الرسمية أو تقديم PR.
|
||||
|
||||
## شكر وتقدير
|
||||
|
||||
- [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) — دعم كبير لهذا المشروع؛ تمت الإشارة إلى بعض الأكواد (بإذن)
|
||||
|
||||
- [AstrBot](https://github.com/AstrBotDevs/AstrBot) — إطار عمل LLM Bot متوافق تماماً مع هذا المشروع
|
||||
|
||||
- [MaiBot](https://github.com/MaiM-with-u/MaiBot) — إطار عمل Bot رفيق سيبراني
|
||||
|
||||
- [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) — أداة تصدير الرسائل مبنية على NapCat
|
||||
|
||||
- والأهم من ذلك كله، شكراً لك — أنت الذي تقرأ هذا الآن~
|
||||
|
||||
---
|
||||
|
||||
## الرخصة
|
||||
|
||||
هذا المشروع مفتوح المصدر بموجب رخصة هجينة. عند استخدام هذا المشروع، يرجى ملاحظة ما يلي:
|
||||
|
||||
1. كود المكتبات الخارجية أو الأجزاء المعدلة تخضع لرخصها مفتوحة المصدر الأصلية.
|
||||
2. حصل هذا المشروع على إذن من بعض المشاريع ولا يخضع لبعض القيود.
|
||||
3. باقي الكود المنطقي للمشروع يخضع [لرخصة هذا المستودع](../LICENSE).
|
||||
|
||||
**هذا المستودع مخصص فقط لتحسين سهولة الاستخدام وتنفيذ ميزات دفع الرسائل. علاوة على ذلك، يُحظر تطوير أي مشروع بناءً على كود NapCat دون إذن مسبق من المؤلف الرئيسي للمستودع. يرجى الامتثال للقوانين واللوائح المحلية عند الاستخدام. أي مشاكل ناتجة عن سوء الاستخدام تقع على عاتق المستخدم ومن يقدم تعليمات الاستخدام غير المصرح به.**
|
||||
|
||||
</div>
|
||||
@@ -1,91 +0,0 @@
|
||||
<img src="https://napneko.github.io/assets/newnewlogo.png" width = "305" height = "411" alt="NapCat" align=right />
|
||||
<div align="center">
|
||||
|
||||
# NapCat
|
||||
|
||||
_NTQQをベースにした最新のプロトコル側フレームワーク._
|
||||
|
||||
> 雲起きて風生じ、心は遠方を向けど路は未だ至らず.
|
||||
|
||||
[English](../README.md) | [简体中文](./README_zh-CN.md) | [繁體中文](./README_zh-TW.md) | 日本語 | [한국어](./README_ko.md) | [Русский](./README_ru.md) | [العربية](./README_ar.md)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## お知らせ
|
||||
NapCat は現在、新しいメインメンテナーを募集しています。nanaeonn@outlook.com までメールでご連絡ください。
|
||||
|
||||
### コミュニティグループ
|
||||
|
||||
**WebUI の「について」ページ** から参加パスワードを直接取得できます:
|
||||
|
||||
- [NapCat Family Group 1](https://qm.qq.com/q/VwpnklcXqo) Group ID(1090875633)
|
||||
- [NapCat Family Group 2](https://qm.qq.com/q/gq18RH7o7S) Group ID(1059714215)
|
||||
- [NapCat Family Group 3](https://qm.qq.com/q/XyiyGPqa42) Group ID(1085662710)
|
||||
- [NapCat Family Group 4](https://qm.qq.com/q/E4nfkGD6oK) Group ID(1085359803)
|
||||
|
||||
> 注意:入会キーは最新の100バージョンにのみ有効で、NapCatバージョン >= 4.17.31 が必要です。エラーが発生した場合は更新してください。
|
||||
|
||||
## ようこそ
|
||||
|
||||
- NapCatQQ は NTQQ をベースにした最新の Bot プロトコル側実装です
|
||||
|
||||
## 特徴
|
||||
|
||||
- **簡単に使える**
|
||||
- 初心者でも簡単に使用できます.
|
||||
- **高速で効率的**
|
||||
- 低メモリ環境のOSで長時間稼働できます.
|
||||
- **豊富な API インターフェース**
|
||||
- ほとんどの標準インターフェースを完全に実装しています.
|
||||
- **安定して信頼できる**
|
||||
- 継続的で安定した開発とメンテナンスを行っています.
|
||||
|
||||
## クイックスタート
|
||||
|
||||
最新バージョンは [Release](https://github.com/NapNeko/NapCatQQ/releases/) ページからダウンロードできます
|
||||
|
||||
**初めてご使用の方**は、以下のドキュメントで使用ガイドを必ずご確認ください
|
||||
|
||||
> このプロジェクトは非営利です。連携に関する問題/基本的な問題/下位フレームワークの問題については、ご自身で検索して解決してください。本プロジェクトのコミュニティではそのような回答は提供していません。
|
||||
|
||||
## リンク
|
||||
|
||||
| ドキュメント | [](https://napneko.github.io/) | [](https://doc.napneko.icu/) | [](https://napcat.napneko.icu/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| ドキュメント | [](https://napneko.pages.dev/) | [](https://napcat.top/) | [](https://napcat.top/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| DeepWiki | [](https://deepwiki.com/NapNeko/NapCatQQ) |
|
||||
|:-:|:-:|
|
||||
|
||||
| QQ グループ | [Happy Family](https://qm.qq.com/q/VwpnklcXqo) | [Royal Relatives](https://qm.qq.com/q/gq18RH7o7S) | [Loving Family](https://qm.qq.com/q/XyiyGPqa42) | [Joyful Family](https://qm.qq.com/q/E4nfkGD6oK) |
|
||||
|:-:|:-:|:-:|:-:|:-:|
|
||||
|
||||
> 他のコミュニティでこのプロジェクト(他のプロトコル側/関連アプリケーション側のプロジェクトを含む)に言及して論争を引き起こさないでください。提案がある場合は、公式交流グループで議論するか、PRを提出してください。
|
||||
|
||||
## 謝辞
|
||||
|
||||
- [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) 本プロジェクトへの多大なサポート、一部コードを参考にしています(許可済み)
|
||||
|
||||
- [AstrBot](https://github.com/AstrBotDevs/AstrBot) 本プロジェクトに完璧に対応した LLM Bot フレームワークです
|
||||
|
||||
- [MaiBot](https://github.com/MaiM-with-u/MaiBot) サイバー仲間の 麦麦 Bot フレームワークです
|
||||
|
||||
- [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) NapCat ベースのメッセージエクスポートツールです
|
||||
|
||||
- そして何より大切なのは、画面の前のあなたに感謝することです~
|
||||
|
||||
---
|
||||
|
||||
## ライセンス
|
||||
|
||||
本プロジェクトはハイブリッドライセンスの下でオープンソース化されています。本プロジェクトを使用する際は、以下の点にご注意ください:
|
||||
|
||||
1. サードパーティライブラリのコードまたは修正部分は、元のオープンソースライセンスに従います.
|
||||
2. 本プロジェクトは一部のプロジェクトから許可を得ており、一部の制約を受けません.
|
||||
3. プロジェクトのその他のロジックコードは[本リポジトリのオープンソースライセンス](../LICENSE)に従います.
|
||||
|
||||
**本リポジトリは使いやすさの향上とメッセージプッシュ機能の実装のみを目的としています。また、リポジトリの主要作者の事前許可なく NapCat のコードに基づいてプロジェクトを開発することは禁止されています。使用する際は現地の法律と規制を遵守してください。これに起因する問題は、使用者および違反使用チュートリアルの提供者の責任となります。**
|
||||
@@ -1,89 +0,0 @@
|
||||
<img src="https://napneko.github.io/assets/newnewlogo.png" width = "305" height = "411" alt="NapCat" align=right />
|
||||
<div align="center">
|
||||
|
||||
# NapCat
|
||||
|
||||
_NTQQ 기반으로 구현된 최신 프로토콜 사이드 프레임워크._
|
||||
|
||||
> 구름이 일고 바람이 불어, 마음은 먼 곳을 향하나 길은 아직 닿지 못했네.
|
||||
|
||||
[English](../README.md) | [简体中文](./README_zh-CN.md) | [繁體中文](./README_zh-TW.md) | [日本語](./README_ja.md) | 한국어 | [Русский](./README_ru.md) | [العربية](./README_ar.md)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## 공지
|
||||
NapCat은 현재 새로운 주요 메인테이너를 찾고 있습니다. nanaeonn@outlook.com 으로 이메일을 보내주세요.
|
||||
### 커뮤니티 그룹
|
||||
|
||||
**WebUI 의 「정보」페이지** 에서 입장 비밀번호를 바로 확인할 수 있습니다:
|
||||
|
||||
- [NapCat Family Group 1](https://qm.qq.com/q/VwpnklcXqo) Group ID(1090875633)
|
||||
- [NapCat Family Group 2](https://qm.qq.com/q/gq18RH7o7S) Group ID(1059714215)
|
||||
- [NapCat Family Group 3](https://qm.qq.com/q/XyiyGPqa42) Group ID(1085662710)
|
||||
- [NapCat Family Group 4](https://qm.qq.com/q/E4nfkGD6oK) Group ID(1085359803)
|
||||
|
||||
> 참고: 가입 키는 최신 100개 버전에서만 유효하며, NapCat 버전 >= 4.17.31이 필요합니다. 오류가 발생하면 업데이트하세요.
|
||||
## 환영합니다
|
||||
|
||||
- NapCatQQ는 NTQQ를 기반으로 한 최신 Bot 프로토콜 구현체입니다
|
||||
|
||||
## 특징
|
||||
|
||||
- **사용하기 쉬움**
|
||||
- 초보자도 쉽게 사용할 수 있습니다.
|
||||
- **빠르고 효율적**
|
||||
- 저메모리 시스템에서도 장시간 안정적으로 실행됩니다.
|
||||
- **풍부한 API 인터페이스**
|
||||
- 대부분의 표준 인터페이스를 완전히 구현했습니다.
|
||||
- **안정적이고 신뢰할 수 있음**
|
||||
- 지속적이고 안정적인 개발과 유지보수를 하고 있습니다.
|
||||
|
||||
## 빠른 시작
|
||||
|
||||
[Release](https://github.com/NapNeko/NapCatQQ/releases/) 페이지에서 최신 버전을 다운로드할 수 있습니다
|
||||
|
||||
**처음 사용하시는 분**은 아래 문서에서 사용 가이드를 반드시 확인해 주세요
|
||||
|
||||
> 이 프로젝트는 비영리입니다. 연동 문제/기본 문제/하위 프레임워크 문제는 직접 검색하여 해결해 주세요. 본 프로젝트 커뮤니티에서는 이러한 지원을 제공하지 않습니다.
|
||||
|
||||
## 링크
|
||||
|
||||
| 문서 | [](https://napneko.github.io/) | [](https://doc.napneko.icu/) | [](https://napcat.napneko.icu/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| 문서 | [](https://napneko.pages.dev/) | [](https://napcat.top/) | [](https://napcat.top/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| DeepWiki | [](https://deepwiki.com/NapNeko/NapCatQQ) |
|
||||
|:-:|:-:|
|
||||
|
||||
| QQ 그룹 | [Happy Family](https://qm.qq.com/q/VwpnklcXqo) | [Royal Relatives](https://qm.qq.com/q/gq18RH7o7S) | [Loving Family](https://qm.qq.com/q/XyiyGPqa42) | [Joyful Family](https://qm.qq.com/q/E4nfkGD6oK) |
|
||||
|:-:|:-:|:-:|:-:|:-:|
|
||||
|
||||
> 다른 커뮤니티에서 이 프로젝트(다른 프로토콜 측/관련 애플리케이션 측 프로젝트 포함)를 언급하여 논쟁을 일으키지 마세요. 제안이 있으시면 공식 그룹에서 토론하거나 PR을 제출해 주세요.
|
||||
|
||||
## 감사의 말
|
||||
|
||||
- [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) — 본 프로젝트에 대한 큰 지원, 일부 코드 참고 (허가 완료)
|
||||
|
||||
- [AstrBot](https://github.com/AstrBotDevs/AstrBot) — 본 프로젝트와 완벽하게 호환되는 LLM Bot 프레임워크
|
||||
|
||||
- [MaiBot](https://github.com/MaiM-with-u/MaiBot) — 사이버 친구 麦麦 Bot 프레임워크
|
||||
|
||||
- [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) — NapCat 기반의 메시지 내보내기 도구
|
||||
|
||||
- 그리고 가장 중요한 것은, 지금 이 글을 읽고 있는 당신에게 감사드립니다~
|
||||
|
||||
---
|
||||
|
||||
## 라이선스
|
||||
|
||||
이 프로젝트는 하이브리드 라이선스로 오픈소스화되어 있습니다. 이 프로젝트를 사용할 때 다음 사항에 유의해 주세요:
|
||||
|
||||
1. 서드파티 라이브러리 코드 또는 수정된 부분은 원래의 오픈소스 라이선스를 따릅니다.
|
||||
2. 이 프로젝트는 일부 프로젝트로부터 허가를 받아 일부 제한을 받지 않습니다.
|
||||
3. 프로젝트의 나머지 로직 코드는 [본 리포지토리 라이선스](../LICENSE)를 따릅니다.
|
||||
|
||||
**이 리포지토리는 사용 편의성 향상과 메시지 푸시 기능 구현만을 목적으로 합니다. 또한, 리포지토리 주요 작성자의 사전 승인 없이 NapCat 코드를 기반으로 프로젝트를 개발하는 것은 금지되어 있습니다. 사용 시 현지 법률 및 규정을 준수해 주세요. 이로 인해 발생하는 문제는 사용자 및 위반 사용 튜토리얼 제공자의 책임입니다.**
|
||||
@@ -1,91 +0,0 @@
|
||||
<img src="https://napneko.github.io/assets/newnewlogo.png" width = "305" height = "411" alt="NapCat" align=right />
|
||||
<div align="center">
|
||||
|
||||
# NapCat
|
||||
|
||||
_Современный фреймворк на стороне протокола, реализованный на базе NTQQ._
|
||||
|
||||
> Облака поднимаются, ветер рождается, сердце стремится вдаль, но путь ещё не пройден.
|
||||
|
||||
[English](../README.md) | [简体中文](./README_zh-CN.md) | [繁體中文](./README_zh-TW.md) | [日本語](./README_ja.md) | [한국어](./README_ko.md) | Русский | [العربية](./README_ar.md)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## Объявление
|
||||
NapCat в настоящее время ищет нового основного мейнтейнера. Пожалуйста, свяжитесь с нами по электронной почте nanaeonn@outlook.com.
|
||||
|
||||
### Группы сообщества
|
||||
|
||||
Пароль для вступления можно получить прямо на **странице «О программе» в WebUI**:
|
||||
|
||||
- [NapCat Family Group 1](https://qm.qq.com/q/VwpnklcXqo) Group ID(1090875633)
|
||||
- [NapCat Family Group 2](https://qm.qq.com/q/gq18RH7o7S) Group ID(1059714215)
|
||||
- [NapCat Family Group 3](https://qm.qq.com/q/XyiyGPqa42) Group ID(1085662710)
|
||||
- [NapCat Family Group 4](https://qm.qq.com/q/E4nfkGD6oK) Group ID(1085359803)
|
||||
|
||||
> Примечание: Ключ для входа действителен только для последних 100 версий и требует версию NapCat >= 4.17.31. Если возникает ошибка, пожалуйста, обновитесь.
|
||||
|
||||
## Добро пожаловать
|
||||
|
||||
- NapCatQQ — это современная реализация протокола Bot на базе NTQQ
|
||||
|
||||
## Особенности
|
||||
|
||||
- **Простота использования**
|
||||
- Начинающие пользователи смогут легко освоить работу.
|
||||
- **Скорость и эффективность**
|
||||
- Длительная работа на системах с ограниченным объёмом памяти.
|
||||
- **Богатый API-интерфейс**
|
||||
- Полная реализация большинства стандартных интерфейсов.
|
||||
- **Стабильность и надёжность**
|
||||
- Постоянная стабильная разработка и поддержка.
|
||||
|
||||
## Быстрый старт
|
||||
|
||||
Скачайте последнюю версию на странице [Release](https://github.com/NapNeko/NapCatQQ/releases/)
|
||||
|
||||
**При первом использовании** обязательно ознакомьтесь с руководством в документации ниже
|
||||
|
||||
> Проект является некоммерческим. Вопросы интеграции, базовые вопросы и вопросы по нижележащему фреймворку решайте самостоятельно — сообщество данного проекта не предоставляет такой поддержки.
|
||||
|
||||
## Ссылки
|
||||
|
||||
| Документация | [](https://napneko.github.io/) | [](https://doc.napneko.icu/) | [](https://napcat.napneko.icu/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| Документация | [](https://napneko.pages.dev/) | [](https://napcat.top/) | [](https://napcat.top/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| DeepWiki | [](https://deepwiki.com/NapNeko/NapCatQQ) |
|
||||
|:-:|:-:|
|
||||
|
||||
| QQ группы | [Happy Family](https://qm.qq.com/q/VwpnklcXqo) | [Royal Relatives](https://qm.qq.com/q/gq18RH7o7S) | [Loving Family](https://qm.qq.com/q/XyiyGPqa42) | [Joyful Family](https://qm.qq.com/q/E4nfkGD6oK) |
|
||||
|:-:|:-:|:-:|:-:|:-:|
|
||||
|
||||
> Пожалуйста, не упоминайте данный проект (включая другие протокольные/прикладные проекты) в других сообществах во избежание споров. Если у вас есть предложения, обсуждайте их в официальной группе или отправляйте PR.
|
||||
|
||||
## Благодарности
|
||||
|
||||
- [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) — большая поддержка данного проекта, частично использован код (с разрешения)
|
||||
|
||||
- [AstrBot](https://github.com/AstrBotDevs/AstrBot) — фреймворк LLM Bot, идеально совместимый с данным проектом
|
||||
|
||||
- [MaiBot](https://github.com/MaiM-with-u/MaiBot) — кибер-друг 麦麦, Bot-фреймворк
|
||||
|
||||
- [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) — инструмент экспорта сообщений на базе NapCat
|
||||
|
||||
- И самое главное — спасибо вам, читающему это~
|
||||
|
||||
---
|
||||
|
||||
## Лицензия
|
||||
|
||||
Данный проект распространяется с открытым исходным кодом под гибридной лицензией. При использовании данного проекта обратите внимание на следующее:
|
||||
|
||||
1. Код сторонних библиотек или модифицированные части подчиняются их исходным лицензиям с открытым исходным кодом.
|
||||
2. Данный проект получил разрешение от ряда проектов и не подчиняется некоторым ограничениям.
|
||||
3. Остальной логический код проекта распространяется по [лицензии данного репозитория](../LICENSE).
|
||||
|
||||
**Данный репозиторий предназначен исключительно для повышения удобства использования и реализации функций отправки сообщений. Кроме того, запрещается разработка проектов на основе кода NapCat без предварительного разрешения главного автора репозитория. При использовании соблюдайте местное законодательство. За любые проблемы, вызванные нарушением, несут ответственность пользователь и лицо, предоставившее инструкции по незаконному использованию.**
|
||||
@@ -1,91 +0,0 @@
|
||||
<img src="https://napneko.github.io/assets/newnewlogo.png" width = "305" height = "411" alt="NapCat" align=right />
|
||||
<div align="center">
|
||||
|
||||
# NapCat
|
||||
|
||||
_基于 NTQQ 实现的现代化协议端框架._
|
||||
|
||||
> 云起兮风生,心向远方兮路未曾至.
|
||||
|
||||
[English](../README.md) | 简体中文 | [繁體中文](./README_zh-TW.md) | [日本語](./README_ja.md) | [한국어](./README_ko.md) | [Русский](./README_ru.md) | [العربية](./README_ar.md)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## 公告
|
||||
NapCat 当前正在寻找新的主要维护者,欢迎email到 nanaeonn@outlook.com 。
|
||||
|
||||
### 交流群
|
||||
|
||||
可直接在 **WebUI 关于页面** 获取入群密码:
|
||||
|
||||
- [NapCat家族一群](https://qm.qq.com/q/VwpnklcXqo) 群号(1090875633)
|
||||
- [NapCat家族二群](https://qm.qq.com/q/gq18RH7o7S) 群号(1059714215)
|
||||
- [NapCat家族三群](https://qm.qq.com/q/XyiyGPqa42) 群号(1085662710)
|
||||
- [NapCat家族四群](https://qm.qq.com/q/E4nfkGD6oK) 群号(1085359803)
|
||||
|
||||
> 注意:入群密钥只适合最新的100个版本,且 NapCat 版本需 >= 4.17.31,如果不符合请更新。
|
||||
|
||||
## 欢迎
|
||||
|
||||
- NapCatQQ 是现代化的基于 NTQQ 的 Bot 协议端实现
|
||||
|
||||
## 特性
|
||||
|
||||
- **易于使用**
|
||||
- 作为初学者能够轻松使用.
|
||||
- **快速高效**
|
||||
- 在低内存操作系统长时运行.
|
||||
- **丰富的 API 接口**
|
||||
- 完整实现了大部分标准接口.
|
||||
- **稳定可靠**
|
||||
- 持续稳定的开发与维护.
|
||||
|
||||
## 快速开始
|
||||
|
||||
可前往 [Release](https://github.com/NapNeko/NapCatQQ/releases/) 页面下载最新版本
|
||||
|
||||
**首次使用**请务必查看如下文档看使用教程
|
||||
|
||||
> 项目非盈利,涉及 对接问题/基础问题/下层框架问题 请自行搜索解决,本项目社区不提供此类解答。
|
||||
|
||||
## 链接
|
||||
|
||||
| 文档 | [](https://napneko.github.io/) | [](https://doc.napneko.icu/) | [](https://napcat.napneko.icu/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| 文档 | [](https://napneko.pages.dev/) | [](https://napcat.top/) | [](https://napcat.top/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| DeepWiki | [](https://deepwiki.com/NapNeko/NapCatQQ) |
|
||||
|:-:|:-:|
|
||||
|
||||
| QQ 群 | [欢乐一家亲](https://qm.qq.com/q/VwpnklcXqo) | [皇亲国戚](https://qm.qq.com/q/gq18RH7o7S) | [相亲相爱一家人](https://qm.qq.com/q/XyiyGPqa42) | [开心家族](https://qm.qq.com/q/E4nfkGD6oK) |
|
||||
|:-:|:-:|:-:|:-:|:-:|
|
||||
|
||||
> 请不要在其余社区提及本项目(包括其余协议端/相关应用端项目)引发争论,如有建议到达官方交流群讨论或PR。
|
||||
|
||||
## 致谢
|
||||
|
||||
- [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) 对本项目的大力支持 参考部分代码 已获授权
|
||||
|
||||
- [AstrBot](https://github.com/AstrBotDevs/AstrBot) 是完美适配本项目的LLM Bot框架 在此推荐一下
|
||||
|
||||
- [MaiBot](https://github.com/MaiM-with-u/MaiBot) 一只赛博群友 麦麦 Bot框架 在此推荐一下
|
||||
|
||||
- [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) 基于NapCat的消息导出工具 在此推荐一下
|
||||
|
||||
- 不过最最重要的 还是需要感谢屏幕前的你哦~
|
||||
|
||||
---
|
||||
|
||||
## 许可证
|
||||
|
||||
本项目采用 混合协议 开源,因此使用本项目时,你需要注意以下几点:
|
||||
|
||||
1. 第三方库代码或修改部分遵循其原始开源许可.
|
||||
2. 本项目获取部分项目授权而不受部分约束
|
||||
2. 项目其余逻辑代码采用[本仓库开源许可](../LICENSE).
|
||||
|
||||
**本仓库仅用于提高易用性,实现消息推送类功能,此外,禁止任何项目未经仓库主作者授权基于 NapCat 代码开发。使用请遵守当地法律法规,由此造成的问题由使用者和提供违规使用教程者负责。**
|
||||
@@ -1,91 +0,0 @@
|
||||
<img src="https://napneko.github.io/assets/newnewlogo.png" width = "305" height = "411" alt="NapCat" align=right />
|
||||
<div align="center">
|
||||
|
||||
# NapCat
|
||||
|
||||
_基於 NTQQ 實現的現代化協議端框架._
|
||||
|
||||
> 雲起兮風生,心向遠方兮路未曾至.
|
||||
|
||||
[English](../README.md) | [简体中文](./README_zh-CN.md) | 繁體中文 | [日本語](./README_ja.md) | [한국어](./README_ko.md) | [Русский](./README_ru.md) | [العربية](./README_ar.md)
|
||||
|
||||
</div>
|
||||
|
||||
---
|
||||
|
||||
## 公告
|
||||
NapCat 目前正在尋找新的主要維護者,歡迎透過 email 聯繫 nanaeonn@outlook.com。
|
||||
|
||||
### 交流群
|
||||
|
||||
可直接在 **WebUI 關於頁面** 取得入群密碼:
|
||||
|
||||
- [NapCat家族一群](https://qm.qq.com/q/VwpnklcXqo) 群號(1090875633)
|
||||
- [NapCat家族二群](https://qm.qq.com/q/gq18RH7o7S) 群號(1059714215)
|
||||
- [NapCat家族三群](https://qm.qq.com/q/XyiyGPqa42) 群號(1085662710)
|
||||
- [NapCat家族四群](https://qm.qq.com/q/E4nfkGD6oK) 群號(1085359803)
|
||||
|
||||
> 注意:入群密鑰只適用於最新的100個版本,且 NapCat 版本需 >= 4.17.31,如果錯誤請更新。
|
||||
|
||||
## 歡迎
|
||||
|
||||
- NapCatQQ 是現代化的基於 NTQQ 的 Bot 協議端實現
|
||||
|
||||
## 特性
|
||||
|
||||
- **易於使用**
|
||||
- 初學者也能輕鬆上手.
|
||||
- **快速高效**
|
||||
- 在低記憶體系統長時間穩定運行.
|
||||
- **豐富的 API 介面**
|
||||
- 完整實現了大部分標準介面.
|
||||
- **穩定可靠**
|
||||
- 持續穩定的開發與維護.
|
||||
|
||||
## 快速開始
|
||||
|
||||
可前往 [Release](https://github.com/NapNeko/NapCatQQ/releases/) 頁面下載最新版本
|
||||
|
||||
**首次使用**請務必查看以下文件中的使用教學
|
||||
|
||||
> 專案為非營利性質,涉及 對接問題/基礎問題/底層框架問題 請自行搜尋解決,本專案社群不提供此類解答。
|
||||
|
||||
## 連結
|
||||
|
||||
| 文件 | [](https://napneko.github.io/) | [](https://doc.napneko.icu/) | [](https://napcat.napneko.icu/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| 文件 | [](https://napneko.pages.dev/) | [](https://napcat.top/) | [](https://napcat.top/) |
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|
||||
| DeepWiki | [](https://deepwiki.com/NapNeko/NapCatQQ) |
|
||||
|:-:|:-:|
|
||||
|
||||
| QQ 群 | [歡樂一家親](https://qm.qq.com/q/VwpnklcXqo) | [皇親國戚](https://qm.qq.com/q/gq18RH7o7S) | [相親相愛一家人](https://qm.qq.com/q/XyiyGPqa42) | [開心家族](https://qm.qq.com/q/E4nfkGD6oK) |
|
||||
|:-:|:-:|:-:|:-:|:-:|
|
||||
|
||||
> 請不要在其他社群提及本專案(包括其他協議端/相關應用端專案)以免引發爭論。如有建議,請到官方交流群討論或提交 PR。
|
||||
|
||||
## 致謝
|
||||
|
||||
- [Lagrange](https://github.com/LagrangeDev/Lagrange.Core) 對本專案的大力支持,參考部分程式碼(已獲授權)
|
||||
|
||||
- [AstrBot](https://github.com/AstrBotDevs/AstrBot) 是完美適配本專案的 LLM Bot 框架,在此推薦
|
||||
|
||||
- [MaiBot](https://github.com/MaiM-with-u/MaiBot) 一隻賽博群友 麥麥 Bot 框架,在此推薦
|
||||
|
||||
- [qq-chat-exporter](https://github.com/shuakami/qq-chat-exporter/) 基於 NapCat 的訊息匯出工具,在此推薦
|
||||
|
||||
- 不過最最重要的,還是要感謝螢幕前的你哦~
|
||||
|
||||
---
|
||||
|
||||
## 授權條款
|
||||
|
||||
本專案採用混合協議開源,因此使用本專案時,您需要注意以下幾點:
|
||||
|
||||
1. 第三方函式庫程式碼或修改部分遵循其原始開源授權.
|
||||
2. 本專案已獲取部分專案授權而不受部分約束.
|
||||
3. 專案其餘邏輯程式碼採用[本倉庫開源授權](../LICENSE).
|
||||
|
||||
**本倉庫僅用於提高易用性,實現訊息推送類功能,此外,禁止任何專案未經倉庫主作者授權基於 NapCat 程式碼開發。使用請遵守當地法律法規,由此造成的問題由使用者和提供違規使用教學者負責。**
|
||||
@@ -12,11 +12,12 @@ export interface HttpDownloadOptions {
|
||||
proxy?: string;
|
||||
}
|
||||
|
||||
type Uri2LocalRes = {
|
||||
export type Uri2LocalRes = {
|
||||
success: boolean,
|
||||
errMsg: string,
|
||||
fileName: string,
|
||||
path: string;
|
||||
isLocal: boolean; // true=用户本地文件(不可删除),false=临时下载/解码文件(需清理)
|
||||
};
|
||||
|
||||
// 定义一个异步函数来检查文件是否存在
|
||||
@@ -416,25 +417,24 @@ export async function uriToLocalFile (dir: string, uri: string, filename: string
|
||||
case FileUriType.Local: {
|
||||
const fileExt = path.extname(HandledUri);
|
||||
const localFileName = path.basename(HandledUri, fileExt) + fileExt;
|
||||
const tempFilePath = path.join(dir, filename + fileExt);
|
||||
fs.copyFileSync(HandledUri, tempFilePath);
|
||||
return { success: true, errMsg: '', fileName: localFileName, path: tempFilePath };
|
||||
// 直接返回原始路径,不复制,避免不必要的 IO
|
||||
return { success: true, errMsg: '', fileName: localFileName, path: HandledUri, isLocal: true };
|
||||
}
|
||||
|
||||
case FileUriType.Remote: {
|
||||
const buffer = await httpDownload({ url: HandledUri, headers: headers ?? {}, proxy });
|
||||
fs.writeFileSync(filePath, buffer);
|
||||
return { success: true, errMsg: '', fileName: filename, path: filePath };
|
||||
return { success: true, errMsg: '', fileName: filename, path: filePath, isLocal: false };
|
||||
}
|
||||
|
||||
case FileUriType.Base64: {
|
||||
const base64 = HandledUri.replace(/^base64:\/\//, '');
|
||||
const base64Buffer = Buffer.from(base64, 'base64');
|
||||
fs.writeFileSync(filePath, base64Buffer);
|
||||
return { success: true, errMsg: '', fileName: filename, path: filePath };
|
||||
return { success: true, errMsg: '', fileName: filename, path: filePath, isLocal: false };
|
||||
}
|
||||
|
||||
default:
|
||||
return { success: false, errMsg: `识别URL失败, uri= ${uri}`, fileName: '', path: '' };
|
||||
return { success: false, errMsg: `识别URL失败, uri= ${uri}`, fileName: '', path: '', isLocal: false };
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"target": "ES2021",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Node",
|
||||
"moduleResolution": "bundler",
|
||||
"lib": [
|
||||
"ES2021"
|
||||
],
|
||||
@@ -34,10 +34,15 @@
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"resolveJsonModule": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"napcat-common/src/*": [
|
||||
"../../packages/napcat-common/src/*"
|
||||
],
|
||||
"napcat-image-size/src/*": [
|
||||
"../../packages/napcat-image-size/src/*"
|
||||
],
|
||||
"@/*": [
|
||||
"../*"
|
||||
"../../packages/*"
|
||||
]
|
||||
},
|
||||
"skipLibCheck": true,
|
||||
|
||||
@@ -24,12 +24,28 @@ export class NTQQGroupApi {
|
||||
core: NapCatCore;
|
||||
groupMemberCache: Map<string, Map<string, GroupMember>> = new Map<string, Map<string, GroupMember>>();
|
||||
essenceLRU = new LimitedHashTable<number, string>(1000);
|
||||
// psKey 滑动缓存,TTL 60 秒,惰性删除(不主动清理,等下次访问检测到过期再刷新)
|
||||
private _qunPskeyCache: { value: string; expireAt: number; } | null = null;
|
||||
|
||||
constructor (context: InstanceContext, core: NapCatCore) {
|
||||
this.context = context;
|
||||
this.core = core;
|
||||
}
|
||||
|
||||
/** 获取 qun.qq.com 域名的 psKey,滑动 TTL 60 秒(每次访问顺延) */
|
||||
private async getQunPskey (): Promise<string> {
|
||||
const now = Date.now();
|
||||
if (this._qunPskeyCache && this._qunPskeyCache.expireAt > now) {
|
||||
// 滑动 TTL:每次访问都顺延过期时间
|
||||
this._qunPskeyCache.expireAt = now + 60 * 1000;
|
||||
return this._qunPskeyCache.value;
|
||||
}
|
||||
// 过期或为空,惰性删除旧值(直接覆盖)并重新获取
|
||||
const psKey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com')!;
|
||||
this._qunPskeyCache = { value: psKey, expireAt: now + 60 * 1000 };
|
||||
return psKey;
|
||||
}
|
||||
|
||||
async setGroupRemark (groupCode: string, remark: string) {
|
||||
return this.context.session.getGroupService().modifyGroupRemark(groupCode, remark);
|
||||
}
|
||||
@@ -75,7 +91,7 @@ export class NTQQGroupApi {
|
||||
}
|
||||
|
||||
async fetchGroupEssenceList (groupCode: string) {
|
||||
const pskey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com')!;
|
||||
const pskey = await this.getQunPskey();
|
||||
return this.context.session.getGroupService().fetchGroupEssenceList({
|
||||
groupCode,
|
||||
pageStart: 0,
|
||||
@@ -319,7 +335,7 @@ export class NTQQGroupApi {
|
||||
}
|
||||
|
||||
async deleteGroupBulletin (groupCode: string, noticeId: string) {
|
||||
const psKey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com')!;
|
||||
const psKey = await this.getQunPskey();
|
||||
return this.context.session.getGroupService().deleteGroupBulletin(groupCode, psKey, noticeId);
|
||||
}
|
||||
|
||||
@@ -423,7 +439,7 @@ export class NTQQGroupApi {
|
||||
}
|
||||
|
||||
async uploadGroupBulletinPic (groupCode: string, imageurl: string) {
|
||||
const _Pskey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com')!;
|
||||
const _Pskey = await this.getQunPskey();
|
||||
return this.context.session.getGroupService().uploadGroupBulletinPic(groupCode, _Pskey, imageurl);
|
||||
}
|
||||
|
||||
@@ -466,8 +482,8 @@ export class NTQQGroupApi {
|
||||
return this.context.session.getGroupService().modifyMemberRole(groupCode, memberUid, role);
|
||||
}
|
||||
|
||||
async setGroupName (groupCode: string, groupName: string) {
|
||||
return this.context.session.getGroupService().modifyGroupName(groupCode, groupName, false);
|
||||
async setGroupName (groupCode: string, groupName: string, isNormalMember: boolean = false) {
|
||||
return this.context.session.getGroupService().modifyGroupName(groupCode, groupName, isNormalMember);
|
||||
}
|
||||
|
||||
async publishGroupBulletin (groupCode: string, content: string, picInfo: {
|
||||
@@ -475,7 +491,7 @@ export class NTQQGroupApi {
|
||||
width: number,
|
||||
height: number;
|
||||
} | undefined = undefined, pinned: number = 0, confirmRequired: number = 0) {
|
||||
const psKey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com');
|
||||
const psKey = await this.getQunPskey();
|
||||
// text是content内容url编码
|
||||
const data = {
|
||||
text: encodeURI(content),
|
||||
|
||||
@@ -67,6 +67,18 @@ export class NTQQMsgApi {
|
||||
return this.context.session.getMsgService().fetchFavEmojiList('', num, true, true);
|
||||
}
|
||||
|
||||
async addFavEmoji (req: Parameters<NodeIKernelMsgService['addFavEmoji']>[0]) {
|
||||
return this.context.session.getMsgService().addFavEmoji(req);
|
||||
}
|
||||
|
||||
async deleteFavEmoji (ids: string[]) {
|
||||
return this.context.session.getMsgService().deleteFavEmoji(ids);
|
||||
}
|
||||
|
||||
async modifyFavEmojiDesc (items: Parameters<NodeIKernelMsgService['modifyFavEmojiDesc']>[0]) {
|
||||
return this.context.session.getMsgService().modifyFavEmojiDesc(items);
|
||||
}
|
||||
|
||||
async queryMsgsWithFilterExWithSeq (peer: Peer, msgSeq: string) {
|
||||
return await this.context.session.getMsgService().queryMsgsWithFilterEx('0', '0', msgSeq, {
|
||||
chatInfo: peer,
|
||||
|
||||
@@ -328,6 +328,10 @@ export class NTQQWebApi {
|
||||
return (hash & 0x7FFFFFFF).toString();
|
||||
}
|
||||
|
||||
public getBknFromPSKey (psKey: string) {
|
||||
return this.getBknFromSKey(psKey);
|
||||
}
|
||||
|
||||
async getAlbumListByNTQQ (gc: string, attach_info: string = '') {
|
||||
return await this.context.session.getAlbumService().getAlbumList({
|
||||
qun_id: gc,
|
||||
@@ -503,20 +507,73 @@ export class NTQQWebApi {
|
||||
async doAlbumMediaLikeByNTQQ (
|
||||
qunId: string,
|
||||
albumId: string,
|
||||
lloc: string,
|
||||
id: string) {
|
||||
batchId: string,
|
||||
lloc: string | undefined,
|
||||
isLike: boolean
|
||||
) {
|
||||
const random_seq = Math.floor(Math.random() * 9000) + 1000;
|
||||
const uin = this.core.selfInfo.uin || '10001';
|
||||
|
||||
const type = isLike ? 2 : 1;
|
||||
const status = isLike ? 0 : 1;
|
||||
|
||||
let id = '';
|
||||
if (lloc) {
|
||||
id = `421_1_0_${qunId}|${albumId}|${batchId}^||^421_1_0_${qunId}|${albumId}|${lloc}^||^0`;
|
||||
} else {
|
||||
id = `421_1_0_${qunId}|${albumId}|${batchId}`;
|
||||
}
|
||||
|
||||
return await this.context.session.getAlbumService().doQunLike(
|
||||
random_seq, {
|
||||
random_seq,
|
||||
{
|
||||
map_info: [],
|
||||
map_bytes_info: [],
|
||||
map_user_account: [],
|
||||
}, {
|
||||
id,
|
||||
status: 1,
|
||||
},
|
||||
createAlbumFeedPublish(qunId, uin, albumId, lloc)
|
||||
type,
|
||||
{
|
||||
id,
|
||||
status,
|
||||
},
|
||||
createAlbumFeedPublish(qunId, uin, albumId, batchId)
|
||||
);
|
||||
}
|
||||
|
||||
async getDaySignedList (groupCode: string) {
|
||||
const pSkey = (await this.core.apis.UserApi.getPSkey(['qun.qq.com'])).domainPskeyMap.get('qun.qq.com')!;
|
||||
const selfUin = this.core.selfInfo.uin;
|
||||
const cookie = `p_uin=o${selfUin}; p_skey=${pSkey}; uin=o${selfUin}`;
|
||||
const post = await RequestUtil.HttpGetJson<{
|
||||
retCode: number,
|
||||
costTime: number,
|
||||
response: {
|
||||
ret?: {
|
||||
code: string,
|
||||
msg: string,
|
||||
},
|
||||
page?: {
|
||||
infos?: {
|
||||
uid: string,
|
||||
uidGroupNick: string,
|
||||
signedTimeStamp: string,
|
||||
signInRank: number,
|
||||
}[],
|
||||
offset: number,
|
||||
total: number,
|
||||
}[],
|
||||
},
|
||||
funcCode: number,
|
||||
}>(`https://qun.qq.com/v2/signin/trpc/GetDaySignedList?g_tk=${this.getBknFromPSKey(pSkey)}`, 'POST', {
|
||||
dayYmd: new Date().toISOString().slice(0, 10).replace(/-/g, ''),
|
||||
offset: 0,
|
||||
limit: 100,
|
||||
uid: selfUin,
|
||||
groupId: groupCode,
|
||||
}, {
|
||||
Cookie: cookie,
|
||||
'Content-Type': 'application/json',
|
||||
});
|
||||
return post;
|
||||
}
|
||||
}
|
||||
@@ -163,14 +163,14 @@ export interface AlbumFeedLikePublish {
|
||||
};
|
||||
cell_media: {
|
||||
album_id: string;
|
||||
batch_id: number;
|
||||
media_items: Array<{
|
||||
batch_id: string | number;
|
||||
media_items?: {
|
||||
type: number;
|
||||
image: {
|
||||
lloc: string;
|
||||
sloc: string;
|
||||
};
|
||||
}>;
|
||||
}[];
|
||||
};
|
||||
cell_qun_info: {
|
||||
qun_id: string;
|
||||
@@ -182,21 +182,19 @@ export interface AlbumFeedLikePublish {
|
||||
* @param qunId 群号
|
||||
* @param uin 用户QQ号
|
||||
* @param albumId 相册ID
|
||||
* @param lloc 信息
|
||||
* @param sloc 信息(可选,默认与lloc相同)
|
||||
* @param batchId 批次ID
|
||||
* @returns 动态发布请求参数对象
|
||||
*/
|
||||
export function createAlbumFeedPublish (
|
||||
qunId: string,
|
||||
uin: string,
|
||||
albumId: string,
|
||||
lloc: string,
|
||||
sloc?: string
|
||||
): AlbumFeedLikePublish {
|
||||
batchId: string
|
||||
) {
|
||||
return {
|
||||
cell_common: {
|
||||
time: Date.now(),
|
||||
feed_id: '',
|
||||
feed_id: `422_0_${batchId}`, // 需要补全feed_id
|
||||
},
|
||||
cell_user_info: {
|
||||
user: {
|
||||
@@ -205,14 +203,7 @@ export function createAlbumFeedPublish (
|
||||
},
|
||||
cell_media: {
|
||||
album_id: albumId,
|
||||
batch_id: 0,
|
||||
media_items: [{
|
||||
type: 0,
|
||||
image: {
|
||||
lloc,
|
||||
sloc: sloc || lloc,
|
||||
},
|
||||
}],
|
||||
batch_id: batchId,
|
||||
},
|
||||
cell_qun_info: {
|
||||
qun_id: qunId,
|
||||
|
||||
+56
@@ -534,5 +534,61 @@
|
||||
"9.9.27-45758": {
|
||||
"appid": 537340213,
|
||||
"qua": "V1_WIN_NQ_9.9.27_45758_GW_B"
|
||||
},
|
||||
"3.2.26-46494": {
|
||||
"appid": 537345891,
|
||||
"qua": "V1_LNX_NQ_3.2.26_46494_GW_B"
|
||||
},
|
||||
"9.9.28-46494": {
|
||||
"appid": 537345855,
|
||||
"qua": "V1_WIN_NQ_9.9.28_46494_GW_B"
|
||||
},
|
||||
"6.9.90-46494": {
|
||||
"appid": 537345879,
|
||||
"qua": "V1_MAC_NQ_6.9.90_46494_GW_B"
|
||||
},
|
||||
"3.2.26-46928": {
|
||||
"appid": 537345994,
|
||||
"qua": "V1_LNX_NQ_3.2.26_46928_GW_B"
|
||||
},
|
||||
"9.9.28-46928": {
|
||||
"appid": 537345957,
|
||||
"qua": "V1_WIN_NQ_9.9.28_46928_GW_B"
|
||||
},
|
||||
"3.2.27-47354": {
|
||||
"appid": 537346908,
|
||||
"qua": "V1_LNX_NQ_3.2.27_47354_GW_B"
|
||||
},
|
||||
"9.9.29-47354": {
|
||||
"appid": 537346872,
|
||||
"qua": "V1_WIN_NQ_9.9.29_47354_GW_B"
|
||||
},
|
||||
"6.9.93-47354": {
|
||||
"appid": 537346896,
|
||||
"qua": "V1_MAC_NQ_6.9.93_47354_GW_B"
|
||||
},
|
||||
"9.9.30-48517": {
|
||||
"appid": 537352474,
|
||||
"qua": "V1_WIN_NQ_9.9.30_48517_GW_B"
|
||||
},
|
||||
"3.2.28-48517": {
|
||||
"appid": 537352510,
|
||||
"qua": "V1_LNX_NQ_3.2.28_48517_GW_B"
|
||||
},
|
||||
"9.9.30-48762": {
|
||||
"appid": 537352525,
|
||||
"qua": "V1_WIN_NQ_9.9.30_48762_GW_B"
|
||||
},
|
||||
"9.9.31-49599": {
|
||||
"appid": 537355779,
|
||||
"qua": "V1_WIN_NQ_9.9.31_49599_GW_B"
|
||||
},
|
||||
"9.9.31-49738": {
|
||||
"appid": 537355830,
|
||||
"qua": "V1_WIN_NQ_9.9.31_49738_GW_B"
|
||||
},
|
||||
"3.2.29-49738": {
|
||||
"appid": 537355867,
|
||||
"qua": "V1_LNX_NQ_3.2.29_49738_GW_B"
|
||||
}
|
||||
}
|
||||
+76
@@ -178,5 +178,81 @@
|
||||
"9.9.27-45758-x64": {
|
||||
"send": "0A6A6BC",
|
||||
"recv": "1E87EC1"
|
||||
},
|
||||
"9.9.28-46494-x64": {
|
||||
"send": "0A6D66C",
|
||||
"recv": "1E9890D"
|
||||
},
|
||||
"3.2.26-46494-x64": {
|
||||
"send": "5D30910",
|
||||
"recv": "31814B0"
|
||||
},
|
||||
"3.2.26-46494-arm64": {
|
||||
"send": "3EDC654",
|
||||
"recv": "14A3124"
|
||||
},
|
||||
"3.2.26-46928-x64": {
|
||||
"send": "5D30910",
|
||||
"recv": "31814B0"
|
||||
},
|
||||
"3.2.26-46928-arm64": {
|
||||
"send": "3EDC654",
|
||||
"recv": "14A3124"
|
||||
},
|
||||
"9.9.28-46928-x64": {
|
||||
"send": "0A6D66C",
|
||||
"recv": "1E9890D"
|
||||
},
|
||||
"3.2.27-47354-x64": {
|
||||
"send": "5D38930",
|
||||
"recv": "318D090"
|
||||
},
|
||||
"3.2.27-47354-arm64": {
|
||||
"send": "3EE8B24",
|
||||
"recv": "14D422C"
|
||||
},
|
||||
"9.9.29-47354-x64": {
|
||||
"send": "0A70B3C",
|
||||
"recv": "1EAFD51"
|
||||
},
|
||||
"6.9.93-47354-arm64": {
|
||||
"send": "244066C",
|
||||
"recv": "09BCCF8"
|
||||
},
|
||||
"6.9.93-47354-x64": {
|
||||
"send": "28ADE46",
|
||||
"recv": "0A8FD5A"
|
||||
},
|
||||
"9.9.30-48517-x64": {
|
||||
"send": "0A9B1BC",
|
||||
"recv": "1F0324D"
|
||||
},
|
||||
"3.2.28-48517-x64": {
|
||||
"send": "5E41890",
|
||||
"recv": "3216D10"
|
||||
},
|
||||
"3.2.28-48517-arm64": {
|
||||
"send": "3F9C7E4",
|
||||
"recv": "14E1AA8"
|
||||
},
|
||||
"9.9.30-48762-x64": {
|
||||
"send": "0A9B1BC",
|
||||
"recv": "1F0324D"
|
||||
},
|
||||
"9.9.31-49599-x64": {
|
||||
"send": "0AF885C",
|
||||
"recv": "20058E1"
|
||||
},
|
||||
"9.9.31-49738-x64": {
|
||||
"send": "0AF9FCC",
|
||||
"recv": "2007901"
|
||||
},
|
||||
"3.2.29-49738-x64": {
|
||||
"send": "6234600",
|
||||
"recv": "33D89D0"
|
||||
},
|
||||
"3.2.29-49738-arm64": {
|
||||
"send": "426AA04",
|
||||
"recv": "1596254"
|
||||
}
|
||||
}
|
||||
+76
@@ -686,5 +686,81 @@
|
||||
"3.2.25-45758-arm64": {
|
||||
"send": "6D6F9A0",
|
||||
"recv": "6D73350"
|
||||
},
|
||||
"3.2.26-46494-x64": {
|
||||
"send": "AB341C0",
|
||||
"recv": "AB37C60"
|
||||
},
|
||||
"9.9.28-46494-x64": {
|
||||
"send": "2E77C20",
|
||||
"recv": "2E7B1A0"
|
||||
},
|
||||
"3.2.26-46494-arm64": {
|
||||
"send": "6DBBBB0",
|
||||
"recv": "6DBF560"
|
||||
},
|
||||
"3.2.26-46928-arm64": {
|
||||
"send": "6DBBBB0",
|
||||
"recv": "6DBF560"
|
||||
},
|
||||
"3.2.26-46928-x64": {
|
||||
"send": "AB341C0",
|
||||
"recv": "AB37C60"
|
||||
},
|
||||
"9.9.28-46928-x64": {
|
||||
"send": "2E77C20",
|
||||
"recv": "2E7B1A0"
|
||||
},
|
||||
"3.2.27-47354-x64": {
|
||||
"send": "AB6A6C0",
|
||||
"recv": "AB6E160"
|
||||
},
|
||||
"3.2.27-47354-arm64": {
|
||||
"send": "6DE1438",
|
||||
"recv": "6DE4DE8"
|
||||
},
|
||||
"9.9.29-47354-x64": {
|
||||
"send": "2E84920",
|
||||
"recv": "2E87EA0"
|
||||
},
|
||||
"6.9.93-47354-arm64": {
|
||||
"send": "3FD1E98",
|
||||
"recv": "3FD47A8"
|
||||
},
|
||||
"6.9.93-47354-x64": {
|
||||
"send": "47CD940",
|
||||
"recv": "47D04F0"
|
||||
},
|
||||
"3.2.28-48517-x64": {
|
||||
"send": "AD7C280",
|
||||
"recv": "AD7FD20"
|
||||
},
|
||||
"9.9.30-48517-x64": {
|
||||
"send": "2F3B960",
|
||||
"recv": "2F3EEE0"
|
||||
},
|
||||
"3.2.28-48517-arm64": {
|
||||
"send": "6F48B70",
|
||||
"recv": "6F4C520"
|
||||
},
|
||||
"9.9.30-48762-x64": {
|
||||
"send": "2F3B960",
|
||||
"recv": "2F3EEE0"
|
||||
},
|
||||
"9.9.31-49599-x64": {
|
||||
"send": "3082C40",
|
||||
"recv": "30861C8"
|
||||
},
|
||||
"9.9.31-49738-x64": {
|
||||
"send": "3086C80",
|
||||
"recv": "308A208"
|
||||
},
|
||||
"3.2.29-49738-x64": {
|
||||
"send": "B3B20A0",
|
||||
"recv": "B3B5B40"
|
||||
},
|
||||
"3.2.29-49738-arm64": {
|
||||
"send": "7342800",
|
||||
"recv": "73461B0"
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
import { ConfigBase } from '@/napcat-core/helper/config-base';
|
||||
import { NapCatCore } from '@/napcat-core/index';
|
||||
import { Type, Static } from '@sinclair/typebox';
|
||||
import { Type, Static, TSchema } from '@sinclair/typebox';
|
||||
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
import { TSchema } from '@sinclair/typebox';
|
||||
|
||||
import path from 'node:path';
|
||||
import fs from 'node:fs';
|
||||
import json5 from 'json5';
|
||||
|
||||
@@ -101,7 +101,7 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
|
||||
// 获取文件大小和类型
|
||||
const [fileType, duration] = await Promise.all([
|
||||
fileTypeFromFile(videoPath).catch(() => null),
|
||||
this.getDuration(videoPath),
|
||||
this.getDuration(videoPath).catch(() => 60),
|
||||
]);
|
||||
|
||||
// 创建临时缩略图路径
|
||||
@@ -136,22 +136,24 @@ export class FFmpegExecAdapter implements IFFmpegAdapter {
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取时长
|
||||
*/
|
||||
* 获取时长
|
||||
*/
|
||||
async getDuration (filePath: string): Promise<number> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(this.ffprobePath, [
|
||||
'-v', 'error',
|
||||
'-show_entries', 'format=duration',
|
||||
'-of', 'default=noprint_wrappers=1:nokey=1',
|
||||
filePath,
|
||||
]);
|
||||
const { stdout } = await execFileAsync(this.ffprobePath, [
|
||||
'-v',
|
||||
'error',
|
||||
'-show_entries',
|
||||
'format=duration',
|
||||
'-of',
|
||||
'default=noprint_wrappers=1:nokey=1',
|
||||
filePath,
|
||||
]);
|
||||
|
||||
const duration = parseFloat(stdout.trim());
|
||||
return isNaN(duration) ? 60 : duration;
|
||||
} catch {
|
||||
return 60; // 默认时长
|
||||
const duration = parseFloat(stdout.trim());
|
||||
if (isNaN(duration)) {
|
||||
throw new Error(`ffprobe 返回了无效的时长值: "${stdout.trim()}"`);
|
||||
}
|
||||
return duration;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -59,13 +59,17 @@ class Subscription {
|
||||
export const logSubscription = new Subscription();
|
||||
|
||||
export class LogWrapper implements ILogWrapper {
|
||||
fileLogEnabled = true;
|
||||
fileLogEnabled = false;
|
||||
consoleLogEnabled = true;
|
||||
logger: winston.Logger;
|
||||
|
||||
private logPath: string;
|
||||
private fileTransportAdded = false;
|
||||
private fileLogLevel: string = LogLevel.DEBUG;
|
||||
|
||||
constructor (logDir: string) {
|
||||
const filename = `${getFormattedTimestamp()}.log`;
|
||||
const logPath = path.join(logDir, filename);
|
||||
this.logPath = path.join(logDir, filename);
|
||||
|
||||
this.logger = winston.createLogger({
|
||||
level: 'debug',
|
||||
@@ -77,12 +81,6 @@ export class LogWrapper implements ILogWrapper {
|
||||
})
|
||||
),
|
||||
transports: [
|
||||
new transports.File({
|
||||
filename: logPath,
|
||||
level: 'debug',
|
||||
maxsize: 5 * 1024 * 1024, // 5MB
|
||||
maxFiles: 5,
|
||||
}),
|
||||
new transports.Console({
|
||||
format: format.combine(
|
||||
format.colorize(),
|
||||
@@ -107,7 +105,7 @@ export class LogWrapper implements ILogWrapper {
|
||||
this.deleteOldLogFile(filePath, oneWeekAgo);
|
||||
});
|
||||
}).catch((err) => {
|
||||
this.logger.error('Failed to read log directory', err);
|
||||
this.logError('Failed to read log directory', err);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -117,21 +115,22 @@ export class LogWrapper implements ILogWrapper {
|
||||
fs.unlink(filePath).catch((err) => {
|
||||
if (err) {
|
||||
if (err.code === 'ENOENT') {
|
||||
this.logger.warn(`File already deleted: ${filePath}`);
|
||||
this.logWarn(`File already deleted: ${filePath}`);
|
||||
} else {
|
||||
this.logger.error('Failed to delete old log file', err);
|
||||
this.logError('Failed to delete old log file', err);
|
||||
}
|
||||
} else {
|
||||
this.logger.info(`Deleted old log file: ${filePath}`);
|
||||
this.log(`Deleted old log file: ${filePath}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
}).catch((err) => {
|
||||
this.logger.error('Failed to get file stats', err);
|
||||
this.logError('Failed to get file stats', err);
|
||||
});
|
||||
}
|
||||
|
||||
setFileAndConsoleLogLevel (fileLogLevel: LogLevel, consoleLogLevel: LogLevel) {
|
||||
this.fileLogLevel = fileLogLevel;
|
||||
this.logger.transports.forEach((transport) => {
|
||||
if (transport instanceof transports.File) {
|
||||
transport.level = fileLogLevel;
|
||||
@@ -148,6 +147,15 @@ export class LogWrapper implements ILogWrapper {
|
||||
|
||||
setFileLogEnabled (isEnabled: boolean) {
|
||||
this.fileLogEnabled = isEnabled;
|
||||
if (isEnabled && !this.fileTransportAdded) {
|
||||
this.fileTransportAdded = true;
|
||||
this.logger.add(new transports.File({
|
||||
filename: this.logPath,
|
||||
level: this.fileLogLevel,
|
||||
maxsize: 5 * 1024 * 1024, // 5MB
|
||||
maxFiles: 5,
|
||||
}));
|
||||
}
|
||||
this.logger.transports.forEach((transport) => {
|
||||
if (transport instanceof transports.File) {
|
||||
transport.silent = !isEnabled;
|
||||
@@ -178,16 +186,18 @@ export class LogWrapper implements ILogWrapper {
|
||||
}
|
||||
|
||||
_log (level: LogLevel, ...args: any[]) {
|
||||
const message = this.formatMsg(args);
|
||||
if (this.consoleLogEnabled && this.fileLogEnabled) {
|
||||
this.logger.log(level, message);
|
||||
} else if (this.consoleLogEnabled) {
|
||||
this.logger.log(level, message);
|
||||
} else if (this.fileLogEnabled) {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
this.logger.log(level, message.replace(/\x1B[@-_][0-?]*[ -/]*[@-~]/g, ''));
|
||||
if (this.consoleLogEnabled || this.fileLogEnabled) {
|
||||
const message = this.formatMsg(args);
|
||||
if (this.consoleLogEnabled && this.fileLogEnabled) {
|
||||
this.logger.log(level, message);
|
||||
} else if (this.consoleLogEnabled) {
|
||||
this.logger.log(level, message);
|
||||
} else if (this.fileLogEnabled) {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
this.logger.log(level, message.replace(/\x1B[@-_][0-?]*[ -/]*[@-~]/g, ''));
|
||||
}
|
||||
logSubscription.notify(JSON.stringify({ level, message }));
|
||||
}
|
||||
logSubscription.notify(JSON.stringify({ level, message }));
|
||||
}
|
||||
|
||||
log (...args: any[]) {
|
||||
|
||||
@@ -180,16 +180,22 @@ export class NapCatCore {
|
||||
if (process.env['NAPCAT_DISABLE_TIME_SYNC'] === '1' || !this.configLoader.configData.autoTimeSync) {
|
||||
this.context.logger.log('[ServerTime] 自动对时已禁用');
|
||||
} else {
|
||||
try {
|
||||
const offsetMs = hookGlobalDateNow(() => this.context.session.getMSFService().getServerTime());
|
||||
if (Math.abs(offsetMs) > 5000) {
|
||||
this.context.logger.logWarn(`[ServerTime] 本地时间与服务器时间偏差 ${(offsetMs / 1000).toFixed(1)}s,已自动矫正`);
|
||||
} else {
|
||||
this.context.logger.log(`[ServerTime] 时间同步完成,偏差 ${offsetMs}ms`);
|
||||
const doTimeSync = () => {
|
||||
try {
|
||||
const offsetMs = hookGlobalDateNow(() => this.context.session.getMSFService().getServerTime());
|
||||
if (Math.abs(offsetMs) > 5000) {
|
||||
this.context.logger.logWarn(`[ServerTime] 本地时间与服务器时间偏差 ${(offsetMs / 1000).toFixed(1)}s,已自动矫正`);
|
||||
} else {
|
||||
this.context.logger.log(`[ServerTime] 时间同步完成,偏差 ${offsetMs}ms`);
|
||||
}
|
||||
} catch (e) {
|
||||
this.context.logger.logError('[ServerTime] 时间矫正失败', e);
|
||||
}
|
||||
} catch (e) {
|
||||
this.context.logger.logError('[ServerTime] 时间矫正失败', e);
|
||||
}
|
||||
};
|
||||
doTimeSync();
|
||||
// 每小时定期重同步,防止长时间运行后本地时钟漂移触发风控
|
||||
const syncTimer = setInterval(doTimeSync, 3600000);
|
||||
syncTimer.unref();
|
||||
}
|
||||
// 遍历this.apis[i].initApi 如果存在该函数进行async 调用
|
||||
for (const apiKey in this.apis) {
|
||||
|
||||
@@ -41,6 +41,16 @@ export class PacketOperationContext {
|
||||
await this.context.client.sendOidbPacket(req, true);
|
||||
}
|
||||
|
||||
async CompleteGroupTodo (groupUin: number, msgSeq: string) {
|
||||
const req = trans.CompleteGroupTodo.build(groupUin, msgSeq);
|
||||
await this.context.client.sendOidbPacket(req, true);
|
||||
}
|
||||
|
||||
async CancelGroupTodo (groupUin: number, msgSeq: string) {
|
||||
const req = trans.CancelGroupTodo.build(groupUin, msgSeq);
|
||||
await this.context.client.sendOidbPacket(req, true);
|
||||
}
|
||||
|
||||
async FetchRkey (timeout: number = 10000) {
|
||||
const req = trans.FetchRkey.build();
|
||||
const resp = await this.context.client.sendOidbPacket(req, true, timeout);
|
||||
@@ -363,8 +373,19 @@ export class PacketOperationContext {
|
||||
return element;
|
||||
})
|
||||
);
|
||||
const isGroup = msg?.responseHead.grp !== undefined;
|
||||
const peerUin = isGroup
|
||||
? String(msg?.responseHead.grp?.groupUin ?? 0)
|
||||
: String(msg?.responseHead.fromUin ?? 0);
|
||||
const peerUid = isGroup
|
||||
? String(msg?.responseHead.grp?.groupUin ?? 0)
|
||||
: String(msg?.responseHead.fromUid ?? '');
|
||||
const sendNickName = isGroup
|
||||
? (msg?.responseHead.grp?.memberName ?? '')
|
||||
: (msg?.responseHead.forward?.friendName ?? '');
|
||||
|
||||
return {
|
||||
chatType: ChatType.KCHATTYPEGROUP,
|
||||
chatType: isGroup ? ChatType.KCHATTYPEGROUP : ChatType.KCHATTYPEC2C,
|
||||
elements,
|
||||
guildId: '',
|
||||
isOnlineMsg: false,
|
||||
@@ -375,18 +396,18 @@ export class PacketOperationContext {
|
||||
msgType: NTMsgType.KMSGTYPEMIX,
|
||||
parentMsgIdList: [],
|
||||
parentMsgPeer: {
|
||||
chatType: ChatType.KCHATTYPEGROUP,
|
||||
peerUid: String(msg?.responseHead.grp?.groupUin ?? 0),
|
||||
chatType: isGroup ? ChatType.KCHATTYPEGROUP : ChatType.KCHATTYPEC2C,
|
||||
peerUid,
|
||||
},
|
||||
peerName: '',
|
||||
peerUid: '1094950020',
|
||||
peerUin: '1094950020',
|
||||
peerUid,
|
||||
peerUin,
|
||||
recallTime: '0',
|
||||
records: [],
|
||||
sendNickName: msg?.responseHead.grp?.memberName ?? '',
|
||||
sendRemarkName: msg?.responseHead.grp?.memberName ?? '',
|
||||
senderUid: '',
|
||||
senderUin: '1094950020',
|
||||
sendNickName,
|
||||
sendRemarkName: sendNickName,
|
||||
senderUid: msg?.responseHead.fromUid ?? '',
|
||||
senderUin: String(msg?.responseHead.fromUin ?? 0),
|
||||
sourceType: MsgSourceType.K_DOWN_SOURCETYPE_UNKNOWN,
|
||||
subMsgType: 1,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
import * as proto from '@/napcat-core/packet/transformer/proto';
|
||||
import { NapProtoMsg } from 'napcat-protobuf';
|
||||
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
|
||||
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
|
||||
|
||||
class CancelGroupTodo extends PacketTransformer<typeof proto.OidbSvcTrpcTcpBase> {
|
||||
build (peer: number, msgSeq: string): OidbPacket {
|
||||
const data = new NapProtoMsg(proto.OidbSvcTrpcTcp0XF90).encode({
|
||||
groupUin: peer,
|
||||
msgSeq: BigInt(msgSeq),
|
||||
});
|
||||
return OidbBase.build(0xF90, 3, data);
|
||||
}
|
||||
|
||||
parse (data: Buffer) {
|
||||
return OidbBase.parse(data);
|
||||
}
|
||||
}
|
||||
|
||||
export default new CancelGroupTodo();
|
||||
@@ -0,0 +1,20 @@
|
||||
import * as proto from '@/napcat-core/packet/transformer/proto';
|
||||
import { NapProtoMsg } from 'napcat-protobuf';
|
||||
import { OidbPacket, PacketTransformer } from '@/napcat-core/packet/transformer/base';
|
||||
import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
|
||||
|
||||
class CompleteGroupTodo extends PacketTransformer<typeof proto.OidbSvcTrpcTcpBase> {
|
||||
build (peer: number, msgSeq: string): OidbPacket {
|
||||
const data = new NapProtoMsg(proto.OidbSvcTrpcTcp0XF90).encode({
|
||||
groupUin: peer,
|
||||
msgSeq: BigInt(msgSeq),
|
||||
});
|
||||
return OidbBase.build(0xF90, 2, data);
|
||||
}
|
||||
|
||||
parse (data: Buffer) {
|
||||
return OidbBase.parse(data);
|
||||
}
|
||||
}
|
||||
|
||||
export default new CompleteGroupTodo();
|
||||
@@ -5,7 +5,7 @@ import OidbBase from '@/napcat-core/packet/transformer/oidb/oidbBase';
|
||||
|
||||
class SetGroupTodo extends PacketTransformer<typeof proto.OidbSvcTrpcTcpBase> {
|
||||
build (peer: number, msgSeq: string): OidbPacket {
|
||||
const data = new NapProtoMsg(proto.OidbSvcTrpcTcp0XF90_1).encode({
|
||||
const data = new NapProtoMsg(proto.OidbSvcTrpcTcp0XF90).encode({
|
||||
groupUin: peer,
|
||||
msgSeq: BigInt(msgSeq),
|
||||
});
|
||||
|
||||
@@ -8,4 +8,6 @@ export { default as SetSpecialTitle } from './SetSpecialTitle';
|
||||
export { default as ImageOCR } from './ImageOCR';
|
||||
export { default as MoveGroupFile } from './MoveGroupFile';
|
||||
export { default as RenameGroupFile } from './RenameGroupFile';
|
||||
export { default as CompleteGroupTodo } from './CompleteGroupTodo';
|
||||
export { default as CancelGroupTodo } from './CancelGroupTodo';
|
||||
export { default as SetGroupTodo } from './SetGroupTodo';
|
||||
@@ -31,4 +31,4 @@ export * from './oidb/Oidb.0xED3_1';
|
||||
export * from './oidb/Oidb.0XFE1_2';
|
||||
export * from './oidb/OidbBase';
|
||||
export * from './oidb/Oidb.0xE07';
|
||||
export * from './oidb/Oidb.0xf90_1';
|
||||
export * from './oidb/Oidb.0xf90';
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { ProtoField, ScalarType } from 'napcat-protobuf';
|
||||
|
||||
export const OidbSvcTrpcTcp0XF90_1 = {
|
||||
export const OidbSvcTrpcTcp0XF90 = {
|
||||
groupUin: ProtoField(1, ScalarType.UINT32),
|
||||
msgSeq: ProtoField(2, ScalarType.UINT64),
|
||||
};
|
||||
@@ -88,6 +88,7 @@ export interface NodeIKernelAlbumService {
|
||||
map_bytes_info: unknown[],
|
||||
map_user_account: unknown[];
|
||||
},
|
||||
type: number, // type : number 1 取消 2 点赞
|
||||
param: {
|
||||
// {"id":"421_1_0_1012959257|V61Yiali4PELg90bThrH4Bo2iI1M5Kab|V5bCgAxMDEyOTU5MjU3e*KqaLVYdic!^||^421_1_0_1012959257|V61Yiali4PELg90bThrH4Bo2iI1M5Kab|17560336594^||^1","status":1}
|
||||
id: string,
|
||||
|
||||
@@ -341,7 +341,7 @@ export interface NodeIKernelMsgService {
|
||||
|
||||
getFileThumbSavePath (arg1: string, arg2: number, arg3: boolean): unknown;
|
||||
|
||||
translatePtt2Text (msgId: string, peer: Peer, msgElement: MessageElement): unknown;
|
||||
translatePtt2Text (msgId: string, peer: Peer, msgElement: MessageElement): Promise<GeneralCallResult>;
|
||||
|
||||
setPttPlayedState (arg1: string, arg2: Peer, arg3: string): unknown;
|
||||
|
||||
@@ -369,7 +369,16 @@ export interface NodeIKernelMsgService {
|
||||
}>;
|
||||
}>;
|
||||
|
||||
addFavEmoji (arg: unknown): unknown;
|
||||
addFavEmoji (arg: {
|
||||
emojiId?: string,
|
||||
packageId?: number,
|
||||
emojiPath: string,
|
||||
fileSize: string,
|
||||
fileName: string,
|
||||
md5: string,
|
||||
isMarkFace?: boolean,
|
||||
isOrigin?: boolean,
|
||||
}): unknown;
|
||||
|
||||
fetchMarketEmoticonList (arg1: number, arg2: number): unknown;
|
||||
|
||||
@@ -397,9 +406,14 @@ export interface NodeIKernelMsgService {
|
||||
|
||||
downloadEmojiPic (arg1: number, arg2: Array<unknown>[], arg3: number, arg4: Map<unknown, unknown>): unknown;
|
||||
|
||||
deleteFavEmoji (arg: unknown): unknown;
|
||||
deleteFavEmoji (arg: string[]): unknown;
|
||||
|
||||
modifyFavEmojiDesc (arg: unknown): unknown;
|
||||
modifyFavEmojiDesc (arg: Array<{
|
||||
emojiId: number,
|
||||
resId: string,
|
||||
md5: string,
|
||||
desc: string,
|
||||
}>): unknown;
|
||||
|
||||
queryFavEmojiByDesc (arg: unknown): unknown;
|
||||
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": ".."
|
||||
},
|
||||
"include": [
|
||||
"*.ts",
|
||||
"**/*.ts"
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
// LiteLoader需要提供部分IPC接口,以便于其他插件调用
|
||||
const { ipcMain, BrowserWindow } = require('electron');
|
||||
const napcat = require('./napcat.cjs');
|
||||
const { shell } = require('electron');
|
||||
ipcMain.handle('napcat_get_webui', async () => {
|
||||
return napcat.NCgetWebUiUrl();
|
||||
});
|
||||
ipcMain.on('open_external_url', (event, url) => {
|
||||
shell.openExternal(url);
|
||||
});
|
||||
ipcMain.on('napcat_open_inner_url', (event, url) => {
|
||||
const win = new BrowserWindow({
|
||||
autoHideMenuBar: true,
|
||||
});
|
||||
win.loadURL(url);
|
||||
win.webContents.setWindowOpenHandler(details => {
|
||||
win.loadURL(details.url);
|
||||
});
|
||||
});
|
||||
@@ -1,29 +0,0 @@
|
||||
{
|
||||
"manifest_version": 4,
|
||||
"type": "extension",
|
||||
"name": "NapCatQQ",
|
||||
"slug": "NapCat.Framework",
|
||||
"description": "高性能的 OneBot 11 协议实现",
|
||||
"version": "0.0.1",
|
||||
"icon": "./logo.png",
|
||||
"authors": [
|
||||
{
|
||||
"name": "NapNeko",
|
||||
"link": "https://github.com/NapNeko"
|
||||
}
|
||||
],
|
||||
"repository": {
|
||||
"repo": "NapNeko/NapCatQQ",
|
||||
"branch": "main"
|
||||
},
|
||||
"platform": [
|
||||
"win32",
|
||||
"linux",
|
||||
"darwin"
|
||||
],
|
||||
"injects": {
|
||||
"renderer": "./renderer.js",
|
||||
"main": "./liteloader.cjs",
|
||||
"preload": "./preload.cjs"
|
||||
}
|
||||
}
|
||||
@@ -195,6 +195,11 @@ export async function NCoreInitFramework (
|
||||
if (oneBotAdapter) {
|
||||
WebUiDataRuntime.setOneBotContext(oneBotAdapter);
|
||||
}
|
||||
|
||||
// 监听下线通知并同步到 WebUI(兜底保障,防止 WebUI 状态不同步)
|
||||
loaderObject.core.event.on('KickedOffLine', () => {
|
||||
WebUiDataRuntime.setQQLoginStatus(false);
|
||||
});
|
||||
}
|
||||
|
||||
function registerWebUiLoginCallbacks (
|
||||
|
||||
@@ -1,14 +0,0 @@
|
||||
const { contextBridge, ipcRenderer } = require('electron');
|
||||
const napcat = {
|
||||
getWebUiUrl: async () => {
|
||||
return ipcRenderer.invoke('napcat_get_webui');
|
||||
},
|
||||
openExternalUrl: async (url) => {
|
||||
ipcRenderer.send('open_external_url', url);
|
||||
},
|
||||
openInnerUrl: async (url) => {
|
||||
ipcRenderer.send('napcat_open_inner_url', url);
|
||||
},
|
||||
};
|
||||
// 在window对象下导出只读对象
|
||||
contextBridge.exposeInMainWorld('napcat', napcat);
|
||||
@@ -1,41 +0,0 @@
|
||||
export const onSettingWindowCreated = async (view) => {
|
||||
const webui = await window.napcat.getWebUiUrl();
|
||||
view.innerHTML = `
|
||||
<setting-section data-title="">
|
||||
<setting-panel>
|
||||
<setting-list data-direction="column">
|
||||
<setting-item>
|
||||
<setting-button data-type="primary" class="nc_openwebui">在QQ内打开配置页面</setting-button>
|
||||
<setting-button data-type="primary" class="nc_openwebui_ex">在默认浏览器打开配置页面</setting-button>
|
||||
</setting-item>
|
||||
<setting-item>
|
||||
<div>
|
||||
<setting-text>WebUi远程地址可以点击下方复制哦~</setting-text>
|
||||
<setting-text class="nc_webui">WebUi</setting-text>
|
||||
</div>
|
||||
</setting-item>
|
||||
</setting-list>
|
||||
</setting-panel>
|
||||
</setting-section>
|
||||
`;
|
||||
|
||||
view.querySelector('.nc_openwebui').addEventListener('click', () => {
|
||||
window.napcat.openInnerUrl(webui);
|
||||
});
|
||||
view.querySelector('.nc_openwebui_ex').addEventListener('click', () => {
|
||||
window.napcat.openExternalUrl(webui);
|
||||
});
|
||||
|
||||
view.querySelector('.nc_webui').innerText = webui;
|
||||
|
||||
// 添加点击复制功能
|
||||
view.querySelector('.nc_webui').addEventListener('click', async () => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(webui);
|
||||
// eslint-disable-next-line no-undef
|
||||
alert('WebUi URL 已复制到剪贴板');
|
||||
} catch (err) {
|
||||
console.error('复制到剪贴板失败: ', err);
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -1,5 +1,8 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": ".."
|
||||
},
|
||||
"include": [
|
||||
"*.ts",
|
||||
"**/*.ts"
|
||||
|
||||
@@ -24,10 +24,8 @@ const FrameworkBaseConfigPlugin: PluginOption[] = [
|
||||
targets: [
|
||||
{ src: '../napcat-napi-loader/', dest: 'dist', flatten: true },
|
||||
{ src: '../napcat-native/', dest: 'dist/native', flatten: false },
|
||||
{ src: './manifest.json', dest: 'dist' },
|
||||
{ src: '../napcat-core/external/napcat.json', dest: 'dist/config/' },
|
||||
{ src: '../napcat-webui-frontend/dist/', dest: 'dist/static/', flatten: false },
|
||||
{ src: './liteloader.cjs', dest: 'dist' },
|
||||
{ src: './napcat.cjs', dest: 'dist' },
|
||||
{ src: './nativeLoader.cjs', dest: 'dist' },
|
||||
{ src: './preload.cjs', dest: 'dist' },
|
||||
|
||||
@@ -11,4 +11,12 @@ export const PacketActionsExamples = {
|
||||
payload: { group_id: '123456', message_id: '123456789' },
|
||||
response: {},
|
||||
},
|
||||
CompleteGroupTodo: {
|
||||
payload: { group_id: '123456', message_id: '123456789' },
|
||||
response: {},
|
||||
},
|
||||
CancelGroupTodo: {
|
||||
payload: { group_id: '123456', message_id: '123456789' },
|
||||
response: {},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,162 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
import { stat, readFile } from 'node:fs/promises';
|
||||
import { basename } from 'node:path';
|
||||
import { Type, Static } from '@sinclair/typebox';
|
||||
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
|
||||
const FetchCustomFaceDetailPayloadSchema = Type.Object({
|
||||
count: Type.Union([Type.Number(), Type.String()], { default: 48, description: '获取数量' }),
|
||||
});
|
||||
|
||||
type FetchCustomFaceDetailPayloadType = Static<typeof FetchCustomFaceDetailPayloadSchema>;
|
||||
|
||||
const FetchCustomFaceDetailReturnSchema = Type.Any({ description: '自定义表情详情列表' });
|
||||
|
||||
type FetchCustomFaceDetailReturnType = Static<typeof FetchCustomFaceDetailReturnSchema>;
|
||||
|
||||
export class FetchCustomFaceDetail extends OneBotAction<FetchCustomFaceDetailPayloadType, FetchCustomFaceDetailReturnType> {
|
||||
override actionName = ActionName.FetchCustomFaceDetail;
|
||||
override payloadSchema = FetchCustomFaceDetailPayloadSchema;
|
||||
override returnSchema = FetchCustomFaceDetailReturnSchema;
|
||||
override actionSummary = '获取自定义表情详情';
|
||||
override actionTags = ['系统扩展'];
|
||||
override payloadExample = {
|
||||
count: 10,
|
||||
};
|
||||
|
||||
override returnExample = null;
|
||||
|
||||
async _handle (payload: FetchCustomFaceDetailPayloadType) {
|
||||
const ret = await this.core.apis.MsgApi.fetchFavEmojiList(+payload.count);
|
||||
return ret.emojiInfoList;
|
||||
}
|
||||
}
|
||||
|
||||
const AddCustomFacePayloadSchema = Type.Object({
|
||||
file: Type.String({ description: '本地表情文件路径' }),
|
||||
emoji_id: Type.Optional(Type.Union([Type.String(), Type.Number()], { description: '表情ID,未提供时传空字符串' })),
|
||||
package_id: Type.Optional(Type.Union([Type.String(), Type.Number()], { description: '表情包ID,未提供时传0' })),
|
||||
file_name: Type.Optional(Type.String({ description: '文件名,未提供时从file路径取basename' })),
|
||||
file_size: Type.Optional(Type.Union([Type.String(), Type.Number()], { description: '文件大小,未提供时读取本地文件' })),
|
||||
md5: Type.Optional(Type.String({ description: '文件MD5,未提供时读取本地文件计算' })),
|
||||
is_mark_face: Type.Optional(Type.Boolean({ description: '是否商城表情' })),
|
||||
is_origin: Type.Optional(Type.Boolean({ description: '是否原图' })),
|
||||
});
|
||||
|
||||
type AddCustomFacePayloadType = Static<typeof AddCustomFacePayloadSchema>;
|
||||
|
||||
const AddCustomFaceReturnSchema = Type.Any({ description: '添加结果' });
|
||||
|
||||
type AddCustomFaceReturnType = Static<typeof AddCustomFaceReturnSchema>;
|
||||
|
||||
export class AddCustomFace extends OneBotAction<AddCustomFacePayloadType, AddCustomFaceReturnType> {
|
||||
override actionName = ActionName.AddCustomFace;
|
||||
override payloadSchema = AddCustomFacePayloadSchema;
|
||||
override returnSchema = AddCustomFaceReturnSchema;
|
||||
override actionSummary = '添加自定义表情';
|
||||
override actionTags = ['系统扩展'];
|
||||
override payloadExample = {
|
||||
file: 'C:\\Users\\Public\\face.png',
|
||||
is_origin: true,
|
||||
};
|
||||
|
||||
override returnExample = null;
|
||||
|
||||
async _handle (payload: AddCustomFacePayloadType) {
|
||||
const fileStat = await stat(payload.file);
|
||||
const md5 = payload.md5 ?? createHash('md5').update(await readFile(payload.file)).digest('hex');
|
||||
return await this.core.apis.MsgApi.addFavEmoji({
|
||||
emojiId: payload.emoji_id?.toString() ?? '',
|
||||
packageId: payload.package_id === undefined ? 0 : Number(payload.package_id),
|
||||
emojiPath: payload.file,
|
||||
fileSize: payload.file_size?.toString() ?? fileStat.size.toString(),
|
||||
fileName: payload.file_name ?? basename(payload.file),
|
||||
md5,
|
||||
isMarkFace: payload.is_mark_face ?? false,
|
||||
isOrigin: payload.is_origin ?? true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const DeleteCustomFacePayloadSchema = Type.Object({
|
||||
res_id: Type.Optional(Type.Union([
|
||||
Type.String({ description: 'fetch_custom_face_detail返回的resId' }),
|
||||
Type.Array(Type.String({ description: 'fetch_custom_face_detail返回的resId' })),
|
||||
])),
|
||||
id: Type.Optional(Type.Union([
|
||||
Type.String({ description: 'native deleteFavEmoji字符串ID,通常为resId' }),
|
||||
Type.Array(Type.String({ description: 'native deleteFavEmoji字符串ID,通常为resId' })),
|
||||
])),
|
||||
ids: Type.Optional(Type.Array(Type.String({ description: 'native deleteFavEmoji字符串ID列表,通常为resId列表' }))),
|
||||
md5: Type.Optional(Type.Union([
|
||||
Type.String({ description: '表情MD5,不能直接删除,请先通过fetch_custom_face_detail获取resId' }),
|
||||
Type.Array(Type.String({ description: '表情MD5,不能直接删除,请先通过fetch_custom_face_detail获取resId' })),
|
||||
])),
|
||||
});
|
||||
|
||||
type DeleteCustomFacePayloadType = Static<typeof DeleteCustomFacePayloadSchema>;
|
||||
|
||||
const DeleteCustomFaceReturnSchema = Type.Any({ description: '删除结果' });
|
||||
|
||||
type DeleteCustomFaceReturnType = Static<typeof DeleteCustomFaceReturnSchema>;
|
||||
|
||||
export class DeleteCustomFace extends OneBotAction<DeleteCustomFacePayloadType, DeleteCustomFaceReturnType> {
|
||||
override actionName = ActionName.DeleteCustomFace;
|
||||
override payloadSchema = DeleteCustomFacePayloadSchema;
|
||||
override returnSchema = DeleteCustomFaceReturnSchema;
|
||||
override actionSummary = '删除自定义表情';
|
||||
override actionTags = ['系统扩展'];
|
||||
override payloadExample = {
|
||||
res_id: '2707600964_0_0_0_D8EAA70984B402EE10B0F33DB88F4173_0_0',
|
||||
};
|
||||
|
||||
override returnExample = null;
|
||||
|
||||
async _handle (payload: DeleteCustomFacePayloadType) {
|
||||
const ids = payload.ids ??
|
||||
(Array.isArray(payload.res_id) ? payload.res_id : payload.res_id ? [payload.res_id] : undefined) ??
|
||||
(Array.isArray(payload.id) ? payload.id : payload.id ? [payload.id] : undefined) ??
|
||||
[];
|
||||
if (ids.length === 0) throw new Error('res_id or ids is required');
|
||||
return await this.core.apis.MsgApi.deleteFavEmoji(ids);
|
||||
}
|
||||
}
|
||||
|
||||
const SetCustomFaceDescPayloadSchema = Type.Object({
|
||||
emoji_id: Type.Union([Type.Number(), Type.String()], { description: '表情ID' }),
|
||||
res_id: Type.String({ description: '资源ID' }),
|
||||
md5: Type.String({ description: '表情MD5' }),
|
||||
desc: Type.String({ description: '新的表情描述' }),
|
||||
});
|
||||
|
||||
type SetCustomFaceDescPayloadType = Static<typeof SetCustomFaceDescPayloadSchema>;
|
||||
|
||||
const SetCustomFaceDescReturnSchema = Type.Any({ description: '修改结果' });
|
||||
|
||||
type SetCustomFaceDescReturnType = Static<typeof SetCustomFaceDescReturnSchema>;
|
||||
|
||||
export class SetCustomFaceDesc extends OneBotAction<SetCustomFaceDescPayloadType, SetCustomFaceDescReturnType> {
|
||||
override actionName = ActionName.SetCustomFaceDesc;
|
||||
override payloadSchema = SetCustomFaceDescPayloadSchema;
|
||||
override returnSchema = SetCustomFaceDescReturnSchema;
|
||||
override actionSummary = '修改自定义表情描述';
|
||||
override actionTags = ['系统扩展'];
|
||||
override payloadExample = {
|
||||
emoji_id: 1,
|
||||
res_id: 'resource-id',
|
||||
md5: 'd41d8cd98f00b204e9800998ecf8427e',
|
||||
desc: '新的描述',
|
||||
};
|
||||
|
||||
override returnExample = null;
|
||||
|
||||
async _handle (payload: SetCustomFaceDescPayloadType) {
|
||||
return await this.core.apis.MsgApi.modifyFavEmojiDesc([{
|
||||
emojiId: Number(payload.emoji_id),
|
||||
resId: payload.res_id,
|
||||
md5: payload.md5,
|
||||
desc: payload.desc,
|
||||
}]);
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { Static, Type } from '@sinclair/typebox';
|
||||
const PayloadSchema = Type.Object({
|
||||
group_id: Type.String({ description: '群号' }),
|
||||
album_id: Type.String({ description: '相册ID' }),
|
||||
attach_info: Type.String({ default: '', description: '附加信息(用于分页)' }),
|
||||
attach_info: Type.Optional(Type.String({ default: '', description: '附加信息(用于分页)' })),
|
||||
});
|
||||
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { Type, Static } from '@sinclair/typebox';
|
||||
|
||||
const PayloadSchema = Type.Object({
|
||||
group_id: Type.Union([Type.String(), Type.Number()], { description: '群号' }),
|
||||
});
|
||||
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
|
||||
const ReturnSchema = Type.Array(
|
||||
Type.Object({
|
||||
user_id: Type.Number({ description: '打卡者QQ' }),
|
||||
nick: Type.String({ description: '打卡者昵称' }),
|
||||
time: Type.Number({ description: '打卡时间' }),
|
||||
rank: Type.Number({ description: '打卡排名' }),
|
||||
}),
|
||||
{ description: '群组今日打卡列表' }
|
||||
);
|
||||
|
||||
type ReturnType = Static<typeof ReturnSchema>;
|
||||
|
||||
export class GetGroupSignedList extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionName = ActionName.GetGroupSignedList;
|
||||
override actionSummary = '获取群组今日打卡列表';
|
||||
override actionTags = ['群组扩展'];
|
||||
override payloadExample = {
|
||||
group_id: '123456',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
|
||||
};
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
const data = await this.core.apis.WebApi.getDaySignedList(payload.group_id.toString());
|
||||
if (!data.response.page) throw new Error('无法获取该群组打卡列表');
|
||||
return data.response.page[0]?.infos?.map(info => ({
|
||||
user_id: +info.uid,
|
||||
nick: info.uidGroupNick,
|
||||
time: +info.signedTimeStamp,
|
||||
rank: (info.signInRank - 1) / 2 + 1,
|
||||
})) ?? [];
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { Static, Type } from '@sinclair/typebox';
|
||||
|
||||
const PayloadSchema = Type.Object({
|
||||
group_id: Type.String({ description: '群号' }),
|
||||
attach_info: Type.String({ default: '', description: '附加信息(用于分页,从上一次返回结果中获取)' }),
|
||||
attach_info: Type.Optional(Type.String({ default: '', description: '附加信息(用于分页,从上一次返回结果中获取)' })),
|
||||
});
|
||||
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
|
||||
@@ -26,7 +26,7 @@ class OCRImageBase extends OneBotAction<PayloadType, ReturnType> {
|
||||
override returnExample = ExtendsActionsExamples.OCRImage.response;
|
||||
|
||||
async _handle (payload: PayloadType): Promise<ReturnType> {
|
||||
const { path, success } = await uriToLocalFile(this.core.NapCatTempPath, payload.image);
|
||||
const { path, success, isLocal } = await uriToLocalFile(this.core.NapCatTempPath, payload.image);
|
||||
if (!success) {
|
||||
throw new Error(`OCR ${payload.image}失败, image字段可能格式不正确`);
|
||||
}
|
||||
@@ -39,7 +39,7 @@ class OCRImageBase extends OneBotAction<PayloadType, ReturnType> {
|
||||
}
|
||||
return ret.result;
|
||||
} finally {
|
||||
fs.unlink(path, () => { });
|
||||
if (!isLocal) fs.unlink(path, () => { });
|
||||
}
|
||||
}
|
||||
throw new Error(`OCR ${payload.image}失败, 文件可能不存在`);
|
||||
|
||||
@@ -5,9 +5,8 @@ import { Static, Type } from '@sinclair/typebox';
|
||||
const PayloadSchema = Type.Object({
|
||||
group_id: Type.String({ description: '群号' }),
|
||||
album_id: Type.String({ description: '相册ID' }),
|
||||
lloc: Type.String({ description: '媒体ID (lloc)' }),
|
||||
id: Type.String({ description: '点赞ID' }), // 421_1_0_1012959257|V61Yiali4PELg90bThrH4Bo2iI1M5Kab|V5bCgAxMDEyOTU5MjU3.PyqaPndPxg!^||^421_1_0_1012959257|V61Yiali4PELg90bThrH4Bo2iI1M5Kab|17560363448^||^1
|
||||
set: Type.Boolean({ default: true, description: '是否点赞' }), // true=点赞 false=取消点赞 未实现
|
||||
batch_id: Type.String({ description: 'batch_id' }),
|
||||
lloc: Type.Optional(Type.String({ description: 'lloc,若对整个上传操作则不填' })),
|
||||
});
|
||||
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
@@ -22,9 +21,9 @@ export class SetGroupAlbumMediaLike extends OneBotAction<PayloadType, ReturnType
|
||||
override actionTags = ['群组扩展'];
|
||||
override payloadExample = {
|
||||
group_id: '123456',
|
||||
album_id: 'album_id_1',
|
||||
lloc: 'media_id_1',
|
||||
id: '123456',
|
||||
album_id: 'album_id_123',
|
||||
batch_id: '112233',
|
||||
lloc: 'aabbcc12213123',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
@@ -38,8 +37,38 @@ export class SetGroupAlbumMediaLike extends OneBotAction<PayloadType, ReturnType
|
||||
return await this.core.apis.WebApi.doAlbumMediaLikeByNTQQ(
|
||||
payload.group_id,
|
||||
payload.album_id,
|
||||
payload.batch_id,
|
||||
payload.lloc,
|
||||
payload.id
|
||||
true // isLike = true
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export class CancelGroupAlbumMediaLike extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionName = ActionName.CancelGroupAlbumMediaLike; // 注意:需要在 router/index.ts 的 ActionName 枚举中补充该定义
|
||||
override actionSummary = '取消点赞群相册媒体';
|
||||
override actionTags = ['群组扩展'];
|
||||
override payloadExample = {
|
||||
group_id: '123456',
|
||||
album_id: 'album_id',
|
||||
batch_id: '112233',
|
||||
lloc: 'aabbcc',
|
||||
};
|
||||
|
||||
override returnExample = {
|
||||
result: {},
|
||||
};
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
return await this.core.apis.WebApi.doAlbumMediaLikeByNTQQ(
|
||||
payload.group_id,
|
||||
payload.album_id,
|
||||
payload.batch_id,
|
||||
payload.lloc,
|
||||
false
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -27,14 +27,14 @@ export default class SetAvatar extends OneBotAction<PayloadType, ReturnType> {
|
||||
override returnExample = ExtendsActionsExamples.SetQQAvatar.response;
|
||||
|
||||
async _handle (payload: PayloadType): Promise<ReturnType> {
|
||||
const { path, success } = (await uriToLocalFile(this.core.NapCatTempPath, payload.file));
|
||||
const { path, success, isLocal } = (await uriToLocalFile(this.core.NapCatTempPath, payload.file));
|
||||
if (!success) {
|
||||
throw new Error(`头像${payload.file}设置失败,file字段可能格式不正确`);
|
||||
}
|
||||
if (path) {
|
||||
await checkFileExist(path, 5000);// 避免崩溃
|
||||
const ret = await this.core.apis.UserApi.setQQAvatar(path);
|
||||
fs.unlink(path).catch(() => { });
|
||||
if (!isLocal) fs.unlink(path).catch(() => { });
|
||||
if (!ret) {
|
||||
throw new Error(`头像${payload.file}设置失败,api无返回`);
|
||||
}
|
||||
@@ -45,7 +45,6 @@ export default class SetAvatar extends OneBotAction<PayloadType, ReturnType> {
|
||||
throw new Error(`头像${payload.file}设置失败,未知的错误,${ret.result}:${ret.errMsg}`);
|
||||
}
|
||||
} else {
|
||||
fs.unlink(path).catch(() => { });
|
||||
throw new Error(`头像${payload.file}设置失败,无法获取头像,文件可能不存在`);
|
||||
}
|
||||
return null;
|
||||
|
||||
@@ -41,7 +41,7 @@ export class UploadImageToQunAlbum extends OneBotAction<PayloadType, ReturnType>
|
||||
try {
|
||||
return await this.core.apis.WebApi.uploadImageToQunAlbum(payload.group_id, payload.album_id, payload.album_name, downloadResult.path);
|
||||
} finally {
|
||||
if (downloadResult.path && existsSync(downloadResult.path)) {
|
||||
if (!downloadResult.isLocal && downloadResult.path && existsSync(downloadResult.path)) {
|
||||
await unlink(downloadResult.path);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { FileNapCatOneBotUUID } from 'napcat-common/src/file-uuid';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { OB11MessageImage, OB11MessageVideo } from '@/napcat-onebot/types';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
import { calculateTimeout } from '@/napcat-onebot/config/config';
|
||||
|
||||
import { FileActionsExamples } from '../example/FileActionsExamples';
|
||||
|
||||
@@ -96,7 +97,10 @@ export class GetFileBase extends OneBotAction<GetFilePayload, GetFileResponse> {
|
||||
// 搜索名字模式
|
||||
const searchResult = (await this.core.apis.FileApi.searchForFile([payload.file]));
|
||||
if (searchResult) {
|
||||
const downloadPath = await this.core.apis.FileApi.downloadFileById(searchResult.id, parseInt(searchResult.fileSize));
|
||||
const fileSize = parseInt(searchResult.fileSize);
|
||||
const timeoutConfig = this.obContext.configLoader.configData.timeout;
|
||||
const estimatedTime = calculateTimeout(timeoutConfig, fileSize, timeoutConfig.downloadSpeedKBps);
|
||||
const downloadPath = await this.core.apis.FileApi.downloadFileById(searchResult.id, fileSize, estimatedTime);
|
||||
const res: GetFileResponse = {
|
||||
file: downloadPath,
|
||||
url: downloadPath,
|
||||
|
||||
@@ -35,6 +35,7 @@ export class SendGroupNotice extends OneBotAction<SendGroupNoticePayload, void>
|
||||
const {
|
||||
path,
|
||||
success,
|
||||
isLocal,
|
||||
} = (await uriToLocalFile(this.core.NapCatTempPath, payload.image));
|
||||
if (!success) {
|
||||
throw new Error(`群公告${payload.image}设置失败,image字段可能格式不正确`);
|
||||
@@ -48,7 +49,7 @@ export class SendGroupNotice extends OneBotAction<SendGroupNoticePayload, void>
|
||||
throw new Error(`群公告${payload.image}设置失败,图片上传失败 , 错误信息:${ImageUploadResult.errMsg}`);
|
||||
}
|
||||
|
||||
unlink(path).catch(() => { });
|
||||
if (!isLocal) unlink(path).catch(() => { });
|
||||
|
||||
UploadImage = ImageUploadResult.picInfo;
|
||||
}
|
||||
|
||||
@@ -30,14 +30,14 @@ export default class SetGroupPortrait extends OneBotAction<SetGroupPortraitPaylo
|
||||
override returnExample = GoCQHTTPActionsExamples.SetGroupPortrait.response;
|
||||
|
||||
async _handle (payload: SetGroupPortraitPayload): Promise<ReturnType> {
|
||||
const { path, success } = (await uriToLocalFile(this.core.NapCatTempPath, payload.file));
|
||||
const { path, success, isLocal } = (await uriToLocalFile(this.core.NapCatTempPath, payload.file));
|
||||
if (!success) {
|
||||
throw new Error(`头像${payload.file}设置失败,file字段可能格式不正确`);
|
||||
}
|
||||
if (path) {
|
||||
await checkFileExistV2(path, 5000); // 文件不存在QQ会崩溃,需要提前判断
|
||||
const ret = await this.core.apis.GroupApi.setGroupAvatar(payload.group_id.toString(), path);
|
||||
fs.unlink(path).catch(() => { });
|
||||
if (!isLocal) fs.unlink(path).catch(() => { });
|
||||
if (!ret) {
|
||||
throw new Error(`头像${payload.file}设置失败,api无返回`);
|
||||
}
|
||||
@@ -51,7 +51,6 @@ export default class SetGroupPortrait extends OneBotAction<SetGroupPortraitPaylo
|
||||
errMsg: ret.errMsg,
|
||||
};
|
||||
} else {
|
||||
fs.unlink(path).catch(() => { });
|
||||
throw new Error(`头像${payload.file}设置失败,无法获取头像,文件可能不存在`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,8 +51,10 @@ export default class GoCQHTTPUploadGroupFile extends OneBotAction<GoCQHTTPUpload
|
||||
peer,
|
||||
deleteAfterSentFiles: [],
|
||||
};
|
||||
const sendFileEle = await this.obContext.apis.FileApi.createValidSendFileElement(msgContext, downloadResult.path, payload.name, payload.folder ?? payload.folder_id, payload.upload_file);
|
||||
msgContext.deleteAfterSentFiles.push(downloadResult.path);
|
||||
const sendFileEle = await this.obContext.apis.FileApi.createValidSendFileElement(msgContext, downloadResult.path, payload.name, payload.folder ?? payload.folder_id, payload.upload_file, downloadResult.isLocal);
|
||||
if (!downloadResult.isLocal) {
|
||||
msgContext.deleteAfterSentFiles.push(downloadResult.path);
|
||||
}
|
||||
const returnMsg = await this.obContext.apis.MsgApi.sendMsgWithOb11UniqueId(peer, [sendFileEle], msgContext.deleteAfterSentFiles);
|
||||
|
||||
const fileElement = returnMsg.elements.find(ele => ele.elementType === ElementType.FILE);
|
||||
|
||||
@@ -61,8 +61,10 @@ export default class GoCQHTTPUploadPrivateFile extends OneBotAction<GoCQHTTPUplo
|
||||
}, ContextMode.Private),
|
||||
deleteAfterSentFiles: [],
|
||||
};
|
||||
const sendFileEle: SendFileElement = await this.obContext.apis.FileApi.createValidSendFileElement(msgContext, downloadResult.path, payload.name, '', payload.upload_file);
|
||||
msgContext.deleteAfterSentFiles.push(downloadResult.path);
|
||||
const sendFileEle: SendFileElement = await this.obContext.apis.FileApi.createValidSendFileElement(msgContext, downloadResult.path, payload.name, '', payload.upload_file, downloadResult.isLocal);
|
||||
if (!downloadResult.isLocal) {
|
||||
msgContext.deleteAfterSentFiles.push(downloadResult.path);
|
||||
}
|
||||
const returnMsg = await this.obContext.apis.MsgApi.sendMsgWithOb11UniqueId(await this.getPeer(payload), [sendFileEle], msgContext.deleteAfterSentFiles);
|
||||
|
||||
const fileElement = returnMsg.elements.find(ele => ele.elementType === ElementType.FILE);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
|
||||
import { GroupActionsExamples } from '../example/GroupActionsExamples';
|
||||
import { NTGroupMemberRole } from '@/napcat-core';
|
||||
|
||||
const PayloadSchema = Type.Object({
|
||||
group_id: Type.String({ description: '群号' }),
|
||||
@@ -30,7 +31,13 @@ export default class SetGroupBan extends OneBotAction<PayloadType, ReturnType> {
|
||||
const uid = await this.core.apis.UserApi.getUidByUinV2(payload.user_id.toString());
|
||||
if (!uid) throw new Error('uid error');
|
||||
const member_role = (await this.core.apis.GroupApi.getGroupMemberEx(payload.group_id.toString(), uid, true))?.role;
|
||||
if (member_role === 4) throw new Error('cannot ban owner');
|
||||
if (member_role === undefined) throw new Error('user not in group');
|
||||
if (member_role === NTGroupMemberRole.KOWNER) throw new Error('cannot ban owner');
|
||||
if (member_role === NTGroupMemberRole.KADMIN) {
|
||||
const self_role = (await this.core.apis.GroupApi.getGroupMemberEx(payload.group_id.toString(), this.core.selfInfo.uid, true))?.role;
|
||||
if (self_role === undefined) throw new Error('failed to fetch bot role');
|
||||
if (self_role !== NTGroupMemberRole.KOWNER) throw new Error('cannot ban admin');
|
||||
}
|
||||
// 例如无管理员权限时 result为 120101005 errMsg为 'ERR_NOT_GROUP_ADMIN'
|
||||
const ret = await this.core.apis.GroupApi.banMember(payload.group_id.toString(),
|
||||
[{ uid, timeStamp: +payload.duration }]);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
import { sleep } from '@/napcat-common/src/helper';
|
||||
|
||||
import { GroupActionsExamples } from '../example/GroupActionsExamples';
|
||||
|
||||
@@ -27,8 +28,24 @@ export default class SetGroupCard extends OneBotAction<PayloadType, ReturnType>
|
||||
override returnExample = GroupActionsExamples.SetGroupCard.response;
|
||||
|
||||
async _handle (payload: PayloadType): Promise<null> {
|
||||
const member = await this.core.apis.GroupApi.getGroupMember(payload.group_id.toString(), payload.user_id.toString());
|
||||
if (member) await this.core.apis.GroupApi.setMemberCard(payload.group_id.toString(), member.uid, payload.card || '');
|
||||
return null;
|
||||
const groupId = payload.group_id.toString();
|
||||
const userId = payload.user_id.toString();
|
||||
const card = payload.card || '';
|
||||
|
||||
const member = await this.core.apis.GroupApi.getGroupMember(groupId, userId);
|
||||
if (!member) {
|
||||
throw new Error(`群(${groupId})成员${userId}不存在`);
|
||||
}
|
||||
|
||||
await this.core.apis.GroupApi.setMemberCard(groupId, member.uid, card);
|
||||
|
||||
for (let i = 0; i < 3; i++) {
|
||||
await sleep(1000);
|
||||
const updatedMember = await this.core.apis.GroupApi.refreshGroupMemberCachePartial(groupId, member.uid);
|
||||
if (updatedMember?.cardName === card) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
throw new Error('设置群名片未生效');
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,10 @@ export default class SetGroupName extends OneBotAction<PayloadType, ReturnType>
|
||||
override returnExample = GroupActionsExamples.SetGroupName.response;
|
||||
|
||||
async _handle (payload: PayloadType): Promise<null> {
|
||||
const ret = await this.core.apis.GroupApi.setGroupName(payload.group_id.toString(), payload.group_name);
|
||||
let ret = await this.core.apis.GroupApi.setGroupName(payload.group_id.toString(), payload.group_name);
|
||||
if (ret.result.toString() === '1287') {
|
||||
ret = await this.core.apis.GroupApi.setGroupName(payload.group_id.toString(), payload.group_name, true);
|
||||
}
|
||||
if (ret.result !== 0) {
|
||||
throw new Error(`设置群名称失败 ErrCode: ${ret.result} ErrMsg: ${ret.errMsg}`);
|
||||
}
|
||||
|
||||
@@ -63,6 +63,7 @@ import GetRecentContact from './user/GetRecentContact';
|
||||
import { GetProfileLike } from './extends/GetProfileLike';
|
||||
import SetGroupPortrait from './go-cqhttp/SetGroupPortrait';
|
||||
import { FetchCustomFace } from './extends/FetchCustomFace';
|
||||
import { AddCustomFace, DeleteCustomFace, FetchCustomFaceDetail, SetCustomFaceDesc } from './extends/CustomFace';
|
||||
import GoCQHTTPUploadPrivateFile from './go-cqhttp/UploadPrivateFile';
|
||||
import { FetchEmojiLike } from './extends/FetchEmojiLike';
|
||||
import { GetEmojiLikes } from './extends/GetEmojiLikes';
|
||||
@@ -127,12 +128,14 @@ import SetGroupKickMembers from './extends/SetGroupKickMembers';
|
||||
import { GetGroupDetailInfo } from './group/GetGroupDetailInfo';
|
||||
import GetGroupAddRequest from './extends/GetGroupAddRequest';
|
||||
import { GetCollectionList } from './extends/GetCollectionList';
|
||||
import { CompleteGroupTodo } from './packet/CompleteGroupTodo';
|
||||
import { CancelGroupTodo } from './packet/CancelGroupTodo';
|
||||
import { SetGroupTodo } from './packet/SetGroupTodo';
|
||||
import { GetQunAlbumList } from './extends/GetQunAlbumList';
|
||||
import { UploadImageToQunAlbum } from './extends/UploadImageToQunAlbum';
|
||||
import { DoGroupAlbumComment } from './extends/DoGroupAlbumComment';
|
||||
import { GetGroupAlbumMediaList } from './extends/GetGroupAlbumMediaList';
|
||||
import { SetGroupAlbumMediaLike } from './extends/SetGroupAlbumMediaLike';
|
||||
import { SetGroupAlbumMediaLike, CancelGroupAlbumMediaLike } from './extends/SetGroupAlbumMediaLike';
|
||||
import { DelGroupAlbumMedia } from './extends/DelGroupAlbumMedia';
|
||||
import { CleanStreamTempFile } from './stream/CleanStreamTempFile';
|
||||
import { DownloadFileStream } from './stream/DownloadFileStream';
|
||||
@@ -155,6 +158,8 @@ import { CancelOnlineFile } from './file/online/CancelOnlineFile';
|
||||
import { ReceiveOnlineFile } from './file/online/ReceiveOnlineFile';
|
||||
import { RefuseOnlineFile } from './file/online/RefuseOnlineFile';
|
||||
import { GetFilesetId } from './file/flash/GetFilesetIdByCode';
|
||||
import { FetchPttText } from '@/napcat-onebot/action/msg/FetchPttText';
|
||||
import { GetGroupSignedList } from './extends/GetGroupSignedList';
|
||||
|
||||
export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCore) {
|
||||
const actionHandlers = [
|
||||
@@ -166,11 +171,14 @@ export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCo
|
||||
new UploadFileStream(obContext, core),
|
||||
new DelGroupAlbumMedia(obContext, core),
|
||||
new SetGroupAlbumMediaLike(obContext, core),
|
||||
new CancelGroupAlbumMediaLike(obContext, core),
|
||||
new DoGroupAlbumComment(obContext, core),
|
||||
new GetGroupAlbumMediaList(obContext, core),
|
||||
new GetQunAlbumList(obContext, core),
|
||||
new UploadImageToQunAlbum(obContext, core),
|
||||
new SetGroupTodo(obContext, core),
|
||||
new CompleteGroupTodo(obContext, core),
|
||||
new CancelGroupTodo(obContext, core),
|
||||
new GetGroupDetailInfo(obContext, core),
|
||||
new SetGroupKickMembers(obContext, core),
|
||||
new SetGroupAddOption(obContext, core),
|
||||
@@ -185,6 +193,7 @@ export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCo
|
||||
new GetGroupInfoEx(obContext, core),
|
||||
new FetchEmojiLike(obContext, core),
|
||||
new GetEmojiLikes(obContext, core),
|
||||
new FetchPttText(obContext, core),
|
||||
new GetFile(obContext, core),
|
||||
new SetQQProfile(obContext, core),
|
||||
new ShareGroupEx(obContext, core),
|
||||
@@ -206,6 +215,7 @@ export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCo
|
||||
new MoveGroupFile(obContext, core),
|
||||
new RenameGroupFile(obContext, core),
|
||||
new TransGroupFile(obContext, core),
|
||||
new GetGroupSignedList(obContext, core),
|
||||
// onebot11
|
||||
new SendLike(obContext, core),
|
||||
new GetMsg(obContext, core),
|
||||
@@ -270,6 +280,10 @@ export function getAllHandlers (obContext: NapCatOneBot11Adapter, core: NapCatCo
|
||||
new GetProfileLike(obContext, core),
|
||||
new SetGroupPortrait(obContext, core),
|
||||
new FetchCustomFace(obContext, core),
|
||||
new FetchCustomFaceDetail(obContext, core),
|
||||
new AddCustomFace(obContext, core),
|
||||
new DeleteCustomFace(obContext, core),
|
||||
new SetCustomFaceDesc(obContext, core),
|
||||
new GoCQHTTPUploadPrivateFile(obContext, core),
|
||||
new GetGuildProfile(obContext, core),
|
||||
new GoCQHTTPGetModelShow(obContext, core),
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { MessageUnique } from 'napcat-common/src/message-unique';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
import { PromiseTimer } from '@/napcat-common/src/helper';
|
||||
import { ElementType } from '@/napcat-core';
|
||||
import { MsgActionsExamples } from '@/napcat-onebot/action/msg/examples';
|
||||
|
||||
const PayloadSchema = Type.Object({
|
||||
message_id: Type.Union([Type.Number(), Type.String()], { description: '消息ID' }),
|
||||
});
|
||||
|
||||
type PayloadType = Static<typeof PayloadSchema>;
|
||||
|
||||
const ReturnSchema = Type.Object({ text: Type.String({ description: '得到的文本' }) });
|
||||
|
||||
type ReturnType = Static<typeof ReturnSchema>;
|
||||
|
||||
export class FetchPttText extends OneBotAction<PayloadType, ReturnType> {
|
||||
override actionName = ActionName.FetchPttText;
|
||||
override actionSummary = '获取语音转文字结果';
|
||||
override actionTags = ['消息扩展'];
|
||||
override payloadExample = MsgActionsExamples.FetchPttText.payload;
|
||||
override returnExample = MsgActionsExamples.FetchPttText.response;
|
||||
|
||||
override payloadSchema = PayloadSchema;
|
||||
override returnSchema = ReturnSchema;
|
||||
|
||||
async _handle (payload: PayloadType) {
|
||||
if (!payload.message_id) {
|
||||
throw Error('参数message_id不能为空');
|
||||
}
|
||||
const MsgShortId = MessageUnique.getShortIdByMsgId(payload.message_id.toString());
|
||||
const msgIdWithPeer = MessageUnique.getMsgIdAndPeerByShortId(MsgShortId ?? +payload.message_id);
|
||||
if (!msgIdWithPeer) {
|
||||
throw new Error('消息不存在');
|
||||
}
|
||||
const peer = { guildId: '', peerUid: msgIdWithPeer?.Peer.peerUid, chatType: msgIdWithPeer.Peer.chatType };
|
||||
const getMsgTimeout = this.obContext.configLoader.configData.timeout.baseTimeout;
|
||||
const msgRes = await PromiseTimer(
|
||||
this.core.apis.MsgApi.getMsgsByMsgId(peer, [msgIdWithPeer?.MsgId || payload.message_id.toString()]),
|
||||
getMsgTimeout
|
||||
).catch((e: unknown) => {
|
||||
if (e instanceof Error && e.message.startsWith('PromiseTimer:')) {
|
||||
throw new Error(`消息不存在或已被撤回: ${e.message || String(e)}`);
|
||||
}
|
||||
throw e;
|
||||
});
|
||||
const msg = msgRes.msgList[0];
|
||||
if (!msg) throw Error('消息不存在或已被撤回');
|
||||
const pttSegment = msg.elements.find((s) =>
|
||||
s.elementType === ElementType.PTT
|
||||
);
|
||||
if (!pttSegment) {
|
||||
throw Error('消息中不包含语音');
|
||||
}
|
||||
const getPttTextTimeout = this.obContext.configLoader.configData.timeout.baseTimeout;
|
||||
await PromiseTimer(
|
||||
this.core.context.session.getMsgService().translatePtt2Text(msgIdWithPeer.MsgId, msgIdWithPeer.Peer, pttSegment),
|
||||
getPttTextTimeout
|
||||
).catch((e: unknown) => {
|
||||
if (e instanceof Error && e.message.startsWith('PromiseTimer:')) {
|
||||
throw new Error(`获取语音转文字结果失败: ${e.message || String(e)}`);
|
||||
}
|
||||
throw e;
|
||||
});
|
||||
const msgRes2 = await PromiseTimer(
|
||||
this.core.apis.MsgApi.getMsgsByMsgId(peer, [msgIdWithPeer?.MsgId || payload.message_id.toString()]),
|
||||
getMsgTimeout
|
||||
).catch((e: unknown) => {
|
||||
if (e instanceof Error && e.message.startsWith('PromiseTimer:')) {
|
||||
throw new Error(`消息不存在或已被撤回: ${e.message || String(e)}`);
|
||||
}
|
||||
throw e;
|
||||
});
|
||||
const msg2 = msgRes2.msgList[0];
|
||||
if (!msg2) throw Error('消息不存在或已被撤回');
|
||||
for (const s of msg2.elements) {
|
||||
if (s.elementType === ElementType.PTT) {
|
||||
if (s.pttElement?.text) {
|
||||
return { text: s.pttElement?.text };
|
||||
}
|
||||
}
|
||||
}
|
||||
throw new Error('获取语音转文字结果失败');
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { OneBotAction } from '@/napcat-onebot/action/OneBotAction';
|
||||
import { ActionName } from '@/napcat-onebot/action/router';
|
||||
import { MessageUnique } from 'napcat-common/src/message-unique';
|
||||
import { PromiseTimer } from 'napcat-common/src/helper';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
import { NetworkAdapterConfig } from '@/napcat-onebot/config/config';
|
||||
|
||||
@@ -49,8 +50,18 @@ class GetMsg extends OneBotAction<PayloadType, ReturnType> {
|
||||
throw new Error('消息不存在');
|
||||
}
|
||||
const peer = { guildId: '', peerUid: msgIdWithPeer?.Peer.peerUid, chatType: msgIdWithPeer.Peer.chatType };
|
||||
const msg = (await this.core.apis.MsgApi.getMsgsByMsgId(peer, [msgIdWithPeer?.MsgId || payload.message_id.toString()])).msgList[0];
|
||||
if (!msg) throw Error('消息不存在');
|
||||
const getMsgTimeout = this.obContext.configLoader.configData.timeout.baseTimeout;
|
||||
const msgRes = await PromiseTimer(
|
||||
this.core.apis.MsgApi.getMsgsByMsgId(peer, [msgIdWithPeer?.MsgId || payload.message_id.toString()]),
|
||||
getMsgTimeout
|
||||
).catch((e: unknown) => {
|
||||
if (e instanceof Error && e.message.startsWith('PromiseTimer:')) {
|
||||
throw new Error(`消息不存在或已被撤回: ${e.message || String(e)}`);
|
||||
}
|
||||
throw e;
|
||||
});
|
||||
const msg = msgRes.msgList[0];
|
||||
if (!msg) throw Error('消息不存在或已被撤回');
|
||||
const retMsg = await this.obContext.apis.MsgApi.parseMessage(msg, config.messagePostFormat);
|
||||
if (!retMsg) throw Error('消息为空');
|
||||
retMsg.emoji_likes_list = [];
|
||||
|
||||
@@ -30,6 +30,7 @@ export const SendMsgPayloadSchema = Type.Object({
|
||||
news: Type.Optional(Type.Array(Type.Object({ text: Type.String() }), { description: '合并转发新闻' })),
|
||||
summary: Type.Optional(Type.String({ description: '合并转发摘要' })),
|
||||
prompt: Type.Optional(Type.String({ description: '合并转发提示' })),
|
||||
timeout: Type.Optional(Type.Number({ description: '自定义发送超时(毫秒),覆盖自动计算值' })),
|
||||
});
|
||||
|
||||
export type SendMsgPayload = Static<typeof SendMsgPayloadSchema>;
|
||||
@@ -200,7 +201,7 @@ export class SendMsgBase extends OneBotAction<SendMsgPayload, ReturnDataType> {
|
||||
|
||||
const { sendElements, deleteAfterSentFiles } = await this.obContext.apis.MsgApi
|
||||
.createSendElements(messages, peer);
|
||||
const returnMsg = await this.obContext.apis.MsgApi.sendMsgWithOb11UniqueId(peer, sendElements, deleteAfterSentFiles);
|
||||
const returnMsg = await this.obContext.apis.MsgApi.sendMsgWithOb11UniqueId(peer, sendElements, deleteAfterSentFiles, payload.timeout);
|
||||
return { message_id: returnMsg.id! };
|
||||
}
|
||||
|
||||
|
||||
@@ -14,6 +14,12 @@ export const MsgActionsExamples = {
|
||||
message: 'hello',
|
||||
},
|
||||
},
|
||||
FetchPttText: {
|
||||
payload: { message_id: 123456 },
|
||||
response: {
|
||||
text: 'hello',
|
||||
},
|
||||
},
|
||||
MarkMsgAsRead: {
|
||||
payload: { group_id: '123456' },
|
||||
response: {},
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { MessageUnique } from 'napcat-common/src/message-unique';
|
||||
import { ChatType, Peer } from 'napcat-core';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
import { GetPacketStatusDepends } from '@/napcat-onebot/action/packet/GetPacketStatus';
|
||||
|
||||
export const GroupTodoPayloadSchema = Type.Object({
|
||||
group_id: Type.Union([Type.String(), Type.Number()], { description: '群号' }),
|
||||
message_id: Type.Optional(Type.String({ description: '消息ID' })),
|
||||
message_seq: Type.Optional(Type.String({ description: '消息Seq (可选)' })),
|
||||
});
|
||||
|
||||
export type GroupTodoPayload = Static<typeof GroupTodoPayloadSchema>;
|
||||
|
||||
export abstract class BaseGroupTodoAction extends GetPacketStatusDepends<GroupTodoPayload, void> {
|
||||
override payloadSchema = GroupTodoPayloadSchema;
|
||||
override returnSchema = Type.Null();
|
||||
override actionTags = ['核心接口'];
|
||||
|
||||
protected abstract handleGroupTodo (groupId: number, msgSeq: string): Promise<void>;
|
||||
|
||||
async _handle (payload: GroupTodoPayload) {
|
||||
const groupId = +payload.group_id;
|
||||
if (payload.message_seq) {
|
||||
return await this.handleGroupTodo(groupId, payload.message_seq.toString());
|
||||
}
|
||||
if (!payload.message_id) {
|
||||
throw new Error('缺少参数 message_id 或 message_seq');
|
||||
}
|
||||
const peer: Peer = {
|
||||
chatType: ChatType.KCHATTYPEGROUP,
|
||||
peerUid: payload.group_id.toString(),
|
||||
};
|
||||
const { MsgId, Peer } = MessageUnique.getMsgIdAndPeerByShortId(+payload.message_id) ?? { Peer: peer, MsgId: payload.message_id.toString() };
|
||||
const msg = (await this.core.apis.MsgApi.getMsgsByMsgId(Peer, [MsgId])).msgList[0];
|
||||
if (!msg) {
|
||||
throw new Error('消息不存在');
|
||||
}
|
||||
await this.handleGroupTodo(groupId, msg.msgSeq);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { ActionName } from '../router';
|
||||
import { PacketActionsExamples } from '../example/PacketActionsExamples';
|
||||
import { BaseGroupTodoAction } from './BaseGroupTodoAction';
|
||||
|
||||
export class CancelGroupTodo extends BaseGroupTodoAction {
|
||||
override actionName = ActionName.CancelGroupTodo;
|
||||
override actionSummary = '取消群待办';
|
||||
override actionDescription = '将指定消息对应的群待办取消';
|
||||
override payloadExample = PacketActionsExamples.CancelGroupTodo.payload;
|
||||
override returnExample = PacketActionsExamples.CancelGroupTodo.response;
|
||||
|
||||
protected override async handleGroupTodo (groupId: number, msgSeq: string) {
|
||||
await this.core.apis.PacketApi.pkt.operation.CancelGroupTodo(groupId, msgSeq);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { ActionName } from '../router';
|
||||
import { PacketActionsExamples } from '../example/PacketActionsExamples';
|
||||
import { BaseGroupTodoAction } from './BaseGroupTodoAction';
|
||||
|
||||
export class CompleteGroupTodo extends BaseGroupTodoAction {
|
||||
override actionName = ActionName.CompleteGroupTodo;
|
||||
override actionSummary = '完成群待办';
|
||||
override actionDescription = '将指定消息对应的群待办标记为已完成';
|
||||
override payloadExample = PacketActionsExamples.CompleteGroupTodo.payload;
|
||||
override returnExample = PacketActionsExamples.CompleteGroupTodo.response;
|
||||
|
||||
protected override async handleGroupTodo (groupId: number, msgSeq: string) {
|
||||
await this.core.apis.PacketApi.pkt.operation.CompleteGroupTodo(groupId, msgSeq);
|
||||
}
|
||||
}
|
||||
@@ -1,42 +1,14 @@
|
||||
import { MessageUnique } from 'napcat-common/src/message-unique';
|
||||
import { ChatType, Peer } from 'napcat-core';
|
||||
import { GetPacketStatusDepends } from '@/napcat-onebot/action/packet/GetPacketStatus';
|
||||
import { Static, Type } from '@sinclair/typebox';
|
||||
import { ActionName } from '../router';
|
||||
|
||||
import { PacketActionsExamples } from '../example/PacketActionsExamples';
|
||||
|
||||
export const SetGroupTodoPayloadSchema = Type.Object({
|
||||
group_id: Type.Union([Type.String(), Type.Number()], { description: '群号' }),
|
||||
message_id: Type.Optional(Type.String({ description: '消息ID' })),
|
||||
message_seq: Type.Optional(Type.String({ description: '消息Seq (可选)' })),
|
||||
});
|
||||
|
||||
export type SetGroupTodoPayload = Static<typeof SetGroupTodoPayloadSchema>;
|
||||
export class SetGroupTodo extends GetPacketStatusDepends<SetGroupTodoPayload, void> {
|
||||
import { BaseGroupTodoAction } from './BaseGroupTodoAction';
|
||||
export class SetGroupTodo extends BaseGroupTodoAction {
|
||||
override actionName = ActionName.SetGroupTodo;
|
||||
override payloadSchema = SetGroupTodoPayloadSchema;
|
||||
override returnSchema = Type.Null();
|
||||
override actionSummary = '设置群待办';
|
||||
override actionDescription = '将指定消息设置为群待办';
|
||||
override actionTags = ['核心接口'];
|
||||
override payloadExample = PacketActionsExamples.SetGroupTodo.payload;
|
||||
override returnExample = PacketActionsExamples.SetGroupTodo.response;
|
||||
|
||||
async _handle (payload: SetGroupTodoPayload) {
|
||||
if (payload.message_seq) {
|
||||
return await this.core.apis.PacketApi.pkt.operation.SetGroupTodo(+payload.group_id, payload.message_seq.toString());
|
||||
}
|
||||
if (!payload.message_id) {
|
||||
throw new Error('缺少参数 message_id 或 message_seq');
|
||||
}
|
||||
const peer: Peer = {
|
||||
chatType: ChatType.KCHATTYPEGROUP,
|
||||
peerUid: payload.group_id.toString(),
|
||||
};
|
||||
const { MsgId, Peer } = MessageUnique.getMsgIdAndPeerByShortId(+payload.message_id) ?? { Peer: peer, MsgId: payload.message_id.toString() };
|
||||
const msg = (await this.core.apis.MsgApi.getMsgsByMsgId(Peer, [MsgId])).msgList[0];
|
||||
if (!msg) throw new Error('消息不存在');
|
||||
await this.core.apis.PacketApi.pkt.operation.SetGroupTodo(+payload.group_id, msg.msgSeq);
|
||||
protected override async handleGroupTodo (groupId: number, msgSeq: string) {
|
||||
await this.core.apis.PacketApi.pkt.operation.SetGroupTodo(groupId, msgSeq);
|
||||
}
|
||||
}
|
||||
@@ -24,11 +24,14 @@ export const ActionName = {
|
||||
|
||||
DelGroupAlbumMedia: 'del_group_album_media',
|
||||
SetGroupAlbumMediaLike: 'set_group_album_media_like',
|
||||
CancelGroupAlbumMediaLike: 'cancel_group_album_media_like',
|
||||
DoGroupAlbumComment: 'do_group_album_comment',
|
||||
GetGroupAlbumMediaList: 'get_group_album_media_list',
|
||||
UploadImageToQunAlbum: 'upload_image_to_qun_album',
|
||||
GetQunAlbumList: 'get_qun_album_list',
|
||||
SetGroupTodo: 'set_group_todo',
|
||||
CompleteGroupTodo: 'complete_group_todo',
|
||||
CancelGroupTodo: 'cancel_group_todo',
|
||||
SetGroupKickMembers: 'set_group_kick_members',
|
||||
SetGroupRobotAddOption: 'set_group_robot_add_option',
|
||||
SetGroupAddOption: 'set_group_add_option',
|
||||
@@ -139,6 +142,7 @@ export const ActionName = {
|
||||
ForwardFriendSingleMsg: 'forward_friend_single_msg',
|
||||
ForwardGroupSingleMsg: 'forward_group_single_msg',
|
||||
TranslateEnWordToZn: 'translate_en2zh',
|
||||
FetchPttText: 'fetch_ptt_text',
|
||||
SetMsgEmojiLike: 'set_msg_emoji_like',
|
||||
GoCQHTTP_SendForwardMsg: 'send_forward_msg',
|
||||
MarkPrivateMsgAsRead: 'mark_private_msg_as_read',
|
||||
@@ -151,6 +155,10 @@ export const ActionName = {
|
||||
_MarkAllMsgAsRead: '_mark_all_as_read',
|
||||
GetProfileLike: 'get_profile_like',
|
||||
FetchCustomFace: 'fetch_custom_face',
|
||||
FetchCustomFaceDetail: 'fetch_custom_face_detail',
|
||||
AddCustomFace: 'add_custom_face',
|
||||
DeleteCustomFace: 'delete_custom_face',
|
||||
SetCustomFaceDesc: 'set_custom_face_desc',
|
||||
FetchEmojiLike: 'fetch_emoji_like',
|
||||
GetEmojiLikes: 'get_emoji_likes',
|
||||
SetInputStatus: 'set_input_status',
|
||||
@@ -204,4 +212,6 @@ export const ActionName = {
|
||||
ReceiveOnlineFile: 'receive_online_file',
|
||||
RefuseOnlineFile: 'refuse_online_file',
|
||||
CancelOnlineFile: 'cancel_online_file',
|
||||
|
||||
GetGroupSignedList: 'get_group_signed_list',
|
||||
} as const;
|
||||
@@ -2,6 +2,7 @@ import { OneBotAction, OneBotRequestToolkit } from '@/napcat-onebot/action/OneBo
|
||||
import { StreamPacket, StreamStatus } from './StreamBasic';
|
||||
import fs from 'fs';
|
||||
import { FileNapCatOneBotUUID } from 'napcat-common/src/file-uuid';
|
||||
import { calculateTimeout } from '@/napcat-onebot/config/config';
|
||||
|
||||
export interface ResolvedFileInfo {
|
||||
downloadPath: string;
|
||||
@@ -64,8 +65,11 @@ export abstract class BaseDownloadStream<PayloadType, ResultType> extends OneBot
|
||||
|
||||
const searchResult = (await this.core.apis.FileApi.searchForFile([target]));
|
||||
if (searchResult) {
|
||||
downloadPath = await this.core.apis.FileApi.downloadFileById(searchResult.id, parseInt(searchResult.fileSize));
|
||||
fileSize = parseInt(searchResult.fileSize);
|
||||
const fileSizeNum = parseInt(searchResult.fileSize);
|
||||
const timeoutConfig = this.obContext.configLoader.configData.timeout;
|
||||
const estimatedTime = calculateTimeout(timeoutConfig, fileSizeNum, timeoutConfig.downloadSpeedKBps);
|
||||
downloadPath = await this.core.apis.FileApi.downloadFileById(searchResult.id, fileSizeNum, estimatedTime);
|
||||
fileSize = fileSizeNum;
|
||||
fileName = searchResult.fileName;
|
||||
return { downloadPath, fileName, fileSize };
|
||||
}
|
||||
|
||||
@@ -35,7 +35,16 @@ export class GetCookies extends OneBotAction<GetCookiesPayload, GetCookiesRespon
|
||||
const cookiesObject = await this.core.apis.UserApi.getCookies(payload.domain);
|
||||
// 把获取到的cookiesObject转换成 k=v; 格式字符串拼接在一起
|
||||
const cookies = Object.entries(cookiesObject).map(([key, value]) => `${key}=${value}`).join('; ');
|
||||
const bkn = cookiesObject?.['skey'] ? this.core.apis.WebApi.getBknFromCookie(cookiesObject) : '';
|
||||
let bkn = '';
|
||||
if (payload.domain.includes('qzone.qq.com')) {
|
||||
if (cookiesObject?.['p_skey']) {
|
||||
bkn = this.core.apis.WebApi.getBknFromPSKey(cookiesObject['p_skey']);
|
||||
} else {
|
||||
bkn = cookiesObject?.['skey'] ? this.core.apis.WebApi.getBknFromCookie(cookiesObject) : '';
|
||||
}
|
||||
} else {
|
||||
bkn = cookiesObject?.['skey'] ? this.core.apis.WebApi.getBknFromCookie(cookiesObject) : '';
|
||||
}
|
||||
return { cookies, bkn };
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { fileTypeFromFile } from 'file-type';
|
||||
import pathLib from 'node:path';
|
||||
import fsPromises from 'fs/promises';
|
||||
import fs from 'fs';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { defaultVideoThumbB64 } from '@/napcat-core/helper/ffmpeg/video';
|
||||
export class OneBotFileApi {
|
||||
obContext: NapCatOneBot11Adapter;
|
||||
@@ -19,7 +20,7 @@ export class OneBotFileApi {
|
||||
this.core = core;
|
||||
}
|
||||
|
||||
async createValidSendFileElement (context: SendMessageContext, filePath: string, fileName: string = '', folderId: string = '', uploadGroupFile: boolean = false): Promise<SendFileElement> {
|
||||
async createValidSendFileElement (context: SendMessageContext, filePath: string, fileName: string = '', folderId: string = '', uploadGroupFile: boolean = false, _isLocal: boolean = false): Promise<SendFileElement> {
|
||||
const {
|
||||
fileName: _fileName,
|
||||
path,
|
||||
@@ -43,7 +44,7 @@ export class OneBotFileApi {
|
||||
};
|
||||
}
|
||||
|
||||
async createValidSendPicElement (context: SendMessageContext, picPath: string, summary: string = '', subType: PicSubType = 0): Promise<SendPicElement> {
|
||||
async createValidSendPicElement (context: SendMessageContext, picPath: string, summary: string = '', subType: PicSubType = 0, _isLocal: boolean = false): Promise<SendPicElement> {
|
||||
const { md5, fileName, path, fileSize } = await this.core.apis.FileApi.uploadFile(picPath, ElementType.PIC, subType);
|
||||
if (fileSize === 0) {
|
||||
throw new Error('文件异常,大小为0');
|
||||
@@ -71,7 +72,7 @@ export class OneBotFileApi {
|
||||
};
|
||||
}
|
||||
|
||||
async createValidSendVideoElement (context: SendMessageContext, filePath: string, fileName: string = '', _diyThumbPath: string = ''): Promise<SendVideoElement> {
|
||||
async createValidSendVideoElement (context: SendMessageContext, filePath: string, fileName: string = '', _diyThumbPath: string = '', isLocal: boolean = false): Promise<SendVideoElement> {
|
||||
let videoInfo = {
|
||||
width: 1920,
|
||||
height: 1080,
|
||||
@@ -87,10 +88,24 @@ export class OneBotFileApi {
|
||||
} catch (e) {
|
||||
this.core.context.logger.logError('获取文件类型失败', e);
|
||||
}
|
||||
const newFilePath = `${filePath}.${fileExt}`;
|
||||
fs.copyFileSync(filePath, newFilePath);
|
||||
context.deleteAfterSentFiles.push(newFilePath);
|
||||
filePath = newFilePath;
|
||||
const currentExt = pathLib.extname(filePath).slice(1).toLowerCase();
|
||||
const needsExtCopy = currentExt !== fileExt.toLowerCase();
|
||||
if (needsExtCopy) {
|
||||
if (isLocal) {
|
||||
// 本地文件缺少正确扩展名:拷贝到临时目录,避免污染用户目录
|
||||
const tempFilePath = pathLib.join(this.core.NapCatTempPath, `${randomUUID()}.${fileExt}`);
|
||||
fs.copyFileSync(filePath, tempFilePath);
|
||||
context.deleteAfterSentFiles.push(tempFilePath);
|
||||
filePath = tempFilePath;
|
||||
} else {
|
||||
// 临时文件缺少正确扩展名:在原位置加扩展名
|
||||
const newFilePath = `${filePath}.${fileExt}`;
|
||||
fs.copyFileSync(filePath, newFilePath);
|
||||
context.deleteAfterSentFiles.push(newFilePath);
|
||||
filePath = newFilePath;
|
||||
}
|
||||
}
|
||||
// 扩展名已匹配时:本地文件直接用原始路径(零拷贝),临时文件也无需额外操作
|
||||
|
||||
const { fileName: _fileName, path, fileSize, md5 } = await this.core.apis.FileApi.uploadFile(filePath, ElementType.VIDEO);
|
||||
context.deleteAfterSentFiles.push(path);
|
||||
|
||||
@@ -34,9 +34,9 @@ import { EventType } from '@/napcat-onebot/event/OneBotEvent';
|
||||
import { encodeCQCode } from '@/napcat-onebot/helper/cqcode';
|
||||
import { uriToLocalFile } from 'napcat-common/src/file';
|
||||
import { RequestUtil } from 'napcat-common/src/request';
|
||||
import fsPromise from 'node:fs/promises';
|
||||
import { OB11FriendAddNoticeEvent } from '@/napcat-onebot/event/notice/OB11FriendAddNoticeEvent';
|
||||
import { ForwardMsgBuilder } from '@/napcat-core/helper/forward-msg-builder';
|
||||
import { calculateTimeout, capTimeout } from '@/napcat-onebot/config/config';
|
||||
import { NapProtoMsg } from 'napcat-protobuf';
|
||||
import { OB11GroupIncreaseEvent } from '../event/notice/OB11GroupIncreaseEvent';
|
||||
import { GroupDecreaseSubType, OB11GroupDecreaseEvent } from '../event/notice/OB11GroupDecreaseEvent';
|
||||
@@ -736,32 +736,36 @@ export class OneBotMsgApi {
|
||||
|
||||
// File service
|
||||
[OB11MessageDataType.image]: async (sendMsg, context) => {
|
||||
const result = await this.handleOb11FileLikeMessage(sendMsg, context);
|
||||
return await this.obContext.apis.FileApi.createValidSendPicElement(
|
||||
context,
|
||||
(await this.handleOb11FileLikeMessage(sendMsg, context)).path,
|
||||
result.path,
|
||||
sendMsg.data.summary,
|
||||
sendMsg.data.sub_type
|
||||
sendMsg.data.sub_type,
|
||||
result.isLocal
|
||||
);
|
||||
},
|
||||
|
||||
[OB11MessageDataType.file]: async (sendMsg, context) => {
|
||||
const { path, fileName } = await this.handleOb11FileLikeMessage(sendMsg, context);
|
||||
return await this.obContext.apis.FileApi.createValidSendFileElement(context, path, fileName);
|
||||
const { path, fileName, isLocal } = await this.handleOb11FileLikeMessage(sendMsg, context);
|
||||
return await this.obContext.apis.FileApi.createValidSendFileElement(context, path, fileName, '', false, isLocal);
|
||||
},
|
||||
|
||||
[OB11MessageDataType.video]: async (sendMsg, context) => {
|
||||
const { path, fileName } = await this.handleOb11FileLikeMessage(sendMsg, context);
|
||||
const { path, fileName, isLocal } = await this.handleOb11FileLikeMessage(sendMsg, context);
|
||||
|
||||
let thumb = sendMsg.data.thumb;
|
||||
if (thumb) {
|
||||
const uri2LocalRes = await uriToLocalFile(this.core.NapCatTempPath, thumb);
|
||||
if (uri2LocalRes.success) {
|
||||
thumb = uri2LocalRes.path;
|
||||
context.deleteAfterSentFiles.push(thumb);
|
||||
if (!uri2LocalRes.isLocal) {
|
||||
context.deleteAfterSentFiles.push(thumb);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return await this.obContext.apis.FileApi.createValidSendVideoElement(context, path, fileName, thumb);
|
||||
return await this.obContext.apis.FileApi.createValidSendVideoElement(context, path, fileName, thumb, isLocal);
|
||||
},
|
||||
|
||||
[OB11MessageDataType.voice]: async (sendMsg, context) =>
|
||||
@@ -1241,36 +1245,34 @@ export class OneBotMsgApi {
|
||||
return { sendElements, deleteAfterSentFiles };
|
||||
}
|
||||
|
||||
async sendMsgWithOb11UniqueId (peer: Peer, sendElements: SendMessageElement[], deleteAfterSentFiles: string[]) {
|
||||
async sendMsgWithOb11UniqueId (peer: Peer, sendElements: SendMessageElement[], deleteAfterSentFiles: string[], timeoutOverride?: number) {
|
||||
if (!sendElements.length) {
|
||||
throw new Error('消息体无法解析, 请检查是否发送了不支持的消息类型');
|
||||
}
|
||||
|
||||
const calculateTotalSize = async (elements: SendMessageElement[]): Promise<number> => {
|
||||
const sizePromises = elements.map(async element => {
|
||||
const timeoutConfig = this.obContext.configLoader.configData.timeout;
|
||||
|
||||
let timeout: number;
|
||||
if (timeoutOverride !== undefined && timeoutOverride > 0) {
|
||||
timeout = capTimeout(timeoutConfig, timeoutOverride);
|
||||
} else {
|
||||
const totalSize = sendElements.reduce((total, element) => {
|
||||
switch (element.elementType) {
|
||||
case ElementType.PTT:
|
||||
return (await fsPromise.stat(element.pttElement.filePath)).size;
|
||||
return total + (+(element.pttElement.fileSize || '3000'));
|
||||
case ElementType.FILE:
|
||||
return (await fsPromise.stat(element.fileElement.filePath)).size;
|
||||
return total + (+(element.fileElement.fileSize || '3000'));
|
||||
case ElementType.VIDEO:
|
||||
return (await fsPromise.stat(element.videoElement.filePath)).size;
|
||||
return total + (+(element.videoElement.fileSize || '3000'));
|
||||
case ElementType.PIC:
|
||||
return (await fsPromise.stat(element.picElement.sourcePath)).size;
|
||||
return total + (+(element.picElement.fileSize || '3000'));
|
||||
default:
|
||||
return 0;
|
||||
return total;
|
||||
}
|
||||
});
|
||||
const sizes = await Promise.all(sizePromises);
|
||||
return sizes.reduce((total, size) => total + size, 0);
|
||||
};
|
||||
}, 0);
|
||||
|
||||
const totalSize = await calculateTotalSize(sendElements).catch(e => {
|
||||
this.core.context.logger.logError('发送消息计算预计时间异常', e);
|
||||
return 0;
|
||||
});
|
||||
|
||||
const timeout = 10000 + (totalSize / 1024 / 256 * 1000);
|
||||
timeout = calculateTimeout(timeoutConfig, totalSize, timeoutConfig.uploadSpeedKBps);
|
||||
}
|
||||
try {
|
||||
const returnMsg = await this.core.apis.MsgApi.sendMsg(peer, sendElements, timeout);
|
||||
if (!returnMsg) throw new Error('发送消息失败');
|
||||
@@ -1309,13 +1311,15 @@ export class OneBotMsgApi {
|
||||
realUri = await this.handleObfuckName(realUri) ?? realUri;
|
||||
try {
|
||||
const proxy = this.obContext.configLoader.configData.imageDownloadProxy || undefined;
|
||||
const { path, fileName, errMsg, success } = await uriToLocalFile(this.core.NapCatTempPath, realUri, undefined, undefined, proxy);
|
||||
const { path, fileName, errMsg, success, isLocal } = await uriToLocalFile(this.core.NapCatTempPath, realUri, undefined, undefined, proxy);
|
||||
if (!success) {
|
||||
this.core.context.logger.logError('文件处理失败', errMsg);
|
||||
throw new Error('文件处理失败: ' + errMsg);
|
||||
}
|
||||
deleteAfterSentFiles.push(path);
|
||||
return { path, fileName: inputdata.name ?? fileName };
|
||||
if (!isLocal) {
|
||||
deleteAfterSentFiles.push(path);
|
||||
}
|
||||
return { path, fileName: inputdata.name ?? fileName, isLocal };
|
||||
} catch (e: unknown) {
|
||||
throw new Error((e as Error).message);
|
||||
}
|
||||
|
||||
@@ -59,6 +59,7 @@ const WebsocketClientConfigSchema = Type.Object({
|
||||
token: Type.String({ default: '' }),
|
||||
debug: Type.Boolean({ default: false }),
|
||||
heartInterval: Type.Number({ default: 30000 }),
|
||||
verifyCertificate: Type.Optional(Type.Boolean({ default: true })),
|
||||
});
|
||||
|
||||
const PluginConfigSchema = Type.Object({
|
||||
@@ -78,12 +79,20 @@ const NetworkConfigSchema = Type.Object({
|
||||
plugins: Type.Array(PluginConfigSchema, { default: [] }),
|
||||
}, { default: {} });
|
||||
|
||||
const TimeoutConfigSchema = Type.Object({
|
||||
baseTimeout: Type.Number({ default: 10000 }),
|
||||
uploadSpeedKBps: Type.Number({ default: 256 }),
|
||||
downloadSpeedKBps: Type.Number({ default: 256 }),
|
||||
maxTimeout: Type.Number({ default: 1800000 }),
|
||||
}, { default: {} });
|
||||
|
||||
export const OneBotConfigSchema = Type.Object({
|
||||
network: NetworkConfigSchema,
|
||||
musicSignUrl: Type.String({ default: '' }),
|
||||
enableLocalFile2Url: Type.Boolean({ default: false }),
|
||||
parseMultMsg: Type.Boolean({ default: false }),
|
||||
imageDownloadProxy: Type.String({ default: '' }),
|
||||
timeout: TimeoutConfigSchema,
|
||||
});
|
||||
|
||||
export type OneBotConfig = Static<typeof OneBotConfigSchema>;
|
||||
@@ -108,3 +117,21 @@ export function loadConfig (config: Partial<OneBotConfig>): OneBotConfig {
|
||||
}
|
||||
return data as OneBotConfig;
|
||||
}
|
||||
|
||||
export function calculateTimeout (
|
||||
config: OneBotConfig['timeout'],
|
||||
dataSizeBytes: number,
|
||||
speedKBps: number
|
||||
): number {
|
||||
return Math.min(
|
||||
config.baseTimeout + (dataSizeBytes / 1024 / Math.max(speedKBps, 1) * 1000),
|
||||
config.maxTimeout
|
||||
);
|
||||
}
|
||||
|
||||
export function capTimeout (
|
||||
config: OneBotConfig['timeout'],
|
||||
timeoutMs: number
|
||||
): number {
|
||||
return Math.min(timeoutMs, config.maxTimeout);
|
||||
}
|
||||
@@ -157,10 +157,6 @@ export class NapCatOneBot11Adapter {
|
||||
|
||||
// 创建NetWork服务
|
||||
|
||||
// 注册Plugin 如果需要基于NapCat进行快速开发
|
||||
// this.networkManager.registerAdapter(
|
||||
// new OB11PluginAdapter('myPlugin', this.core, this,this.actions)
|
||||
// );
|
||||
// 检查插件目录是否存在,不存在则不加载插件管理器
|
||||
if (existsSync(this.context.pathWrapper.pluginPath)) {
|
||||
this.context.logger.log('[Plugins] 插件目录存在,开始加载插件');
|
||||
|
||||
@@ -250,7 +250,7 @@ export class OB11HttpServerAdapter extends IOB11NetworkAdapter<HttpServerConfig>
|
||||
|
||||
async httpApiRequest (req: Request, res: Response, request_sse: boolean = false) {
|
||||
let payload = req.body;
|
||||
if (req.method === 'get') {
|
||||
if (req.method === 'GET') {
|
||||
payload = req.query;
|
||||
} else if (req.query) {
|
||||
payload = { ...req.body, ...req.query };
|
||||
@@ -307,6 +307,7 @@ export class OB11HttpServerAdapter extends IOB11NetworkAdapter<HttpServerConfig>
|
||||
async reload (newConfig: HttpServerConfig) {
|
||||
const wasEnabled = this.isEnable;
|
||||
const oldPort = this.config.port;
|
||||
const oldHost = this.config.host;
|
||||
const oldEnableWebsocket = this.config.enableWebsocket;
|
||||
this.config = newConfig;
|
||||
|
||||
@@ -318,7 +319,7 @@ export class OB11HttpServerAdapter extends IOB11NetworkAdapter<HttpServerConfig>
|
||||
return OB11NetworkReloadType.NetWorkClose;
|
||||
}
|
||||
|
||||
if (oldPort !== newConfig.port || oldEnableWebsocket !== newConfig.enableWebsocket) {
|
||||
if (oldPort !== newConfig.port || oldHost !== newConfig.host || oldEnableWebsocket !== newConfig.enableWebsocket) {
|
||||
this.close();
|
||||
if (newConfig.enable) {
|
||||
this.open();
|
||||
|
||||
@@ -1,378 +0,0 @@
|
||||
import { OB11EmitEventContent, OB11NetworkReloadType } from './index';
|
||||
import { NapCatOneBot11Adapter, OB11Message } from '@/napcat-onebot/index';
|
||||
import { NapCatCore } from 'napcat-core';
|
||||
import { PluginConfig } from '../config/config';
|
||||
import { ActionMap } from '../action';
|
||||
import { IOB11NetworkAdapter } from '@/napcat-onebot/network/adapter';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
|
||||
export interface PluginPackageJson {
|
||||
name?: string;
|
||||
plugin?: string;
|
||||
version?: string;
|
||||
main?: string;
|
||||
}
|
||||
|
||||
export interface PluginModule<T extends OB11EmitEventContent = OB11EmitEventContent> {
|
||||
plugin_init: (core: NapCatCore, obContext: NapCatOneBot11Adapter, actions: ActionMap, instance: OB11PluginAdapter) => void | Promise<void>;
|
||||
plugin_onmessage?: (adapter: string, core: NapCatCore, obCtx: NapCatOneBot11Adapter, event: OB11Message, actions: ActionMap, instance: OB11PluginAdapter) => void | Promise<void>;
|
||||
plugin_onevent?: (adapter: string, core: NapCatCore, obCtx: NapCatOneBot11Adapter, event: T, actions: ActionMap, instance: OB11PluginAdapter) => void | Promise<void>;
|
||||
plugin_cleanup?: (core: NapCatCore, obContext: NapCatOneBot11Adapter, actions: ActionMap, instance: OB11PluginAdapter) => void | Promise<void>;
|
||||
}
|
||||
|
||||
export interface LoadedPlugin {
|
||||
name: string;
|
||||
version?: string;
|
||||
pluginPath: string;
|
||||
entryPath: string;
|
||||
packageJson?: PluginPackageJson;
|
||||
module: PluginModule;
|
||||
}
|
||||
|
||||
export class OB11PluginAdapter extends IOB11NetworkAdapter<PluginConfig> {
|
||||
private readonly pluginPath: string;
|
||||
private loadedPlugins: Map<string, LoadedPlugin> = new Map();
|
||||
declare config: PluginConfig;
|
||||
override get isActive (): boolean {
|
||||
return this.isEnable && this.loadedPlugins.size > 0;
|
||||
}
|
||||
|
||||
constructor (
|
||||
name: string, core: NapCatCore, obContext: NapCatOneBot11Adapter, actions: ActionMap
|
||||
) {
|
||||
const config = {
|
||||
name,
|
||||
messagePostFormat: 'array',
|
||||
reportSelfMessage: true,
|
||||
enable: true,
|
||||
debug: true,
|
||||
};
|
||||
super(name, config, core, obContext, actions);
|
||||
this.pluginPath = this.core.context.pathWrapper.pluginPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 扫描并加载插件
|
||||
*/
|
||||
private async loadPlugins (): Promise<void> {
|
||||
try {
|
||||
// 确保插件目录存在
|
||||
if (!fs.existsSync(this.pluginPath)) {
|
||||
this.logger.logWarn(`[Plugin Adapter] Plugin directory does not exist: ${this.pluginPath}`);
|
||||
fs.mkdirSync(this.pluginPath, { recursive: true });
|
||||
return;
|
||||
}
|
||||
|
||||
const items = fs.readdirSync(this.pluginPath, { withFileTypes: true });
|
||||
|
||||
// 扫描文件和目录
|
||||
for (const item of items) {
|
||||
if (item.isFile()) {
|
||||
// 处理单文件插件
|
||||
await this.loadFilePlugin(item.name);
|
||||
} else if (item.isDirectory()) {
|
||||
// 处理目录插件
|
||||
await this.loadDirectoryPlugin(item.name);
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.log(`[Plugin Adapter] Loaded ${this.loadedPlugins.size} plugins`);
|
||||
} catch (error) {
|
||||
this.logger.logError('[Plugin Adapter] Error loading plugins:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载单文件插件 (.mjs, .js)
|
||||
*/
|
||||
private async loadFilePlugin (filename: string): Promise<void> {
|
||||
// 只处理支持的文件类型
|
||||
if (!this.isSupportedFile(filename)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const filePath = path.join(this.pluginPath, filename);
|
||||
const pluginName = path.parse(filename).name;
|
||||
|
||||
try {
|
||||
const module = await this.importModule(filePath);
|
||||
if (!this.isValidPluginModule(module)) {
|
||||
this.logger.logWarn(`[Plugin Adapter] File ${filename} is not a valid plugin (missing plugin methods)`);
|
||||
return;
|
||||
}
|
||||
|
||||
const plugin: LoadedPlugin = {
|
||||
name: pluginName,
|
||||
pluginPath: this.pluginPath,
|
||||
entryPath: filePath,
|
||||
module,
|
||||
};
|
||||
|
||||
await this.registerPlugin(plugin);
|
||||
} catch (error) {
|
||||
this.logger.logError(`[Plugin Adapter] Error loading file plugin ${filename}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载目录插件
|
||||
*/
|
||||
private async loadDirectoryPlugin (dirname: string): Promise<void> {
|
||||
const pluginDir = path.join(this.pluginPath, dirname);
|
||||
|
||||
try {
|
||||
// 尝试读取 package.json
|
||||
let packageJson: PluginPackageJson | undefined;
|
||||
const packageJsonPath = path.join(pluginDir, 'package.json');
|
||||
|
||||
if (fs.existsSync(packageJsonPath)) {
|
||||
try {
|
||||
const packageContent = fs.readFileSync(packageJsonPath, 'utf-8');
|
||||
packageJson = JSON.parse(packageContent);
|
||||
} catch (error) {
|
||||
this.logger.logWarn(`[Plugin Adapter] Invalid package.json in ${dirname}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
// 确定入口文件
|
||||
const entryFile = this.findEntryFile(pluginDir, packageJson);
|
||||
if (!entryFile) {
|
||||
this.logger.logWarn(`[Plugin Adapter] No valid entry file found for plugin directory: ${dirname}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const entryPath = path.join(pluginDir, entryFile);
|
||||
const module = await this.importModule(entryPath);
|
||||
|
||||
if (!this.isValidPluginModule(module)) {
|
||||
this.logger.logWarn(`[Plugin Adapter] Directory ${dirname} does not contain a valid plugin`);
|
||||
return;
|
||||
}
|
||||
|
||||
const plugin: LoadedPlugin = {
|
||||
name: packageJson?.name || dirname,
|
||||
version: packageJson?.version,
|
||||
pluginPath: pluginDir,
|
||||
entryPath,
|
||||
packageJson,
|
||||
module,
|
||||
};
|
||||
|
||||
await this.registerPlugin(plugin);
|
||||
} catch (error) {
|
||||
this.logger.logError(`[Plugin Adapter] Error loading directory plugin ${dirname}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找插件目录的入口文件
|
||||
*/
|
||||
private findEntryFile (pluginDir: string, packageJson?: PluginPackageJson): string | null {
|
||||
// 优先级:package.json main > 默认文件名
|
||||
const possibleEntries = [
|
||||
packageJson?.main,
|
||||
'index.mjs',
|
||||
'index.js',
|
||||
'main.mjs',
|
||||
'main.js',
|
||||
].filter(Boolean) as string[];
|
||||
|
||||
for (const entry of possibleEntries) {
|
||||
const entryPath = path.join(pluginDir, entry);
|
||||
if (fs.existsSync(entryPath) && fs.statSync(entryPath).isFile()) {
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否为支持的文件类型
|
||||
*/
|
||||
private isSupportedFile (filename: string): boolean {
|
||||
const ext = path.extname(filename).toLowerCase();
|
||||
return ['.mjs', '.js'].includes(ext);
|
||||
}
|
||||
|
||||
/**
|
||||
* 动态导入模块
|
||||
*/
|
||||
private async importModule (filePath: string): Promise<any> {
|
||||
const fileUrl = `file://${filePath.replace(/\\/g, '/')}`;
|
||||
return await import(fileUrl);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查模块是否为有效的插件模块
|
||||
*/
|
||||
private isValidPluginModule (module: any): module is PluginModule {
|
||||
return module && typeof module.plugin_init === 'function';
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册插件
|
||||
*/
|
||||
private async registerPlugin (plugin: LoadedPlugin): Promise<void> {
|
||||
// 检查名称冲突
|
||||
if (this.loadedPlugins.has(plugin.name)) {
|
||||
this.logger.logWarn(`[Plugin Adapter] Plugin name conflict: ${plugin.name}, skipping...`);
|
||||
return;
|
||||
}
|
||||
|
||||
this.loadedPlugins.set(plugin.name, plugin);
|
||||
this.logger.log(`[Plugin Adapter] Registered plugin: ${plugin.name}${plugin.version ? ` v${plugin.version}` : ''}`);
|
||||
|
||||
// 调用插件初始化方法(必须存在)
|
||||
try {
|
||||
await plugin.module.plugin_init(this.core, this.obContext, this.actions, this);
|
||||
this.logger.log(`[Plugin Adapter] Initialized plugin: ${plugin.name}`);
|
||||
} catch (error) {
|
||||
this.logger.logError(`[Plugin Adapter] Error initializing plugin ${plugin.name}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 卸载插件
|
||||
*/
|
||||
private async unloadPlugin (pluginName: string): Promise<void> {
|
||||
const plugin = this.loadedPlugins.get(pluginName);
|
||||
if (!plugin) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 调用插件清理方法
|
||||
if (typeof plugin.module.plugin_cleanup === 'function') {
|
||||
try {
|
||||
await plugin.module.plugin_cleanup(this.core, this.obContext, this.actions, this);
|
||||
this.logger.log(`[Plugin Adapter] Cleaned up plugin: ${pluginName}`);
|
||||
} catch (error) {
|
||||
this.logger.logError(`[Plugin Adapter] Error cleaning up plugin ${pluginName}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
this.loadedPlugins.delete(pluginName);
|
||||
this.logger.log(`[Plugin Adapter] Unloaded plugin: ${pluginName}`);
|
||||
}
|
||||
|
||||
async onEvent<T extends OB11EmitEventContent> (event: T) {
|
||||
if (!this.isEnable) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 遍历所有已加载的插件,调用它们的事件处理方法
|
||||
for (const [, plugin] of this.loadedPlugins) {
|
||||
this.callPluginEventHandler(plugin, event);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用插件的事件处理方法
|
||||
*/
|
||||
private async callPluginEventHandler (plugin: LoadedPlugin, event: OB11EmitEventContent): Promise<void> {
|
||||
try {
|
||||
// 优先使用 plugin_onevent 方法
|
||||
if (typeof plugin.module.plugin_onevent === 'function') {
|
||||
await plugin.module.plugin_onevent(this.name, this.core, this.obContext, event, this.actions, this);
|
||||
}
|
||||
|
||||
// 如果是消息事件并且插件有 plugin_onmessage 方法,也调用
|
||||
if ((event as any).message_type && typeof plugin.module.plugin_onmessage === 'function') {
|
||||
await plugin.module.plugin_onmessage(this.name, this.core, this.obContext, event as OB11Message, this.actions, this);
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.logError(`[Plugin Adapter] Error calling plugin ${plugin.name} event handler:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
async open () {
|
||||
if (this.isEnable) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.logger.log('[Plugin Adapter] Opening plugin adapter...');
|
||||
this.isEnable = true;
|
||||
|
||||
// 加载所有插件
|
||||
await this.loadPlugins();
|
||||
|
||||
this.logger.log(`[Plugin Adapter] Plugin adapter opened with ${this.loadedPlugins.size} plugins loaded`);
|
||||
}
|
||||
|
||||
async close () {
|
||||
if (!this.isEnable) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.logger.log('[Plugin Adapter] Closing plugin adapter...');
|
||||
this.isEnable = false;
|
||||
|
||||
// 卸载所有插件
|
||||
const pluginNames = Array.from(this.loadedPlugins.keys());
|
||||
for (const pluginName of pluginNames) {
|
||||
await this.unloadPlugin(pluginName);
|
||||
}
|
||||
|
||||
this.logger.log('[Plugin Adapter] Plugin adapter closed');
|
||||
}
|
||||
|
||||
async reload () {
|
||||
this.logger.log('[Plugin Adapter] Reloading plugin adapter...');
|
||||
|
||||
// 先关闭然后重新打开
|
||||
await this.close();
|
||||
await this.open();
|
||||
|
||||
this.logger.log('[Plugin Adapter] Plugin adapter reloaded');
|
||||
return OB11NetworkReloadType.Normal;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取已加载的插件列表
|
||||
*/
|
||||
public getLoadedPlugins (): LoadedPlugin[] {
|
||||
return Array.from(this.loadedPlugins.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取插件信息
|
||||
*/
|
||||
public getPluginInfo (pluginName: string): LoadedPlugin | undefined {
|
||||
return this.loadedPlugins.get(pluginName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 重载指定插件
|
||||
*/
|
||||
public async reloadPlugin (pluginName: string): Promise<boolean> {
|
||||
const plugin = this.loadedPlugins.get(pluginName);
|
||||
if (!plugin) {
|
||||
this.logger.logWarn(`[Plugin Adapter] Plugin ${pluginName} not found`);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
// 卸载插件
|
||||
await this.unloadPlugin(pluginName);
|
||||
|
||||
// 重新加载插件
|
||||
const isDirectory = fs.statSync(plugin.pluginPath).isDirectory() &&
|
||||
plugin.pluginPath !== this.pluginPath;
|
||||
|
||||
if (isDirectory) {
|
||||
const dirname = path.basename(plugin.pluginPath);
|
||||
await this.loadDirectoryPlugin(dirname);
|
||||
} else {
|
||||
const filename = path.basename(plugin.entryPath);
|
||||
await this.loadFilePlugin(filename);
|
||||
}
|
||||
|
||||
this.logger.log(`[Plugin Adapter] Plugin ${pluginName} reloaded successfully`);
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.logger.logError(`[Plugin Adapter] Error reloading plugin ${pluginName}:`, error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,31 @@ import {
|
||||
} from './types';
|
||||
const require = createRequire(import.meta.url);
|
||||
|
||||
/** 允许加载的官方插件 ID 白名单。不在表内的插件一律拒绝加载。 */
|
||||
const OFFICIAL_PLUGIN_IDS = new Set<string>([
|
||||
'napcat-plugin-builtin',
|
||||
'napcat-plugin-cleaner',
|
||||
'napcat-plugin-ssqq',
|
||||
'napcat-plugin-qce',
|
||||
]);
|
||||
|
||||
/**
|
||||
* 敏感词表:插件源码命中(黑灰产 / 支付发卡相关)即拒绝加载。
|
||||
* 仅作启发式威慑,混淆/编码可绕过,并非唯一防线。
|
||||
*/
|
||||
const SENSITIVE_KEYWORDS: string[] = [
|
||||
'发卡', '卡密', '卡网', '自动发卡', '寄售', '代刷', '刷单', '跑分',
|
||||
'四件套', '洗钱', '黑产', '灰产', '博彩', '赌博', '菠菜', '涉黄',
|
||||
'色情', '收款码', '代付', '担保交易', '第三方支付', 'USDT',
|
||||
];
|
||||
|
||||
/** 纳入敏感词检测的源码扩展名 */
|
||||
const SCAN_EXTS = new Set(['.js', '.mjs', '.cjs', '.ts']);
|
||||
/** 跳过敏感词扫描的目录名 */
|
||||
const SCAN_SKIP_DIRS = new Set(['data', 'node_modules', '.git']);
|
||||
/** 单文件扫描大小上限,避免超大文件拖慢启动 */
|
||||
const SCAN_MAX_FILE_BYTES = 5 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* 插件加载器
|
||||
* 负责扫描、加载和导入插件模块
|
||||
@@ -121,6 +146,15 @@ export class PluginLoader {
|
||||
// 获取插件 ID(包名或目录名)
|
||||
const pluginId = packageJson?.name || dirname;
|
||||
|
||||
// 官方白名单 + 敏感词校验:被拒绝的插件视为不可见,
|
||||
// 不入列表、不加载、更不会被动态导入执行。
|
||||
// 该检查置于此处统一拦截 scanPlugins 与 rescanPlugin(安装/重载)两条路径。
|
||||
const rejectReason = this.getRejectReason(pluginId, pluginDir);
|
||||
if (rejectReason) {
|
||||
this.logger.logWarn(`[PluginLoader] Rejected ${pluginId} (${dirname}): ${rejectReason}`);
|
||||
return null;
|
||||
}
|
||||
|
||||
// 确定入口文件
|
||||
const entryFile = this.findEntryFile(pluginDir, packageJson);
|
||||
const entryPath = entryFile ? path.join(pluginDir, entryFile) : undefined;
|
||||
@@ -184,7 +218,12 @@ export class PluginLoader {
|
||||
].filter(Boolean) as string[];
|
||||
|
||||
for (const entry of possibleEntries) {
|
||||
const entryPath = path.join(pluginDir, entry);
|
||||
const root = path.resolve(pluginDir);
|
||||
const entryPath = path.resolve(pluginDir, entry);
|
||||
// 拒绝 package.json main 指向插件目录之外(防路径穿越)
|
||||
if (entryPath !== root && !entryPath.startsWith(root + path.sep)) {
|
||||
continue;
|
||||
}
|
||||
if (fs.existsSync(entryPath) && fs.statSync(entryPath).isFile()) {
|
||||
return entry;
|
||||
}
|
||||
@@ -193,6 +232,75 @@ export class PluginLoader {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** 是否为白名单内的官方插件 */
|
||||
isOfficialPlugin (pluginId: string): boolean {
|
||||
return OFFICIAL_PLUGIN_IDS.has(pluginId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断插件是否应被拒绝(非官方 / 命中敏感词)。
|
||||
* @returns 拒绝原因;通过校验返回 null
|
||||
*/
|
||||
private getRejectReason (pluginId: string, pluginDir: string): string | null {
|
||||
const hit = this.scanSensitiveWords(pluginDir);
|
||||
if (this.isOfficialPlugin(pluginId)) {
|
||||
return null;
|
||||
}
|
||||
if (hit) {
|
||||
return `sensitive keyword "${hit}"`;
|
||||
}
|
||||
return "not in official plugin whitelist";
|
||||
}
|
||||
|
||||
/**
|
||||
* 递归扫描插件目录内源码是否命中敏感词(黑灰产 / 支付发卡)。
|
||||
* @returns 命中的敏感词;未命中返回 null
|
||||
*/
|
||||
scanSensitiveWords (pluginDir: string): string | null {
|
||||
const visit = (dir: string): string | null => {
|
||||
let items: fs.Dirent[];
|
||||
try {
|
||||
items = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
for (const item of items) {
|
||||
if (item.isDirectory()) {
|
||||
if (SCAN_SKIP_DIRS.has(item.name)) {
|
||||
continue;
|
||||
}
|
||||
const hit = visit(path.join(dir, item.name));
|
||||
if (hit) {
|
||||
return hit;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (!item.isFile()) {
|
||||
continue;
|
||||
}
|
||||
if (!SCAN_EXTS.has(path.extname(item.name).toLowerCase())) {
|
||||
continue;
|
||||
}
|
||||
const filePath = path.join(dir, item.name);
|
||||
try {
|
||||
if (fs.statSync(filePath).size > SCAN_MAX_FILE_BYTES) {
|
||||
continue;
|
||||
}
|
||||
const content = fs.readFileSync(filePath, 'utf-8');
|
||||
for (const word of SENSITIVE_KEYWORDS) {
|
||||
if (content.includes(word)) {
|
||||
return word;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// 读取失败忽略该文件
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
return visit(pluginDir);
|
||||
}
|
||||
|
||||
/**
|
||||
* 动态导入模块
|
||||
*/
|
||||
|
||||
@@ -1,529 +0,0 @@
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { ActionMap } from '@/napcat-onebot/action';
|
||||
import { NapCatCore } from 'napcat-core';
|
||||
import { NapCatOneBot11Adapter, OB11Message } from '@/napcat-onebot/index';
|
||||
import { OB11EmitEventContent, OB11NetworkReloadType } from '@/napcat-onebot/network/index';
|
||||
import { IOB11NetworkAdapter } from '@/napcat-onebot/network/adapter';
|
||||
import { PluginConfig } from '@/napcat-onebot/config/config';
|
||||
import { NapCatConfig } from './config';
|
||||
import { PluginLoader } from './loader';
|
||||
import { PluginRouterRegistryImpl } from './router-registry';
|
||||
import {
|
||||
PluginEntry,
|
||||
PluginLogger,
|
||||
PluginStatusConfig,
|
||||
NapCatPluginContext,
|
||||
IPluginManager,
|
||||
} from './types';
|
||||
|
||||
export class OB11PluginManager extends IOB11NetworkAdapter<PluginConfig> implements IPluginManager {
|
||||
private readonly pluginPath: string;
|
||||
private readonly configPath: string;
|
||||
private readonly loader: PluginLoader;
|
||||
|
||||
/** 插件注册表: ID -> 插件条目 */
|
||||
private plugins: Map<string, PluginEntry> = new Map();
|
||||
|
||||
/** 插件路由注册表: pluginId -> PluginRouterRegistry */
|
||||
private pluginRouters: Map<string, PluginRouterRegistryImpl> = new Map();
|
||||
|
||||
declare config: PluginConfig;
|
||||
public NapCatConfig = NapCatConfig;
|
||||
|
||||
override get isActive (): boolean {
|
||||
return this.isEnable && this.getLoadedPlugins().length > 0;
|
||||
}
|
||||
|
||||
constructor (
|
||||
name: string,
|
||||
core: NapCatCore,
|
||||
obContext: NapCatOneBot11Adapter,
|
||||
actions: ActionMap
|
||||
) {
|
||||
const config = {
|
||||
name,
|
||||
messagePostFormat: 'array',
|
||||
reportSelfMessage: true,
|
||||
enable: true,
|
||||
debug: true,
|
||||
};
|
||||
super(name, config, core, obContext, actions);
|
||||
this.pluginPath = this.core.context.pathWrapper.pluginPath;
|
||||
this.configPath = path.join(this.core.context.pathWrapper.configPath, 'plugins.json');
|
||||
this.loader = new PluginLoader(this.pluginPath, this.configPath, this.logger);
|
||||
}
|
||||
|
||||
// ==================== 插件状态配置 ====================
|
||||
|
||||
public getPluginConfig (): PluginStatusConfig {
|
||||
return this.loader.loadPluginStatusConfig();
|
||||
}
|
||||
|
||||
private savePluginConfig (config: PluginStatusConfig): void {
|
||||
this.loader.savePluginStatusConfig(config);
|
||||
}
|
||||
|
||||
// ==================== 插件扫描与加载 ====================
|
||||
|
||||
/**
|
||||
* 扫描并加载所有插件
|
||||
*/
|
||||
private async scanAndLoadPlugins (): Promise<void> {
|
||||
// 扫描所有插件目录
|
||||
const entries = await this.loader.scanPlugins();
|
||||
|
||||
// 清空现有注册表
|
||||
this.plugins.clear();
|
||||
|
||||
// 注册所有插件条目
|
||||
for (const entry of entries) {
|
||||
this.plugins.set(entry.id, entry);
|
||||
}
|
||||
|
||||
this.logger.log(`[PluginManager] Scanned ${this.plugins.size} plugins`);
|
||||
|
||||
// 加载启用的插件
|
||||
for (const entry of this.plugins.values()) {
|
||||
if (entry.enable && entry.runtime.status !== 'error') {
|
||||
await this.loadPlugin(entry);
|
||||
}
|
||||
}
|
||||
|
||||
const loadedCount = this.getLoadedPlugins().length;
|
||||
this.logger.log(`[PluginManager] Loaded ${loadedCount} plugins`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载单个插件
|
||||
*/
|
||||
private async loadPlugin (entry: PluginEntry): Promise<boolean> {
|
||||
if (entry.loaded) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (entry.runtime.status === 'error') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 加载模块
|
||||
const module = await this.loader.loadPluginModule(entry);
|
||||
if (!module) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 创建上下文
|
||||
const context = this.createPluginContext(entry);
|
||||
|
||||
// 初始化插件
|
||||
try {
|
||||
await module.plugin_init(context);
|
||||
|
||||
entry.loaded = true;
|
||||
entry.runtime = {
|
||||
status: 'loaded',
|
||||
module,
|
||||
context,
|
||||
};
|
||||
|
||||
this.logger.log(`[PluginManager] Initialized plugin: ${entry.id}${entry.version ? ` v${entry.version}` : ''}`);
|
||||
return true;
|
||||
} catch (error: any) {
|
||||
entry.loaded = false;
|
||||
entry.runtime = {
|
||||
status: 'error',
|
||||
error: error.message || 'Initialization failed',
|
||||
};
|
||||
|
||||
this.logger.logError(`[PluginManager] Error initializing plugin ${entry.id}:`, error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 卸载单个插件
|
||||
*/
|
||||
private async unloadPlugin (entry: PluginEntry): Promise<void> {
|
||||
if (!entry.loaded || entry.runtime.status !== 'loaded') {
|
||||
return;
|
||||
}
|
||||
|
||||
const { module, context } = entry.runtime;
|
||||
|
||||
// 调用清理方法
|
||||
if (module && context && typeof module.plugin_cleanup === 'function') {
|
||||
try {
|
||||
await module.plugin_cleanup(context);
|
||||
this.logger.log(`[PluginManager] Cleaned up plugin: ${entry.id}`);
|
||||
} catch (error) {
|
||||
this.logger.logError(`[PluginManager] Error cleaning up plugin ${entry.id}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
// 重置状态
|
||||
entry.loaded = false;
|
||||
entry.runtime = {
|
||||
status: 'unloaded',
|
||||
};
|
||||
|
||||
this.logger.log(`[PluginManager] Unloaded plugin: ${entry.id}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建插件上下文
|
||||
*/
|
||||
private createPluginContext (entry: PluginEntry): NapCatPluginContext {
|
||||
const dataPath = path.join(this.core.context.pathWrapper.configPath, 'plugins', entry.id);
|
||||
const configPath = path.join(dataPath, 'config.json');
|
||||
|
||||
// 确保插件配置目录存在
|
||||
if (!fs.existsSync(dataPath)) {
|
||||
fs.mkdirSync(dataPath, { recursive: true });
|
||||
}
|
||||
|
||||
// 创建插件专用日志器
|
||||
const pluginPrefix = `[Plugin: ${entry.id}]`;
|
||||
const coreLogger = this.logger;
|
||||
const pluginLogger: PluginLogger = {
|
||||
log: (...args: any[]) => coreLogger.log(pluginPrefix, ...args),
|
||||
debug: (...args: any[]) => coreLogger.logDebug(pluginPrefix, ...args),
|
||||
info: (...args: any[]) => coreLogger.log(pluginPrefix, ...args),
|
||||
warn: (...args: any[]) => coreLogger.logWarn(pluginPrefix, ...args),
|
||||
error: (...args: any[]) => coreLogger.logError(pluginPrefix, ...args),
|
||||
};
|
||||
|
||||
// 创建或获取插件路由注册器
|
||||
let router = this.pluginRouters.get(entry.id);
|
||||
if (!router) {
|
||||
router = new PluginRouterRegistryImpl(entry.id, entry.pluginPath);
|
||||
this.pluginRouters.set(entry.id, router);
|
||||
}
|
||||
|
||||
// 创建获取其他插件导出的方法
|
||||
const getPluginExports = <T = any> (pluginId: string): T | undefined => {
|
||||
const targetEntry = this.plugins.get(pluginId);
|
||||
if (!targetEntry || !targetEntry.loaded || targetEntry.runtime.status !== 'loaded') {
|
||||
return undefined;
|
||||
}
|
||||
return targetEntry.runtime.module as T;
|
||||
};
|
||||
|
||||
return {
|
||||
core: this.core,
|
||||
oneBot: this.obContext,
|
||||
actions: this.actions,
|
||||
pluginName: entry.id,
|
||||
pluginPath: entry.pluginPath,
|
||||
dataPath,
|
||||
configPath,
|
||||
NapCatConfig,
|
||||
adapterName: this.name,
|
||||
pluginManager: this,
|
||||
logger: pluginLogger,
|
||||
router,
|
||||
getPluginExports,
|
||||
};
|
||||
}
|
||||
|
||||
// ==================== 公共 API ====================
|
||||
|
||||
/**
|
||||
* 获取插件目录路径
|
||||
*/
|
||||
public getPluginPath (): string {
|
||||
return this.pluginPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有插件条目
|
||||
*/
|
||||
public getAllPlugins (): PluginEntry[] {
|
||||
return Array.from(this.plugins.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取已加载的插件列表
|
||||
*/
|
||||
public getLoadedPlugins (): PluginEntry[] {
|
||||
return Array.from(this.plugins.values()).filter(p => p.loaded);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过 ID 获取插件信息
|
||||
*/
|
||||
public getPluginInfo (pluginId: string): PluginEntry | undefined {
|
||||
return this.plugins.get(pluginId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置插件状态(启用/禁用)
|
||||
*/
|
||||
public async setPluginStatus (pluginId: string, enable: boolean): Promise<void> {
|
||||
const config = this.getPluginConfig();
|
||||
config[pluginId] = enable;
|
||||
this.savePluginConfig(config);
|
||||
|
||||
const entry = this.plugins.get(pluginId);
|
||||
if (entry) {
|
||||
entry.enable = enable;
|
||||
|
||||
if (enable && !entry.loaded) {
|
||||
// 启用插件
|
||||
await this.loadPlugin(entry);
|
||||
} else if (!enable && entry.loaded) {
|
||||
// 禁用插件
|
||||
await this.unloadPlugin(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过 ID 加载插件
|
||||
*/
|
||||
public async loadPluginById (pluginId: string): Promise<boolean> {
|
||||
let entry = this.plugins.get(pluginId);
|
||||
|
||||
if (!entry) {
|
||||
// 尝试查找并扫描
|
||||
const dirname = this.loader.findPluginDirById(pluginId);
|
||||
if (!dirname) {
|
||||
this.logger.logWarn(`[PluginManager] Plugin ${pluginId} not found in filesystem`);
|
||||
return false;
|
||||
}
|
||||
|
||||
const newEntry = this.loader.rescanPlugin(dirname);
|
||||
if (!newEntry) {
|
||||
return false;
|
||||
}
|
||||
|
||||
this.plugins.set(newEntry.id, newEntry);
|
||||
entry = newEntry;
|
||||
}
|
||||
|
||||
if (!entry.enable) {
|
||||
this.logger.log(`[PluginManager] Skipping loading disabled plugin: ${pluginId}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
return await this.loadPlugin(entry);
|
||||
}
|
||||
|
||||
/**
|
||||
* 卸载插件(仅从内存卸载)
|
||||
*/
|
||||
public async unregisterPlugin (pluginId: string): Promise<void> {
|
||||
const entry = this.plugins.get(pluginId);
|
||||
if (entry) {
|
||||
await this.unloadPlugin(entry);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 卸载并删除插件
|
||||
*/
|
||||
public async uninstallPlugin (pluginId: string, cleanData: boolean = false): Promise<void> {
|
||||
const entry = this.plugins.get(pluginId);
|
||||
if (!entry) {
|
||||
throw new Error(`Plugin ${pluginId} not found`);
|
||||
}
|
||||
|
||||
const pluginPath = entry.pluginPath;
|
||||
const dataPath = path.join(this.core.context.pathWrapper.configPath, 'plugins', pluginId);
|
||||
|
||||
// 先卸载插件
|
||||
await this.unloadPlugin(entry);
|
||||
|
||||
// 从注册表移除
|
||||
this.plugins.delete(pluginId);
|
||||
|
||||
// 删除插件目录
|
||||
if (fs.existsSync(pluginPath)) {
|
||||
fs.rmSync(pluginPath, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
// 清理插件配置数据
|
||||
if (cleanData && fs.existsSync(dataPath)) {
|
||||
fs.rmSync(dataPath, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 重载指定插件
|
||||
*/
|
||||
public async reloadPlugin (pluginId: string): Promise<boolean> {
|
||||
const entry = this.plugins.get(pluginId);
|
||||
if (!entry) {
|
||||
this.logger.logWarn(`[PluginManager] Plugin ${pluginId} not found`);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
// 卸载插件
|
||||
await this.unloadPlugin(entry);
|
||||
|
||||
// 重新扫描
|
||||
const newEntry = this.loader.rescanPlugin(entry.fileId);
|
||||
if (!newEntry) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 更新注册表
|
||||
this.plugins.set(newEntry.id, newEntry);
|
||||
|
||||
// 重新加载
|
||||
if (newEntry.enable) {
|
||||
await this.loadPlugin(newEntry);
|
||||
}
|
||||
|
||||
this.logger.log(`[PluginManager] Plugin ${pluginId} reloaded successfully`);
|
||||
return true;
|
||||
} catch (error) {
|
||||
this.logger.logError(`[PluginManager] Error reloading plugin ${pluginId}:`, error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载目录插件(用于新安装的插件)
|
||||
*/
|
||||
public async loadDirectoryPlugin (dirname: string): Promise<void> {
|
||||
const entry = this.loader.rescanPlugin(dirname);
|
||||
if (!entry) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查是否已存在
|
||||
if (this.plugins.has(entry.id)) {
|
||||
this.logger.logWarn(`[PluginManager] Plugin ${entry.id} already exists`);
|
||||
return;
|
||||
}
|
||||
|
||||
this.plugins.set(entry.id, entry);
|
||||
|
||||
if (entry.enable && entry.runtime.status !== 'error') {
|
||||
await this.loadPlugin(entry);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取插件数据目录路径
|
||||
*/
|
||||
public getPluginDataPath (pluginId: string): string {
|
||||
return path.join(this.core.context.pathWrapper.configPath, 'plugins', pluginId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取插件配置文件路径
|
||||
*/
|
||||
public getPluginConfigPath (pluginId: string): string {
|
||||
return path.join(this.getPluginDataPath(pluginId), 'config.json');
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取插件路由注册器
|
||||
*/
|
||||
public getPluginRouter (pluginId: string): PluginRouterRegistryImpl | undefined {
|
||||
return this.pluginRouters.get(pluginId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有插件路由注册器
|
||||
*/
|
||||
public getAllPluginRouters (): Map<string, PluginRouterRegistryImpl> {
|
||||
return this.pluginRouters;
|
||||
}
|
||||
|
||||
// ==================== 事件处理 ====================
|
||||
|
||||
async onEvent<T extends OB11EmitEventContent> (event: T): Promise<void> {
|
||||
if (!this.isEnable) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await Promise.allSettled(
|
||||
this.getLoadedPlugins().map((entry) =>
|
||||
this.callPluginEventHandler(entry, event)
|
||||
)
|
||||
);
|
||||
} catch (error) {
|
||||
this.logger.logError('[PluginManager] Error handling event:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用插件的事件处理方法
|
||||
*/
|
||||
private async callPluginEventHandler (
|
||||
entry: PluginEntry,
|
||||
event: OB11EmitEventContent
|
||||
): Promise<void> {
|
||||
if (entry.runtime.status !== 'loaded' || !entry.runtime.module || !entry.runtime.context) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { module, context } = entry.runtime;
|
||||
|
||||
try {
|
||||
// 优先使用 plugin_onevent 方法
|
||||
if (typeof module.plugin_onevent === 'function') {
|
||||
await module.plugin_onevent(context, event);
|
||||
}
|
||||
|
||||
// 如果是消息事件并且插件有 plugin_onmessage 方法,也调用
|
||||
if (
|
||||
(event as any).message_type &&
|
||||
typeof module.plugin_onmessage === 'function'
|
||||
) {
|
||||
await module.plugin_onmessage(context, event as OB11Message);
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.logError(`[PluginManager] Error calling plugin ${entry.id} event handler:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
// ==================== 生命周期 ====================
|
||||
|
||||
async open (): Promise<void> {
|
||||
if (this.isEnable) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.logger.log('[PluginManager] Opening plugin manager...');
|
||||
this.isEnable = true;
|
||||
|
||||
// 扫描并加载所有插件
|
||||
await this.scanAndLoadPlugins();
|
||||
|
||||
this.logger.log(`[PluginManager] Plugin manager opened with ${this.getLoadedPlugins().length} plugins loaded`);
|
||||
}
|
||||
|
||||
async close (): Promise<void> {
|
||||
if (!this.isEnable) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.logger.log('[PluginManager] Closing plugin manager...');
|
||||
this.isEnable = false;
|
||||
|
||||
// 卸载所有已加载的插件
|
||||
for (const entry of this.plugins.values()) {
|
||||
if (entry.loaded) {
|
||||
await this.unloadPlugin(entry);
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.log('[PluginManager] Plugin manager closed');
|
||||
}
|
||||
|
||||
async reload (): Promise<OB11NetworkReloadType> {
|
||||
this.logger.log('[PluginManager] Reloading plugin manager...');
|
||||
|
||||
// 先关闭然后重新打开
|
||||
await this.close();
|
||||
await this.open();
|
||||
|
||||
this.logger.log('[PluginManager] Plugin manager reloaded');
|
||||
return OB11NetworkReloadType.Normal;
|
||||
}
|
||||
}
|
||||
@@ -73,7 +73,7 @@ export class OB11WebSocketClientAdapter extends IOB11NetworkAdapter<WebsocketCli
|
||||
if (!this.connection && this.isEnable) {
|
||||
let isClosedByError = false;
|
||||
|
||||
this.connection = new WebSocket(this.config.url, {
|
||||
const wsOptions: WebSocket.ClientOptions = {
|
||||
maxPayload: 50 * 1024 * 1024, // 50 MB
|
||||
handshakeTimeout: 2000,
|
||||
perMessageDeflate: false,
|
||||
@@ -83,8 +83,14 @@ export class OB11WebSocketClientAdapter extends IOB11NetworkAdapter<WebsocketCli
|
||||
'x-client-role': 'Universal', // 为koishi adpter适配
|
||||
'User-Agent': 'OneBot/11',
|
||||
},
|
||||
};
|
||||
|
||||
});
|
||||
// 如果配置了 verifyCertificate,设置 rejectUnauthorized
|
||||
if (this.config.verifyCertificate !== undefined) {
|
||||
wsOptions.rejectUnauthorized = this.config.verifyCertificate;
|
||||
}
|
||||
|
||||
this.connection = new WebSocket(this.config.url, wsOptions);
|
||||
this.connection.on('pong', () => {
|
||||
// this.logger.logDebug('[OneBot] [WebSocket Client] 收到pong');
|
||||
});
|
||||
|
||||
@@ -1,61 +0,0 @@
|
||||
import { TypeCompiler } from '@sinclair/typebox/compiler';
|
||||
import { Value } from '@sinclair/typebox/value';
|
||||
import { OB11MessageDataSchema, OB11MessageSchema, OB11PostSendMsgSchema } from './types/message';
|
||||
import { OB11MessageSchema as OB11ActionMessageSchema } from './action/schemas';
|
||||
|
||||
try {
|
||||
TypeCompiler.Compile(OB11MessageDataSchema);
|
||||
console.log("Compile OB11MessageDataSchema OK");
|
||||
} catch (e: any) {
|
||||
console.error("Error in OB11MessageDataSchema:", e.message);
|
||||
}
|
||||
|
||||
try {
|
||||
TypeCompiler.Compile(OB11MessageSchema);
|
||||
console.log("Compile OB11MessageSchema OK");
|
||||
} catch (e: any) {
|
||||
console.error("Error in OB11MessageSchema:", e.message);
|
||||
}
|
||||
|
||||
try {
|
||||
TypeCompiler.Compile(OB11ActionMessageSchema);
|
||||
console.log("Compile OB11ActionMessageSchema OK");
|
||||
} catch (e: any) {
|
||||
console.error("Error in OB11ActionMessageSchema:", e.message);
|
||||
}
|
||||
|
||||
import { Type } from '@sinclair/typebox';
|
||||
try {
|
||||
const QA = Type.Object({ message: OB11PostSendMsgSchema, quick_action: OB11ActionMessageSchema });
|
||||
TypeCompiler.Compile(QA);
|
||||
console.log("Compile Quick Action OK");
|
||||
} catch (e: any) {
|
||||
console.error("Error in Quick Action:", e.message);
|
||||
}
|
||||
|
||||
// Test validation
|
||||
const testObj = {
|
||||
message_type: 'private',
|
||||
user_id: 12345,
|
||||
message: [
|
||||
{ type: 'text', data: { text: 'hello' } }
|
||||
]
|
||||
};
|
||||
|
||||
try {
|
||||
let data = structuredClone(testObj);
|
||||
data = Value.Default(OB11PostSendMsgSchema, data) as any;
|
||||
data = Value.Convert(OB11PostSendMsgSchema, data) as any;
|
||||
|
||||
const compiler = TypeCompiler.Compile(OB11PostSendMsgSchema);
|
||||
const isValid = compiler.Check(data);
|
||||
console.log("Validation result:", isValid);
|
||||
if (!isValid) {
|
||||
const errors = [...compiler.Errors(data)];
|
||||
errors.forEach(e => console.error(e.path, e.message));
|
||||
} else {
|
||||
console.log("Data after Convert and Check:", JSON.stringify(data, null, 2));
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.error("Test validation error:", e.message);
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "../../packages"
|
||||
},
|
||||
"include": [
|
||||
"*.ts",
|
||||
"**/*.ts"
|
||||
|
||||
@@ -2,84 +2,10 @@ import { defineConfig } from 'vite';
|
||||
import { resolve } from 'path';
|
||||
import nodeResolve from '@rollup/plugin-node-resolve';
|
||||
import { builtinModules } from 'module';
|
||||
import fs from 'fs';
|
||||
|
||||
const nodeModules = [...builtinModules, builtinModules.map((m) => `node:${m}`)].flat();
|
||||
// 依赖排除
|
||||
const external = [];
|
||||
// 构建后拷贝插件
|
||||
function copyToShellPlugin () {
|
||||
return {
|
||||
name: 'copy-to-shell',
|
||||
writeBundle () {
|
||||
try {
|
||||
const sourceDir = resolve(__dirname, 'dist');
|
||||
const targetDir = resolve(__dirname, '../napcat-shell/dist/plugins/napcat-plugin-builtin');
|
||||
const packageJsonSource = resolve(__dirname, 'package.json');
|
||||
const webuiSourceDir = resolve(__dirname, 'webui');
|
||||
const webuiTargetDir = resolve(targetDir, 'webui');
|
||||
|
||||
// 确保目标目录存在
|
||||
if (!fs.existsSync(targetDir)) {
|
||||
fs.mkdirSync(targetDir, { recursive: true });
|
||||
console.log(`[copy-to-shell] Created directory: ${targetDir}`);
|
||||
}
|
||||
|
||||
// 拷贝 dist 目录下的所有文件
|
||||
const files = fs.readdirSync(sourceDir);
|
||||
let copiedCount = 0;
|
||||
|
||||
files.forEach(file => {
|
||||
const sourcePath = resolve(sourceDir, file);
|
||||
const targetPath = resolve(targetDir, file);
|
||||
|
||||
if (fs.statSync(sourcePath).isFile()) {
|
||||
fs.copyFileSync(sourcePath, targetPath);
|
||||
copiedCount++;
|
||||
}
|
||||
});
|
||||
|
||||
// 拷贝 package.json
|
||||
if (fs.existsSync(packageJsonSource)) {
|
||||
const packageJsonTarget = resolve(targetDir, 'package.json');
|
||||
fs.copyFileSync(packageJsonSource, packageJsonTarget);
|
||||
copiedCount++;
|
||||
}
|
||||
|
||||
// 拷贝 webui 目录
|
||||
if (fs.existsSync(webuiSourceDir)) {
|
||||
copyDirRecursive(webuiSourceDir, webuiTargetDir);
|
||||
console.log(`[copy-to-shell] Copied webui directory to ${webuiTargetDir}`);
|
||||
}
|
||||
|
||||
console.log(`[copy-to-shell] Successfully copied ${copiedCount} file(s) to ${targetDir}`);
|
||||
} catch (error) {
|
||||
console.error('[copy-to-shell] Failed to copy files:', error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// 递归复制目录
|
||||
function copyDirRecursive (src: string, dest: string) {
|
||||
if (!fs.existsSync(dest)) {
|
||||
fs.mkdirSync(dest, { recursive: true });
|
||||
}
|
||||
|
||||
const entries = fs.readdirSync(src, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
const srcPath = resolve(src, entry.name);
|
||||
const destPath = resolve(dest, entry.name);
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
copyDirRecursive(srcPath, destPath);
|
||||
} else {
|
||||
fs.copyFileSync(srcPath, destPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default defineConfig({
|
||||
resolve: {
|
||||
@@ -102,5 +28,5 @@ export default defineConfig({
|
||||
external: [...nodeModules, ...external],
|
||||
},
|
||||
},
|
||||
plugins: [nodeResolve(), copyToShellPlugin()],
|
||||
plugins: [nodeResolve()],
|
||||
});
|
||||
@@ -10,14 +10,14 @@ export type CamelCaseHelper<
|
||||
IsFirstChar extends boolean
|
||||
> = S extends `${infer F}${infer R}`
|
||||
? F extends '_'
|
||||
? CamelCaseHelper<R, true, false>
|
||||
: F extends `${number}`
|
||||
? `${F}${CamelCaseHelper<R, true, false>}`
|
||||
: CapNext extends true
|
||||
? `${Uppercase<F>}${CamelCaseHelper<R, false, false>}`
|
||||
: IsFirstChar extends true
|
||||
? `${Lowercase<F>}${CamelCaseHelper<R, false, false>}`
|
||||
: `${F}${CamelCaseHelper<R, false, false>}`
|
||||
? CamelCaseHelper<R, true, false>
|
||||
: F extends `${number}`
|
||||
? `${F}${CamelCaseHelper<R, true, false>}`
|
||||
: CapNext extends true
|
||||
? `${Uppercase<F>}${CamelCaseHelper<R, false, false>}`
|
||||
: IsFirstChar extends true
|
||||
? `${Lowercase<F>}${CamelCaseHelper<R, false, false>}`
|
||||
: `${F}${CamelCaseHelper<R, false, false>}`
|
||||
: '';
|
||||
|
||||
export type ScalarTypeToTsType<T extends ScalarType> = T extends
|
||||
@@ -30,14 +30,14 @@ export type ScalarTypeToTsType<T extends ScalarType> = T extends
|
||||
| ScalarType.SINT32
|
||||
? number
|
||||
: T extends ScalarType.INT64 | ScalarType.UINT64 | ScalarType.FIXED64 | ScalarType.SFIXED64 | ScalarType.SINT64
|
||||
? bigint
|
||||
: T extends ScalarType.BOOL
|
||||
? boolean
|
||||
: T extends ScalarType.STRING
|
||||
? string
|
||||
: T extends ScalarType.BYTES
|
||||
? Uint8Array
|
||||
: never;
|
||||
? bigint
|
||||
: T extends ScalarType.BOOL
|
||||
? boolean
|
||||
: T extends ScalarType.STRING
|
||||
? string
|
||||
: T extends ScalarType.BYTES
|
||||
? Uint8Array
|
||||
: never;
|
||||
|
||||
export interface BaseProtoFieldType<T, O extends boolean, R extends O extends true ? false : boolean> {
|
||||
kind: 'scalar' | 'message';
|
||||
@@ -93,25 +93,25 @@ export function ProtoField (
|
||||
|
||||
export type ProtoFieldReturnType<T, E extends boolean> =
|
||||
NonNullable<T> extends ScalarProtoFieldType<infer S, infer _O, infer _R>
|
||||
? ScalarTypeToTsType<S>
|
||||
: T extends NonNullable<MessageProtoFieldType<infer S, infer _O, infer _R>>
|
||||
? NonNullable<NapProtoStructType<ReturnType<S>, E>>
|
||||
: never;
|
||||
? ScalarTypeToTsType<S>
|
||||
: T extends NonNullable<MessageProtoFieldType<infer S, infer _O, infer _R>>
|
||||
? NonNullable<NapProtoStructType<ReturnType<S>, E>>
|
||||
: never;
|
||||
|
||||
export type RequiredFieldsBaseType<T, E extends boolean> = {
|
||||
[K in keyof T as T[K] extends { optional: true; } ? never : LowerCamelCase<K & string>]: T[K] extends {
|
||||
repeat: true;
|
||||
}
|
||||
? ProtoFieldReturnType<T[K], E>[]
|
||||
: ProtoFieldReturnType<T[K], E>;
|
||||
? ProtoFieldReturnType<T[K], E>[]
|
||||
: ProtoFieldReturnType<T[K], E>;
|
||||
};
|
||||
|
||||
export type OptionalFieldsBaseType<T, E extends boolean> = {
|
||||
[K in keyof T as T[K] extends { optional: true; } ? LowerCamelCase<K & string> : never]?: T[K] extends {
|
||||
repeat: true;
|
||||
}
|
||||
? ProtoFieldReturnType<T[K], E>[]
|
||||
: ProtoFieldReturnType<T[K], E>;
|
||||
? ProtoFieldReturnType<T[K], E>[]
|
||||
: ProtoFieldReturnType<T[K], E>;
|
||||
};
|
||||
|
||||
export type RequiredFieldsType<T, E extends boolean> = E extends true
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"target": "ESNext",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Node",
|
||||
"moduleResolution": "bundler",
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"strict": true,
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"compilerOptions": {
|
||||
"target": "ES2021",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "Node",
|
||||
"moduleResolution": "bundler",
|
||||
"lib": [
|
||||
"ES2021"
|
||||
],
|
||||
@@ -34,7 +34,6 @@
|
||||
"experimentalDecorators": true,
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"resolveJsonModule": true,
|
||||
"baseUrl": ".",
|
||||
"skipLibCheck": true,
|
||||
"skipDefaultLibCheck": true
|
||||
},
|
||||
|
||||
@@ -4,10 +4,9 @@
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"noEmit": true,
|
||||
"baseUrl": ".",
|
||||
"paths": {
|
||||
"@/*": [
|
||||
"../*/"
|
||||
"../../packages/*"
|
||||
]
|
||||
}
|
||||
},
|
||||
|
||||
@@ -483,17 +483,27 @@ async function handleLoginInner (context: { isLogined: boolean; }, logger: LogWr
|
||||
} else {
|
||||
logger.log('没有 -q 指令指定快速登录,将使用二维码登录方式');
|
||||
if (historyLoginList.length > 0) {
|
||||
logger.log(`可用于快速登录的 QQ:\n${historyLoginList
|
||||
logger.log(`可用于快速登录 of QQ:\n${historyLoginList
|
||||
.map((u, index) => `${index + 1}. ${u.uin} ${u.nickName}`)
|
||||
.join('\n')
|
||||
}`);
|
||||
}
|
||||
loginService.getQRCodePicture();
|
||||
let hasAttemptedFallback = false;
|
||||
try {
|
||||
// 检查是否配置了自动登录账号,并尝试 WebUi 快速/密码回退登录。
|
||||
// 这可以避免在已经有自动登录配置的情况下过早输出二维码。
|
||||
const quickLoginList = WebUiDataRuntime.getQQQuickLoginList() || [];
|
||||
const hasAutoLogin = process.env['NAPCAT_QUICK_ACCOUNT'] || (quickLoginList.length > 0); // 假如有历史登录列表
|
||||
if (hasAutoLogin || process.env['NAPCAT_QUICK_PASSWORD'] || process.env['NAPCAT_QUICK_PASSWORD_MD5']) {
|
||||
hasAttemptedFallback = true;
|
||||
}
|
||||
await WebUiDataRuntime.runWebUiConfigQuickFunction();
|
||||
} catch (error) {
|
||||
logger.logError('WebUi 快速登录失败 执行失败', error);
|
||||
}
|
||||
if (!hasAttemptedFallback && !context.isLogined) {
|
||||
loginService.getQRCodePicture();
|
||||
}
|
||||
}
|
||||
|
||||
loginService.getLoginList().then((res) => {
|
||||
@@ -581,7 +591,7 @@ export async function NCoreInitShell () {
|
||||
console.log('NapCat Shell App Loading...');
|
||||
const pathWrapper = new NapCatPathWrapper();
|
||||
const logger = new LogWrapper(pathWrapper.logsPath);
|
||||
if (process.env['NAPCAT_WORKER_PROCESS'] !== '1' && process.env['NAPCAT_DISABLE_MULTI_PROCESS'] !== '1') {
|
||||
if (process.env['NAPCAT_WORKER_PROCESS'] !== '1' && process.env['NAPCAT_DISABLE_MULTI_PROCESS'] !== '1' && process.env['NAPCAT_DISABLE_MULTIPROCESSING'] !== '1') {
|
||||
logger.setFileLogEnabled(false);
|
||||
}
|
||||
handleUncaughtExceptions(logger);
|
||||
@@ -784,6 +794,7 @@ export class NapCatShell {
|
||||
|
||||
// 监听下线通知并同步到 WebUI
|
||||
this.core.event.on('KickedOffLine', (tips: string) => {
|
||||
WebUiDataRuntime.setQQLoginStatus(false);
|
||||
WebUiDataRuntime.setQQLoginError(tips);
|
||||
});
|
||||
// 使用 NapCatAdapterManager 统一管理协议适配器
|
||||
|
||||
Loaded 100 of 135 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user