PHP Telegram Bot
, (*1)
, (*2)
A Telegram Bot based on the official Telegram Bot API, (*3)
Table of Contents
Introduction
This is a pure PHP Telegram Bot, fully extensible via plugins.
Telegram recently announced official support for a Bot
API allowing integrators of
all sorts to bring automated interactions to the mobile platform. This
Bot aims to provide a platform where one can simply write a plugin
and have interactions in a matter of minutes., (*4)
The Bot can:
- retrieve updates with webhook and getUpdates methods.
- supports all types and methods according to Telegram API (25 May 2016).
- supports supergroups.
- handle commands in chat with other bots.
- manage Channel from the bot admin interface.
- full support for inline bots.
- inline keyboard.
- Messages, InlineQuery and ChosenInlineQuery are stored in the Database.
- Botan.io integration and database cache system. (new!)
- Conversation feature, (*5)
This code is available on
Github. Pull requests are welcome., (*6)
Instructions
Create your first bot
-
Message @botfather https://telegram.me/botfather with the following
text: /newbot
If you don't know how to message by username, click the search
field on your Telegram app and type @botfather, where you should be able
to initiate a conversation. Be careful not to send it to the wrong
contact, because some users has similar usernames to botfather., (*7)
, (*8)
-
@botfather replies with Alright, a new bot. How are we going to
call it? Please choose a name for your bot., (*9)
-
Type whatever name you want for your bot., (*10)
-
@botfather replies with Good. Now let's choose a username for your
bot. It must end in `bot`. Like this, for example: TetrisBot or
tetris_bot., (*11)
-
Type whatever username you want for your bot, minimum 5 characters,
and must end with bot. For example: telesample_bot, (*12)
-
@botfather replies with:, (*13)
Done! Congratulations on your new bot. You will find it at
telegram.me/telesample_bot. You can now add a description, about
section and profile picture for your bot, see /help for a list of
commands.
Use this token to access the HTTP API:
123456789:AAG90e14-0f8-40183D-18491dDE
For a description of the Bot API, see this page:
https://core.telegram.org/bots/api
-
Note down the 'token' mentioned above., (*14)
-
Type /setprivacy to @botfather., (*15)
, (*16)
-
@botfather replies with Choose a bot to change group messages settings., (*17)
-
Type (or select) @telesample_bot (change to the username you set at step 5
above, but start it with @), (*18)
-
@botfather replies with, (*19)
'Enable' - your bot will only receive messages that either start with the '/' symbol or mention the bot by username.
'Disable' - your bot will receive all messages that people send to groups.
Current status is: ENABLED
-
Type (or select) Disable to let your bot receive all messages sent to a
group. This step is up to you actually., (*20)
-
@botfather replies with Success! The new status is: DISABLED. /help, (*21)
Require this package with Composer
Install this package through Composer.
Edit your project's composer.json file to require longman/telegram-bot., (*22)
Create composer.json file, (*23)
{
"name": "yourproject/yourproject",
"type": "project",
"require": {
"php": ">=5.5",
"longman/telegram-bot": "*"
}
}
and run composer update, (*24)
or, (*25)
run this command in your command line:, (*26)
composer require longman/telegram-bot
Choose how to retrieve Telegram updates
The bot can handle updates with Webhook or getUpdates method:, (*27)
|
Webhook |
getUpdates |
| Description |
Telegram sends the updates directly to your host |
You have to fetch Telegram updates manually |
| Host with https |
Required |
Not required |
| MySQL |
Not required |
Required |
Webhook installation
Note: For a more detailed explanation, head over to the example-bot repository and follow the instructions there., (*28)
In order to set a Webhook you need a server with HTTPS and composer support.
(For a self signed certificate you need to add some extra code), (*29)
Create set.php with the following contents:, (*30)
<?php
// Load composer
require __DIR__ . '/vendor/autoload.php';
$bot_api_key = 'your:bot_api_key';
$bot_username = 'username_bot';
$hook_url = 'https://your-domain/path/to/hook.php';
try {
// Create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username);
// Set webhook
$result = $telegram->setWebhook($hook_url);
if ($result->isOk()) {
echo $result->getDescription();
}
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
// log telegram errors
// echo $e->getMessage();
}
Open your set.php via the browser to register the webhook with Telegram.
You should see Webhook was set., (*31)
Now, create hook.php with the following contents:, (*32)
<?php
// Load composer
require __DIR__ . '/vendor/autoload.php';
$bot_api_key = 'your:bot_api_key';
$bot_username = 'username_bot';
try {
// Create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username);
// Handle telegram webhook request
$telegram->handle();
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
// Silence is golden!
// log telegram errors
// echo $e->getMessage();
}
Self Signed Certificate
To upload the certificate, add the certificate path as a parameter in set.php:, (*33)
$result = $telegram->setWebhook($hook_url, ['certificate' => '/path/to/certificate']);
Unset Webhook
Edit unset.php with your bot credentials and execute it., (*34)
getUpdates installation
The MySQL database must be enabled for the getUpdates method!, (*35)
Create getUpdatesCLI.php with the following contents:, (*36)
#!/usr/bin/env php
<?php
require __DIR__ . '/vendor/autoload.php';
$bot_api_key = 'your:bot_api_key';
$bot_username = 'username_bot';
$mysql_credentials = [
'host' => 'localhost',
'user' => 'dbuser',
'password' => 'dbpass',
'database' => 'dbname',
];
try {
// Create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($bot_api_key, $bot_username);
// Enable MySQL
$telegram->enableMySql($mysql_credentials);
// Handle telegram getUpdates request
$telegram->handleGetUpdates();
} catch (Longman\TelegramBot\Exception\TelegramException $e) {
// log telegram errors
// echo $e->getMessage();
}
Next, give the file permission to execute:, (*37)
$ chmod +x getUpdatesCLI.php
Lastly, run it!, (*38)
$ ./getUpdatesCLI.php
Support
Types
All types are implemented according to Telegram API (20 January 2016)., (*39)
Inline Query
Full support for inline query according to Telegram API (20 January 2016)., (*40)
Methods
All methods are implemented according to Telegram API (20 January 2016)., (*41)
Send Message
Messages longer than 4096 characters are split up into multiple messages., (*42)
$result = Request::sendMessage(['chat_id' => $chat_id, 'text' => 'Your utf8 text 😜 ...']);
Send Photo
To send a local photo, add it properly to the $data parameter using the file path:, (*43)
$data = [
'chat_id' => $chat_id,
'photo' => Request::encodeFile('/path/to/pic.jpg'),
];
$result = Request::sendPhoto($data);
If you know the file_id of a previously uploaded file, just use it directly in the data array:, (*44)
$data = [
'chat_id' => $chat_id,
'photo' => $file_id,
];
$result = Request::sendPhoto($data);
To send a remote photo, use the direct URL instead:, (*45)
$data = [
'chat_id' => $chat_id,
'photo' => 'https://example.com/path/to/pic.jpg',
];
$result = Request::sendPhoto($data);
sendAudio, sendDocument, sendSticker, sendVideo, sendVoice and sendVideoNote all work in the same way, just check the API documentation for the exact usage.
See the ImageCommand.php for a full example., (*46)
Send Chat Action
Request::sendChatAction(['chat_id' => $chat_id, 'action' => 'typing']);
getUserProfilePhoto
Retrieve the user photo, see WhoamiCommand.php for a full example., (*47)
getFile and downloadFile
Get the file path and download it, see WhoamiCommand.php for a full example., (*48)
Send message to all active chats
To do this you have to enable the MySQL connection.
Here's an example of use (check DB::selectChats() for parameter usage):, (*49)
$results = Request::sendToActiveChats(
'sendMessage', // Callback function to execute (see Request.php methods)
['text' => 'Hey! Check out the new features!!'], // Param to evaluate the request
[
'groups' => true,
'supergroups' => true,
'channels' => false,
'users' => true,
]
);
You can also broadcast a message to users, from the private chat with your bot. Take a look at the admin commands below., (*50)
Utils
MySQL storage (Recommended)
If you want to save messages/users/chats for further usage in commands, create a new database (utf8mb4_unicode_520_ci), import structure.sql and enable MySQL support after object creation and BEFORE handle() method:, (*51)
$mysql_credentials = [
'host' => 'localhost',
'user' => 'dbuser',
'password' => 'dbpass',
'database' => 'dbname',
];
$telegram->enableMySql($mysql_credentials);
You can set a custom prefix to all the tables while you are enabling MySQL:, (*52)
$telegram->enableMySql($mysql_credentials, $bot_username . '_');
You can also store inline query and chosen inline query data in the database., (*53)
External Database connection
It is possible to provide the library with an external MySQL PDO connection.
Here's how to configure it:, (*54)
$telegram->enableExternalMySql($external_pdo_connection)
//$telegram->enableExternalMySql($external_pdo_connection, $table_prefix)
Channels Support
All methods implemented can be used to manage channels.
With admin commands you can manage your channels directly with your bot private chat., (*55)
Botan.io integration (Optional)
You can enable the integration using this line in you hook.php:, (*56)
$telegram->enableBotan('your_token');
Replace your_token with your Botan.io token, check this page to see how to obtain one., (*57)
The following actions will be tracked:
- Commands (shown as Command (/command_name) in the stats
- Inline Queries, Chosen Inline Results and Callback Queries
- Messages sent to the bot (or replies in groups), (*58)
In order to use the URL shortener you must include the class use Longman\TelegramBot\Botan; and call it like this:, (*59)
Botan::shortenUrl('https://github.com/php-telegram-bot/core', $user_id);
Shortened URLs are cached in the database (if MySQL storage is enabled)., (*60)
Commands
Predefined Commands
The bot is able to recognise commands in a chat with multiple bots (/command@mybot)., (*61)
It can execute commands that get triggered by chat events., (*62)
Here's the list:, (*63)
-
StartCommand.php (A new user starts to use the bot.)
-
NewChatMembersCommand.php (A new member(s) was added to the group, information about them.)
-
LeftChatMemberCommand.php (A member was removed from the group, information about them.)
-
NewChatTitleCommand.php (A chat title was changed to this value.)
-
NewChatPhotoCommand.php (A chat photo was changed to this value.)
-
DeleteChatPhotoCommand.php (Service message: the chat photo was deleted.)
-
GroupChatCreatedCommand.php (Service message: the group has been created.)
-
SupergroupChatCreatedCommand.php (Service message: the supergroup has been created.)
-
ChannelChatCreatedCommand.php (Service message: the channel has been created.)
-
MigrateToChatIdCommand.php (The group has been migrated to a supergroup with the specified identifier.)
-
MigrateFromChatIdCommand.php (The supergroup has been migrated from a group with the specified identifier.)
-
PinnedMessageCommand.php (Specified message was pinned.), (*64)
-
GenericmessageCommand.php (Handle any type of message.), (*65)
-
GenericCommand.php (Handle commands that don't exist or to use commands as a variable.)
- Favourite colour? /black, /red
- Favourite number? /1, /134
Custom Commands
Maybe you would like to develop your own commands.
There is a guide to help you create your own commands., (*66)
Also, be sure to have a look at the example commands to learn more about custom commands and how they work., (*67)
Commands Configuration
With this method you can set some command specific parameters, for example:, (*68)
// Google geocode/timezone API key for /date command
$telegram->setCommandConfig('date', ['google_api_key' => 'your_google_api_key_here']);
// OpenWeatherMap API key for /weather command
$telegram->setCommandConfig('weather', ['owm_api_key' => 'your_owm_api_key_here']);
Admin Commands
Enabling this feature, the bot admin can perform some super user commands like:
- List all the chats started with the bot /chats
- Clean up old database entries /cleanup
- Show debug information about the bot /debug
- Send message to all chats /sendtoall
- Post any content to your channels /sendtochannel
- Inspect a user or a chat with /whois, (*69)
Take a look at all default admin commands stored in the src/Commands/AdminCommands/ folder., (*70)
Set Admins
You can specify one or more admins with this option:, (*71)
// Single admin
$telegram->enableAdmin(your_telegram_user_id);
// Multiple admins
$telegram->enableAdmins([your_telegram_user_id, other_telegram_user_id]);
Telegram user id can be retrieved with the /whoami command., (*72)
Channel Administration
To enable this feature follow these steps:
- Add your bot as channel administrator, this can be done with any Telegram client.
- Enable admin interface for your user as explained in the admin section above.
- Enter your channel name as a parameter for the /sendtochannel command:, (*73)
$telegram->setCommandConfig('sendtochannel', ['your_channel' => ['@type_here_your_channel']]);
- If you want to manage more channels:
$telegram->setCommandConfig('sendtochannel', ['your_channel' => ['@type_here_your_channel', '@type_here_another_channel', '@and_so_on']]);
Upload and Download directory path
To use the Upload and Download functionality, you need to set the paths with:, (*74)
$telegram->setDownloadPath('/your/path/Download');
$telegram->setUploadPath('/your/path/Upload');
Documentation
Take a look at the repo Wiki for further information and tutorials!
Feel free to improve!, (*75)
Example bot
We're busy working on a full A-Z example bot, to help get you started with this library and to show you how to use all its features.
You can check the progress of the example bot repository)., (*76)
Projects with this library
Here's a list of projects that feats this library, feel free to add yours!
- Inline Games (@inlinegamesbot)
- Super-Dice-Roll (@superdiceroll_bot)
- tg-mentioned-bot, (*77)
Troubleshooting
If you like living on the edge, please report any bugs you find on the
PHP Telegram Bot issues page., (*78)
Contributing
See CONTRIBUTING for more information., (*79)
Donate
All work on this bot consists of many hours of coding during our free time, to provide you with a Telegram Bot library that is easy to use and extend.
If you enjoy using this library and would like to say thank you, donations are a great way to show your support., (*80)
Donations are invested back into the project :+1:, (*81)
License
Please see the LICENSE included in this repository for a full copy of the MIT license,
which this project is licensed under., (*82)
Credits
Credit list in CREDITS, (*83)