Giter VIP home page Giter VIP logo

laravel-notification-channels / telegram Goto Github PK

View Code? Open in Web Editor NEW
923.0 923.0 155.0 233 KB

✈️ Telegram Notifications Channel for Laravel

Home Page: https://laravel-notification-channels.com/telegram/

License: MIT License

PHP 99.95% Blade 0.05%
bot-api hacktoberfest laravel laravel-5-package laravel-6-package laravel-7-package laravel-8-package laravel-notification-channels laravel-notifications laravel-package laravel-telegram telegram telegram-bot telegram-notification

telegram's Introduction

Telegram Notifications Channel for Laravel

Join PHP Chat Chat on Telegram Latest Version on Packagist Software License Total Downloads

This package makes it easy to send Telegram notification using Telegram Bot API with Laravel.

Contents

Installation

You can install the package via composer:

composer require laravel-notification-channels/telegram

Setting up your Telegram Bot

Talk to @BotFather and generate a Bot API Token.

Then, configure your Telegram Bot API Token:

# config/services.php

'telegram-bot-api' => [
    'token' => env('TELEGRAM_BOT_TOKEN', 'YOUR BOT TOKEN HERE')
],

Retrieving Chat ID

For us to send notifications to your Telegram Bot user/channel or group, we need to know their Chat ID.

This can be done by fetching the updates for your Bot using the getUpdates method as per Telegram Bot API docs.

An update is an object containing relevant fields based on the type of update it represents, some examples of an update object are message, callback_query, and poll. For a complete list of fields, see Telegram Bot API docs.

To make things easier, the library comes with a handy method that can be used to get the updates from which you can parse the relevant Chat ID.

Please keep in mind the user has to first interact with your bot for you to be able to obtain their Chat ID which you can then store in your database for future interactions or notifications.

Here's an example of fetching an update:

use NotificationChannels\Telegram\TelegramUpdates;

// Response is an array of updates.
$updates = TelegramUpdates::create()
    // (Optional). Get's the latest update. NOTE: All previous updates will be forgotten using this method.
    // ->latest()
    
    // (Optional). Limit to 2 updates (By default, updates starting with the earliest unconfirmed update are returned).
    ->limit(2)
    
    // (Optional). Add more params to the request.
    ->options([
        'timeout' => 0,
    ])
    ->get();

if($updates['ok']) {
    // Chat ID
    $chatId = $updates['result'][0]['message']['chat']['id'];
}

Note: This method will not work if an outgoing webhook is set up.

For a complete list of available parameters for the options, see Telegram Bot API docs.

Using in Lumen

If you're using this notification channel in your Lumen project, you will have to add the below code in your bootstrap/app.php file.

# bootstrap/app.php

// Make sure to create a "config/services.php" file and add the config from the above step.
$app->configure('services');

# Register the notification service providers.
$app->register(Illuminate\Notifications\NotificationServiceProvider::class);
$app->register(NotificationChannels\Telegram\TelegramServiceProvider::class);

Proxy or Bridge Support

You may not be able to send notifications if Telegram Bot API is not accessible in your country, you can either set a proxy by following the instructions here or use a web bridge by setting the base_uri config above with the bridge uri.

You can set HTTPS_PROXY in your .env file.

Usage

You can now use the channel in your via() method inside the Notification class.

Text Notification

use NotificationChannels\Telegram\TelegramMessage;
use Illuminate\Notifications\Notification;

class InvoicePaid extends Notification
{
    public function via($notifiable)
    {
        return ["telegram"];
    }

    public function toTelegram($notifiable)
    {
        $url = url('/invoice/' . $this->invoice->id);

        return TelegramMessage::create()
            // Optional recipient user id.
            ->to($notifiable->telegram_user_id)
            // Markdown supported.
            ->content("Hello there!")
            ->line("Your invoice has been *PAID*")
            ->lineIf($notifiable->amount > 0, "Amount paid: {$notifiable->amount}")
            ->line("Thank you!")

            // (Optional) Blade template for the content.
            // ->view('notification', ['url' => $url])

            // (Optional) Inline Buttons
            ->button('View Invoice', $url)
            ->button('Download Invoice', $url)
            // (Optional) Inline Button with callback. You can handle callback in your bot instance
            ->buttonWithCallback('Confirm', 'confirm_invoice ' . $this->invoice->id);
    }
}

Here's a screenshot preview of the above notification on Telegram Messenger:

Laravel Telegram Notification Example

Send with Keyboard

public function toTelegram($notifiable)
{
    return TelegramPoll::create()
        ->to($notifiable)
        ->content('Choose an option:')
        ->keyboard('Button 1')
        ->keyboard('Button 2');
        // ->keyboard('send your number', request_contact: true)
        // ->keyboard('send your location', request_location: true);
}

