TeleBot - Easy way to create Telegram-bots in PHP. Rich Laravel support out of the box.

Overview

Project Logo

Latest Stable Version Bot API Version Build Status Coverage Status Code quality Total Downloads License

TeleBot is a PHP library for telegram bots development. Rich Laravel support out of the box. Has an easy, clean, and extendable way to handle telegram Updates.

Documentation

Documentation for the library can be found on the website.

Features

Bot Manager

Work easily with multiple bots using BotManager:

$manager->getMe(); // Fired by default bot specified in BotManager
$manager->bot('bot2')->getMe(); // Fired by `bot2` specified in BotManager

Laravel Support

Library provides a Facade, artisan commands and notification channel to simplify the development process of your bot, if you are using Laravel:

Facade
TeleBot::getMe();
TeleBot::bot('bot2')->getMe(); 
Automatic webhook generation

After you insert your bot token, to create a webhook you need only to fire the following command:

$ php artisan telebot:webhook --setup

Route for handling updates is generated automaticaly for your APP_URL

Long polling

If you are not using webhook, or want to use bot in local or test environment, you may start long polling by only firyng this command:

$ php artisan telebot:polling
Setup commands autocompletion

The following command will automaticaly setup autocompletion for all registered bot commands on Telegram servers:

$ php artisan telebot:commands --setup
Notification channel


namespace App\Notifications;

use Illuminate\Notifications\Notification;
use WeStacks\TeleBot\Laravel\TelegramNotification;

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

    public function toTelegram($notifiable)
    {
        return (new TelegramNotification)->bot('bot')
            ->sendMessage([
                'chat_id' => $notifiable->telegram_chat_id,
                'text'    => 'Hello, from Laravel\'s notifications!'
            ])
            ->sendMessage([
                'chat_id' => $notifiable->telegram_chat_id,
                'text'    => 'Second message'
            ]);
    }
}
Log driver

You may log your application errors by sending them to some Telegram chat. Simply add new log driver to a config/logging.php:

'telegram' => [
    'driver'    => 'custom',
    'via'       => \WeStacks\TeleBot\Laravel\Log\TelegramLogger::class,
    'level'     => 'debug',
    'bot'       => 'bot',
    'chat_id'   => env('TELEGRAM_LOG_CHAT_ID') // Any chat where bot can write messages.
]

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Credits

Dontations

Support this project by sending us a tip.

Currency Wallet
BTC bc1qfqn93hczerczjj76kcn62nv0c5kt2xqar355g7
ETH 0xf3762Fdaf4dC0FD623433070F34c2eDC5224724b
BCH qz23y9vjn8xzgz5j9ztllv6pxflal4p94s87e47edc
LTC ltc1qu9pdvvh4u5z6a97mevhnueszcu6m5zmx2lsplp

License

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

