Files
2meet-data-optimizer/includes/notifications/class-tmdo-telegram-notifier.php
T
wpdev d36bb954d1 chore: initial snapshot of 2meet-data-optimizer v0.1.0
Baseline before backporting wp-data-optimizer v3.0.1-v3.4.6.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01TbG1keQQ7XBa7qMQY16KCY
2026-07-31 05:06:36 +08:00

96 lines
2.6 KiB
PHP

<?php
/**
* TMDO_Telegram_Notifier — Telegram bot channel (v2.5.0 M15).
*
* Settings: wpdo_telegram_enabled, wpdo_telegram_bot_token,
* wpdo_telegram_chat_id, wpdo_telegram_throttle_hours, wpdo_telegram_severity.
*
* Bot token is sensitive: stored as-is in wp_options for now (admin-only).
* Future hardening: integrate TMDO_Crypto encryption (note in v2.5+).
*
* @package WP_Data_Optimizer
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Telegram channel.
*/
class TMDO_Telegram_Notifier extends TMDO_Abstract_Notifier {
/**
* Channel identifier used as option key prefix.
*
* @return string
*/
public static function channel_id(): string {
return 'telegram';
}
/**
* Build Telegram-specific context (bot token + chat ID).
*
* @return array|null Null if token or chat ID is missing or invalid.
*/
public static function build_context(): ?array {
$token = class_exists( 'TMDO_Crypto' )
? TMDO_Crypto::get_option( 'wpdo_telegram_bot_token' )
: (string) get_option( 'wpdo_telegram_bot_token', '' );
$chat = (string) get_option( 'wpdo_telegram_chat_id', '' );
if ( '' === $token || '' === $chat ) {
return null;
}
// Bot tokens are formatted as 123456:ABC-DEF...; minimal validation.
if ( ! preg_match( '/^\d+:[A-Za-z0-9_\-]{20,}$/', $token ) ) {
return null;
}
return array(
'token' => $token,
'chat_id' => $chat,
);
}
/**
* Send alert via Telegram Bot API.
*
* @param string $subject Alert subject / title.
* @param string $body Alert body text.
* @param array $context Channel context (token, chat_id).
* @return bool True on HTTP 2xx response.
*/
public static function actually_send( string $subject, string $body, array $context ): bool {
$token = (string) ( $context['token'] ?? '' );
$chat = (string) ( $context['chat_id'] ?? '' );
if ( '' === $token || '' === $chat ) {
return false;
}
// Telegram MarkdownV2 has many escaped chars; use plain text mode for safety.
$text = "🚨 {$subject}\n\n{$body}";
// Telegram message limit = 4096 chars.
$text = substr( $text, 0, 4000 );
$url = sprintf( 'https://api.telegram.org/bot%s/sendMessage', rawurlencode( $token ) );
$resp = wp_remote_post(
$url,
array(
'headers' => array( 'Content-Type' => 'application/json' ),
'body' => wp_json_encode(
array(
'chat_id' => $chat,
'text' => $text,
)
),
'timeout' => 5,
'blocking' => true,
)
);
if ( is_wp_error( $resp ) ) {
return false;
}
$code = (int) wp_remote_retrieve_response_code( $resp );
return $code >= 200 && $code < 300;
}
}