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", '
', $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('<BR />', "\n", $translated);
// $translated = str_replace('
', "\n", $translated);
$forwardedFrom = $message->getForwardFrom();
if ($forwardedFrom) {
$translated = $forwardedFrom['first_name'] . ': ' . $translated;
}
return $this->replyToChat($translated, ['disable_notification' => true, 'parse_mode' => $htmlMode ? 'HTML' : null]);
}
}