Comments
  • php artisan telebot:webhook issue

    php artisan telebot:webhook issue

    Hi,

    I cant seem to get the webhook artisan command to work.. I can get the help command for it but it fails to execute no matter the options I try!

    The error is more or less the same each time:

       WeStacks\TeleBot\Exception\TeleBotRequestException
    
      Not Found
    
      at vendor/westacks/telebot/src/Exception/TeleBotRequestException.php:17
         13▕             $parameters = ResponseParameters::create($result->parameters ?? null);
         14▕             $text .= '; Parameters: '.$parameters;
         15▕         }
         16▕
      ➜  17▕         return new TeleBotRequestException($text, $result->error_code);
         18▕     }
         19▕ }
         20▕
    
          +30 vendor frames
      31  artisan:37
          Illuminate\Foundation\Console\Kernel::handle()
    

    Any help appreciated! :)

    documentation enhancement good first issue question 
    opened by JTD420 14
  • Registering commands; Check command bot name using regexp

    Registering commands; Check command bot name using regexp

    Could you write an example like "Creating command" for "Registering commands", please? I don't understand where I should write this code.

    Screenshot 2021-02-12 at 16 36 09 bug documentation good first issue 
    opened by IgorPr 7
  • [Cannot cast value of type NULL to type string error in Inline mode]

    [Cannot cast value of type NULL to type string error in Inline mode]

    Describe the bug Hello, The library does not support Inline mode and I tested it with a simple bot and got Cannot cast value of type NULL to type string error in log channel

    To Reproduce Steps to reproduce the behavior:

    1.Turn on Inline mode in BotFather 2.use Inline mode : @bot_username some_thing

    Then you will receive the following error in log channel if you add it: Laravel ERROR (local): Cannot cast value of type NULL to type string {"exception":"[object] (WeStacks\\TeleBot\\Exceptions\\TeleBotException(code: 0): Cannot cast value of type NULL to type string at /var/www/vendor/westacks/telebot/src/Helpers/Type.php:96)"} []

    Additional context The first time I encountered this problem was September 3. on September 2nd you released version 2.2.2 but I installed earlier versions and it still didn't work.

    bug duplicate 
    opened by DyarWeb 6
  • Handle Throwable

    Handle Throwable

    Очень нубский вопрос. Можно ли как то перехватить TelegramRequestException для всех уже существующих хендлеров.

    Дописывать в каждом хендлере try..catch совсем не комильфо. Как лучше перегрузить или переопределить и какой именно класс

    question 
    opened by bosskokoss 5
  • Error Handling

    Error Handling

    Hi,

    The exceptions property is set to true but I still cannot handle the error because no error was thrown but only logged. image

    On my investigation, the telegram notification channel is just handling the error and logging a warning on send, then returns a null image

    To share, what I'd like to do why I wanted to catch an errors is because I wanted to remove the registered telegram ID of a user if I get a request exception that contains "user deactivated" or "bot was blocked"

    enhancement 
    opened by FallenKnight85 4
  • ErrorException  Use of undefined constant SIGINT - assumed 'SIGINT'

    ErrorException Use of undefined constant SIGINT - assumed 'SIGINT'

    php artisan telebot:polling
    
       ErrorException 
    
      Use of undefined constant SIGINT - assumed 'SIGINT' (this will throw an Error in a future version of PHP)
    
      at *******\vendor\westacks\telebot\src\Laravel\Artisan\LongPollCommad.php:72
         68▕     }
    
    
    php -v
    
    PHP 7.4.4 (cli) (built: Mar 17 2020 13:49:19) ( ZTS Visual C++ 2017 x64 )
    Copyright (c) The PHP Group
    Zend Engine v3.4.0, Copyright (c) Zend Technologies
    
    "require": {
            "php": "^7.3|^8.0",
            "fruitcake/laravel-cors": "^2.0",
            "guzzlehttp/guzzle": "^7.0.1",
            "laravel/framework": "^8.75",
            "laravel/sanctum": "^2.11",
            "laravel/tinker": "^2.5",
            "westacks/telebot": "^1.14"
        },
    

    p.s. "westacks/telebot": "1.13.0" - OK version > 1.13.0 - error

    bug 
    opened by kagatan 4
  • $bot->answerInlineQuery

    $bot->answerInlineQuery

    Hi. I can't send answerInlineQuery I got from Telegram this error: Bad Request: can't parse inline query result: Can't find field "message_text"

    Here is the code. What wrong I do? I cant understand.

    if ($update->callback_query) {
        $callback_query_id = $update->callback_query->id;
        $results = [[
            'type' => 'article',
            'id' => '001',
            'title' => 'Test',
            'message_text' => 'Text of the first message'
        ]];
        $message = $bot->answerInlineQuery([
            'inline_query_id' => $callback_query_id,
            'results' => $results
        ]);
    }
    

    Please help. Thank you.

    question 
    opened by kamuzon 4
  • How to access to config data related to Bot update

    How to access to config data related to Bot update

    It's there a way to access to local config data in an update handler? When an update is received, how I know the related bot?. I can get Telegram bot info, but I don't know how to get local config info. Perhaps new methods in TeleBot class?

    enhancement good first issue question 
    opened by rsimonru 4
  • Cannot cast value of type NULL to type string in Inline mode

    Cannot cast value of type NULL to type string in Inline mode

    Hello, The library does not support Inline mode and I tested it with a simple bot and got Cannot cast value of type NULL to type string error in log channel

    wontfix 
    opened by DyarWeb 3
  • Problem in istallation

    Problem in istallation

    Laravel Framework 9.0.2 PHP 8.0.6 & PHP 7.4.9

    composer require westacks/telebot

    Output:

    Problem 1 - Root composer.json requires laravel/framework ^9.0, found laravel/framework[v9.0.0-beta.1, ..., 9.x-dev] but the package is fixed to v8.81.0 (lock file version) by a partial update and that version does not match. Make sure yo u list it as an argument for the update command. Problem 2 - Root composer.json requires nunomaduro/collision ^6.1, found nunomaduro/collision[v6.1.0] but the package is fixed to v5.11.0 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command.

    Use the option --with-all-dependencies (-W) to allow upgrades, downgrades and removals for packages currently locked to specific versions.

    When using composer require westacks/telebot -W

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

    Problem 1 - Root composer.json requires laravel/framework ^9.0, found laravel/framework[v9.0.0-beta.1, ..., 9.x-dev] but these were not loaded, likely because it conflicts with another require. Problem 2 - Root composer.json requires nunomaduro/collision ^6.1, found nunomaduro/collision[v6.1.0] but the package is fixed to v5.11.0 (lock file version) by a partial update and that version does not match. Make sure you list it as an argument for the update command. Problem 3 - laravel/sanctum is locked to version v2.14.0 and an update of this package was not requested. - laravel/sanctum v2.14.0 requires illuminate/database ^6.9|^7.0|^8.0|^9.0 -> found illuminate/database[v6.10.0, ..., 6.x-dev, v7.0.0, ..., 7.x-dev, v8.0.0, ..., 8.x-dev, v9.0.0-beta.1, ..., 9.x-dev] but these were not loaded, l ikely because it conflicts with another require. Problem 4 - laravel/tinker is locked to version v2.7.0 and an update of this package was not requested. - laravel/tinker v2.7.0 requires illuminate/console ^6.0|^7.0|^8.0|^9.0 -> found illuminate/console[v6.0.0, ..., 6.x-dev, v7.0.0, ..., 7.x-dev, v8.0.0, ..., 8.x-dev, v9.0.0-beta.1, ..., 9.x-dev] but these were not loaded, likely because it conflicts with another require. Problem 5 - laravel/sail is locked to version v1.13.1 and an update of this package was not requested. - laravel/sail v1.13.1 requires illuminate/console ^8.0|^9.0 -> found illuminate/console[v8.0.0, ..., 8.x-dev, v9.0.0-beta.1, ..., 9.x-dev] but these were not loaded, likely because it conflicts with another require.

    Installation failed, reverting ./composer.json and ./composer.lock to their original content.

    opened by ynaderi1959 3
  • Tests are failing when using handleUpdate() in loop

    Tests are failing when using handleUpdate() in loop

    Hello!

    I was writing tests for my application, and noticed that some tests are failing if i use $bot->handleUpdate() in a loop. The exception message was Not Found, so it seems that after first iteration bot is not considered fake anymore. This only occures in loops and only if i need to send something through bot : message, photo, location, etc.

    Here is an code example :

    public function testIssueExample(): void
        {
            $bot = LaravelWrapper::bot()->fake(); // LaravelWrapper is a Facade for Laravel
            $bot->clearHandlers();
            $bot->addHandler(
                [
                    function (TeleBot $bot, Update $update, $next) {
                        return $bot->sendMessage(
                            [
                                'chat_id' => -1,
                                'text'    => $update->message->text,
                            ]
                        );
                    },
                ]
            );
    
            $messages = ['random', 'text'];
    
            foreach ($messages as $message) {
                $update   = Update::create(
                    [
                        'message' => [
                            'chat' => [
                                'id' => -1,
                            ],
                            'text' => $message,
                        ],
                    ]
                );
                // On second iteration will try to send message like a real bot and will fail test
                $response = $bot->handleUpdate($update);
                $this->assertEquals($response->text, $message);
            }
        }
    

    If you dump bot on each iteration, you can see that on first iteration bot fake property will be set to true :

    WeStacks\TeleBot\TeleBot^ { 
       // ommited config and other properties
       +"fake": true
    }
    

    And on the second iteration and further it will be set to null :

    WeStacks\TeleBot\TeleBot^ { 
       // ommited config and other properties
       +"fake": null
    }
    

    So to make my tests work i need to manually call fake() on each iteration :

    public function testIssueExample(): void
        {
            $bot = LaravelWrapper::bot()->fake(); // LaravelWrapper is a Facade for Laravel
            $bot->clearHandlers();
            $bot->addHandler(
                [
                    function (TeleBot $bot, Update $update, $next) {
                        return $bot->sendMessage(
                            [
                                'chat_id' => -1,
                                'text'    => $update->message->text,
                            ]
                        );
                    },
                ]
            );
    
            $messages = ['random', 'text'];
    
            foreach ($messages as $message) {
                $update   = Update::create(
                    [
                        'message' => [
                            'chat' => [
                                'id' => -1,
                            ],
                            'text' => $message,
                        ],
                    ]
                );
    	     // Will pass
                $response = $bot->fake()->handleUpdate($update);
                $this->assertEquals($response->text, $message);
            }
        }
    

    I've investigated a bit more and i think problem can be in this lines of code : https://github.com/westacks/telebot/blob/master/src/TeleBot.php#L101-L103.

    Can this be fixed somehow or is it intentional behaviour?

    I would also like to thank you for all your hard work with this library, it made my development so much easier and fast :heart_eyes: :heart_eyes:

    opened by VampireAotD 2
  • Testing support

    Testing support

    Discussed in https://github.com/westacks/telebot/discussions/27

    Originally posted by roelofr September 21, 2021 Hey there,

    I just discovered this package via my GitHub homepage (I didn't know it did that).

    It looks great, but I'm seeing no docs on testing from an end-user perspective (which is something a lot of Telegram bot packages don't have).

    What would be the best way to test this, I'd be glad to help.

    enhancement good first issue 
    opened by punyflash 2
