Skip to content

Instantly share code, notes, and snippets.

@Sentinel-7
Last active March 24, 2023 14:41
Show Gist options
  • Save Sentinel-7/3e3c5d069c4c5d230253db007aede40d to your computer and use it in GitHub Desktop.
Save Sentinel-7/3e3c5d069c4c5d230253db007aede40d to your computer and use it in GitHub Desktop.
отправляем сообщение в телеграм из EasyComm
<?php
switch($modx->event->name){
// событие на OnEcMessageSave
case 'OnEcMessageSave':
if($object){
$data = $object->toArray();
$time = time();
$newMessage = 5;
$createdon = strtotime($object->get("createdon")) + $newMessage;
if ($createdon > $time) {
// если сообщение новое то дальше отправляем в телеграм
$token = "6054983020:AAF9LDucQ292KuJe4FCZ3weqp5vxEiYxOxY";
$chat_id = "-10016097409";
// Массив допустимых значений типа файла.
$types = array('image/gif', 'image/png', 'image/jpeg', 'application/pdf');
// Максимальный размер файла в килобайтах
// 1048576; // 1 МБ
$size = 1073741824; // 1 ГБ
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$fileSendStatus = '';
$textSendStatus = '';
$msgs = [];
// Проверяем не пусты ли поля с именем и телефоном
if (!empty($_POST['user_name']) && !empty($_POST['user_email'])) {
// Если не пустые, то валидируем эти поля и сохраняем и добавляем в тело сообщения. Минимально для теста так:
$txt = "";
if (isset($_POST['user_name']) && !empty($_POST['user_name'])) {
$txt .= "Страница: " . "Отзывы" . "%0A";
}
// Имя
if (isset($_POST['user_name']) && !empty($_POST['user_name'])) {
$txt .= "Имя: " . strip_tags(trim(urlencode($_POST['user_name']))) . "%0A";
}
// Номер телефона
if (isset($_POST['user_email']) && !empty($_POST['user_email'])) {
$txt .= "Телефон: " . strip_tags(trim(urlencode($_POST['user_email']))) . "%0A";
}
// Не забываем про тему сообщения
if (isset($_POST['text']) && !empty($_POST['text'])) {
$txt .= "Отзыв: " . strip_tags(urlencode($_POST['text']));
}
$textSendStatus = @file_get_contents('https://api.telegram.org/bot'. $token .'/sendMessage?chat_id=' . $chat_id . '&parse_mode=html&text=' . $txt);
if( isset(json_decode($textSendStatus)->{'ok'}) && json_decode($textSendStatus)->{'ok'} ) {
if (!empty($_FILES['files']['tmp_name'])) {
$urlFile = "https://api.telegram.org/bot" . $token . "/sendMediaGroup";
// Путь загрузки файлов
$path = $_SERVER['DOCUMENT_ROOT'] . '/telegramform/tmp/';
// Загрузка файла и вывод сообщения
$mediaData = [];
$postContent = [
'chat_id' => CHATID,
];
for ($ct = 0; $ct < count($_FILES['files']['tmp_name']); $ct++) {
if ($_FILES['files']['name'][$ct] && @copy($_FILES['files']['tmp_name'][$ct], $path . $_FILES['files']['name'][$ct])) {
if ($_FILES['files']['size'][$ct] < $size && in_array($_FILES['files']['type'][$ct], $types)) {
$filePath = $path . $_FILES['files']['name'][$ct];
$postContent[$_FILES['files']['name'][$ct]] = new CURLFile(realpath($filePath));
$mediaData[] = ['type' => 'document', 'media' => 'attach://'. $_FILES['files']['name'][$ct]];
}
}
}
$postContent['media'] = json_encode($mediaData);
$curl = curl_init();
curl_setopt($curl, CURLOPT_HTTPHEADER, ["Content-Type:multipart/form-data"]);
curl_setopt($curl, CURLOPT_URL, $urlFile);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $postContent);
$fileSendStatus = curl_exec($curl);
curl_close($curl);
$files = glob($path.'*');
foreach($files as $file){
if(is_file($file))
unlink($file);
}
}
echo json_encode('SUCCESS');
} else {
echo json_encode('ERROR');
//
// echo json_decode($textSendStatus);
}
} else {
echo json_encode('NOTVALID');
}
} else {
header("Location: /");
}
//
}
}
break;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment