feat: |Telegram Bot| add new command to clean invalid jwts (#543)

This commit is contained in:
Dream Hunter
2025-01-05 01:52:07 +08:00
committed by GitHub
parent 934e58e23b
commit 479322c430
3 changed files with 32 additions and 2 deletions

View File

@@ -42,9 +42,13 @@ export const tgUserNewAddress = async (
export const jwtListToAddressData = async (
c: Context<HonoCustomType>, jwtList: string[]
): Promise<{ addressList: string[], addressIdMap: Record<string, number> }> => {
): Promise<{
addressList: string[], addressIdMap: Record<string, number>,
invalidJwtList: string[]
}> => {
const addressList = [] as string[];
const addressIdMap = {} as Record<string, number>;
const invalidJwtList = [] as string[];
for (const jwt of jwtList) {
try {
const { address, address_id } = await Jwt.verify(jwt, c.env.JWT_SECRET, "HS256");
@@ -52,10 +56,11 @@ export const jwtListToAddressData = async (
addressIdMap[address as string] = address_id as number;
} catch (e) {
addressList.push("无效凭证");
invalidJwtList.push(jwt);
console.log(`获取地址列表失败: ${(e as Error).message}`);
}
}
return { addressList, addressIdMap };
return { addressList, addressIdMap, invalidJwtList };
}
export const bindTelegramAddress = async (

View File

@@ -41,6 +41,10 @@ const COMMANDS = [
command: "mails",
description: "查看邮件, 请输入 /mails <邮箱地址>, 不输入地址默认查看第一个地址"
},
{
command: "cleaninvalidadress",
description: "清理无效地址, 请输入 /cleaninvalidadress"
},
]
export function newTelegramBot(c: Context<HonoCustomType>, token: string): Telegraf {
@@ -180,6 +184,26 @@ export function newTelegramBot(c: Context<HonoCustomType>, token: string): Teleg
}
});
bot.command("cleaninvalidadress", async (ctx: TgContext) => {
const userId = ctx?.message?.from?.id;
if (!userId) {
return await ctx.reply("无法获取用户信息");
}
try {
const jwtList = await c.env.KV.get<string[]>(`${CONSTANTS.TG_KV_PREFIX}:${userId}`, 'json') || [];
const { invalidJwtList } = await jwtListToAddressData(c, jwtList);
const newJwtList = jwtList.filter(jwt => !invalidJwtList.includes(jwt));
await c.env.KV.put(`${CONSTANTS.TG_KV_PREFIX}:${userId}`, JSON.stringify(newJwtList));
const { addressList } = await jwtListToAddressData(c, newJwtList);
return await ctx.reply(`清理无效地址成功:\n\n`
+ `当前地址列表:\n\n`
+ addressList.map(a => `地址: ${a}`).join("\n")
);
} catch (e) {
return await ctx.reply(`清理无效地址失败: ${(e as Error).message}`);
}
});
const queryMail = async (ctx: TgContext, queryAddress: string, mailIndex: number, edit: boolean) => {
const userId = ctx?.message?.from?.id || ctx.callbackQuery?.message?.chat?.id;
if (!userId) {