【技術分享】在 Laravel 中使用 Telegram bot API 製作免費通知功能

因應 LINE 在前陣子宣布,
LINE Notify 即將停止服務。

詳細內容:
LINE Notify 關閉說明

原先我從 telegram 轉移至 LINE Notify 的各項通知功能,
都得再移轉回去 telegram 中。

藉此機會來撰寫一篇 telegram bot 的簡易使用文章。
用於日後查找資料時有參考資料可用。

這次將使用 laravel-notification-channels/telegram 這項套件快速完成這項服務。



步驟 1:
安裝 laravel-notification-channels/telegram
composer require laravel-notification-channels/telegram

步驟 2:
在 telegram 中加入 BotFather 好友。
https://telegram.me/BotFather

可藉由 /start 去找到 BotFather 的各項功能。
首先先輸入 /newbot 來創建一個新的 bot。

BotFather 就會問你要如何稱呼這個 bot,
命名上接受駝峰式及底線式命名,且一定要以 bot 作為結尾。


創建完成後,便會得到該 bot 的連結及 token。



步驟 3:
在 config/service.php 中加入 telegram bot token 資訊
...
    'telegram-bot-api' => [
        'token' => env('TELEGRAM_BOT_TOKEN', 'YOUR BOT TOKEN HERE')
    ],
...
並且將剛剛提供的 token 寫入 .env 中。
 

步驟 4:

將 IDBot 加入好友。
https://telegram.me/myidbot

這個 IDBot 有兩種用法,
一種是查找自己的 id,可以輸入 /getid 獲得;
另一種則是將此 bot 加入群組中,並使用 /getgroupid,
便可以得到群組的 id。



接著我先介紹傳通知給自己的用法,
<?php

namespace App\Http\Controllers;

use App\Notifications\TelegramContactBot;
use Illuminate\Support\Facades\Notification;
use NotificationChannels\Telegram\TelegramChannel;


class ContactController extends Controller
{
    public function store(ContactRequest $request)
    {
        ...

        Notification::route(TelegramChannel::class, '')
            ->notify(new TelegramContactBot($message));

        ...
    }
}
在 controller 中使用 Notification 及 TelegramChannel,
並再 app/Notifications 中創建 TelegramContactBot.php 檔案。
檔案內容如下:
 
<?php

namespace App\Notifications;

use App\Models\Contact;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use NotificationChannels\Telegram\TelegramChannel;
use NotificationChannels\Telegram\TelegramMessage;

class TelegramContactBot extends Notification
{
    use Queueable;
    private $content;

    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($content)
    {
        /** @var Contact $this->contact */
        $this->content = $content;
    }

    /**
     * Get the notification's delivery channels.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function via($notifiable)
    {
        return [TelegramChannel::class];
    }

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toTelegram($notifiable)
    {
        $content = $this->content;

        return TelegramMessage::create()
            ->to('YOUR_TELEGRAM_ID')
            ->content($content);
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}
其中在 toTelegram function 中創建要傳送的訊息及對象。
對象就是填入 /getid 所生成的 ID。

完成後就可以試著去呼叫使用,
這裡的情境是,當有人使用聯絡我們發送表單時,
bot 就會通知我有人使用聯絡我們。
得到的訊息會如下圖:




而另一種情境,
則是當我有新文章時,發送通知至群組中。
在 controller 端寫法一樣,
只是 TelegramContactBot.php 是專屬於發送聯絡我們通知使用,
所以要另外再創建一個 TelegramArticleBot.php 來使用。
 
...
public function toTelegram($notifiable)
    {
        $article = $this->article;

        $url = route('article_main', $article->id);

        return TelegramFile::create()
            ->to('YOUR_GROUP_ID')
            ->content("【新文章通知】\n*$article->title*")
            ->photo(asset($article->cover_image))
            ->button('前往閱讀', $url)
            ->button('小額支持', route('page', 'donate'));
    }
...
只要將 toTelegram function 中要發送的訊息做替換即可,
也可以加入照片、按鈕等功能。

同時也別忘記將這個 bot 加入至對應的群組中,
它才會在群組中發送訊息通知。

這次的應用結果如下:


這樣就可以免費的使用 Telegram Bot API 的各項通知了,
至於上面的發布新文章的群組,有興趣的讀者也可以加入。

加入群組獲取最新文章通知



當然也有更多的應用場景及方式,
這裡僅提及兩種比較常使用的作法。
更多使用方式可以前往 Telegram Bot API 網站查詢,
或者至 套件的 GitHub 頁面去查找其他使用方式。

Telegram Bot API 頁面
GitHub 頁面

希望以上的說明對讀者們有幫助,
也希望能幫助到日後要使用的自己。