一个可以获取QQ群头像和用户头像的Cloudflare Worker, 没有源站保护, 可用于前端
- URL:
/group/?id=<群号>
- URL:
/user/?id=<群号>&size=<头像尺寸>- 头像尺寸单位为像素(
px), 最大640
- 头像尺寸单位为像素(
| addEventListener("fetch", (event) => { | |
| event.respondWith( | |
| router(event.request).catch((err) => | |
| err instanceof HttpError | |
| ? err.toResponse() | |
| : new Response(err.stack, { status: 500 }) | |
| ) | |
| ); | |
| }); | |
| class HttpError extends Error { | |
| /** | |
| * @param {Number} status | |
| * @param {String} message | |
| */ | |
| constructor(status, message) { | |
| super(message); | |
| this.status = status; | |
| } | |
| toResponse() { | |
| return new Response( | |
| JSON.stringify({ | |
| status: this.status, | |
| message: this.message, | |
| stack: this.stack, | |
| }), | |
| { status: this.status, headers: { "Content-Type": "application/json" } } | |
| ); | |
| } | |
| } | |
| /** | |
| * @param {Request} request | |
| * @returns {Promise<Response>} | |
| */ | |
| async function router(request) { | |
| const url = new URL(request.url); | |
| switch (url.pathname) { | |
| case "/group/": | |
| return getGroupAvatar(url); | |
| case "/user/": | |
| return getUserAvatar(url); | |
| default: | |
| throw new HttpError(404, "Not Found"); | |
| } | |
| } | |
| /** | |
| * @param {URL} url | |
| * @returns {Promise<Response>} | |
| */ | |
| async function getGroupAvatar(url) { | |
| const id = +url.searchParams.get("id"); | |
| if (!id >= 1) { | |
| throw new HttpError(400, "Invalid Group ID"); | |
| } | |
| return fetch(`https://p.qlogo.cn/gh/${id}/${id}/0`); | |
| } | |
| /** | |
| * @param {URL} url | |
| * @returns {Promise<Response>} | |
| */ | |
| async function getUserAvatar(url) { | |
| const id = +url.searchParams.get("id"); | |
| const size = Math.min(+url.searchParams.get("size") || 640, 640); | |
| if (!id >= 1) { | |
| throw new HttpError(400, "Invalid User ID"); | |
| } | |
| if (size > 640) { | |
| throw new HttpError(400, "Invalid Image Size, maximum to 640"); | |
| } | |
| return fetch(`https://q1.qlogo.cn/g?b=qq&nk=${id}&s=${size}`); | |
| } |
一个可以获取QQ群头像和用户头像的Cloudflare Worker, 没有源站保护, 可用于前端
/group/?id=<群号>/user/?id=<群号>&size=<头像尺寸>
px), 最大640