Skip to content

Instantly share code, notes, and snippets.

@mnixry
Last active July 19, 2021 10:35
Show Gist options
  • Save mnixry/457a99a2c9c1eef837ca99df587df2de to your computer and use it in GitHub Desktop.
Save mnixry/457a99a2c9c1eef837ca99df587df2de to your computer and use it in GitHub Desktop.
A Cloudflare worker to get QQ group or user avatar without site refer protection
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头像获取

一个可以获取QQ群头像和用户头像的Cloudflare Worker, 没有源站保护, 可用于前端

演示站点


请求方法

群头像

  • URL: /group/?id=<群号>

用户头像

  • URL: /user/?id=<群号>&size=<头像尺寸>
    • 头像尺寸单位为像素(px), 最大640
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment