Files
tangmo_trans_bot/src/Commands/GenericmessageCommand.php

83 lines
3.0 KiB
PHP

<?php
namespace Longman\TelegramBot\Commands\SystemCommands;
use Longman\TelegramBot\Commands\SystemCommand;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Request;
use DeepL\Translator;
use DeepL\TranslateTextOptions;
use lucadevelop\TelegramEntitiesDecoder\EntityDecoder;
// This class name is magic
class GenericmessageCommand extends SystemCommand
{
/** @var string */
protected $name = 'genericmessage';
/** @var string */
protected $description = 'Handle generic message';
/** @var string */
protected $version = '1.0.0';
private Translator $translator;
public function execute(): ServerResponse
{
global $deepl_api_key, $deepl_glossary_id, $allowed_chat_ids;
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
if (!in_array($chat_id, $allowed_chat_ids)) {
return $this->replyToChat("Chat ID `$chat_id` not allowed");
}
$text = $message->getText(true) ?? $message->getCaption();
if (empty($text)) {
return Request::emptyResponse();
}
$text_chara_count = count(preg_split('//u', $text, -1, PREG_SPLIT_NO_EMPTY));
$text_english_count = count(preg_split('~[^a-z 0-9\'\",.]*~i', $text, 0, PREG_SPLIT_NO_EMPTY));
if ($text_english_count >= ($text_chara_count * 2 / 3)) {
$sourceLang = 'en';
$targetLang = 'zh-hans';
} else {
$sourceLang = 'zh';
$targetLang = 'en-US';
}
$htmlMode = $message->getEntities() && count($message->getEntities()) > 0;
$deeplOptions = [
TranslateTextOptions::FORMALITY => 'prefer_less',
TranslateTextOptions::MODEL_TYPE => 'prefer_quality_optimized',
TranslateTextOptions::SPLIT_SENTENCES => 'on',
];
if ($htmlMode) {
$deeplOptions[TranslateTextOptions::TAG_HANDLING] = 'html';
}
if (isset($deepl_glossary_id)) {
$deeplOptions[TranslateTextOptions::GLOSSARY] = $deepl_glossary_id;
}
$this->translator = new Translator($deepl_api_key);
try {
if ($htmlMode) {
$text = (new EntityDecoder('HTML'))->decode(json_decode($message->toJson()));
// $text = str_replace("\n", '<br />', $text);
}
$translated = $this->translator->translateText($text, $sourceLang, $targetLang, $deeplOptions);
$translated = $translated->text;
} catch (\Exception $e) {
return $this->replyToChat(get_class($e) . ': ' . $e->getMessage()); // ?? var_export($e, true)
}
$translated = str_replace('&lt;BR /&gt;', "\n", $translated);
// $translated = str_replace('<br />', "\n", $translated);
$forwardedFrom = $message->getForwardFrom();
if ($forwardedFrom) {
$translated = $forwardedFrom['first_name'] . ': ' . $translated;
}
return $this->replyToChat($translated, ['disable_notification' => true, 'parse_mode' => $htmlMode ? 'HTML' : null]);
}
}