fix(formatter+telegram): drop tel: inline button, mark all 4xx as permanent

Pilot on washanyanya.ru exposed that Telegram Bot API rejects tel:
URLs in inline_keyboard with HTTP 400 "Wrong port number specified
in the URL". Queue was stuck on 5 items retrying the same failure
4 times each.

- MessageFormatter: always returns reply_markup = null. The phone
  number is already rendered in the '📱 ...' line, and mobile
  Telegram clients linkify it automatically.
- TelegramClient::is_permanent: treat all 4xx except 429 as permanent
  client-side errors, so future payload-shape bugs surface in the
  dashboard widget immediately instead of burning five retry cycles.
- MessageFormatterTest updated: the old test asserting tel: in
  reply_markup is replaced with one asserting reply_markup is null
  and the phone still appears in the text body.
- Spec §9 + §19 updated, §19's open question closed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
Vladimir Bryzgalov
2026-04-17 23:55:06 +05:00
parent 1f89052f72
commit 2de8f0be57
5 changed files with 38 additions and 45 deletions
@@ -978,8 +978,12 @@ final class MessageFormatterTest extends TestCase
self::assertStringContainsString('Akismet', $result['text']); self::assertStringContainsString('Akismet', $result['text']);
} }
public function test_tel_button_present_when_phone_valid(): void public function test_reply_markup_is_null_because_tg_rejects_tel_urls(): void
{ {
// Telegram Bot API rejects tel: URLs in inline_keyboard with
// HTTP 400 "Wrong port number specified in the URL". We no longer
// emit any inline button; the phone number is rendered in the
// message body instead and mobile TG clients auto-linkify it.
$fields = ['your-tel' => '+79031234567', 'your-name' => 'Анна']; $fields = ['your-tel' => '+79031234567', 'your-name' => 'Анна'];
$classification = Classifier::classify($fields, ['reason' => 'Akismet']); $classification = Classifier::classify($fields, ['reason' => 'Akismet']);
$r = MessageFormatter::build([ $r = MessageFormatter::build([
@@ -989,9 +993,9 @@ final class MessageFormatterTest extends TestCase
'ip' => '', 'user_agent' => '', 'is_retro' => false, 'ip' => '', 'user_agent' => '', 'is_retro' => false,
]); ]);
self::assertNotNull($r['reply_markup']); self::assertNull($r['reply_markup']);
$json = json_encode($r['reply_markup']); // Phone must still be present in the text, formatted as Russian pretty.
self::assertStringContainsString('tel:+79031234567', $json); self::assertStringContainsString('+7 (903) 123-45-67', $r['text']);
} }
public function test_no_tel_button_when_no_phone(): void public function test_no_tel_button_when_no_phone(): void
@@ -1174,16 +1178,11 @@ final class MessageFormatter
$text = implode("\n", $lines); $text = implode("\n", $lines);
$text = self::truncate($text); $text = self::truncate($text);
$markup = null; // Telegram Bot API rejects tel: URLs in inline_keyboard with HTTP 400
if ($phone !== null) { // ("Wrong port number specified"), so no inline button is emitted.
$markup = [ // The phone number is already shown in the message body (line '📱 ...')
'inline_keyboard' => [[ // and mobile Telegram clients make such numbers tappable automatically.
['text' => '📞 Позвонить: ' . $phone['pretty'], 'url' => 'tel:' . $phone['e164']], return ['text' => $text, 'reply_markup' => null];
]],
];
}
return ['text' => $text, 'reply_markup' => $markup];
} }
private static function pick(array $fields, array $keys): string private static function pick(array $fields, array $keys): string
@@ -1766,13 +1765,11 @@ final class TelegramClient
private static function is_permanent(int $code, string $desc): bool private static function is_permanent(int $code, string $desc): bool
{ {
if ($code === 401 || $code === 403) return true; // 4xx (except 429 rate-limit) are client-side errors: bad request,
if ($code === 400) { // invalid chat, revoked token, malformed payload — retrying will not
$d = strtolower($desc); // help. Mark as permanent so the queue gives up immediately and the
if (strpos($d, 'chat not found') !== false) return true; // admin is notified via the dashboard widget.
if (strpos($d, 'bot was blocked') !== false) return true; if ($code >= 400 && $code < 500 && $code !== 429) return true;
if (strpos($d, 'user is deactivated') !== false) return true;
}
return false; return false;
} }
} }
@@ -249,8 +249,7 @@ apply_filters('cf7stg_classifier_thresholds', ['client' => 3, 'spam' => -2]);
``` ```
**Inline-клавиатура:** **Inline-клавиатура:**
- Если распарсился валидный RU-телефон — одна кнопка `"📞 Позвонить: {phone_formatted}"``url: "tel:{e164}"`. - `reply_markup = null` всегда. Telegram Bot API отклоняет `tel:` URLs в inline_keyboard с ошибкой HTTP 400 `Wrong port number specified in the URL`. Номер показывается в теле сообщения (строка `📱 ...`), мобильный TG-клиент автоматически делает его кликабельным.
- Без телефона — `reply_markup = null` (кнопок нет).
**Site title:** `Settings::get_site_title()` возвращает либо оверрайд из настроек, либо декодированный через `idn_to_utf8()` host из `home_url()`. Например, `xn--80aae0ca7d8bb.xn--p1ai``вашаняня.рф`. **Site title:** `Settings::get_site_title()` возвращает либо оверрайд из настроек, либо декодированный через `idn_to_utf8()` host из `home_url()`. Например, `xn--80aae0ca7d8bb.xn--p1ai``вашаняня.рф`.
@@ -397,6 +396,6 @@ $schedules['cf7stg_every_minute'] = ['interval' => 60, 'display' => 'Раз в
## 19. Открытые вопросы (решаем во время реализации) ## 19. Открытые вопросы (решаем во время реализации)
1. **`tel:`-ссылки в inline-кнопках Telegram.** Bot API документация разрешает только `http/https/tg`, но практика показывает, что `tel:` работает в клиентах. Проверить на первом пилотном сайте; если Telegram отклонит — fallback: показать номер текстом без кнопки, добавить префикс `📞 ` для ясности. 1. ~~**`tel:`-ссылки в inline-кнопках Telegram.**~~ **РЕШЕНО (2026-04-17 пилот).** Telegram Bot API отклонил `tel:` URLs (HTTP 400, `Wrong port number specified in the URL`). Inline-кнопки полностью убраны; номер показывается в теле сообщения, мобильные клиенты сами делают его кликабельным.
2. **Извлечение `flamingo_post_id`.** Flamingo не даёт прямой ссылки submission→post после сохранения. План: после сохранения Flamingo (`wpcf7_submission` priority 20) искать в `wp_posts` записи `post_type=flamingo_inbound`, sort by date DESC, limit 1, фильтр по содержимому `post_content` (сравнение с полями submission). Если совпадение ненадёжное — плагин всё равно работает (`flamingo_post_id = NULL`, dedup ретро-выгрузки пропускается для этой записи, но основной поток не зависит от наличия id). 2. **Извлечение `flamingo_post_id`.** Flamingo не даёт прямой ссылки submission→post после сохранения. План: после сохранения Flamingo (`wpcf7_submission` priority 20) искать в `wp_posts` записи `post_type=flamingo_inbound`, sort by date DESC, limit 1, фильтр по содержимому `post_content` (сравнение с полями submission). Если совпадение ненадёжное — плагин всё равно работает (`flamingo_post_id = NULL`, dedup ретро-выгрузки пропускается для этой записи, но основной поток не зависит от наличия id).
3. **Акцент HTML vs MarkdownV2.** Если в процессе пилота выяснится, что клиенты часто пишут символы, ломающие HTML даже после экранирования — рассмотреть переход на plain text (без форматирования, эмодзи — unicode-символы, не требуют разметки). 3. **Акцент HTML vs MarkdownV2.** Если в процессе пилота выяснится, что клиенты часто пишут символы, ломающие HTML даже после экранирования — рассмотреть переход на plain text (без форматирования, эмодзи — unicode-символы, не требуют разметки).
+5 -10
View File
@@ -71,16 +71,11 @@ final class MessageFormatter
$text = implode("\n", $lines); $text = implode("\n", $lines);
$text = self::truncate($text); $text = self::truncate($text);
$markup = null; // Telegram Bot API rejects tel: URLs in inline_keyboard with HTTP 400
if ($phone !== null) { // ("Wrong port number specified"), so no inline button is emitted.
$markup = [ // The phone number is already shown in the message body (line '📱 ...')
'inline_keyboard' => [[ // and mobile Telegram clients make such numbers tappable automatically.
['text' => '📞 Позвонить: ' . $phone['pretty'], 'url' => 'tel:' . $phone['e164']], return ['text' => $text, 'reply_markup' => null];
]],
];
}
return ['text' => $text, 'reply_markup' => $markup];
} }
private static function pick(array $fields, array $keys): string private static function pick(array $fields, array $keys): string
+5 -7
View File
@@ -64,13 +64,11 @@ final class TelegramClient
private static function is_permanent(int $code, string $desc): bool private static function is_permanent(int $code, string $desc): bool
{ {
if ($code === 401 || $code === 403) return true; // 4xx (except 429 rate-limit) are client-side errors: bad request,
if ($code === 400) { // invalid chat, revoked token, malformed payload — retrying will not
$d = strtolower($desc); // help. Mark as permanent so the queue gives up immediately and the
if (strpos($d, 'chat not found') !== false) return true; // admin is notified via the dashboard widget.
if (strpos($d, 'bot was blocked') !== false) return true; if ($code >= 400 && $code < 500 && $code !== 429) return true;
if (strpos($d, 'user is deactivated') !== false) return true;
}
return false; return false;
} }
} }
+8 -4
View File
@@ -42,8 +42,12 @@ final class MessageFormatterTest extends TestCase
self::assertStringContainsString('Akismet', $result['text']); self::assertStringContainsString('Akismet', $result['text']);
} }
public function test_tel_button_present_when_phone_valid(): void public function test_reply_markup_is_null_because_tg_rejects_tel_urls(): void
{ {
// Telegram Bot API rejects tel: URLs in inline_keyboard with
// HTTP 400 "Wrong port number specified in the URL". We no longer
// emit any inline button; the phone number is rendered in the
// message body instead and mobile TG clients auto-linkify it.
$fields = ['your-tel' => '+79031234567', 'your-name' => 'Анна']; $fields = ['your-tel' => '+79031234567', 'your-name' => 'Анна'];
$classification = Classifier::classify($fields, ['reason' => 'Akismet']); $classification = Classifier::classify($fields, ['reason' => 'Akismet']);
$r = MessageFormatter::build([ $r = MessageFormatter::build([
@@ -53,9 +57,9 @@ final class MessageFormatterTest extends TestCase
'ip' => '', 'user_agent' => '', 'is_retro' => false, 'ip' => '', 'user_agent' => '', 'is_retro' => false,
]); ]);
self::assertNotNull($r['reply_markup']); self::assertNull($r['reply_markup']);
$json = json_encode($r['reply_markup']); // Phone must still be present in the text, formatted as Russian pretty.
self::assertStringContainsString('tel:+79031234567', $json); self::assertStringContainsString('+7 (903) 123-45-67', $r['text']);
} }
public function test_no_tel_button_when_no_phone(): void public function test_no_tel_button_when_no_phone(): void