Bot for notification (Laravel Telegram Bot API) - Gianguyen1234/app-doc GitHub Wiki

You want a Telegram bot for notifications in your Laravel app using the Telegram Bot API. Here’s how to do it step by step. 🚀


1️⃣ Create a Telegram Bot

  1. Open [@BotFather](https://t.me/BotFather) in Telegram.
  2. Send:
    /newbot
    
  3. Follow the prompts to create your bot.
  4. Copy the Bot Token (you’ll need it for Laravel).

2️⃣ Get Your Chat ID

To send notifications, you need your Telegram Chat ID.

  1. Open [@userinfobot](https://t.me/userinfobot).
  2. Send:
    /start
    
  3. It will show your Chat ID. Copy it!

3️⃣ Install Telegram SDK in Laravel

Run this in your Laravel project:

composer require telegram-bot/api

4️⃣ Create a Laravel Service to Send Messages

Run this command to create a new service class:

php artisan make:service TelegramService

Edit app/Services/TelegramService.php:

<?php

namespace App\Services;

use Telegram\Bot\Api;

class TelegramService
{
    protected $telegram;
    protected $chat_id;

    public function __construct()
    {
        $this->telegram = new Api(env('TELEGRAM_BOT_TOKEN'));
        $this->chat_id = env('TELEGRAM_CHAT_ID'); // Set this in .env
    }

    public function sendMessage($message)
    {
        return $this->telegram->sendMessage([
            'chat_id' => $this->chat_id,
            'text' => $message
        ]);
    }
}

5️⃣ Add Bot Credentials to .env

Edit your .env file:

TELEGRAM_BOT_TOKEN=your_bot_token_here
TELEGRAM_CHAT_ID=your_chat_id_here

6️⃣ Create a Laravel Notification Route

Edit routes/web.php:

use App\Services\TelegramService;

Route::get('/send-telegram-notification', function (TelegramService $telegram) {
    $telegram->sendMessage("🚀 This is a test notification from Laravel!");
    return "Notification sent!";
});

7️⃣ Test Your Bot! 🎯

Run your Laravel app and open this URL in your browser:

http://your-app-url/send-telegram-notification

If everything is set up correctly, you should get a message in your Telegram! 🎉


Now you can use TelegramService::sendMessage($text) anywhere in your Laravel app to send notifications. Want me to add more features like sending images, buttons, or handling user replies? 🤖