Releases(2.3.0)
Owner
WeStacks
The devoted artisans
WeStacks
Create modern Telegram Bots with PHP.

Telepath Create Telegram Bots with this modern PHP library Explore the docs » Report Bug · Request Feature Table of Contents About The Project Before

Telepath 5 Nov 7, 2022
Telegraph - a Laravel package for fluently interaction with Telegram Bots

Telegraph - a Laravel package for fluently interaction with Telegram Bots

def:studio 412 Dec 30, 2022
SDK for latest version of Telegram bots API

SDK for latest version of Telegram bots API (from April 24, 2020) Using Examples Installing composer require "DiyorbekUz/Telelib: dev-master" Init bot

Diyorbek 2 Sep 5, 2021
PHP Telegram Bot based on the official Telegram Bot API with iTelegram Class.

iTelegram PHP Telegram Bot based on the official Telegram Bot API Bots: An introduction for developers Bots are special Telegram accounts designed to

iNeoTeam | آی نئو 5 Nov 9, 2022
PHP Telegram Bot based on the official Telegram Bot API

PHP Telegram Bot based on the official Telegram Bot API

null 4 Dec 8, 2021
Robot increase telegram post 👁‍🗨Telegram Fake Posts Viewer👁‍🗨

Program Features - ?? Very and stylish design. - ?? It has glass buttons. - ?? Has a professional management panel. - ?? Has a user area. - ?? Free di

