( target: any, mention?: boolean, throwErrorIfFailed?: boolean, )
| 25 | } |
| 26 | |
| 27 | async function formatEntity( |
| 28 | target: any, |
| 29 | mention?: boolean, |
| 30 | throwErrorIfFailed?: boolean, |
| 31 | ) { |
| 32 | const client = await getGlobalClient(); |
| 33 | if (!client) throw new Error("Telegram 客户端未初始化"); |
| 34 | if (!target) throw new Error("无效的目标"); |
| 35 | let id: any; |
| 36 | let entity: any; |
| 37 | try { |
| 38 | entity = target?.className |
| 39 | ? target |
| 40 | : ((await client?.getEntity(target)) as any); |
| 41 | if (!entity) throw new Error("无法获取 entity"); |
| 42 | id = entity.id; |
| 43 | if (!id) throw new Error("无法获取 entity id"); |
| 44 | } catch (e: any) { |
| 45 | console.error(e); |
| 46 | if (throwErrorIfFailed) |
| 47 | throw new Error( |
| 48 | `无法获取 ${target} 的 entity: ${e?.message || "未知错误"}`, |
| 49 | ); |
| 50 | } |
| 51 | const displayParts: string[] = []; |
| 52 | |
| 53 | if (entity?.title) displayParts.push(htmlEscape(entity.title)); |
| 54 | if (entity?.firstName) displayParts.push(htmlEscape(entity.firstName)); |
| 55 | if (entity?.lastName) displayParts.push(htmlEscape(entity.lastName)); |
| 56 | if (entity?.username) |
| 57 | displayParts.push( |
| 58 | mention |
| 59 | ? htmlEscape(`@${entity.username}`) |
| 60 | : `<code>@${htmlEscape(entity.username)}</code>`, |
| 61 | ); |
| 62 | |
| 63 | if (id) { |
| 64 | displayParts.push( |
| 65 | entity instanceof Api.User |
| 66 | ? `<a href="tg://user?id=${id}">${id}</a>` |
| 67 | : `<a href="https://t.me/c/${id}">${id}</a>`, |
| 68 | ); |
| 69 | } else if (!target?.className) { |
| 70 | displayParts.push(`<code>${htmlEscape(String(target))}</code>`); |
| 71 | } |
| 72 | |
| 73 | return { |
| 74 | id, |
| 75 | entity, |
| 76 | display: displayParts.join(" ").trim(), |
| 77 | }; |
| 78 | } |
| 79 | function htmlEscape(text: string): string { |
| 80 | return String(text) |
| 81 | .replace(/&/g, "&") |
no test coverage detected