Preview:

Laravel Telegram Notification Keyboard

Send a Poll

public function toTelegram($notifiable)
{
    return TelegramPoll::create()
        ->to($notifiable)
        ->question("Aren't Laravel Notification Channels awesome?")
        ->choices(['Yes', 'YEs', 'YES']);
}

Preview:

Laravel Telegram Poll Example

Attach a Contact

public function toTelegram($notifiable)
{
    return TelegramContact::create()
            ->to($notifiable->telegram_user_id) // Optional
            ->firstName('John')
            ->lastName('Doe') // Optional
            ->phoneNumber('00000000');
}

Preview:

Laravel Telegram Contact Example

Attach an Audio

public function toTelegram($notifiable)
{
    return TelegramFile::create()
            ->to($notifiable->telegram_user_id) // Optional
            ->content('Audio') // Optional Caption
            ->audio('/path/to/audio.mp3');
}

Preview:

Laravel Telegram Audio Notification Example

Attach a Photo

public function toTelegram($notifiable)
{
    return TelegramFile::create()
        ->to($notifiable->telegram_user_id) // Optional
        ->content('Awesome *bold* text and [inline URL](http://www.example.com/)')
        ->file('/storage/archive/6029014.jpg', 'photo'); // local photo

        // OR using a helper method with or without a remote file.
        // ->photo('https://file-examples-com.github.io/uploads/2017/10/file_example_JPG_1MB.jpg');
}

Preview:

Laravel Telegram Photo Notification Example

Attach a Document

public function toTelegram($notifiable)
{
    return TelegramFile::create()
        ->to($notifiable->telegram_user_id) // Optional
        ->content('Did you know we can set a custom filename too?')
        ->document('https://file-examples-com.github.io/uploads/2017/10/file-sample_150kB.pdf', 'sample.pdf');
}

Preview:

Laravel Telegram Document Notification Example

Attach a Location

public function toTelegram($notifiable)
{
    return TelegramLocation::create()
        ->latitude('40.6892494')
        ->longitude('-74.0466891');
}

Preview:

Laravel Telegram Location Notification Example

Attach a Video

public function toTelegram($notifiable)
{
    return TelegramFile::create()
        ->content('Sample *video* notification!')
        ->video('https://file-examples-com.github.io/uploads/2017/04/file_example_MP4_480_1_5MG.mp4');
}

Preview:

Laravel Telegram Video Notification Example

Attach a GIF File

public function toTelegram($notifiable)
{
    return TelegramFile::create()
        ->content('Woot! We can send animated gif notifications too!')
        ->animation('https://sample-videos.com/gif/2.gif');

        // Or local file
        // ->animation('/path/to/some/animated.gif');
}

Preview:

Laravel Telegram Gif Notification Example

Routing a Message

You can either send the notification by providing with the chat ID of the recipient to the to($chatId) method like shown in the previous examples or add a routeNotificationForTelegram() method in your notifiable model:

/**
 * Route notifications for the Telegram channel.
 *
 * @return int
 */
public function routeNotificationForTelegram()
{
    return $this->telegram_user_id;
}

Handling Response

You can make use of the notification events to handle the response from Telegram. On success, your event listener will receive a Message object with various fields as appropriate to the notification type.

For a complete list of response fields, please refer the Telegram Bot API's Message object docs.

On-Demand Notifications

Sometimes you may need to send a notification to someone who is not stored as a "user" of your application. Using the Notification::route method, you may specify ad-hoc notification routing information before sending the notification. For more details, you can check out the on-demand notifications docs.

use Illuminate\Support\Facades\Notification;

Notification::route('telegram', 'TELEGRAM_CHAT_ID')
            ->notify(new InvoicePaid($invoice));

Sending to Multiple Recipients

Using the notification facade you can send a notification to multiple recipients at once.

If you're sending bulk notifications to multiple users, the Telegram Bot API will not allow more than 30 messages per second or so. Consider spreading out notifications over large intervals of 8—12 hours for best results.

Also note that your bot will not be able to send more than 20 messages per minute to the same group.

If you go over the limit, you'll start getting 429 errors. For more details, refer Telegram Bots FAQ.

use Illuminate\Support\Facades\Notification;

// Recipients can be an array of chat IDs or collection of notifiable entities.
Notification::send($recipients, new InvoicePaid());

Available Methods

Shared Methods

