PhpBotFramework  2.0.2
A framework for Telegram Bots' APIs.
PhpBotFramework Documentation

Description

PhpBotFramework is a lightweight framework for Telegram Bot API. Designed to be fast and easy to use, it provides all the features a user need in order to start developing Telegram bots..

Installation

You can install PhpBotFramework using Composer.

Go to your project's folder and type:

composer require danyspin97/php-bot-framework
composer install --no-dev

Usage

You can start working on your bot creating a new instance of Bot or by creating a class that inherits from it.

Each API call will have $_chat_id set to the current user: you can use CoreBot::setChatID() to change it.

Below an example bot you can look to:

<?php

// Include the framework
require './vendor/autoload.php';

// Create the bot
$bot = new PhpBotFramework\Bot("token");

// Create a command that will be triggered every time the user send /start
$start_command = new PhpBotFramework\Commands\MessageCommand("start", function($bot, $message) {
    $bot->sendMessage("Hello, folks!");
});

$bot->addCommand($start_command);

// Receive updates from Telegram using getUpdates
$bot->getUpdatesLocal();

Inheriting by Bot class

<?php

// Include the framework
require './vendor/autoload.php';

// Create the class that will extends Bot class
class EchoBot extends PhpBotFramework\Bot {

    // Add the function for processing messages
    protected function processMessage($message) {

        // Answer each message with the text received
        $this->sendMessage($message['text']);
    }
}

$bot = new EchoBot("token");

// Process updates using webhook
$bot->processWebhookUpdate();

Override these method to make your bot handle each update type:

Features

Requirements

Getting updates

Everytime a user interacts with the bot, an update is generated by Telegram's servers.

There are two ways of receiving this updates:

If you want to use getUpdates in order to receive updates, add one of these functions at the end of your bot:

The bot will process updates one a time and will call Bot::processUpdate() for each.

The connection will be opened at the creation and used for the entire life of the bot.

Webhook

An alternative way to receive updates is using webhooks.

Everytime a user interacts with the bot, Telegram servers send the update through a POST request to a URL chose by you.

A web server will create an instance of the bot for every update received.

If you want to use webhook: call Bot::processWebhookUpdate() at the end of your bot.

The bot will get data from php://input and process it using Bot::processUpdate(). Each instance of the bot will open its connection.

Set webhook

You can set a URL for your bot's webhook using CoreBot::setWebhook():

//...
$bot->setWebhook([ 'url' => 'https://example.com/mybotSECRETPATH' ])

You can learn more about setWebhook and webhooks here.

Bot's commands

One of the most important tasks during a Telegram bot's development is register the commands the bot will respond to.

PhpBotFrameworks makes it easy:

$start_message_command = new PhpBotFramework\Commands\MessageCommand("start", function($bot, $message) {
    $bot->sendMessage("I am your personal bot, try /help command");
});

$bot->addCommand($start_message_command);

$help_closure = function($bot, $message) {
    $bot->sendMessage("This is the help message")
};

$help_message_command = new PhpBotFramework\Commands\MessageCommand("/help", $help_function);

$bot->addCommand($help_message_command);

Check commands using regex

You can also use regular expressions to check for the given command:

$regex_command = new PhpBotFramework\Commands\MessageRegexCommand("number\d", $help_function);

The closure will be called when the user send a command that match the given regex, in this example: both /number1 or /number135.

Callback commands

You can also check for a callback query containing a particular string as data:

$callback_command = new PhpBotFramework\Commands\CallbackCommand("back", function($bot, $callback_query) {
    $bot->editMessageText($callback_query['message']['message_id'], "You pressed back");
});

You should absolutely check Bot::addCommand() for learning more.

Inline keyboards

Telegram implements something called inline keyboards which allows users to send commands to a bot tapping on buttons instead of typing text.

PhpBotFrameworks supports inline keyboard and you can easily integrate it with your bot:

$bot = new PhpBotFramework\Bot("token");

$command = ("start", function($bot, $message) {
    // Add a button to the inline keyboard with written 'Click me!' and
    // that open the Telegram site if pressed.
    $bot->inline_keyboard->addLevelButtons([
        'text' => 'Click me!',
        'url' => 'telegram.me'
    ]);

    // Then send a message, with our keyboard in the parameter $reply_markup of sendMessage
    $bot->sendMessage("This is a test message", $bot->inline_keyboard->get());
});

// Add the command
$bot->addCommand($command);

Database

A database is required in order to save offsets (if you use local updates) and save user's language.

We implemented a simpler way to connect to a database which is based on PDO:

$bot->database->connect([
    'adapter' => 'pgsql',
    'username' => 'sysuser',
    'password' => 'myshinypassword',
    'dbname' => 'my_shiny_bot'
]);

This method will istantiate a new PDO connection and a new PDO object you can access through $bot->getPdo().

If no adapter and host are specified: mysql and localhost are assigned.

Redis

Redis is used across PhpBotFramework in order to save offsets for local updates, to store user's language (both as cache and persistent) and save bot states.

Redis and the main database are complementary so you need to set both.

All you need to do, in order to enable Redis for your bot, is create a new Redis object:

$bot->redis = new Redis();

Multi-language Bot

This framework offers methods and facilities for develop a multi-language bot.

All you need to do is create a localization folder in your project's root folder and store there the JSON files with bot's messages:

localization/en.json:

{ "Welcome_Message": "Hello, folks!" }

localization/it.json:

{ "Welcome_Message": "Ciao, gente!" }

main.php:

// ...

$start_command = PhpBotFramework\Commands\MessageCommand("start", function($bot, $message) {
    $bot->sendMessage($bot->local->getStr('Greetings_Msg'));
});

$bot->addCommand($start_command);

So you can have a wonderful (multi-language) bot with a small effort.

Source

PhpBotFramework is an open-source project so everyone can contribute to it.

It's currently hosted on GitHub here.

Made with PhpBotFramework

Testing

PhpBotFramework comes with a test suite you can run using PHPUnit.

You need a valid bot token and chat ID in order to run tests:

 export BOT_TOKEN=YOURBOTTOKEN
 export CHAT_ID=YOURCHATID

After you've set the necessary, you can run the test suite typing:

 phpunit

Authors

This framework is developed and mantained by Danilo Spinella and Dom Corvasce.

License

PhpBotFramework is released under GNU Lesser General Public License v3.

You may copy, distribute and modify the software provided that modifications are described and licensed for free under LGPL-3.

Derivatives works (including modifications) can only be redistributed under LGPL-3, but applications that use the wrapper don't have to be.