feat(telegram): render markdown and send author avatar photo

This commit is contained in:
RhenCloud 2026-08-03 06:42:29 +08:00
parent 568e206643
commit 50ae8c7607
No known key found for this signature in database
GPG key ID: A574A617378C4E0B
4 changed files with 175 additions and 32 deletions

View file

@ -1,8 +1,13 @@
import type { RouteTarget, Env, NeutralMessage } from "../../types";
import type { PlatformDriver, SendResult } from "../types";
import { sendMessage } from "./rest";
import { sendMessage, sendPhoto } from "./rest";
import { renderNeutralMessage } from "./render";
function smallAvatar(url: string): string {
const sep = url.includes("?") ? "&" : "?";
return `${url}${sep}s=64`;
}
export class TelegramDriver implements PlatformDriver {
readonly id = "telegram";
@ -12,6 +17,11 @@ export class TelegramDriver implements PlatformDriver {
return { ok: false, error: "target.chatId is required", errorCode: "NO_TARGET" };
}
const token = env.TELEGRAM_TOKEN ?? "";
return sendMessage(token, chatId, renderNeutralMessage(message), target.topicId);
const text = renderNeutralMessage(message);
const avatar = message.author?.iconUrl;
if (avatar) {
return sendPhoto(token, chatId, smallAvatar(avatar), text, target.topicId);
}
return sendMessage(token, chatId, text, target.topicId);
}
}

View file

@ -8,35 +8,50 @@ function esc(s: string): string {
.replace(/"/g, """);
}
function inlineUrl(url?: string, text?: string): string {
const label = esc(text ?? url ?? "");
if (!url) return label;
return `<a href="${esc(url)}">${label}</a>`;
function mdToHtml(s: string): string {
let out = esc(s);
out = out.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_m, label, url) => `<a href="${esc(url)}">${label}</a>`);
out = out.replace(/\*\*([^*]+)\*\*/g, "<b>$1</b>");
out = out.replace(/`([^`]+)`/g, "<code>$1</code>");
out = out.replace(/(^|[^*])\*([^*]+)\*/g, "$1<i>$2</i>");
out = out.replace(/~~([^~]+)~~/g, "<s>$1</s>");
return out;
}
function formatTimestamp(ts?: string): string {
if (!ts) return "";
const d = new Date(ts);
if (Number.isNaN(d.getTime())) return ts;
const pad = (n: number): string => String(n).padStart(2, "0");
return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(d.getUTCDate())} ${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())} UTC`;
}
export function renderNeutralMessage(message: NeutralMessage): string {
const parts: string[] = [];
const title = inlineUrl(message.url, message.title);
const title = message.url
? `<a href="${esc(message.url)}">${mdToHtml(message.title)}</a>`
: mdToHtml(message.title);
parts.push(`<b>${title}</b>`);
if (message.author) {
const author = message.author.url
? `<a href="${esc(message.author.url)}">${esc(message.author.name)}</a>`
: esc(message.author.name);
const name = mdToHtml(message.author.name);
const author = message.author.url ? `<a href="${esc(message.author.url)}">${name}</a>` : name;
parts.push(`👤 ${author}`);
}
if (message.description) {
parts.push(esc(message.description));
parts.push(mdToHtml(message.description));
}
for (const field of message.fields ?? []) {
parts.push(`<b>${esc(field.name)}</b>: ${esc(field.value)}`);
parts.push(`<b>${mdToHtml(field.name)}</b>: ${mdToHtml(field.value)}`);
}
const meta: string[] = [];
if (message.footer) meta.push(esc(message.footer));
if (message.timestamp) meta.push(esc(message.timestamp));
const ts = formatTimestamp(message.timestamp);
if (ts) meta.push(ts);
if (meta.length > 0) {
parts.push(`<i>${meta.join(" · ")}</i>`);
}

View file

@ -9,27 +9,13 @@ interface TelegramResponse {
result?: { message_id?: number };
}
export async function sendMessage(
async function post(
token: string,
method: string,
body: Record<string, unknown>,
chatId: string,
text: string,
topicId?: string,
): Promise<SendResult> {
if (!token) {
return { ok: false, error: "TELEGRAM_TOKEN not configured", errorCode: "NO_TOKEN" };
}
const body: Record<string, unknown> = {
chat_id: chatId,
text,
parse_mode: "HTML",
disable_web_page_preview: true,
};
if (topicId) {
body.message_thread_id = Number(topicId);
}
const url = `${TELEGRAM_API}/bot${token}/sendMessage`;
const url = `${TELEGRAM_API}/bot${token}/${method}`;
let lastStatus = 0;
let lastError = "";
@ -95,3 +81,48 @@ export async function sendMessage(
attempts: 3,
};
}
export async function sendMessage(
token: string,
chatId: string,
text: string,
topicId?: string,
): Promise<SendResult> {
if (!token) {
return { ok: false, error: "TELEGRAM_TOKEN not configured", errorCode: "NO_TOKEN" };
}
const body: Record<string, unknown> = {
chat_id: chatId,
text,
parse_mode: "HTML",
disable_web_page_preview: true,
};
if (topicId) {
body.message_thread_id = Number(topicId);
}
return post(token, "sendMessage", body, chatId);
}
export async function sendPhoto(
token: string,
chatId: string,
photoUrl: string,
caption?: string,
topicId?: string,
): Promise<SendResult> {
if (!token) {
return { ok: false, error: "TELEGRAM_TOKEN not configured", errorCode: "NO_TOKEN" };
}
const body: Record<string, unknown> = {
chat_id: chatId,
photo: photoUrl,
parse_mode: "HTML",
};
if (caption) {
body.caption = caption;
}
if (topicId) {
body.message_thread_id = Number(topicId);
}
return post(token, "sendPhoto", body, chatId);
}