Skip to content

Breaking backwards compatibility

Armando Lüscher edited this page May 24, 2024 · 26 revisions

This library is still under heavy development, so some changes will break backwards compatibility (BC). We try to keep breaking changes to a minimum, but also try to create the best solution for any given situation.

Here is a list of BC breaking changes in each version.

Minimum PHP 8.1

The minimum PHP requirement is now 8.1, make sure your code is updated accordingly.

"user" to "users"

  • Renamed the class KeyboardButtonRequestUser to KeyboardButtonRequestUsers.
  • Renamed the field request_user to request_users in KeyboardButton.
  • Renamed DB field message.user_shared to message.users_shared.

Commands with Underscores

Uppercase letters in command files and classes get separated by underscores when calling the command. Be aware of this change if you have any classes with multiple uppercase letters.

Before: FooBarCommand handles the /foobar command.

After: FooBarCommand handles the /foo_bar command.

Removed deprecated ChatActions

The ChatAction::RECORD_AUDIO and ChatAction::UPLOAD_AUDIO constants were deprecated a while now and got removed with this update.

Please use ChatAction::RECORD_VOICE and ChatAction::UPLOAD_VOICE instead.

ChatMember Subentities

The ChatMember entity has been split up into individual subentities.

Before:

use Longman\TelegramBot\Entities\ChatMember;

$chat_member = Request::getChatMember([
    'chat_id' => $chat_id,
    'user_id' => $user_id,
])->getResult();

$owner_or_admin = false;
if ($chat_member instanceof ChatMember) {
    $owner_or_admin = in_array($chat_member->getStatus(), ['creator', 'administrator'], true);
}

Now:

You could still use the old way, you'll need to update the use statement for the ChatMember entity though:

use Longman\TelegramBot\Entities\ChatMember\ChatMember;

New way using the subentities:

use Longman\TelegramBot\Entities\ChatMember\ChatMemberAdministrator;
use Longman\TelegramBot\Entities\ChatMember\ChatMemberOwner;

$chat_member = Request::getChatMember([
    'chat_id' => $chat_id,
    'user_id' => $user_id,
])->getResult();

$owner_or_admin = $chat_member instanceof ChatMemberOwner
    || $chat_member instanceof ChatMemberAdministrator;

Minimum PHP 7.3

The minimum PHP requirement is now 7.3 and works with PHP 8.0 too.

With PHP 7.3 comes strict typing for properties, methods parameters, return values, etc.

You may need to update your code to reflect this change and make sure that all types are passed and handled correctly.

Static method Entity::escapeMarkdown

Make the Entity::escapeMarkdown method static, to not require an explicit Entity object.

Before:

// Any object of type `Entity`.
$message = $this->getMessage();
$escaped_markdown = $message->escapeMarkdown('*This* is _not_ bold');

Now:

use Longman\TelegramBot\Entities\Entity;
$escaped_markdown = Entity::escapeMarkdown('*This* is _not_ bold');

Remove Monolog from core

To make the core library adhere to PSR-3 for logging, Monolog has been removed and must now be added manually if desired. (Or any other PSR-3 provider)

Before:

use Longman\TelegramBot\TelegramLog;
...
TelegramLog::initDebugLog('/path/to/debug_log_file');
TelegramLog::initErrorLog('/path/to/error_log_file');
TelegramLog::initUpdateLog('/path/to/updates_log_file');
...

Now:

Install Monolog with Composer: composer require monolog/monolog

Replace the old logger initialisation with the following:

use Longman\TelegramBot\TelegramLog;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
...
TelegramLog::initialize(
    // Main logger that handles all 'debug' and 'error' logs.
    new Logger('telegram_bot', [
        (new StreamHandler('/path/to/debug_log_file', Logger::DEBUG))->setFormatter(new LineFormatter(null, null, true)),
        (new StreamHandler('/path/to/error_log_file', Logger::ERROR))->setFormatter(new LineFormatter(null, null, true)),
    ]),
    // Updates logger for raw updates.
    new Logger('telegram_bot_updates', [
        (new StreamHandler('path/to/updates_log_file', Logger::INFO))->setFormatter(new LineFormatter('%message%' . PHP_EOL)),
    ])
);
...

StartCommand is now a UserCommand

The /start command is now a UserCommand, not a SystemCommand any more.

(Both still work, but start using the UserCommand!)

Before:

class StartCommand extends SystemCommand

Now:

