Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
"@grammyjs/parse-mode": "^1.11.1",
"@grammyjs/runner": "^2.0.3",
"@influxdata/influxdb-client": "^1.35.0",
"@polinetwork/backend": "^0.15.17",
"@polinetwork/backend": "^0.15.18",
"@socket.io/devalue-parser": "^0.1.0",
"@t3-oss/env-core": "^0.13.4",
"@trpc/client": "^11.5.1",
Expand Down
10 changes: 5 additions & 5 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ bot.use(new AutoModerationStack())
bot.use(new GroupSpecificActions())
bot.use(Moderation)
bot.use(new MentionListener())
bot.use(new MessageLink({ chatIds: [POLIADMINS] }))

bot.on("message", async (ctx, next) => {
const { username, id } = ctx.message.from
Expand All @@ -93,7 +94,6 @@ bot.on("message", async (ctx, next) => {
await next()
})

bot.on("message", new MessageLink({ chatIds: [POLIADMINS] }))
bot.on("message", MessageUserStorage.getInstance())
bot.on("message", checkUsername)
// bot.on("message", async (ctx, next) => { console.log(ctx.message); return await next() })
Expand Down
1 change: 1 addition & 0 deletions src/lib/group-management/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ function stripChatInfo(chat: ChatFullInfo) {
is_forum: chat.is_forum,
type: chat.type,
invite_link: chat.invite_link,
username: chat.username,
}
}

Expand Down
126 changes: 71 additions & 55 deletions src/middlewares/message-link.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,37 @@
import { api } from "@/backend"
import { logger } from "@/logger"
import { TrackedMiddleware } from "@/modules/telemetry"
import { padChatId } from "@/utils/chat"
import { padChatId, stripChatId } from "@/utils/chat"
import { fmt, fmtChat, fmtUser } from "@/utils/format"
import { getText } from "@/utils/messages"
import type { Context } from "@/utils/types"
import { MessageUserStorage } from "./message-user-storage"

// --- Configuration ---
const LINK_REGEX = /https?:\/\/t\.me\/c\/(-?\d+)\/(\d+)(?:\/(\d+))?/gi // Regex with global and case-insensitive flags
const LINK_REGEX = /https?:\/\/t\.me\/(?:c\/(-?\d+)|([\w\d]+))\/(\d+)(?:\/(\d+))?/i // Regex with global and case-insensitive flags
const CHAR_LIMIT = 400 // How many initial rows of text to include

export async function parseTelegramMessageLink(link: string): Promise<{
chatId: number
messageId: number
} | null> {
const match = link.match(LINK_REGEX)
if (!match) return null

const chatHandle = match[2]
const chatId = chatHandle
? await api.tg.groups.getByTag
.query({ tag: chatHandle })
.then((r) => stripChatId(r?.telegramId) ?? null)

Check failure on line 26 in src/middlewares/message-link.ts

View workflow job for this annotation

GitHub Actions / Typecheck and Lint

Argument of type 'number | undefined' is not assignable to parameter of type 'number'.
.catch(() => null)
: parseInt(match[1], 10)
const messageId = match[4] ? parseInt(match[4], 10) : parseInt(match[3], 10)

if (chatId === null) return null
if (Number.isNaN(chatId) || Number.isNaN(messageId)) return null

return { chatId, messageId }
}

type Config = {
chatIds: number[]
textRowsLimit?: number
Expand All @@ -24,69 +45,64 @@

this.composer
.filter((ctx) => !!ctx.chatId && config.chatIds.includes(ctx.chatId))
.on(["message:text", "message:caption"])
.filter(
(ctx) => getText(ctx.message).text.match(LINK_REGEX) !== null,
async (ctx, next) => {
logger.debug("[message-link] found a link to parse")

const messageText = getText(ctx.message).text

const matches = messageText.matchAll(LINK_REGEX)
const processedLinks: { chatId: number; messageId: number }[] = [] // Track processed links to avoid duplicates

for (const match of matches) {
// Ensure we have capture groups
if (!match[1] || !match[2]) {
logger.warn(`[message-link] Regex matched but missing capture groups: ${match.join(" - ")}`)
continue
}

const chatId = Number(match[1])
const messageId = match[3] ? Number(match[3]) : Number(match[2])

// Skip if we've already processed this link in this message (e.g., multiple occurrences)
if (processedLinks.some((link) => link.chatId === chatId && link.messageId === messageId)) {
continue
}
logger.info(
{ chatId, messageId, reporter: { username: ctx.from.username, id: ctx.from.id } },
"[message-link] link parsed and sending response"
)
processedLinks.push({ chatId, messageId })

const { message, inviteLink } = await makeResponse(ctx, chatId, messageId, ctx.from)

const inlineKeyboard = new InlineKeyboard()
if (inviteLink) {
inlineKeyboard.url("Join Group", inviteLink)
}

await ctx.reply(message, {
reply_markup: inlineKeyboard,
link_preview_options: { is_disabled: true }, // Prevent previewing the invite link in the reply itself
message_thread_id: ctx.chat.is_forum ? ctx.message.message_thread_id : undefined,
})
await ctx.deleteMessage()
.on(["message:entities:url", "message:entities:text_link"])
.use(async (ctx, next) => {
logger.debug("[message-link] found a link to parse")

const links = ctx
.entities("text_link")
.map((e) => e.url)
.concat(ctx.entities("url").map((e) => e.text))

const processedLinks: { chatId: number; messageId: number }[] = [] // Track processed links to avoid duplicates
for (const link of links) {
const parsed = await parseTelegramMessageLink(link)
if (!parsed) continue
logger.debug({ parsed }, `[message-link] parsed link with regex`)
const { chatId, messageId } = parsed

// Skip if we've already processed this link in this message (e.g., multiple occurrences)
if (processedLinks.some((link) => link.chatId === chatId && link.messageId === messageId)) {
continue
}
logger.info(
{ chatId, messageId, reporter: { username: ctx.from.username, id: ctx.from.id } },
"[message-link] link parsed and sending response"
)
processedLinks.push({ chatId, messageId })

const { message, inviteLink } = await makeResponse(ctx, link, chatId, messageId, ctx.from)

const inlineKeyboard = new InlineKeyboard()
if (inviteLink) {
inlineKeyboard.url("Join Group", inviteLink)
}

return next()
await ctx.reply(message, {
reply_markup: inlineKeyboard,
link_preview_options: { is_disabled: true }, // Prevent previewing the invite link in the reply itself
message_thread_id: ctx.chat.is_forum ? ctx.message.message_thread_id : undefined,
})
await ctx.deleteMessage()
}
)
return next()
})
}
}

type Response = {
message: string
inviteLink?: string
}
async function makeResponse(ctx: Context, chatId: number, messageId: number, reporter: User): Promise<Response> {
async function makeResponse(
ctx: Context,
link: string,
chatId: number,
messageId: number,
reporter: User
): Promise<Response> {
const headerRes = fmt(
({ b, n }) => [
b`Message link reported`,
n`${b`Reporter:`} ${fmtUser(reporter)}`,
n`${b`Link:`} https://t.me/c/${chatId}/${messageId}`,
],
({ b, n }) => [b`🚩 Message link reported`, n`${b`Reporter:`} ${fmtUser(reporter)}`, n`${b`Link:`} ${link}`],
{ sep: "\n" }
)

Expand Down
Loading