A
A
Alexey Sklyarov2019-01-23 23:45:01
Laravel
Alexey Sklyarov, 2019-01-23 23:45:01

How not to send a Notification to Telegram if the user does not have chat_id set?

To send notifications to telegram I use: laravel-notification-channels/telegram .
I pass a collection of users to whom I need to send a notification:

public function notify(array $message)
    {
      try {
        Notification::send($this->getUsers(), new PriceEvent($message));
      } catch (\Exception $e) {
        return $e->getMessage();
      }
    }

Notifications are added to the database (displayed on the website) and sent to Telegram:
/**
     * Get the array representation of the notification.
     *
     * @param  mixed  $notifiable
     * @return array
     */
    public function toTelegram($notifiable)
    {
        $message = "";
        // Отправляем уведомление только тем пользователям,которые включили уведомления в Telegram

        if ($notifiable->notify_settings->telegram_enabled) {
          return TelegramMessage::create()->to($notifiable->telegram_id)->content($message);
        }

    }

In the code above, I check whether the user has notifications enabled in Telegram or not, but unfortunately, this method displays an error when trying to send notifications to a user who has a chat_id and a user who does not have it:
"Telegram notification chat ID was not provided. Please refer usage docs."

I found a similar problem on github ( and more ), but it's not particularly clear how it was solved. How can you correctly determine whether you can send a message to this person THIS METHOD (via Telegram) or not?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Sklyarov, 2019-01-24
@0example

Maybe someone will come in handy someday. I solved the problem like this:
In the created Notification, in the method that describes the methods of delivering the letter, I wrote the following:

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

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question