babenkoivan/telegram-notifications 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

babenkoivan/telegram-notifications

Composer 安装命令:

composer require babenkoivan/telegram-notifications

包简介

Telegram notifications for Laravel

README 文档

README

Packagist Packagist license

The package provides easy way to send Telegram notifications to any notifiable entity in your project. It uses official Telegram Bot API to deliver your message directly to a user. You can send any information you want: text, media, location or contact.

Contents

Requirements

The package has been tested on following configuration:

  • PHP version >= 7.3
  • Laravel Framework version >= 5.5

Installation

To install the package you can use composer:

composer require babenkoivan/telegram-notifications

If the package discovery is disabled, you need to register the service provider in config/app.php file:

'providers' => [
    TelegramNotifications\TelegramServiceProvider::class    
]

To copy the package settings to config directory run:

php artisan vendor:publish --provider='TelegramNotifications\TelegramServiceProvider'

Now you're ready to set up a bot token for your application. If you haven't created a bot you can make new one using BotFather. For more information, visit Bots: An introduction for developers page.

Let's move on and assume you have a token. You can configure the token either in .env file:

TELEGRAM_BOT_TOKEN=335237666:FFF45pYTYm9HkKWByaepSpcKAUWMo2uMF_9

or in config/telegram.php file:

<?php

return [
    'bot_token' => '335237666:FFF45pYTYm9HkKWByaepSpcKAUWMo2uMF_9',
];

Of course, the token above is just an example, you have to specify your own token.

Set up your model

To notify user or any other notifiable entity you need to use Notifiable trait with your model and define routeNotificationForTelegram method, which will return a chat_id:

<?php

namespace App;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable
{
    use Notifiable;

    // ...

    public function routeNotificationForTelegram()
    {
        return 993344556;
    }
}

At this point, you may wonder where to get a chat_id. The answer is it's up to you! You can create a webhook to receive updates for your bot and collect chat ids, or you can specify ids manually for certain users.

To get started, you can send Hello! message to your bot and then get message details by requesting API method:

curl https://api.telegram.org/bot<your_token_here>/getUpdates

You will receive a JSON in return:

{
    "ok": true,
    "result": [
        {
            "message": {
                "chat": {
                    "id": 993344556 // this is what we were looking for 
                    // ...
                }
            }
        }
    ]
}

Usage example

if you installed the package and configured a model you're ready to make your first Telegram notification. You can create a new notification using artisan command:

php artisan make:notification TelegramNotification

And again, TelegramNotification here is just an example, you can specify any name you want.

Now, you can go to app/Notifications folder and you'll see TelegramNotification.php file. In via method specify TelegramChannel::class and initialize a new TelegramMessage instance in toTelegram method:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;

use TelegramNotifications\TelegramChannel;
use TelegramNotifications\Messages\TelegramMessage;

class TelegramNotification extends Notification
{
    use Queueable;

    public function via()
    {
        return [TelegramChannel::class];
    }

    public function toTelegram()
    {
        return (new TelegramMessage())->text('Hello, world!');
    }
}

To send the notification use notify method with notifiable entity.

Let's say we have an authenticated user and we want to send a message from a route callback. We can do it like this:

<?php

use \App\Notifications\TelegramNotification;

Route::post('/', function () {
    Auth::user()->notify(new TelegramNotification());
});

Advanced Usage

You can send either a single message or a message collection at once.

Single Message

Each message class represents certain type of information you can deliver to a user. To send a message return a new instance of necessary type from toTelegram method:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;

use TelegramNotifications\TelegramChannel;
use TelegramNotifications\Messages\TelegramMessage;

class TelegramNotification extends Notification
{
    use Queueable;

    public function via()
    {
        return [TelegramChannel::class];
    }

    public function toTelegram()
    {
        // to set any required or optional field use
        // setter, which name is field name in camelCase
        return (new TelegramMessage())
            ->text('Hello, world!')
            ->disableNotification(true);
    }
}

You can also pass parameters to the constructor, to be more explicit:

<?php

new TelegramMessage([
    'text' => 'Hello, world!',
    'disable_notification' => true
]);

Available message types are listed below.

TelegramMessage

TelegramNotifications\Messages\TelegramMessage

Field Type Description Required
text String Text of the message to be sent Yes
parse_mode String Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width text or inline URLs in your bot's message Optional
disable_web_page_preview Boolean Disables link previews for links in this message Optional
disable_notification Boolean Sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound Optional

TelegramPhoto

TelegramNotifications\Messages\TelegramPhoto

