С 9:00 до 21:00 Без выходных

system/library/notification/telegram_notification.php

Вот содержимое файла system/library/notification/telegram_notification.php:

<?php
// Telegram Notification Library for Task Manager - Handles sending notifications to users via Telegram

class TelegramNotification {

    private $bot_token;
    private $chat_id;
    private $message;
    private $api_url;

    // Constructor to initialize Telegram bot parameters
    public function __construct($bot_token, $chat_id, $message) {
        $this->bot_token = $bot_token;
        $this->chat_id = $chat_id;
        $this->message = $message;
        $this->api_url = "https://api.telegram.org/bot" . $this->bot_token . "/sendMessage";
    }

    // Method to send Telegram notification
    public function sendTelegramNotification() {
        // Prepare the data to send to Telegram API
        $data = array(
            'chat_id' => $this->chat_id,
            'text' => $this->message,
            'parse_mode' => 'HTML'
        );

        // Initialize cURL to send the notification
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->api_url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

        // Execute the cURL request and capture the response
        $response = curl_exec($ch);
        curl_close($ch);

        // Return the response from Telegram API
        return $response;
    }

    // Method to send task-related Telegram notifications
    public function sendTaskNotification($task_name, $chat_id) {
        $this->message = "You have a new task assigned to you: " . $task_name;
        $this->chat_id = $chat_id;

        return $this->sendTelegramNotification();
    }

    // Method to send task completion Telegram notifications
    public function sendTaskCompletionNotification($task_name, $chat_id) {
        $this->message = "The task " . $task_name . " has been completed successfully.";
        $this->chat_id = $chat_id;

        return $this->sendTelegramNotification();
    }

    // Method to send task reminder Telegram notifications
    public function sendTaskReminderNotification($task_name, $chat_id, $reminder_time) {
        $this->message = "Reminder: Task " . $task_name . " is due at " . $reminder_time . ".";
        $this->chat_id = $chat_id;

        return $this->sendTelegramNotification();
    }

    // Method to send task overdue Telegram notifications
    public function sendTaskOverdueNotification($task_name, $chat_id) {
        $this->message = "The task " . $task_name . " is overdue. Please take immediate action.";
        $this->chat_id = $chat_id;

        return $this->sendTelegramNotification();
    }

    // Method to send task status change Telegram notifications
    public function sendTaskStatusChangeNotification($task_name, $chat_id, $new_status) {
        $this->message = "The status of the task " . $task_name . " has changed to: " . $new_status;
        $this->chat_id = $chat_id;

        return $this->sendTelegramNotification();
    }

    // Method to handle Telegram Webhooks for task notifications
    public function handleWebhookNotification($task_name, $chat_id, $status) {
        $this->message = "Webhook Notification: The task " . $task_name . " status is now " . $status;
        $this->chat_id = $chat_id;

        return $this->sendTelegramNotification();
    }
}
?>

Объяснение кода:

  • Класс TelegramNotification:

    • Этот класс используется для отправки уведомлений в Telegram через API бота Telegram. Он позволяет отправлять сообщения пользователям на основе различных событий, таких как создание задачи, завершение задачи, напоминания и изменения статуса задач.

  • Конструктор:

    • Конструктор принимает параметры, такие как bot_token (токен Telegram-бота), chat_id (идентификатор чата получателя) и message (сообщение уведомления). Эти параметры используются для отправки сообщения через API Telegram.

  • Методы:

    • sendTelegramNotification(): Этот метод отправляет уведомление пользователю через Telegram API. Он использует cURL для отправки POST-запроса в Telegram с данными уведомления.

    • sendTaskNotification(): Отправляет уведомление о новой задаче.

    • sendTaskCompletionNotification(): Отправляет уведомление о завершении задачи.

    • sendTaskReminderNotification(): Отправляет уведомление с напоминанием о задаче.

    • sendTaskOverdueNotification(): Отправляет уведомление о просроченной задаче.

    • sendTaskStatusChangeNotification(): Отправляет уведомление об изменении статуса задачи.

    • handleWebhookNotification(): Этот метод обрабатывает уведомления через вебхуки, например, для получения обновлений статуса задачи через Telegram.

Зависимости:

  • Telegram Bot API: Требуется создать бота в Telegram через BotFather для получения bot_token.

  • cURL: Для выполнения HTTP запросов.

Примечания:

  • Убедитесь, что у вас есть доступ к Telegram Bot API и правильный bot_token.

  • Убедитесь, что ваш сервер поддерживает cURL, чтобы отправлять запросы в Telegram.

Этот класс будет использоваться для отправки уведомлений через Telegram для различных событий, связанных с задачами в вашем менеджере задач, таких как создание, завершение, напоминания, изменения статуса и т. д.