Download the PHP package mohammad-zarifiyan/laravel-telegram-bot without Composer
On this page you can find all versions of the php package mohammad-zarifiyan/laravel-telegram-bot. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download mohammad-zarifiyan/laravel-telegram-bot
More information about mohammad-zarifiyan/laravel-telegram-bot
Files in mohammad-zarifiyan/laravel-telegram-bot
Package laravel-telegram-bot
Short Description A Laravel package that helps you to easily create scalable Telegram bots and send notifications through Telegram.
License
Informations about the package laravel-telegram-bot
Introduction
This package helps you to easily use the Telegram Bot API in your Laravel project and utilize its features to build a great Telegram bot.
Please read The Telegram API documentation to gain dipper understanding about how to work with this package.
Installation
To install the package in your project, run the following command in your project root folder:
Basic configuration
If you would like to publish the configuration file, run the following command (optional):
Configure API Key
To use Telegram bots, you must have an API key. Obtain your API key via @BotFather. Then, set your bot's API key. By default, you should add the following code to the config/services.php file:
Then add TELEGRAM_API_KEY to your .env file.
Custom repository
If you want to obtain the API Key through another way, such as a database, you can create your own repository instead of the above method. Simple create a class and implement MohammadZarifiyan\Telegram\Interfaces\ApiKeyRepository in it. Then, in the telegram.php configuration file, set the value of api-key-repository to the address of your class.
Example
app/Repositories/TelegramApiKeyRepository.php file:
The telegram.php configuration file:
Configure Endpoint
You can use an arbitrary endpoint to send HTTP requests to it instead of the default endpoint of Telegram bots (api.telegram.org).
By default, you should add the following code to the config/services.php file.
Then add TELEGRAM_ENDPOINT to your .env file.
Custom repository
If you want to get the endpoint through another way, such as a database, you can create a repository for yourself instead of the above method. Just create a class and implement MohammadZarifiyan\Telegram\Interfaces\EndpointRepository in it. Then, in the telegram.php configuration file, set the value of endpoint-repository to the address of your class.
Example
app/Repositories/TelegramEndpointRepository.php file:
The telegram.php configuration file:
Verify TLS Certificate of the endpoint
You can also set your endpoint's tls certificate to be verified when you send a request to it. For this you can set TELEGRAM_VERIFY_ENDPOINT in your .env. It is recommended that the TELEGRAM_VERIFY_ENDPOINT value is always true.
The telegram.php configuration file:
Retry request
You can set the number of retries and the delay between each retry if the HTTP connection is lost.
The telegram.php configuration file:
Configure Proxy
To use a proxy while sending requests, you need to add the following code to the config/services.php file by default.
Then add TELEGRAM_PROXIES to your .env file.
You need to separate your list of proxies in the .env file with a comma (,). Look at the following example:
Custom repository
If you want to get the proxies through another way, such as a database, you can create a repository for yourself instead of the above method. Just create a class and implement MohammadZarifiyan\Telegram\Interfaces\ProxyRepository in it. Then, in the telegram.php configuration file, set the value of proxy-repository to the address of your class.
Example
app/Repositories/TelegramProxyRepository.php file:
The telegram.php configuration file:
Events
When a request is sent to the Telegram API via a proxy, the MohammadZarifiyan\Telegram\Events\ProxyUsed event is dispatched.
When sending request failed due to a proxy, the MohammadZarifiyan\Telegram\Events\ProxyFailed event is dispatched.
Submit request to Telegram
Use the perform method to send a request to the Telegram API. The first parameter is the method and the second parameter is the data you want to send to the Telegram API.
Note: See available Telegram methods at this link
Example
In the following example, Hello world is sent.
Events
The \MohammadZarifiyan\Telegram\Events\RequestSending event is dispatched just before a request is sent to the Telegram API, allowing you to perform actions or inspect the request before it leaves.
The \MohammadZarifiyan\Telegram\Events\ConnectionFailed event is triggered when there's an issue establishing a connection to the Telegram API.
The \MohammadZarifiyan\Telegram\Events\ResponseReceived event is triggered once a response from the Telegram API has been successfully received, indicating the completion of a request-response cycle.
Concurrent Requests
Sometimes, you may wish to make multiple HTTP requests concurrently. In other words, you want several requests to be dispatched at the same time instead of issuing the requests sequentially.
Thankfully, you may accomplish this using the concurrent method. The concurrent method accepts a closure which receives an MohammadZarifiyan\Telegram\PendingTelegramRequestStack instance, allowing you to easily add requests to the request pool for dispatching.
Example
In the example below, three messages are sent to the user simultaneously.
As you can see, each response instance is accessible based on the order in which it was added to the response collection. If you want, you can name the requests by giving the add method a name, which will allow you to access the corresponding responses by name.
Example
The add method returns an instance of MohammadZarifiyan\Telegram\PendingTelegramRequestBuilder, which provides a variety of methods that may be used to modify the request:
Send notification by Telegram bot
To send a notification via Telegram, define the routeNotificationForTelegram method on your notifiable model. This method should return an instance of MohammadZarifiyan\Telegram\TelegramRequestOptions, indicating how the notification should be delivered.
Return the telegram channel from your notification's via method.
Finally, add toTelegram to your notification class and use MohammadZarifiyan\Telegram\TelegramRequestContent to specify your Telegram notification data.
Example
In the example below, Hello is sent to all users.
The User.php file:
The HelloNotification.php file:
Reply Markup
If you want to add a reusable reply markup to your request payload, simply create a ReplyMarkup class. To create a ReplyMarkup class run the following command:
Example
The app\Telegram\ReplyMarkups\MyKeyboard.php file:
Here is the final code:
You can even use your ReplyMarkup class inside notifications using setReplyMarkup method.
Attachment
Use the MohammadZarifiyan\Telegram\Attachment class to attach a file stored on the server to the request.
Example
In the example below, The photo stored on the server will be sent in the chat.
Manipulating HTTP requests
Sometimes, you may want to manipulate HTTP request before sending it.
First, create a class and implement \MohammadZarifiyan\Telegram\Interfaces\PendingHttpRequest. Then, retrieve \MohammadZarifiyan\Telegram\Interfaces\PendingHttpRequest in its constructor.
Next, in the telegram.php configuration file, set the value of pending-http-request-manipulator to the address of your class.
You can then manipulate the request received in the constructor as needed.
The telegram.php configuration file:
The PendingHttpRequestManipulator.php file:
Generate file url
Use the generateFileUrl method to create a link for a file located on Telegram's servers.
Example
Parsing API Key
You can parse any Telegram API Key.
Use Telegram::parseApikey($apiKey) to get the botId and botTokenHash from any Telegram API Key. It returns a MohammadZarifiyan\Telegram\TelegramBotApiKey instance containing both values. Example:
Get bot ID
Use the getBotId method to get the ID of the bot whose API Key you set.
Example
The .env file:
Validate Telegram Login Widget (Authorization) data
Pass the data received from the Login Widget to the validateAuthorizationData method. If the data is valid, it will return true; otherwise, it will return false.
Example
The routes/web.php file:
The app\Models\User.php file:
Validate WebApp InitData
There are two ways to verify WebApp data.
Validating data for First-Party Use
If you want to validate the WebApp initData for the bot whose API you have configured, pass the initData to the validateWebAppInitData method. This method validates the initData using the configured bot token.
It returns true if the data is valid, and false otherwise.
Validating data for Third-Party Use
If you want to validate the WebApp initData of another bot, or a bot whose API key you do not have, use the Telegram::validateWebAppSignature. This method validates the data without requiring an API key, using only the Telegram bot ID and Telegram’s public key hex.
Note that the public key HEX must be set in your config/services.php file.
You can find the public key HEX at this link.
The config/services.php file:
Then add TELEGRAM_PUBLIC_KEY_HEX to your .env file.
Configure Secret Token
It is strongly recommend to set a secret token for your bot to make sure that the updates are sent by Telegram webhook.
By default, you should add the following code to the config/services.php file.
Then add TELEGRAM_SECRET_TOKEN to your .env file.
Note: Only characters A-Z, a-z, 0-9, _ and - are allowed.
Note: After changing the secret token, you must set your bot's webhook again.
Custom repository
If you want to get the secret token through another way, such as a database, you can create a repository for yourself instead of the above method. Just create a class and implement MohammadZarifiyan\Telegram\Interfaces\SecretTokenRepository in it. Then, in the telegram.php configuration file, set the value of secret-token-repository to the address of your class.
Example
app/Repositories/TelegramSecretTokenRepository.php file:
The telegram.php configuration file:
Handling updates
Handling an update can happen in different steps depending on your needs. This method makes you able to implement all kinds of capabilities you need without considering the obstacles.
Start handling
After creating a route, handles request using the handleRequest method. You can also store requests in database and handle them later.
Example
The api.php file:
Middlewares
If you want to run some codes to modify the processing update or prevent processing it, you can use a Telegram middleware.
Telegram middlewares run before Command Handler and Breakers, If a Middleware returns anything other than an instance of MohammadZarifiyan\Telegram\Update, an instance of MohammadZarifiyan\Telegram\TelegramMiddlewareFailedException will be thrown and processing of the Telegram update will stop.
The method that is called in the Telegram middleware is based on the type of Telegram update that is being processed.
For example, if the update type is callback_query, the method called will be handleCallbackQuery.
If there is no specific method for handling the Telegram update based on its type, a method named handle is called in the Telegram middleware.
Both handle and handleCallbackQuery will receive an instance of MohammadZarifiyan\Telegram\Update as the first argument.
Note that handleCallbackQuery is used as an example, and the method name will vary with different Telegram updates based on the update type.
To generate a new Telegram middleware, run the following command.
You should add your Telegram middleware in telegram.php configuration file.
Telegram middlewares will be executed in the same order as you place them in the telegram.php configuration file.
Command handler
The commands that users send to your bot must be handled by a Command Handler.
The Telegram Command handler will run after all Telegram middlewares have run successfully.
If no Command handler is found for the command the user submitted, an instance of MohammadZarifiyan\Telegram\TelegramCommandNotFoundException is thrown.
You can disable throwing exceptions by setting allow-incognito-command to true in the telegram.php configuration file.
Additionally, you can check with $update->isCommand() whether the Telegram update was created due to a bot command or not.
To generate a new Command handler, run the following command.
You should add your Telegram Command handler to the telegram.php configuration file.
A command handler must implement the MohammadZarifiyan\Telegram\Interfaces\CommandHandler interface and will look like this:
The getSignature method must return the name of the command or commands that the handle method can handle.
Every Command Handler should return MohammadZarifiyan\Telegram\Enums\Signal. If it returns Signal::Exit, update processing stops; If the Command Handler returns Signal::Continue, the next Command Handlers will be executed.
Sometimes a Telegram update comes with a command parameter.
You can access Telegram bot command data by calling the toCommand method. Then, you will receive an instance of MohammadZarifiyan\Telegram\Command.
For example, if your Telegram bot username is MyAwesomeBot, then you can add a parameter to your /start command:
https://t.me/MyAwesomeBot?start=abc
Anonymous command handler
Sometimes you may want to create a command handler without specifying the signature. This feature is mostly used for commands that are case-insensitive or commands with dynamic signature. For this purpose, you can create a class and implement MohammadZarifiyan\Telegram\Interfaces\AnonymousCommandHandler in it. Then add the address of your class to command_handlers in the telegram.php configuration file.
In anonymous command handlers, there is a matchesSignature method, in which you should check the command match.
Breaker
If the Update is not handled by a CommandHandler, it continues its path and reaches the Breakers. A Breaker is a class that can handle the request based on its type, but unlike Telegram Middlewares, it cannot modify the update.
The method that is called when a Breaker is executed is exactly like a Telegram middleware.
Every Breaker should return MohammadZarifiyan\Telegram\Enums\Signal. If it returns Signal::Exit, update processing stops; If the breaker returns Signal::Continue, the next breakers will be executed.
Note that having too many Telegram Middlewares and Breakers can reduce the performance of your Telegram bot.
To generate a new Breaker, run the following command.
You should add your Telegram Breaker to the telegram.php configuration file.
Example
In the example below, we handle all callback query updates related to an inline button to cancel sending notifications to all users.
Gainer
You may want to access something like Illuminate\Support\Facades\Request::user() in your application to interact with the database regarding the current update. This functionality is provided for you in this package. Simply create a class called GainerResolver in app/Telegram and implement the MohammadZarifiyan\Telegram\Interfaces\GainerResolver interface in it. Then set the name of the class you created in the telegram.php configuration file.
The telegram.php configuration file:
By using $update->gainer(), you can access the value returned by the handle method in GainerResolver.php throughout your application.
Example
The app/Models/User.php file:
The app/Telegram/GainerResolver.php file:
Stage
Some bots have an interactive mode where they allow users to access new features upon receiving a new Telegram update. For example, when a user clicks a button on the keyboard, a new set of buttons is displayed, which the user can interact with only after clicking the initial button. This feature is commonly seen in bots that guide users through stages of information gathering. To implement this, you need to save a stage that checks the user's next update, so that when the next update arrives, the corresponding stage code executes. Fortunately, this package simplifies this process significantly. The Stage class has methods similar to those in Middleware and Breaker classes. These methods handle bot updates; for instance, the handleMessage method manages updates triggered by sending messages in the bot's chat. To utilize this feature, define a model for your Gainer, add a stage column to your database table, and store the fully qualified class name that should handle the next update in the stage column. Finally, implement the MohammadZarifiyan\Telegram\Interfaces\Gainer interface in your Gainer model.
To create a stage, run the following command:
The above command creates a file in the path app/Telegram/Stages.
Validation and authorization of updates
You can validate updates in the update handler methods within the stage. Update validation works similar to FormRequest in Laravel. To validate updates, you must create a class that extends MohammadZarifiyan\Telegram\FormUpdate and use it as the first parameter in the update handler method within the stage class. If validation fails, an exception of type MohammadZarifiyan\Telegram\Exceptions\TelegramValidationException is thrown. You can catch TelegramValidationException in the app/Exceptions/Handler.php file and send validation errors to the user.
You can also use the authorize method. If the output of this method is false, an exception of type MohammadZarifiyan\Telegram\Exceptions\TelegramAuthorizationException will be thrown. You can catch TelegramAuthorizationException in the app/Exceptions/Handler.php file and send an authorization error to the user.
Run the following command to create a new update:
This command creates a file at the path app/Telegram/Updates.
Example
In the following example, the bot asks the user for their age, expecting a number between 1 and 100. If the user sends anything other than this number, the bot will respond with a validation error message.
Users migration:
The app\Models\User.php file:
App\Telegram\Stages\Age.php file:
The app\Telegram\Updates\AgeUpdate.php file:
Creating Random Telegram Bot API Keys
Using the telegramBotApiKey() method, you can easily generate a random Telegram Bot API Key. For example:
This method returns an instance of the MohammadZarifiyan\Telegram\TelegramBotApiKey class, containing both the botId and botTokenHash.
Mocking
This package provides similar methods to Laravel Http to assist you in testing interactions with the Telegram API by faking its behavior. This approach allows you to simulate responses and assert expected calls without making actual network requests.
The MohammadZarifiyan\Telegram\Facades\Telegram class provides several methods to control and verify interactions.
To begin faking the Telegram service, you can use the fake method. This method allows you to optionally provide a promise, an array of promises, or a promise to define the behavior of the fake service.
You can define the response that your are expecting from the Telegram::perform(...) by giving an instance of MohammadZarifiyan\Telegram\Promise to Telegram::fake().
For example:
So you can use the following methods to test your Telegram bot.
All versions of laravel-telegram-bot with dependencies
laravel/framework Version >=7
guzzlehttp/guzzle Version >=5
ext-curl Version *
ext-sodium Version *