These methods are optional and shared across all the API methods.

  • to(int|string $chatId): Recipient's chat id.
  • token(string $token): Bot token if you wish to override the default token for a specific notification.
  • button(string $text, string $url, int $columns = 2): Adds an inline "Call to Action" button. You can add as many as you want, and they'll be placed 2 in a row by default.
  • buttonWithCallback(string $text, string $callback_data, int $columns = 2): Adds an inline button with the given callback data. You can add as many as you want, and they'll be placed 2 in a row by default.
  • disableNotification(bool $disableNotification = true): Send the message silently. Users will receive a notification with no sound.
  • options(array $options): Allows you to add additional params or override the payload.
  • getPayloadValue(string $key): Get payload value for given key.

Telegram Message methods

For more information on supported parameters, check out these docs.

  • content(string $content, int $limit = null): Notification message, supports markdown. For more information on supported markdown styles, check out these docs.
  • line(string $content): Adds a message in a new line.
  • lineIf(bool $boolean, string $line): Adds a message in a new line if the given condition is true.
  • escapedLine(string $content): Adds a message in a new line while escaping special characters (For Markdown).
  • view(string $view, array $data = [], array $mergeData = []): (optional) Blade template name with Telegram supported HTML or Markdown syntax content if you wish to use a view file instead of the content() method.
  • chunk(int $limit = 4096): (optional) Message chars chunk size to send in parts (For long messages). Note: Chunked messages will be rate limited to one message per second to comply with rate limitation requirements from Telegram.

Telegram Location methods

  • latitude(float|string $latitude): Latitude of the location.
  • longitude(float|string $longitude): Longitude of the location.

Telegram File methods

  • content(string $content): (optional) File caption, supports markdown. For more information on supported markdown styles, check out these docs.
  • view(string $view, array $data = [], array $mergeData = []): (optional) Blade template name with Telegram supported HTML or Markdown syntax content if you wish to use a view file instead of the content() method.
  • file(string|resource|StreamInterface $file, string $type, string $filename = null): Local file path or remote URL, $type of the file (Ex:photo, audio, document, video, animation, voice, video_note) and optionally filename with extension. Ex: sample.pdf. You can use helper methods instead of using this to make it easier to work with file attachment.
  • photo(string $file): Helper method to attach a photo.
  • audio(string $file): Helper method to attach an audio file (MP3 file).
  • document(string $file, string $filename = null): Helper method to attach a document or any file as document.
  • video(string $file): Helper method to attach a video file.
  • animation(string $file): Helper method to attach an animated gif file.
  • voice(string $file): Helper method to attach a voice note (.ogg file with OPUS encoded).
  • videoNote(string $file): Helper method to attach a video note file (Upto 1 min long, rounded square video).

Telegram Contact methods

  • phoneNumber(string $phoneNumber): Contact phone number.
  • firstName(string $firstName): Contact first name.
  • lastName(string $lastName): (optional) Contact last name.
  • vCard(string $vCard): (optional) Contact vcard.

Telegram Poll methods

  • question(string $question): Poll question.
  • choices(array $choices): Poll choices.

Alternatives

For advance usage, please consider using telegram-bot-sdk instead.

Changelog

Please see CHANGELOG for more information what has changed recently.

Testing

$ composer test

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Contributing

Please see CONTRIBUTING for details.

Credits

License

The MIT License (MIT). Please see License File for more information.

telegram's People

Contributors

4irik avatar abbasudo avatar alexsoft avatar atymic avatar belguinan avatar bmitch avatar casperboone avatar digislexia avatar enniel avatar faissaloux avatar faustbrian avatar freekmurze avatar irajtaghlidi avatar irazasyed avatar ivanvermeyen avatar jackcolley avatar jackellis avatar jaybizzle avatar laravel-shift avatar lotuashvili avatar mammutalex avatar mpociot avatar muetze42 avatar okaufmann avatar oyed avatar peregraum avatar putera avatar rubendl avatar themsaid avatar vladimirrebilly avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

telegram's Issues

cant send file

when i want use file() method, say :

Call to undefined method NotificationChannels\Telegram\TelegramMessage::file();

TelegramChannel not supported

when i call an notification, the system answer as this:

NotificationChannels\Telegram\Exceptions\CouldNotSendNotification: You must provide your telegram bot token to make any API requests. in [...]/vendor/laravel-notification-channels/telegram/src/Exceptions/CouldNotSendNotification.php:38
Stack trace:
#0 [...]/vendor/laravel-notification-channels/telegram/src/Telegram.php(85): NotificationChannels\Telegram\Exceptions\CouldNotSendNotification::telegramBotTokenNotProvided('You must provid...')

Laravel 5.7 compatibility

I'm having problems to require this package:

our requirements could not be resolved to an installable set of packages.