Field Type Description Required
photo String Photo to send. Pass a file_id as String to send a photo that exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a photo from the Internet. More about sending files Yes
caption String Photo caption, 0-200 characters Optional
disable_notification Boolean Sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound Optional

TelegramAudio

TelegramNotifications\Messages\TelegramAudio

Field Type Description Required
audio String Audio file to send. Pass a file_id as String to send a photo that exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a photo from the Internet. More about sending files Yes
caption String Audio caption, 0-200 characters Optional
duration Integer Duration of the audio in seconds Optional
performer String Performer Optional
title String Track name Optional
disable_notification Boolean Sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound Optional

TelegramDocument

TelegramNotifications\Messages\TelegramDocument

Field Type Description Required
document String File to send. Pass a file_id as String to send a photo that exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a photo from the Internet. More about sending files Yes
caption String Document caption, 0-200 characters Optional
disable_notification Boolean Sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound Optional

TelegramSticker

TelegramNotifications\Messages\TelegramSticker

Field Type Description Required
sticker String Sticker to send. Pass a file_id as String to send a photo that exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a photo from the Internet. More about sending files Yes
disable_notification Boolean Sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound Optional

TelegramVideo

TelegramNotifications\Messages\TelegramVideo

Field Type Description Required
video String Video to send. Pass a file_id as String to send a photo that exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a photo from the Internet. More about sending files Yes
duration Integer Duration of sent video in seconds Optional
width Integer Video width Optional
height Integer Video height Optional
caption String Video caption, 0-200 characters Optional
disable_notification Boolean Sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound Optional

TelegramVoice

TelegramNotifications\Messages\TelegramVoice

Field Type Description Required
voice String Audio file to send. Pass a file_id as String to send a photo that exists on the Telegram servers, pass an HTTP URL as a String for Telegram to get a photo from the Internet. More about sending files Yes
caption String Voice message caption, 0-200 characters Optional
duration Integer Duration of the voice message in seconds Optional
disable_notification Boolean Sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound Optional

TelegramLocation

TelegramNotifications\Messages\TelegramLocation

Field Type Description Required
latitude Float number Latitude of location Yes
longitude Float number Longitude of location Yes
disable_notification Boolean Sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound Optional

TelegramVenue

TelegramNotifications\Messages\TelegramVenue

Field Type Description Required
latitude Float number Latitude of the venue Yes
longitude Float number Longitude of the venue Yes
title String Name of the venue Yes
address String Address of the venue Yes
foursquare_id String Foursquare identifier of the venue Optional
disable_notification Boolean Sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound Optional

TelegramContact

TelegramNotifications\Messages\TelegramContact

Field Type Description Required
phone_number String Contact's phone number Yes
first_name String Contact's first name Yes
last_name String Contact's last name Optional
disable_notification Boolean Sends the message silently. iOS users will not receive a notification, Android users will receive a notification with no sound Optional

Message Collection

Instead of sending one message at once you can send bunch of messages using TelegramCollection:

<?php

namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;

use TelegramNotifications\TelegramChannel;
use TelegramNotifications\Messages\TelegramCollection;

class TelegramNotification extends Notification
{
    use Queueable;

    public function via()
    {
        return [TelegramChannel::class];
    }

    public function toTelegram()
    {
        return (new TelegramCollection())
            ->message(['text' => 'Hello, world!'])
            ->location(['latitude' => 55.755768, 'longitude' => 37.617671])
            // ...
            ->sticker(['sticker' => 'CAADBQADJwEAAl7ylwK4Q0M5P7UxhQI']);
    }
}

Each method of the collection creates corresponding message instance and puts it in the collection. Available methods are listed below:

Method Corresponding entity
message TelegramMessage
photo TelegramPhoto
audio TelegramAudio
document TelegramDocument
sticker TelegramSticker
video TelegramVideo
voice TelegramVoice
location TelegramLocation
venue TelegramVenue
contact TelegramContact

babenkoivan/telegram-notifications 适用场景与选型建议

babenkoivan/telegram-notifications 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 49.13k 次下载、GitHub Stars 达 38, 最近一次更新时间为 2017 年 02 月 23 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「notification」 「laravel」 「telegram」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 babenkoivan/telegram-notifications 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 babenkoivan/telegram-notifications 我们能提供哪些服务?
定制开发 / 二次开发

基于 babenkoivan/telegram-notifications 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 49.13k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 38
  • 点击次数: 13
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 38
  • Watchers: 2
  • Forks: 7
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2017-02-23