[GH-ISSUE #6274] [Bug]: Telegram bot silently drops replies over 4096 chars when text has no \r\n\r\n separators (400: message is too long) #4255

Closed
opened 2026-10-31 20:38:20 +07:00 by bsakaguchi · 2 comments
Owner

Originally created by @Artepin on GitHub (Aug 20, 2026).
Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/6274

Describe the bug

Bot buttons that reply with client-specific content (e.g. "individual
subscription links") can silently stop responding — no error visible in
Telegram, the button just appears dead.

Server log at the time of the click:

WARNING - Error sending telegram message: telego: sendMessage: api: 400
"Bad Request: message is too long"

How to reproduce the problem

  1. In Subscription settings, ensure a client has enough individual
    subscription links (or a few sufficiently long ones — e.g. VLESS/Reality
    links with ECH/post-quantum ML-KEM768 params, which routinely run
    800–1900+ characters each) that the batch sent by "individual
    subscription links" exceeds Telegram's 4096-char limit. In practice this
    is close to unconditional at the default batch size (see root cause
    below): with the fixed overhead of the header/markup, the per-link
    budget is well under the length of a minimal vless:// link with just a
    UUID.
  2. In the Telegram bot, open that client and press "Individual links"
    (client_individual_links / admin_client_individual_links).
  3. Observe: no reply arrives in the chat.

Expected behavior

The bot should page the reply into multiple messages, as SendMsgToTgbot's
paging logic is apparently intended to do for any oversized reply.

Actual behavior

The message is sent once, whole, and rejected by the Telegram Bot API with
400: message is too long. The rejection is only logged server-side
(logger.Warning) — from the Telegram side, the button just does nothing.

Relevant logs

WARNING - Error sending telegram message: telego: sendMessage: api: 400 "Bad Request: message is too long"

3x-ui version

3.6.0

Xray-core version

26.7.28

How did you install 3x-ui?

install.sh script

Operating system

Ubuntu 24.04

Which parts of the panel are affected?

Telegram bot

Is the panel behind a reverse proxy or CDN?

No — direct access

Before submitting

  • I searched existing issues and this bug has not been reported.
  • I am running the latest released version of 3x-ui (or have verified the bug still exists on it).
  • This bug report is written in English.
  • I have redacted any sensitive data (tokens, real domains, client UUIDs).
Originally created by @Artepin on GitHub (Aug 20, 2026). Original GitHub issue: https://github.com/MHSanaei/3x-ui/issues/6274 ### Describe the bug Bot buttons that reply with client-specific content (e.g. "individual subscription links") can silently stop responding — no error visible in Telegram, the button just appears dead. Server log at the time of the click: ``` WARNING - Error sending telegram message: telego: sendMessage: api: 400 "Bad Request: message is too long" ``` ### How to reproduce the problem 1. In Subscription settings, ensure a client has enough individual subscription links (or a few sufficiently long ones — e.g. VLESS/Reality links with ECH/post-quantum ML-KEM768 params, which routinely run 800–1900+ characters each) that the batch sent by "individual subscription links" exceeds Telegram's 4096-char limit. In practice this is close to unconditional at the default batch size (see root cause below): with the fixed overhead of the header/markup, the per-link budget is well under the length of a minimal `vless://` link with just a UUID. 2. In the Telegram bot, open that client and press "Individual links" (`client_individual_links` / `admin_client_individual_links`). 3. Observe: no reply arrives in the chat. ### Expected behavior The bot should page the reply into multiple messages, as `SendMsgToTgbot`'s paging logic is apparently intended to do for any oversized reply. ### Actual behavior The message is sent once, whole, and rejected by the Telegram Bot API with `400: message is too long`. The rejection is only logged server-side (`logger.Warning`) — from the Telegram side, the button just does nothing. ### Relevant logs ```shell WARNING - Error sending telegram message: telego: sendMessage: api: 400 "Bad Request: message is too long" ``` ### 3x-ui version 3.6.0 ### Xray-core version 26.7.28 ### How did you install 3x-ui? install.sh script ### Operating system Ubuntu 24.04 ### Which parts of the panel are affected? Telegram bot ### Is the panel behind a reverse proxy or CDN? No — direct access ### Before submitting - [x] I searched [existing issues](../issues?q=is%3Aissue) and this bug has not been reported. - [x] I am running the latest released version of 3x-ui (or have verified the bug still exists on it). - [x] This bug report is written in English. - [x] I have redacted any sensitive data (tokens, real domains, client UUIDs).
Author
Owner

@github-actions[bot] commented on GitHub (Aug 20, 2026):

Confirmed — both halves of your analysis hold against the current default branch (19e71d9a), and the fixed-count batching is worse than "a handful of long links": with maxPerMessage = 50 the message exceeds Telegram's 4096 limit for essentially any realistic link length, not just Reality/ECH ones.

The pager's contract. SendMsgToTgbot pages on a \r\n\r\n boundary only:

// internal/web/service/tgbot/tgbot_send.go:91-96
var allMessages []string
limit := 2000

// paging message if it is big
if len(msg) > limit {
	messages := strings.Split(msg, "\r\n\r\n")

That separator is a real convention elsewhere in the package, which is why the pager works for other long replies. getInboundUsages ends each inbound block with info.WriteString("\r\n") (internal/web/service/tgbot/tgbot_inbound.go:42) on top of a template that already ends in one — "expire": "📅 Expire Date: {{ .Time }}\r\n" (internal/web/translation/en-US.json:1987) — producing the \r\n\r\n the split needs.

Why this path never pages. sendClientIndividualLinks emits single-\r\n separators, and blank lines are stripped beforehand at internal/web/service/tgbot/tgbot_client.go:304-309, so no \r\n\r\n can occur:

// internal/web/service/tgbot/tgbot_client.go:316-329
const maxPerMessage = 50
for i := 0; i < len(cleaned); i += maxPerMessage {
	j := min(i+maxPerMessage, len(cleaned))
	chunk := cleaned[i:j]
	var msg strings.Builder
	msg.WriteString(t.I18nBot("subscription.individualLinks"))
	msg.WriteString(":\r\n")
	for _, link := range chunk {
		// wrap each link in <code>
		msg.WriteString("<code>")
		msg.WriteString(link)
		msg.WriteString("</code>\r\n")
	}
	t.SendMsgToTgbot(chatId, msg.String())
}

strings.Split then returns a one-element slice, the first loop iteration takes the len(allMessages) == 0 branch at tgbot_send.go:100-102 and appends the whole oversized string, and it goes out as one sendMessage call — exactly the 400 in your log.

Sizing, re-derived from the literals above. Each entry adds 15 bytes of markup (<code> = 6, </code>\r\n = 9); the header is "Individual links" (internal/web/translation/en-US.json:90) plus ":\r\n" = 19 bytes in en-US. At 50 links the fixed overhead is 769 bytes, leaving an average budget of ~66 bytes per link before 4096 is crossed — below the length of a minimal vless:// link with a UUID alone. So a client with 50 links overflows unconditionally. Using your figures, 800-char links cross at 6 links and 1900-char links at 3. Note the panel's own cap is limit := 2000 (tgbot_send.go:92), so these messages were meant to be paged well before Telegram ever sees them.

A second, latent case in the same loop. Even when \r\n\r\n separators are present, a single segment longer than limit is appended whole and never split:

// internal/web/service/tgbot/tgbot_send.go:100-105
if (len(allMessages) == 0) || (len(allMessages[lastIndex])+len(message) > limit) {
	allMessages = append(allMessages, message)
	lastIndex++
} else {
	allMessages[lastIndex] += "\r\n\r\n" + message
}

One caveat on the fallback you describe: ParseMode: "HTML" is set at tgbot_send.go:117, so a hard character cut that lands inside <code>…</code> turns the 400 into can't parse entities rather than fixing it. Any hard splitter needs to be tag-aware, or the split has to happen at the call site where the entry boundaries are still known.

Verdict: Confirmed bug
Severity: High
Confidence: High
Root cause: SendMsgToTgbot (internal/web/service/tgbot/tgbot_send.go:96-106) pages only on a \r\n\r\n boundary and never hard-splits, so a message with no such boundary — or a single boundary-delimited segment over limit — is sent whole. Triggered by sendClientIndividualLinks (internal/web/service/tgbot/tgbot_client.go:316-330), which batches by a fixed count of 50 and separates entries with a single \r\n. The count-based batching arrived with ed96fa09 ("tgbot: subscription,qrcode, link", 2025-09-14); the \r\n\r\n-only pager predates it (ceee1e42, 2024-01-01). Both files moved to their current paths in 41645255 (#5167) without behaviour change.
Already fixed: Still present on the default branch at 19e71d9a; git log -- internal/web/service/tgbot/tgbot_send.go internal/web/service/tgbot/tgbot_client.go shows no change to either since v3.6.0.
Duplicate of: None. No other open or closed issue matches on gh search issues --repo MHSanaei/3x-ui "message is too long" or --search "telegram message long" --state all.
Evidence: tgbot_send.go:92 limit := 2000; tgbot_send.go:96 messages := strings.Split(msg, "\r\n\r\n"); tgbot_send.go:100-102 appends an oversized segment unsplit; tgbot_send.go:117 ParseMode: "HTML"; tgbot_client.go:304-309 strips blank lines so no \r\n\r\n can form; tgbot_client.go:316 const maxPerMessage = 50; tgbot_client.go:322/:327 the single-\r\n separators; tgbot_inbound.go:42 + en-US.json:1987 show the \r\n\r\n convention the pager relies on. No test in internal/web/service/tgbot/*_test.go references SendMsgToTgbot or the paging, so nothing pins the current behaviour.
Not determined: Your Environment section reads "Same as above" with nothing above it, so I do not have your 3x-ui version — it does not change the verdict, since the defect is present at the tip. Whether Telegram's 4096 cap is applied before or after HTML entity parsing would only shift the exact overflow threshold, not whether it is crossed; sending one 50-link message would settle it.

Suggested fix: The smallest change that removes the root cause is at the call site — accumulate by byte length in sendClientIndividualLinks and flush the builder before it crosses the pager's limit, instead of counting to 50. A generic hard-split fallback in SendMsgToTgbot would additionally cover the oversized-segment case at tgbot_send.go:100-102, but it has to preserve <code> tag boundaries under ParseMode: "HTML".

@MHSanaei

This reply was generated automatically; a maintainer may follow up.

<!-- gh-comment-id:5355875064 --> @github-actions[bot] commented on GitHub (Aug 20, 2026): Confirmed — both halves of your analysis hold against the current default branch (`19e71d9a`), and the fixed-count batching is worse than "a handful of long links": with `maxPerMessage = 50` the message exceeds Telegram's 4096 limit for essentially any realistic link length, not just Reality/ECH ones. **The pager's contract.** `SendMsgToTgbot` pages on a `\r\n\r\n` boundary only: ```go // internal/web/service/tgbot/tgbot_send.go:91-96 var allMessages []string limit := 2000 // paging message if it is big if len(msg) > limit { messages := strings.Split(msg, "\r\n\r\n") ``` That separator is a real convention elsewhere in the package, which is why the pager works for other long replies. `getInboundUsages` ends each inbound block with `info.WriteString("\r\n")` (`internal/web/service/tgbot/tgbot_inbound.go:42`) on top of a template that already ends in one — `"expire": "📅 Expire Date: {{ .Time }}\r\n"` (`internal/web/translation/en-US.json:1987`) — producing the `\r\n\r\n` the split needs. **Why this path never pages.** `sendClientIndividualLinks` emits single-`\r\n` separators, and blank lines are stripped beforehand at `internal/web/service/tgbot/tgbot_client.go:304-309`, so no `\r\n\r\n` can occur: ```go // internal/web/service/tgbot/tgbot_client.go:316-329 const maxPerMessage = 50 for i := 0; i < len(cleaned); i += maxPerMessage { j := min(i+maxPerMessage, len(cleaned)) chunk := cleaned[i:j] var msg strings.Builder msg.WriteString(t.I18nBot("subscription.individualLinks")) msg.WriteString(":\r\n") for _, link := range chunk { // wrap each link in <code> msg.WriteString("<code>") msg.WriteString(link) msg.WriteString("</code>\r\n") } t.SendMsgToTgbot(chatId, msg.String()) } ``` `strings.Split` then returns a one-element slice, the first loop iteration takes the `len(allMessages) == 0` branch at `tgbot_send.go:100-102` and appends the whole oversized string, and it goes out as one `sendMessage` call — exactly the 400 in your log. **Sizing, re-derived from the literals above.** Each entry adds 15 bytes of markup (`<code>` = 6, `</code>\r\n` = 9); the header is `"Individual links"` (`internal/web/translation/en-US.json:90`) plus `":\r\n"` = 19 bytes in en-US. At 50 links the fixed overhead is 769 bytes, leaving an average budget of ~66 bytes per link before 4096 is crossed — below the length of a minimal `vless://` link with a UUID alone. So a client with 50 links overflows unconditionally. Using your figures, 800-char links cross at 6 links and 1900-char links at 3. Note the panel's own cap is `limit := 2000` (`tgbot_send.go:92`), so these messages were meant to be paged well before Telegram ever sees them. **A second, latent case in the same loop.** Even when `\r\n\r\n` separators *are* present, a single segment longer than `limit` is appended whole and never split: ```go // internal/web/service/tgbot/tgbot_send.go:100-105 if (len(allMessages) == 0) || (len(allMessages[lastIndex])+len(message) > limit) { allMessages = append(allMessages, message) lastIndex++ } else { allMessages[lastIndex] += "\r\n\r\n" + message } ``` One caveat on the fallback you describe: `ParseMode: "HTML"` is set at `tgbot_send.go:117`, so a hard character cut that lands inside `<code>…</code>` turns the 400 into `can't parse entities` rather than fixing it. Any hard splitter needs to be tag-aware, or the split has to happen at the call site where the entry boundaries are still known. Verdict: Confirmed bug Severity: High Confidence: High Root cause: `SendMsgToTgbot` (`internal/web/service/tgbot/tgbot_send.go:96-106`) pages only on a `\r\n\r\n` boundary and never hard-splits, so a message with no such boundary — or a single boundary-delimited segment over `limit` — is sent whole. Triggered by `sendClientIndividualLinks` (`internal/web/service/tgbot/tgbot_client.go:316-330`), which batches by a fixed count of 50 and separates entries with a single `\r\n`. The count-based batching arrived with `ed96fa09` ("tgbot: subscription,qrcode, link", 2025-09-14); the `\r\n\r\n`-only pager predates it (`ceee1e42`, 2024-01-01). Both files moved to their current paths in `41645255` (#5167) without behaviour change. Already fixed: Still present on the default branch at `19e71d9a`; `git log -- internal/web/service/tgbot/tgbot_send.go internal/web/service/tgbot/tgbot_client.go` shows no change to either since v3.6.0. Duplicate of: None. No other open or closed issue matches on `gh search issues --repo MHSanaei/3x-ui "message is too long"` or `--search "telegram message long" --state all`. Evidence: `tgbot_send.go:92` `limit := 2000`; `tgbot_send.go:96` `messages := strings.Split(msg, "\r\n\r\n")`; `tgbot_send.go:100-102` appends an oversized segment unsplit; `tgbot_send.go:117` `ParseMode: "HTML"`; `tgbot_client.go:304-309` strips blank lines so no `\r\n\r\n` can form; `tgbot_client.go:316` `const maxPerMessage = 50`; `tgbot_client.go:322`/`:327` the single-`\r\n` separators; `tgbot_inbound.go:42` + `en-US.json:1987` show the `\r\n\r\n` convention the pager relies on. No test in `internal/web/service/tgbot/*_test.go` references `SendMsgToTgbot` or the paging, so nothing pins the current behaviour. Not determined: Your Environment section reads "Same as above" with nothing above it, so I do not have your 3x-ui version — it does not change the verdict, since the defect is present at the tip. Whether Telegram's 4096 cap is applied before or after HTML entity parsing would only shift the exact overflow threshold, not whether it is crossed; sending one 50-link message would settle it. Suggested fix: The smallest change that removes the root cause is at the call site — accumulate by byte length in `sendClientIndividualLinks` and flush the builder before it crosses the pager's `limit`, instead of counting to 50. A generic hard-split fallback in `SendMsgToTgbot` would additionally cover the oversized-segment case at `tgbot_send.go:100-102`, but it has to preserve `<code>` tag boundaries under `ParseMode: "HTML"`. @MHSanaei *This reply was generated automatically; a maintainer may follow up.* <!-- claude-issue:analyst -->
Author
Owner

@github-actions[bot] commented on GitHub (Aug 20, 2026):

Confirmed on the current default branch (58669f61), and the fix belongs in the pager, not at the call site: SendMsgToTgbot splits only on \r\n\r\n and never enforces its own limit, so any message without that boundary — or any single boundary-delimited block over the limit — is handed to Telegram whole.

Root cause

internal/web/service/tgbot/tgbot_send.go:91-112:

var allMessages []string
limit := 2000

// paging message if it is big
if len(msg) > limit {
	messages := strings.Split(msg, "\r\n\r\n")
	lastIndex := -1

	for _, message := range messages {
		if (len(allMessages) == 0) || (len(allMessages[lastIndex])+len(message) > limit) {
			allMessages = append(allMessages, message)
			lastIndex++
		} else {
			allMessages[lastIndex] += "\r\n\r\n" + message
		}
	}
	...

strings.Split on a string with no \r\n\r\n returns a one-element slice; the single loop iteration takes the len(allMessages) == 0 branch and appends the oversized string unchanged. limit is never enforced on a segment — it only decides whether two segments may be merged.

Most senders happen to satisfy the separator by accident, which is why this looks like it works elsewhere: tgbot.messages.refreshedOn ends in \r\n\r\n (internal/web/translation/en-US.json:2003), and getInboundUsages adds its own info.WriteString("\r\n") on top of a template that already ends in one (internal/web/service/tgbot/tgbot_inbound.go:42 + en-US.json:1987).

sendClientIndividualLinks is the one path that produces none. Blank lines are stripped at internal/web/service/tgbot/tgbot_client.go:302-309, and the batch is then assembled with single-\r\n separators (tgbot_client.go:315-330):

const maxPerMessage = 50
for i := 0; i < len(cleaned); i += maxPerMessage {
	...
	for _, link := range chunk {
		msg.WriteString("<code>")
		msg.WriteString(link)
		msg.WriteString("</code>\r\n")
	}
	t.SendMsgToTgbot(chatId, msg.String())
}

So \r\n\r\n cannot occur, and the whole batch goes out as one sendMessage — the 400 in your log.

On sizing: the Bot API counts the 4096 cap after entity parsing, so the <code> markup itself does not count, but the links do. With the header plus one newline per entry, 50 links overflow once the average link exceeds ~81 characters — below a minimal vless:// link carrying just a UUID, host and port. The reporter's figures follow: 800-char links cross at 6 entries, 1900-char links at 3. The panel's own limit := 2000 should have paged all of these long before Telegram ever saw them.

Fix

Replace tgbot_send.go:91-112 with a single call, and add the two helpers alongside it. Splitting on \r\n rather than at an arbitrary offset matters: ParseMode: "HTML" is set at tgbot_send.go:117, so a cut landing inside <code>…</code> would trade the 400 for can't parse entities.

	allMessages := pageMessage(msg, tgPageLimit)
// Telegram caps sendMessage at 4096 characters after entity parsing; 2000 bytes
// of raw text stays inside that even when the text carries no HTML markup.
const tgPageLimit = 2000

// pageMessage breaks msg into pages of at most limit bytes, preferring the
// \r\n\r\n block boundary the bot's templates emit and falling back to \r\n.
func pageMessage(msg string, limit int) []string {
	if len(msg) <= limit {
		return []string{msg}
	}
	var pages []string
	for _, block := range strings.Split(msg, "\r\n\r\n") {
		for _, page := range splitOnLines(block, limit) {
			last := len(pages) - 1
			if last >= 0 && len(pages[last])+len("\r\n\r\n")+len(page) <= limit {
				pages[last] += "\r\n\r\n" + page
				continue
			}
			pages = append(pages, page)
		}
	}
	if len(pages) > 0 && strings.TrimSpace(pages[len(pages)-1]) == "" {
		pages = pages[:len(pages)-1]
	}
	return pages
}

// splitOnLines pages a block that carries no \r\n\r\n boundary. It never cuts
// inside a line, so a <code>…</code> wrapper stays balanced under ParseMode HTML.
func splitOnLines(block string, limit int) []string {
	if len(block) <= limit {
		return []string{block}
	}
	lines := strings.Split(block, "\r\n")
	pages := []string{lines[0]}
	for _, line := range lines[1:] {
		last := len(pages) - 1
		if len(pages[last])+len("\r\n")+len(line) > limit {
			pages = append(pages, line)
			continue
		}
		pages[last] += "\r\n" + line
	}
	return pages
}

Notes on the shape:

  • Two pages produced from the same block can never be re-merged by the outer loop — splitOnLines only starts a new page when the previous one could not take the next line — so a \r\n separator is never silently promoted to \r\n\r\n. Content is preserved exactly.
  • Behaviour for len(msg) <= limit is unchanged: one page, verbatim.
  • The +len("\r\n\r\n") term also fixes the small existing miscount at the old line 100, which merged two segments without counting the separator it then inserted.
  • Because splitOnLines runs over every block, this also covers the second, latent case: a \r\n\r\n-delimited segment that is on its own longer than limit.
  • Nothing changes at tgbot_client.go:316. maxPerMessage = 50 becomes harmless — each batch is now paged into ~2000-byte messages. Dropping the count-based chunking entirely would work too, but it is not needed for the fix.

Residual, deliberately not handled: a single line longer than the limit still goes out whole. That is a link over ~4096 characters, which Telegram cannot accept in one message under any splitting scheme, and half a link split across two messages is not usable anyway.

Test

internal/web/service/tgbot/tgbot_send_test.go — the helpers are pure, so this drives the real paging code:

package tgbot

import (
	"strings"
	"testing"
)

func TestPageMessageSplitsLinkListWithoutBlankLines(t *testing.T) {
	var b strings.Builder
	b.WriteString("Individual links:\r\n")
	for range 50 {
		b.WriteString("<code>vless://" + strings.Repeat("a", 300) + "</code>\r\n")
	}
	msg := b.String()

	pages := pageMessage(msg, tgPageLimit)
	if len(pages) < 2 {
		t.Fatalf("a %d-byte link list was not paged: got %d page(s)", len(msg), len(pages))
	}

	links := 0
	for i, page := range pages {
		if len(page) > tgPageLimit {
			t.Errorf("page %d is %d bytes, over the %d limit", i, len(page), tgPageLimit)
		}
		open, closed := strings.Count(page, "<code>"), strings.Count(page, "</code>")
		if open != closed {
			t.Errorf("page %d cuts a <code> tag: %d open, %d close", i, open, closed)
		}
		links += open
	}
	if links != 50 {
		t.Errorf("pages carry %d links, want 50", links)
	}
}

func TestPageMessageSplitsOversizedBlock(t *testing.T) {
	msg := "intro\r\n\r\nhead\r\n" + strings.Repeat("line of client usage text\r\n", 200)

	for i, page := range pageMessage(msg, tgPageLimit) {
		if len(page) > tgPageLimit {
			t.Fatalf("page %d is %d bytes, over the %d limit", i, len(page), tgPageLimit)
		}
	}
}

To watch it go red rather than merely fail to build, temporarily replace splitOnLines's body with return []string{block} — that is exactly the old behaviour, and both tests fail on the length assertion.

Adjacent, out of scope

The retry loop at tgbot_send.go:124-151 only retries on connection / timeout / closed substrings, and telego.NewBot is built without a rate-limiter option (internal/web/service/tgbot/tgbot.go:426-433). A 50-link batch now becomes ~9 messages at 100 ms spacing, so a 429: Too Many Requests would be logged and dropped the same way the 400 is today. That is a separate pre-existing gap — worth a look, but not part of this fix.


I only investigate and reply here; I cannot open a PR or push a branch, so the blocks above are meant to be applied by hand.

🤖 Generated with Claude Code

<!-- gh-comment-id:5356732072 --> @github-actions[bot] commented on GitHub (Aug 20, 2026): Confirmed on the current default branch (`58669f61`), and the fix belongs in the pager, not at the call site: `SendMsgToTgbot` splits only on `\r\n\r\n` and never enforces its own limit, so any message without that boundary — or any single boundary-delimited block over the limit — is handed to Telegram whole. ## Root cause `internal/web/service/tgbot/tgbot_send.go:91-112`: ```go var allMessages []string limit := 2000 // paging message if it is big if len(msg) > limit { messages := strings.Split(msg, "\r\n\r\n") lastIndex := -1 for _, message := range messages { if (len(allMessages) == 0) || (len(allMessages[lastIndex])+len(message) > limit) { allMessages = append(allMessages, message) lastIndex++ } else { allMessages[lastIndex] += "\r\n\r\n" + message } } ... ``` `strings.Split` on a string with no `\r\n\r\n` returns a one-element slice; the single loop iteration takes the `len(allMessages) == 0` branch and appends the oversized string unchanged. `limit` is never enforced on a segment — it only decides whether two segments may be merged. Most senders happen to satisfy the separator by accident, which is why this looks like it works elsewhere: `tgbot.messages.refreshedOn` ends in `\r\n\r\n` (`internal/web/translation/en-US.json:2003`), and `getInboundUsages` adds its own `info.WriteString("\r\n")` on top of a template that already ends in one (`internal/web/service/tgbot/tgbot_inbound.go:42` + `en-US.json:1987`). `sendClientIndividualLinks` is the one path that produces none. Blank lines are stripped at `internal/web/service/tgbot/tgbot_client.go:302-309`, and the batch is then assembled with single-`\r\n` separators (`tgbot_client.go:315-330`): ```go const maxPerMessage = 50 for i := 0; i < len(cleaned); i += maxPerMessage { ... for _, link := range chunk { msg.WriteString("<code>") msg.WriteString(link) msg.WriteString("</code>\r\n") } t.SendMsgToTgbot(chatId, msg.String()) } ``` So `\r\n\r\n` cannot occur, and the whole batch goes out as one `sendMessage` — the 400 in your log. On sizing: the Bot API counts the 4096 cap *after* entity parsing, so the `<code>` markup itself does not count, but the links do. With the header plus one newline per entry, 50 links overflow once the average link exceeds ~81 characters — below a minimal `vless://` link carrying just a UUID, host and port. The reporter's figures follow: 800-char links cross at 6 entries, 1900-char links at 3. The panel's own `limit := 2000` should have paged all of these long before Telegram ever saw them. ## Fix Replace `tgbot_send.go:91-112` with a single call, and add the two helpers alongside it. Splitting on `\r\n` rather than at an arbitrary offset matters: `ParseMode: "HTML"` is set at `tgbot_send.go:117`, so a cut landing inside `<code>…</code>` would trade the 400 for `can't parse entities`. ```go allMessages := pageMessage(msg, tgPageLimit) ``` ```go // Telegram caps sendMessage at 4096 characters after entity parsing; 2000 bytes // of raw text stays inside that even when the text carries no HTML markup. const tgPageLimit = 2000 // pageMessage breaks msg into pages of at most limit bytes, preferring the // \r\n\r\n block boundary the bot's templates emit and falling back to \r\n. func pageMessage(msg string, limit int) []string { if len(msg) <= limit { return []string{msg} } var pages []string for _, block := range strings.Split(msg, "\r\n\r\n") { for _, page := range splitOnLines(block, limit) { last := len(pages) - 1 if last >= 0 && len(pages[last])+len("\r\n\r\n")+len(page) <= limit { pages[last] += "\r\n\r\n" + page continue } pages = append(pages, page) } } if len(pages) > 0 && strings.TrimSpace(pages[len(pages)-1]) == "" { pages = pages[:len(pages)-1] } return pages } // splitOnLines pages a block that carries no \r\n\r\n boundary. It never cuts // inside a line, so a <code>…</code> wrapper stays balanced under ParseMode HTML. func splitOnLines(block string, limit int) []string { if len(block) <= limit { return []string{block} } lines := strings.Split(block, "\r\n") pages := []string{lines[0]} for _, line := range lines[1:] { last := len(pages) - 1 if len(pages[last])+len("\r\n")+len(line) > limit { pages = append(pages, line) continue } pages[last] += "\r\n" + line } return pages } ``` Notes on the shape: - Two pages produced from the *same* block can never be re-merged by the outer loop — `splitOnLines` only starts a new page when the previous one could not take the next line — so a `\r\n` separator is never silently promoted to `\r\n\r\n`. Content is preserved exactly. - Behaviour for `len(msg) <= limit` is unchanged: one page, verbatim. - The `+len("\r\n\r\n")` term also fixes the small existing miscount at the old line 100, which merged two segments without counting the separator it then inserted. - Because `splitOnLines` runs over *every* block, this also covers the second, latent case: a `\r\n\r\n`-delimited segment that is on its own longer than `limit`. - Nothing changes at `tgbot_client.go:316`. `maxPerMessage = 50` becomes harmless — each batch is now paged into ~2000-byte messages. Dropping the count-based chunking entirely would work too, but it is not needed for the fix. Residual, deliberately not handled: a single line longer than the limit still goes out whole. That is a link over ~4096 characters, which Telegram cannot accept in one message under any splitting scheme, and half a link split across two messages is not usable anyway. ## Test `internal/web/service/tgbot/tgbot_send_test.go` — the helpers are pure, so this drives the real paging code: ```go package tgbot import ( "strings" "testing" ) func TestPageMessageSplitsLinkListWithoutBlankLines(t *testing.T) { var b strings.Builder b.WriteString("Individual links:\r\n") for range 50 { b.WriteString("<code>vless://" + strings.Repeat("a", 300) + "</code>\r\n") } msg := b.String() pages := pageMessage(msg, tgPageLimit) if len(pages) < 2 { t.Fatalf("a %d-byte link list was not paged: got %d page(s)", len(msg), len(pages)) } links := 0 for i, page := range pages { if len(page) > tgPageLimit { t.Errorf("page %d is %d bytes, over the %d limit", i, len(page), tgPageLimit) } open, closed := strings.Count(page, "<code>"), strings.Count(page, "</code>") if open != closed { t.Errorf("page %d cuts a <code> tag: %d open, %d close", i, open, closed) } links += open } if links != 50 { t.Errorf("pages carry %d links, want 50", links) } } func TestPageMessageSplitsOversizedBlock(t *testing.T) { msg := "intro\r\n\r\nhead\r\n" + strings.Repeat("line of client usage text\r\n", 200) for i, page := range pageMessage(msg, tgPageLimit) { if len(page) > tgPageLimit { t.Fatalf("page %d is %d bytes, over the %d limit", i, len(page), tgPageLimit) } } } ``` To watch it go red rather than merely fail to build, temporarily replace `splitOnLines`'s body with `return []string{block}` — that is exactly the old behaviour, and both tests fail on the length assertion. ## Adjacent, out of scope The retry loop at `tgbot_send.go:124-151` only retries on `connection` / `timeout` / `closed` substrings, and `telego.NewBot` is built without a rate-limiter option (`internal/web/service/tgbot/tgbot.go:426-433`). A 50-link batch now becomes ~9 messages at 100 ms spacing, so a `429: Too Many Requests` would be logged and dropped the same way the 400 is today. That is a separate pre-existing gap — worth a look, but not part of this fix. --- I only investigate and reply here; I cannot open a PR or push a branch, so the blocks above are meant to be applied by hand. <sub>🤖 Generated with [Claude Code](https://claude.com/claude-code)</sub>
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
MHSanaei/3x-ui#4255
No description provided.