Problem 1
- The requested package laravel/framework (locked at v5.7.22, required as 5.6.) is satisfiable by laravel/framework[v5.7.22] but these conflict with your requirements or minimum-stability.
Problem 2
- Conclusion: don't install laravel/framework v5.6.39
- Conclusion: don't install laravel/framework v5.6.38
- Conclusion: don't install laravel/framework v5.6.37
- Conclusion: don't install laravel/framework v5.6.36
- Conclusion: don't install laravel/framework v5.6.35
- Conclusion: don't install laravel/framework v5.6.34
- Conclusion: don't install laravel/framework v5.6.33
- Conclusion: don't install laravel/framework v5.6.32
- Conclusion: don't install laravel/framework v5.6.31
- Conclusion: don't install laravel/framework v5.6.30
- Conclusion: don't install laravel/framework v5.6.29
- Conclusion: don't install laravel/framework v5.6.28
- Conclusion: don't install laravel/framework v5.6.27
- Conclusion: don't install laravel/framework v5.6.26
- Conclusion: don't install laravel/framework v5.6.25
- Conclusion: don't install laravel/framework v5.6.24
- Conclusion: don't install laravel/framework v5.6.23
- Conclusion: don't install laravel/framework v5.6.22
- Conclusion: don't install laravel/framework v5.6.21
- Conclusion: don't install laravel/framework v5.6.20
- Conclusion: don't install laravel/framework v5.6.19
- Conclusion: don't install laravel/framework v5.6.18
- Conclusion: don't install laravel/framework v5.6.17
- Conclusion: don't install laravel/framework v5.6.16
- Conclusion: don't install laravel/framework v5.6.15
- Conclusion: don't install laravel/framework v5.6.14
- Conclusion: don't install laravel/framework v5.6.13
- Conclusion: don't install laravel/framework v5.6.12
- Conclusion: don't install laravel/framework v5.6.11
- Conclusion: don't install laravel/framework v5.6.10
- Conclusion: don't install laravel/framework v5.6.9
- Conclusion: don't install laravel/framework v5.6.8
- Conclusion: don't install laravel/framework v5.6.7
- Conclusion: don't install laravel/framework v5.6.6
- Conclusion: don't install laravel/framework v5.6.5
- Conclusion: don't install laravel/framework v5.6.4
- Conclusion: don't install laravel/framework v5.6.3
- Conclusion: don't install laravel/framework v5.6.2
- Conclusion: don't install laravel/framework v5.6.1
- Conclusion: don't install laravel/framework v5.6.0
- laravel/socialite v4.0.3 requires illuminate/support ~5.7 -> satisfiable by laravel/framework[v5.7.22, 5.7.x-dev], illuminate/support[5.7.17, 5.7.18, 5.7.19, 5.7.x-dev, 5.8.x-dev, v5.7.0, v5.7.1, v5.7.10, v5.7.11, v5.7.15, v5.7.2, v5.7.20, v5.7.21, v5.7.22, v5.7.3, v5.7.4, v5.7.5, v5.7.6, v5.7.7, v5.7.8, v5.7.9].
- laravel/socialite v4.0.3 requires illuminate/support ~5.7 -> satisfiable by laravel/framework[v5.7.22, 5.7.x-dev], illuminate/support[5.7.17, 5.7.18, 5.7.19, 5.7.x-dev, 5.8.x-dev, v5.7.0, v5.7.1, v5.7.10, v5.7.11, v5.7.15, v5.7.2, v5.7.20, v5.7.21, v5.7.22, v5.7.3, v5.7.4, v5.7.5, v5.7.6, v5.7.7, v5.7.8, v5.7.9].
- laravel/socialite v4.0.3 requires illuminate/support ~5.7 -> satisfiable by laravel/framework[v5.7.22, 5.7.x-dev], illuminate/support[5.7.17, 5.7.18, 5.7.19, 5.7.x-dev, 5.8.x-dev, v5.7.0, v5.7.1, v5.7.10, v5.7.11, v5.7.15, v5.7.2, v5.7.20, v5.7.21, v5.7.22, v5.7.3, v5.7.4, v5.7.5, v5.7.6, v5.7.7, v5.7.8, v5.7.9].
- Can only install one of: laravel/framework[5.7.x-dev, 5.6.x-dev].
- Can only install one of: laravel/framework[5.6.x-dev, v5.7.22].
- don't install illuminate/support 5.7.17|don't install laravel/framework 5.6.x-dev
- don't install illuminate/support 5.7.18|don't install laravel/framework 5.6.x-dev
- don't install illuminate/support 5.7.19|don't install laravel/framework 5.6.x-dev
- don't install illuminate/support 5.7.x-dev|don't install laravel/framework 5.6.x-dev
- don't install illuminate/support v5.7.0|don't install laravel/framework 5.6.x-dev
- don't install illuminate/support v5.7.1|don't install laravel/framework 5.6.x-dev
- don't install illuminate/support v5.7.10|don't install laravel/framework 5.6.x-dev
- don't install illuminate/support v5.7.11|don't install laravel/framework 5.6.x-dev
- don't install illuminate/support v5.7.15|don't install laravel/framework 5.6.x-dev
- don't install illuminate/support v5.7.2|don't install laravel/framework 5.6.x-dev
- don't install illuminate/support v5.7.20|don't install laravel/framework 5.6.x-dev
- don't install illuminate/support v5.7.21|don't install laravel/framework 5.6.x-dev
- don't install illuminate/support v5.7.22|don't install laravel/framework 5.6.x-dev
- don't install illuminate/support v5.7.3|don't install laravel/framework 5.6.x-dev
- don't install illuminate/support v5.7.4|don't install laravel/framework 5.6.x-dev
- don't install illuminate/support v5.7.5|don't install laravel/framework 5.6.x-dev
- don't install illuminate/support v5.7.6|don't install laravel/framework 5.6.x-dev
- don't install illuminate/support v5.7.7|don't install laravel/framework 5.6.x-dev
- don't install illuminate/support v5.7.8|don't install laravel/framework 5.6.x-dev
- don't install illuminate/support v5.7.9|don't install laravel/framework 5.6.x-dev
- don't install illuminate/support 5.8.x-dev|don't install laravel/framework 5.6.x-dev
- Installation request for laravel/framework 5.6.
-> satisfiable by laravel/framework[5.6.x-dev, v5.6.0, v5.6.1, v5.6.10, v5.6.11, v5.6.12, v5.6.13, v5.6.14, v5.6.15, v5.6.16, v5.6.17, v5.6.18, v5.6.19, v5.6.2, v5.6.20, v5.6.21, v5.6.22, v5.6.23, v5.6.24, v5.6.25, v5.6.26, v5.6.27, v5.6.28, v5.6.29, v5.6.3, v5.6.30, v5.6.31, v5.6.32, v5.6.33, v5.6.34, v5.6.35, v5.6.36, v5.6.37, v5.6.38, v5.6.39, v5.6.4, v5.6.5, v5.6.6, v5.6.7, v5.6.8, v5.6.9].
- Installation request for laravel/socialite (locked at v4.0.3) -> satisfiable by laravel/socialite[v4.0.3].