class StartCommand extends UserCommand

Return value of empty Entity properties

Entity properties that contain empty arrays now return an empty array instead of null.

Before:

// With no entities in the message.
$message->getEntities(); // null

Now:

// With no entities in the message.
$message->getEntities(); // []

Move Animation out of Games namespace

The Animation entity has moved directly into the Entities namespace.

Before:

namespace Longman\TelegramBot\Entities\Games;

Now:

namespace Longman\TelegramBot\Entities;

Rename constants

The following constants have been renamed

  • BASE_PATH -> TB_BASE_PATH
  • BASE_COMMANDS_PATH -> TB_BASE_COMMANDS_PATH

Message::getCommand() return value

If message is not a command, null is returned instead of false.

Before:

// Text: "testing"
$message->getCommand(); // returns false

Now:

// Text: "testing"
$message->getCommand(); // returns null

Correct printError

ServerResponse->printError method now prints by default and returns by setting $return parameter, similar to print_r function.

Before:

$response->printError();     // returns error

Now:

$response->printError();     // prints error, returns true
$response->printError(true); // returns error

Private-only Admin Commands

Admin commands get the $private_only parameter set by default, making them work only in private chats. (#580)

If you have any admin command(s) that should be accessible in a public chat, you must manually add protected $private_only = false; to your command(s).

Request class refactor

Some Request:: methods that allow sending of files have been changed. As such, these methods no longer take an extra parameter that specifies the path to the file, but instead expect it to be part of the passed $data parameter.

Methods in question: sendPhoto, sendAudio, sendDocument, sendSticker, sendVideo, sendVoice, sendVideoNote.

Before:

$data = [
  'chat_id' => 123,
];
Request::sendPhoto($data, '/path/to/pic.jpg');

Now:

// For remote file paths.
$data = [
  'chat_id' => 123,
  'photo'   => 'https://example.com/path/to/pic.jpg',
];
Request::sendPhoto($data);

or

// For local file paths.
$data = [
  'chat_id' => 123,
  'photo'   => Request::encodeFile('/path/to/pic.jpg'),
];
Request::sendPhoto($data);

Request::setWebhook now without special handling!

Before:

Request::setWebhook($url, $data = []);

Now:

Request::setWebhook($data);

Remove deprecated methods

Before:

Telegram::getBotName();
Entity::getBotName();
Telegram::unsetWebhook();

Now:

Telegram::getBotUsername();
Entity::getBotUsername();
Telegram::deleteWebhook();

Chats params array

Request::sendToActiveChats and DB::selectChats now accept parameters as an options array and allow selecting of channels.

Before: Parameters to limit selection were all passed individually.

$results = DB::selectChats(
    true, // Select groups
    true, // Select supergroups
    true, // Select users
    null, // 'yyyy-mm-dd hh:mm:ss' date range from
    null, // 'yyyy-mm-dd hh:mm:ss' date range to
    null, // Specific chat_id to select
    null  // Text to search in user/group name
);

$results = Request::sendToActiveChats(
    'sendMessage',     // Callback function to execute (see Request.php methods)
    ['text' => $text], // Param to evaluate the request
    true,              // Send to groups
    true,              // Send to supergroups
    true,              // Send to users
);

Now: Parameters to limit selection now gets passed as an associative array.

$results = DB::selectChats([
    'groups'      => true,
    'supergroups' => true,
    'channels'    => true,
    'users'       => true,
    'date_from'   => null,
    'date_to'     => null,
    'chat_id'     => null,
    'text'        => null,
]);

$results = Request::sendToActiveChats(
    'sendMessage',     // Callback function to execute (see Request.php methods)
    ['text' => $text], // Param to evaluate the request
    [
        'groups'      => true,
        'supergroups' => true,
        'channels'    => false,
        'users'       => true,
    ]
);

Up-/Download directories

The upload and download directories are not set any more by default and must be set manually in the hook file.

$telegram->setUploadPath('/path/to/uploads');
$telegram->setDownloadPath('/path/to/downloads');

Before: Returned an array containing the update content.

$m   = $update->getUpdateContent();
$mid = $m['message']['message_id'];
$cid = $m['message']['chat']['id'];
$uid = $m['from']['id'];

Now: Correctly returns the Entity of the update content.

$m   = $update->getUpdateContent();
$mid = $m->getMessage()->getMessageId();
$cid = $m->getMessage()->getChat()->getId();
$uid = $m->getFrom()->getId();