如何用PHP给Telegram Bot发消息?现有代码能否优化?
Telegram Bot 消息发送PHP代码的性能分析与优化方案
原代码性能分析
这段代码在单条消息发送场景下基本能满足需求,但存在不少可优化的点,覆盖性能、健壮性和代码规范层面:
- 循环中用
.拼接字符串:PHP里字符串是不可变类型,每次拼接都会生成新的字符串副本,数据量大时会明显拖慢速度 - 使用GET请求传递消息:当消息较长时容易触发URL长度限制,且安全性不如POST请求
- 缺少错误处理逻辑:CURL请求失败、JSON解码失败时,后续流程会直接报错崩溃
- 参数使用错误:
json_decode($result, JSON_PRETTY_PRINT)中JSON_PRETTY_PRINT是json_encode的参数,此处用错位置 - 输出逻辑问题:如果作为独立脚本运行,最后用
return $result不会输出任何内容,应该用echo
优化后的代码实现
<?php // 配置项抽离,方便后续维护 $config = [ 'chat_id' => '023752053', 'token' => '470129572:HFApoAHFVN37852983HDFON385cNOhvs' ]; // 校验输入合法性 if (empty($fd) || !is_string($fd)) { echo json_encode(['error' => 'Invalid input data']); exit; } // 解析输入JSON并校验 $payload = json_decode($fd, true); if (json_last_error() !== JSON_ERROR_NONE) { echo json_encode(['error' => 'Failed to decode JSON: ' . json_last_error_msg()]); exit; } // 用数组收集消息片段,避免多次字符串复制 $messageParts = []; foreach ($payload as $key => $value) { // 转义HTML特殊字符,避免格式错误或注入风险 $messageParts[] = sprintf('<b>%s</b>: %s', htmlspecialchars($key), htmlspecialchars($value)); } $message = implode("\n", $messageParts); $apiUrl = sprintf('https://api.telegram.org/bot%s/sendMessage', $config['token']); // 使用POST请求传递数据,适配长消息场景 $postData = [ 'text' => $message, 'chat_id' => $config['chat_id'], 'parse_mode' => 'HTML' ]; $ch = curl_init($apiUrl); curl_setopt_array($ch, [ CURLOPT_RETURNTRANSFER => true, CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query($postData), // 设置超时时间,避免请求挂起 CURLOPT_TIMEOUT => 10, CURLOPT_CONNECTTIMEOUT => 5 ]); $result = curl_exec($ch); // 处理CURL请求错误 if (curl_errno($ch)) { $errorMsg = curl_error($ch); curl_close($ch); echo json_encode(['error' => 'CURL request failed: ' . $errorMsg]); exit; } curl_close($ch); // 解析API返回结果并校验 $apiResponse = json_decode($result, true); if (json_last_error() !== JSON_ERROR_NONE) { echo json_encode(['error' => 'Failed to parse API response']); exit; } // 返回最终处理结果 if ($apiResponse['ok'] ?? false) { echo json_encode(['success' => true]); } else { echo json_encode(['error' => $apiResponse]); }
核心优化点说明
- 字符串拼接优化:用数组收集消息片段后通过
implode合并,避免多次字符串复制操作,性能提升明显 - 请求方式升级:改为POST请求,规避URL长度限制,同时更符合API常规使用规范
- 全链路错误处理:增加输入校验、JSON解码校验、CURL错误处理,让代码在异常场景下更健壮
- 安全防护:对消息内容做
htmlspecialchars转义,避免Telegram解析HTML时出错,同时防范注入风险 - 可维护性提升:抽离配置项、增加超时设置,后续修改和运维更便捷
内容的提问来源于stack exchange,提问作者ArtemSites
相关产品推荐
相关产品推荐