hack4lx 4 Nov 25, 2022
A framework agnostic PHP library to build chat bots

BotMan If you want to learn how to create reusable PHP packages yourself, take a look at my upcoming PHP Package Development video course. About BotMa

BotMan 5.8k Jan 3, 2023
The best PHP library for VK Users Longpoll Api (Page Bots).

vk-page-bot-lib Description: There are 2 commands and a logger. There is a logger of new messages and a logger that a friend has entered/left in/from

KirillChimbur 6 Jul 25, 2022
A discord-feature rich API plugin for PMMP.

DiscordBot DiscordBot a core plugin that provides an extensive API for plugins to interact with a discord bot creating endless possibilities. Examples

null 2 Jan 9, 2022
Create and manage advanced polls with this Telegram Bot which has many features available!

MasterPollBot Create and manage advanced polls with this Telegram Bot which has many features available! Requirements Local Telegram Bot API or a webh

NeleB54Gold 7 Oct 21, 2022
Easy to install email tracker with gui and telegram api bot with date device & ip tracking,

mail-php-tracking-with-gui ?? Simple mail tracking program that uses php, html, telegram bot, and a gui The gui The gui lets you create specific links

null 7 Dec 20, 2022
Implementation of a library to process SISP vinti4 payment in a easy way.

Implementation of a library to process SISP vinti4 payment in a easy way.

Faxi 6 Nov 3, 2022
laravel package untuk memudahkan penggunaan MCA dengan Telegram Bot USDI di aplikasi Universitas Udayana.

MCA KubeMQ Laravel laravel package untuk memudahkan penggunaan MCA dengan Telegram Bot USDI di aplikasi Universitas Udayana. Motivasi Proyek ini berfu

Ristek USDI 1 Nov 17, 2021
A telegram bot to check credit cards. written in php & py

MRBANKER BOT A telegram bot to check credit cards. written in php & py. You can find me on telegram STEP1: goto botfather create a bot copy the token

Nitin1818 48 Dec 30, 2022
NovaGram - An elegant, Object-Oriented, reliable PHP Telegram Bot Library

An elegant, Object-Oriented, reliable PHP Telegram Bot Library Full Documentation • Public support group Examples • Features • Installation ?

Gaetano 165 Jan 6, 2023
Telegram API made for php (Simple usage)

Telegram Telegram API made for php (Simple usage) How to use? Download the project & place Telegram folder tp your project directory (For example i se

null 0 Apr 4, 2022
Integrate Your PHP Code With Telegram Bot API for Beginner

Documentation[https://core.telegram.org/bots/api] Resource[https://github.com/bachors/KBBI.sql] Integrate Your PHP Code With Telegram Bot API for Begi

Nova Andre Saputra 1 Oct 19, 2021
Simple telegram auto reminder BOT with PHP

Telebot Script Telegram BOT Auto Reminder Dibuat pake PHP OOP Sebenernya bukan buat dipublish sih, ini cuma buat praktek PHP OOP sama praktek Commit &

its Galih 4 Nov 7, 2022
Simple php telegram bot.

PHPTGBot Description Simple php telegram bot. Just for fun ?? Work In Progress ?? Maybe found error, since im not tested yet! Still on working, so be

Yoga Pranata 2 Nov 24, 2021