Installation failed, reverting ./composer.json to its original content.

Telegram Bot Token (Laravel)

Even after including this;

'telegram-bot-api' => [
        'token' => env('TELEGRAM_BOT_TOKEN')
],

in config/services, and defining it in the .env file, I still get the error:

You must provide your telegram bot token to make any API requests

The only way it goes through is if I hard code the token in the
/vendor/laravel-notification-channels/telegram/src/Telegram.php

which is a bad practice as /vendor is meant to be ignored when you push.

token

Hi,
I did set my token in config/services.php:

'telegram-bot-api' => [ 'token' => env('TELEGRAM_BOT_TOKEN', '<I_did_put_my_token_here>') ]

but when I try to send a request

public function toTelegram($notifiable) { return TelegramMessage::create() ->to(22919823) ->content("Hello there!\nYour invoice has been *PAID*"); }

I get this error:

You must provide your telegram bot token to make any API requests

what am I doing wrong?
thanks

How to disable markdown parsing?

Sometime I got 400 response from telegram api because message contains some bad symbols (I sending json logs)

Im escaping _ new TelegramAdmin(str_replace('_','\_',$msg) but something else breaking it when parsing $msg

Best practice retrieving Telegram ID

This is more of a question, but I'm looking for inspiration how to connect a user's Telegram ID with my Laravel installation. No user will ever know their ID, plus it is spam sensitive. So I would think...

  1. Create two temporary tokens in database
  2. Show first token on website to user
  3. Instruct user to tell first token to my bot in Telegram
  4. Laravel store ID and sends (via notification) the second token to user
  5. User enters second token on website to close the loop (setting verified in DB to true)

This would - to me - resemble a proper opt-in process for Telegram. Thoughts? Ideas?

Laravel 5.7 support?

The commits from 0.0.4 are not applyed !

Check the composer.json from that relase and see that still exists:

        "illuminate/notifications": "5.3.* || 5.4.* || 5.5.* || 5.6.*",
        "illuminate/support": "5.1.* || 5.2.* || 5.3.* || 5.4.* || 5.5.* || 5.6.*"

Can't access the response body in a CouldNotSendNotification exception

When a CouldNotSendNotification exception is returned in response to a ClientException after sending an API request the HTTP response body is omited from the exception object and the only data made available is the description field.

There are cases where there is other meaningful and necessary info in the response body, namely:
When a group is upgraded to supergroup the new chat ID is returned in the response and needs to be used in replacement of the old one.

{
    "ok": false,
    "error_code": 400,
    "description": "Bad Request: group chat was upgraded to a supergroup chat",
    "parameters": {
        "migrate_to_chat_id": (...)
    }
}

Feature: send location with text

Hi, is there a way to send TelegramLocation with a text commentary attached to it (just like it's possible for files)?

Or, maybe it's possible to combine two messages… Something like this pseudocode:

    public function toTelegram($notifiable)
    {
        return TelegramLocation::create()
            ->latitude($this->activity->getCoords()->lat)
            ->longitude($this->activity->getCoords()->lon);
            ->merge(
                TelegramMessage::create()->content($this->getTelegramText())
            );
    }

Send messages to a group (bot integrated in this group)

Good afternoon I would like to be able to send messages to a group where the bot is integrated as an administrator, so that all users of that group can read the notification. it's possible?

This is my code

`public function toTelegram($notifiable)
{
$usuario = User::where('id', $this->comentario->user_id)->value('name');
$servicio = Servicio::where('id', $this->comentario->servicio_id)->value('titulo');
$descripcion = $this->comentario->descripcion;

    return TelegramFile::create()
        ->to(189399173)
        ->file('../public/img/logo.jpg', 'photo')
        ->content("¡Hola! *". $usuario. "* ha escrito el siguiente *comentario*:\n\n". $descripcion . "\n\n*Servicio:* ". $servicio);
        //->button('Ver notificaciones', $url);
}`

Multiple Telegram Bot Token

Is it possible to set multiple telegram bot token? If yes, can let me know how to do it in notification class?

Thanks!

Error 500 un hosting

Hi, when I send a notification locally, the bot works perfectly. When uploading the project to my hosting, it gives me error 500 and tells me message error.

not working with laravel 8.x

Hi,

Today I want to upgrade my laravel from 7 to newest Laravel 8. but received an error by composer that this package is not support Laravel 8.

Can't upgrade Laravel to 5.5

Hi,

I'm trying to upgrade Laravel to version 5.5, but composer says it is not supported by laravel-notification-channels/telegram 0.0.2. Is dev-master safe to use?

Add Proxy

Hello! Can u add proxy?

Telegram.php

protected $proxy;
....
public function __construct($token = null, HttpClient $httpClient = null, $proxy = null)
    {
        $this->token = $token;
        $this->http = $httpClient;
        $this->proxy = $proxy;
    }
   try {
            return $this->httpClient()->request('POST', $endPointUrl, [
                "proxy" => $this->proxy,
                $multipart ? 'multipart' : 'form_params' => $params
            ]);
        }
....
return $this->httpClient()->request('POST', $endPointUrl, [
                "proxy" => $this->proxy,
                $multipart ? 'multipart' : 'form_params' => $params

src/TelegramServiceProvider.php

->give(static function () {
                return new Telegram(
                    config('services.telegram-api.token', null),
                    new HttpClient(),
                    config('services.telegram-api.proxy', null)
                );
            });

html support

Hi does this package support html tags?

e.g. using <br> or <p> tags in ->content() notification that will send?

Driver [NotificationChannels\Telegram\TelegramChannel] not supported for Queued Notification

Hello everybody,
i installed the notification channel following the instructions provided.

I receive the following errors:
Driver [NotificationChannels\Telegram\TelegramChannel] not supported. {"exception":"[object] (InvalidArgumentException(code: 0): Driver [NotificationChannels\Telegram\TelegramChannel] not supported. at /home/mauro/www/queuey/vendor/laravel/framework/src/Illuminate/Support/Manager.php:119)

What i'm trying to do is to send a simple notification when a form is filled.

`
namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;

use NotificationChannels\Telegram\TelegramChannel;
use NotificationChannels\Telegram\TelegramMessage;

use Illuminate\Notifications\Notification;

Use Log;

class MerchantLead extends Notification implements ShouldQueue
{
    use Queueable;
    
    protected $message;
    /**
    * Create a new notification instance.
    *
    * @return void
    */
    public function __construct($message)
    {
        $this->message = $message;
    }
    
    /**
    * 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 toMail($notifiable)
    {
        Log::info('[MERCHANT-LEAD] '. json_encode($this->message));
        return (new MailMessage)
        ->subject('Nuova Richiesta di Contatto da un esercente')
        ->line($this->message['firstname'] . ' ' . $this->message['lastname'] .' ha richiesto informazioni su QApp')
        ->line('Email: ' . $this->message['email'])
        ->line('Phone: ' . $this->message['phone'])
        ->line('Messaggio: ' . $this->message['text']);
        
        
    }
    
    public function toTelegram($notifiable)
    {
        
        $message = "<b>{$this->message['firstname']} {$this->message['lastname']}</b> ha richiesto informazioni su QApp\n";
        $message .= "Email: " . $this->message['email'] ."\n";
        $message .= 'Phone: ' . $this->message['phone']."\n";
        $message .= 'Messaggio: ' . $this->message['text']."\n";
        
        return TelegramMessage::create()
        ->options(['parse_mode' => 'HTML'])
        ->to(env('TELEGRAM_BOT_NOTIFICATION_GROUP_ID'))
        ->content($message);
    }
    
    /**
    * Get the array representation of the notification.
    *
    * @param  mixed  $notifiable
    * @return array
    */
    public function toArray($notifiable)
    {
        return [
            //
        ];
    }
}
`

if i remove the "implement ShouldQueue" the message is sent properly, while if i set the queue the exception above is thrown.

Somebody had a similar problem or an advise on this?

Lumen 5.8

This support for lumen 5.8?
If can how to configure it
Please help

Ability to change button columns in a row

Hi.

I was reading a source code and found that button() function splits buttons as 2 columns in a row. Will be good if we can change column numbers in a row.

From src/TelegramMessage.php:78

$replyMarkup['inline_keyboard'] = array_chunk($this->buttons, 2);

How to avoid toTelegram Function

Hi, i'd like to know how to ignore toTelegram function

I have the next code

public function toTelegram($notifiable)
    {
        $msg = $this->message($notifiable);
        return TelegramMessage::create()
            ->to($notifiable->{$this->telegram_object}->telegram_id)
            ->content($msg['message'])
            ->button($msg['button_text'], $msg['url']);
    }

But i'd like to validate if telegram id exist, and in case it doesnt dont send anything. But i get an error if a dont return anything or if i send it empty

public function toTelegram($notifiable)
    {
        $msg = $this->message($notifiable);
        if(!isset($notifiable->{$this->telegram_object}->telegram_id))
            return;
        return TelegramMessage::create()
            ->to($notifiable->{$this->telegram_object}->telegram_id)
            ->content($msg['message'])
            ->button($msg['button_text'], $msg['url']);
    } 

What code should i put to just ignore and dont try to send anything? If there isnt any way could you please add a method to do this?

Regards

On-Demand/AnonymousNotifiable will not route with TelegramChannel::class

AnonymousNotifiable only uses a basic assoc array to lookup routes. When you're routing with Notification::route(TelegramChannel::class, 'token'), you'll get something like

Illuminate\Notifications\AnonymousNotifiable^ {
  +routes: array:1 [
    "NotificationChannels\Telegram\TelegramChannel" => <token>
  ]
}

instead of

Illuminate\Notifications\AnonymousNotifiable^ {
  +routes: array:1 [
    "telegram" => <token>
  ]
}

so ! $to = $notifiable->routeNotificationFor('telegram') will always throw.

You can either update the on-demand documentation to only use the string "telegram" or check for an instance of AnonymousNotifiable and do something like
$notifiable->routeNotificationFor(TelegramChannel::class).

Feature; for send from blade template

Normally you do;

        return TelegramMessage::create()
            ->options([
                'parse_mode' => 'HTML'
            ])
            ->content('content);

But i think sometimes is nicer that you can use a template!

        return TelegramMessage::create()
            ->options([
                'parse_mode' => 'HTML'
            ])
            ->view('telegram.new-user',$data);

For now i do;

        $telegramView = View::make('telegram.new-user', $data);

        return TelegramMessage::create()
            ->options([
                'parse_mode' => 'HTML',
                'disable_web_page_preview' => true
            ])
            ->content($telegramView->render());

Maybe this is a nice feature :)

Telegram responded with an error `401 - Unauthorized`

Hello. I`am send messages to telegram in Jobs which in queues. When my QUEUE_CONNECTION=sync - its works perfectly. But when i change QUEUE_CONNECTION=database i got filed job and this exception:

NotificationChannels\Telegram\Exceptions\CouldNotSendNotification: Telegram responded with an error 401 - Unauthorizedin /home/admin/web/api.rf.market/app/vendor/laravel-notification-channels/telegram/src/Exceptions/CouldNotSendNotification.php:31
By me its error depends on token. But why?

On-Demand Notifications

Hello Guys,
I could not find any information about this, but "on Demand" is not supported for Telegram Notifications right ?

https://laravel.com/docs/5.8/notifications#on-demand-notifications

It would be great to post existing Notifications also to groups or channels.
Is there a way to do this with like this ?

Notification::route(TelegramChannel::class, env('TELEGRAM_ADMIN_CHAT_ID')) ->notify(new NOTIFICATION($data));
Notification::route('telegram', env('TELEGRAM_ADMIN_CHAT_ID')) ->notify(new NOTIFICATION($data));

Thank you

error CouldNotSendNotification

Hi I got the error I receive when running :

CouldNotSendNotification in CouldNotSendNotification.php line 48:
The communication with Telegram failed.

can't send image

Hi,
I try to send post image with my notification but i cannot do it!

here is my code:

public function toTelegram($post)
     {
         return TelegramMessage::create()
             ->to('@studiotjd')
             ->content([
               'uri' => $post->title.' http://xxxxxxx.com/blog/article/'. $post->slug,
               'photo' => $post->image. 'http://xxxxxxx.com/images/'. $post->image,
               'text' => $post->title,
             ]);
     }

I'm getting error of:

Telegram responded with an error 400 - Bad Request: message text is empty

How to get json response from Telegram?

Hello there, After i send a message to user , How to get json response from telegram ? I want to save message_id to my db which sent by my bot

I did this but it only return payloads:

    public function toTelegram($notifiable)
    {
        $response =  TelegramMessage::create()
            ->to($notifiable->telegram_user_id)
            ->content("Hello there!\nYour invoice has been *PAID*");

          dd($response);
    }

Trying to get property 'telegram_user_id' of non-object

Hello,
This in my notification:


namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use NotificationChannels\Telegram\TelegramChannel;
use NotificationChannels\Telegram\TelegramMessage;

class FreePaid extends Notification
{
    use Queueable;
    public $transaction = null;
    public $user = null;
    /**
     * Create a new notification instance.
     *
     * @return void
     */
    public function __construct($transaction, $user)
    {
        $this->transaction = $transaction;
        $this->$user = $user;
    }

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

    /**
     * Get the mail representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return \Illuminate\Notifications\Messages\MailMessage
     */
    public function toMail($notifiable)
    {
        return (new MailMessage)
                    ->subject('نتیجه پرداخت')
                    ->line('The introduction to the notification.')
                    ->action('Notification Action', url('/'))
                    ->line('Thank you for using our application!');
    }

    /**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toArray($notifiable)
    {
        return [
            'transaction_id' => $this->transaction->id,
            'amount' => $this->transaction->amount,
        ];
    }

    public function toTelegram($notifiable)
    {
        $url = url('/invoice/' . $this->transaction->id);

        return TelegramMessage::create()
            ->to($this->user->telegram_user_id) // Optional.
            ->content("*HELLO!* \n One of your invoices has been paid!") // Markdown supported.
            ->button('View Invoice', $url); // Inline Button
    }
}````

But I get error Trying to get property 'telegram_user_id' of non-object
I am sure that I have telegram_user_id in my database.

driver not supported

Hi,
one more question: got everything perfectly working on my mac dev machine, but in production I get this:

Driver [NotificationChannels\Telegram\TelegramChannel] not supported

Any hint?
Thanks a lot

Call to a member function toNotGiven() on boolean

Hello,
public function toTelegram($notifiable)
{
$pay = route('invoice.pay-link-password', [$this->invoice->id,$this->invoice->password]);
$view = route('invoice.view-password', [$this->invoice->id,$this->invoice->password]);
if($this->user->telegram_user_id) {
return TelegramMessage::create()
->to($this->user->telegram_user_id)
->content("صدور فاکتور جدید:" . $this->invoice->id ."\n" ."مبلغ فاکتور:" . number_format($this->invoice->total) ."\n") // Markdown supported.
->button('نمایش فاکتور', $view)
->button('پرداخت فاکتور', $pay);
} else {
return false;
}
}

And my usage is:
$invoice = Invoice::findOrFail(1);
$user = Auth::user();
try {
Notification::send($user, new InvoiceCreated($invoice, $user));
} catch (\Exception $e) {}

But I get :
Call to a member function toNotGiven() on boolean
vendor/laravel-notification-channels/telegram/src/TelegramChannel.php

Chat not found

I keep on getting CouldNotSendNotification Exception with message Telegram responded with an error 400 - Bad Request: chat not found.

My toTelegram method is pretty straightforward

public function toTelegram($notifiable)
    {
        return TelegramMessage::create()
                              ->to($this->target)
                              ->content($this->message);
    }

where $this->target is the chat_id and $this->message is the message.

Chat_id exists, in fact it's me, and I've already started the conversation with the bot via App.

No more support for PHP 7.1?

I'm currently using PHP 7.1 and Laravel 5.8, however version 0.0.6 and above only supports PHP 7.2 for Laravel v6.0. Is it possible to include PHP 7.1 for those with Laravel 5.x?

Laravel 5.5 support

Hi
I find out that this package does not support laravel 5.5.
What could I do? Please help

"bot-token per-notification" and ShouldQueue interface

when you need to queue notifications (implementing ShouldQueue interface) which use bot-token different from the default one (declared on config('services.telegram-bot-api.token')), there's no way to specify a custom one as an optional additional parameter.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.