First iteration

This commit is contained in:
2022-09-30 01:46:02 +00:00
parent b290f82dc5
commit e3cf8ddca4
7 changed files with 1021 additions and 0 deletions

View File

@@ -0,0 +1,105 @@
<?php
namespace Longman\TelegramBot\Commands\SystemCommands;
use Longman\TelegramBot\Commands\SystemCommand;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Request;
use DeepL\Translator;
use SteelyWing\Chinese\Chinese;
// 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;
private const ALLOWED_CHAT_ID = [
123, 456, 789
];
private const ZH_TO_EN = [
'兽设' => 'fursona',
'兽人' => 'furry character',
'兽控' => 'furry',
'毛毛' => 'fursuit',
'兽装' => 'fursuit',
'大佬' => 'da lao',
'丸吞' => 'vore',
'哦不' => 'oh no',
'哦哇塞' => 'o wa sai'
];
private const EN_TO_ZH = [
'fursona' => '兽设',
'furry character' => '兽人',
'furry' => '兽控',
'fursuit' => '兽装',
'sese' => '色色',
'sheshe' => '射射',
'wun tun' => '丸吞',
'vore' => '丸吞',
'money power' => '钞能力',
'oh no' => '哦不',
];
public function execute(): ServerResponse
{
$message = $this->getMessage();
$chat_id = $message->getChat()->getId();
if(!in_array($chat_id, self::ALLOWED_CHAT_ID)) {
return Request::sendMessage([
'chat_id' => $chat_id,
'text' => "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]*~i', $text, 0, PREG_SPLIT_NO_EMPTY));
if ($text_english_count >= ($text_chara_count / 2)) {
$sourceLang = 'en';
$targetLang = 'zh';
$glossary = self::EN_TO_ZH;
} else {
$sourceLang = 'zh';
$targetLang = 'en-US';
$glossary = self::ZH_TO_EN;
$text = (new Chinese())->to(Chinese::ZH_HANS, $text);
}
foreach ($glossary as $search => $replace) {
$text = str_replace($search, $replace, $text);
}
$this->translator = new Translator(getenv('DEEPL_API_KEY'));
try {
$translated = $this->translator->translateText($text, $sourceLang, $targetLang);
} catch (\Exception $e) {
return Request::sendMessage([
'chat_id' => $chat_id,
'text' => get_class($e) . ': ' . $e->getMessage(), // ?? var_export($e, true),
]);
}
$message_forwarded_from = $message->getForwardFrom()?->getFirstName();
if ($message_forwarded_from !== null) {
$translated = $message_forwarded_from . ': ' . $translated;
}
return Request::sendMessage([
'chat_id' => $chat_id,
'text' => $translated,
]);
//return Request::emptyResponse();
}
}