jccp_a/laravel/app/Services/TomTool/Telegram/Sdk.php
hellcat ac91e1fbe4 1
2025-11-12 17:57:30 +08:00

135 lines
3.2 KiB
PHP
Executable File

<?php
declare(strict_types=1);
namespace App\Services\TomTool\Telegram;
use Telegram\Bot\Api;
use Telegram\Bot\Exceptions\TelegramSDKException;
use App\Services\TomTool\Flow;
class Sdk
{
public $sMsgFormat = [];
public $sMsgFormatType = 'none';
public $sBotToken = '';
public $iChatId = 0;
public $sMsg;
public $oApi;
private const ALLOWED_FORMATS = ['none', 'html', 'markdown', 'markdownV2'];
public static function start()
{
$oInstance = new self();
return $oInstance;
}
public function setBotToken($sBotToken)
{
$this->oApi = new Api($sBotToken);
$this->sBotToken = $sBotToken;
return $this;
}
public function setChatId($iChatId)
{
$this->iChatId = $iChatId;
return $this;
}
public function setMsgS($sMsg = '')
{
$this->sMsg = $sMsg;
return $this;
}
public function send()
{
$oFlow = Flow::start("tg_sdk_send");
$this->msgFormat();
try {
$r = $this->oApi->sendMessage($this->sMsgFormat);
if (!$r->isOk()) {
return $oFlow->fail();
}
} catch (TelegramSDKException $e) {
return $oFlow->fail(['error' => $e->getMessage()]);
}
return $oFlow->done();
}
public function getMsgFormat()
{
$this->msgFormat();
return $this->sMsgFormat;
}
public function msgFormat()
{
if (!in_array($this->sMsgFormatType, self::ALLOWED_FORMATS, true)) {
throw new \RuntimeException("不支持的格式类型: {$this->sMsgFormatType}");
}
$method = 'msgFormat_' . $this->sMsgFormatType;
$this->sMsgFormat = $this->$method();
return $this;
}
private function msgFormat_none()
{
return [
'chat_id' => $this->iChatId,
'text' => $this->sMsg,
'parse_mode' => '',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => null,
];
}
private function msgFormat_html()
{
return [
'chat_id' => $this->iChatId,
'text' => strip_tags($this->sMsg, [
'b', 'strong', 'i', 'em', 'u', 'ins', 's', 'strike', 'del', 'span', 'tg-spoiler', 'a', 'tg-emoji',
'code', 'pre',
]),
'parse_mode' => 'HTML',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => null,
];
}
private function msgFormat_markdown()
{
return [
'chat_id' => $this->iChatId,
'text' => $this->sMsg,
'parse_mode' => 'Markdown',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => null,
];
}
private function msgFormat_markdownV2()
{
return [
'chat_id' => $this->iChatId,
'text' => $this->sMsg,
'parse_mode' => 'MarkdownV2',
'disable_web_page_preview' => false,
'reply_to_message_id' => null,
'reply_markup' => null,
];
}
}