我有一个用 php 编写的电报机器人,当机器人收到 $text 时,它会执行几次转换。
现在我正在尝试通过实体捕获嵌入的网址并在文本中返回清晰的网址。但是,当文本包含表情符号或特殊字符时,实体的长度和偏移量是错误的。我在here读到,问题是 telegram 和 php 由于不同的字符集而执行不同的计数。
所以我尝试过这段代码,但没有运气,有时它可以工作(但可能是随意的),其他时候它会获取比预期更早或更晚的文本。
$admin = ''; // Your user id goes here
$update = file_get_contents('php://input');
$update = json_decode($update, TRUE);
if (!empty($update['message']))
{
$message = $update['message'];
if(!empty($message["text"])){$text = $message['text'];}
if (!empty($message["entities"])) {
foreach ($message["entities"] as $entity) {
if (!empty($entity["type"]) && $entity["type"] === "text_link") {
$url = $entity["url"];
}
}
}
$links = array();
if (!empty($message["entities"])) {
foreach ($message["entities"] as $entity) {
if ($entity["type"] === "text_link") {
$urls[] = $entity["url"];
if (preg_match("/(https?:\/\/(?:www\.)?(?:amazon\.[a-z\.]+|amzn\.to+|amzn\.eu)\/[^\s]+)/i", $entity["url"], $matches)) {
$links[] = array(
"url" => $entity["url"],
"offset" => $entity["offset"],
"length" => $entity["length"]
);
}
}
}
}
$text = htmlspecialchars($text, ENT_QUOTES);
if (!empty($links)) {
foreach ($links as $link) {
$url = $link["url"];
$offset = $link["offset"];
$length = $link["length"];
// Estrai il testo originale dal testo completo utilizzando offset e length
$originalText = mb_substr($text, $offset, $length);
// Replace the original text with the Amazon link
$text = str_replace($originalText, $url, $text);
}
}
inviaMessaggio($admin, $text, null, "true");
function inviaMessaggio($chat_id, $text, $tastiera, $anteprima = "true")
{
$args = [];
$args['chat_id'] = $chat_id;
$args['text'] = $text;
$args['parse_mode'] = "HTML";
$args['disable_web_page_preview'] = $anteprima;
$rm = null;
if (!empty($tastiera))
{
$rm = json_encode(['inline_keyboard' => $tastiera]);
}
$args['reply_markup'] = $rm;
//return curlRequest($GLOBALS['website'].'/sendMessage', $args);
// Invia il messaggio
$response = curlRequest($GLOBALS['website'].'/sendMessage', $args);
// Estrai l'ID del messaggio dal JSON di risposta
$messageData = json_decode($response, true);
if (isset($messageData['result'])) {
$messageId = $messageData['result']['message_id'];
// Restituisci l'ID del messaggio
return ['response' => $response, 'message_id' => $messageId];
}
}
this 类来解码电报实体并使用 PHP 将它们转换为电报格式文本。您可以使用此类来转换文本并使用正则表达式从 HTML 标记中提取链接。