PHP code example of bahramali / telegram-bot-php

1. Go to this page and download the library: Download bahramali/telegram-bot-php library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

bahramali / telegram-bot-php example snippets



use TelegramBotPHP\Bot;

e.telegram.org/bots/api#authorizing-your-bot
 */
$bot = new Bot('__BOT_API_TOKEN__');

if ($_GET['example'] == '1a79a4d60de6718e8e5b326e338ae533') {
    // code
} else {
    // 404 not found
}


$ip = $_SERVER['REMOTE_ADDR'];

if (Bot::isTelegramIp($ip)) {
    // code
} else {
    // 404 not found
}

/**
 * bot api server url
 * @link https://core.telegram.org/bots/api#using-a-local-bot-api-server
 */
public string $botApiServerUrl = 'https://api.telegram.org/bot'; // https://example.com/bot{__BOT_API_TOKEN__}/MethodName?parameters=values

/**
 * bot api server file url
 * @link https://core.telegram.org/bots/api#file
 */
public string $botApiServerFileUrl = 'https://api.telegram.org/file/bot'; // https://example.com/example/file/bot{__BOT_API_TOKEN__}/{__FILE_PATH__}

/**
 * auto convert update and response to class For easier access
 */
public bool $convertToObject = true;

/**
 * Use webhook by default
 * if use getUpdates Set this variable to false
 */
public bool $autoUseWebhook = true;

/**
 * In certain methods, some parameters are filled in automatically
 *
 * For example, in `sendMessage` method,

 * You can, not set "chat_id",

 * And the "chat_id" of the sender is considered automatic.
 */
public bool $autofillParameters = true;

/**
 * Stop the program when it encounters an error
 */
public bool $throwOnError = true;

$config->onLog = function (array $log) {

    $log = json_encode($log);
    file_put_contents(__DIR__ . '/Bot.log', "{$log}\n", FILE_APPEND);
};


$config->onLogUpdate = function (array $update) {

    $logUpdate = json_encode($update);
    file_put_contents(__DIR__ . '/Bot_update.log', "{$logUpdate}\n", FILE_APPEND);
};


$config->onLogRequestAndResponse = function (array $request, array $response) {

    $logRequestAndResponse = [$request, $response];
    $logRequestAndResponse = json_encode($logRequestAndResponse);
    file_put_contents(__DIR__ . '/Bot_request_response.log', "{$logRequestAndResponse}\n", FILE_APPEND);
};


$config->onLogError = function (array $error) {

    $logError = json_encode($error);
    file_put_contents(__DIR__ . '/Bot_error.log', "{$logError}\n", FILE_APPEND);
};



MainConfig::$onLog = function (array $log) {

    $log = json_encode($log);
    file_put_contents(__DIR__ . '/Bot.log', "{$log}\n", FILE_APPEND);
};

// MainConfig::.... = ... ;

$config = new Config();

$config->onLog = function (array $log) {

    $log = json_encode($log);
    file_put_contents(__DIR__ . '/Bot.log', "{$log}\n", FILE_APPEND);
};

$config->onLogUpdate = function ($update) {

    $logUpdate = json_encode($update);
    file_put_contents(__DIR__ . '/Bot_update.log', "{$logUpdate}\n", FILE_APPEND);
};

// $config-> ... = ... ;

$bot = new Bot('__BOT_API_TOKEN__' , $config);

$config->throwOnError = true;
// or
$bot->config->throwOnError = true;

$config->onLog = function (array $log) {

    $log = json_encode($log);
    file_put_contents(__DIR__ . '/Bot.log', "{$log}\n", FILE_APPEND);
};

// $bot->config->... = ...;

// Do not confuse this function with the 'getUpdates' method of Telegram, it is 'getupdate'
$update = $bot->getUpdate(); // TelegramBotPHP\Types\Update Object ([updateId] => 585985242 [message] => TelegramBotPHP\Types\Message Object ( ... ))

$update = $bot->getInput(); // Array ([update_id] => 585985243 [message] => Array ( ... ))

$update = $bot->getUpdate(); // TelegramBotPHP\Types\Update Object ([updateId] => 585985242 [message] => TelegramBotPHP\Types\Message Object ( ... ))

$messageId = $update->message->message_id; // 28236
// or
$messageId = $update->message->messageId; // 28236

$text = $update->message->text; // Example Text

// or
$update = $bot->getInput(); // Array ([update_id] => 585985243 [message] => Array ( ... ))

$messageId = $update['message']['message_id']; // 28236

$text = $update['message']['text']; // Example Text



$updates = $bot->getUpdates()->getResult();// Array ([0] => TelegramBotPHP\Types\Update Object ( ... ) [1] => TelegramBotPHP\Types\Update Object ( ... ) [2] => TelegramBotPHP\Types\Update Object ( ... ))


$updates = $bot->getUpdates()->getResult();// Array ([0] => TelegramBotPHP\Types\Update Object ( ... ) [1] => TelegramBotPHP\Types\Update Object ( ... ) [2] => TelegramBotPHP\Types\Update Object ( ... ))
foreach ($updates as $key => $update) {

    $chatId = $update->chat->id; // 184171927
    // or you can create helper
}


// now you can use all of telegram methods

$bot->methodName([
    // parameters
    'example' => 'test',
]);


// https://core.telegram.org/bots/api#available-methods

// chat_id is Unique identifier for the target chat or username of the target channel (in the format @channelusername)

// send message
$bot->sendMessage([
    'chat_id' => 184171927,
    'text' => 'Example Text',
]);

// send photo
$bot->sendPhoto([
    'chat_id' => 184171927,
    'photo' => new CURLFile('example.png'),
    'caption' => 'Example caption',
]);

// send document
$bot->sendDocument([
    'chat_id' => 184171927,
    'document' => new CURLFile('example.zip'),
    'caption' => 'Example caption',
]);

// ...
// $bot->...([
//   ...
// ]);


// send message
Bot::sendMessage([
    'chat_id' => 184171927,
    'text' => 'Example Text',
]);

// send photo
Bot::sendPhoto([
    'chat_id' => 184171927,
    'photo' => new CURLFile('example.png'),
    'caption' => 'Example caption',
]);

// send document
Bot::sendDocument([
    'chat_id' => 184171927,
    'document' => new CURLFile('example.zip'),
    'caption' => 'Example caption',
]);


// send message
Bot::sendMessage([
    'chat_id' => 184171927,
    'text' => 'Example Text',
], '__BOT_API_TOKEN__');

// send message
$bot->sendMessage([
    'chat_id' => 184171927,
    'text' => 'Example Text',
    'reply_markup' => [
        'inline_keyboard' =>
        [
            [['text' => 'one', 'callback_data' => 'one'], ['text' => 'two', 'callback_data' => 'two']],

            [['text' => 'three', 'callback_data' => 'three'], ['text' => 'four', 'callback_data' => 'four']],

            [['text' => 'url', 'url' => 'https://github.com/ErfanBahramali/Telegram-Bot-PHP']],
        ]
    ]
]);

// send message
$bot->sendMessage([
    'chat_id' => 184171927,
    'text' => 'Example Text',
    'reply_markup' => [
        'keyboard' =>
        [
            [['text' => 'one'], ['text' => 'two']],

            [['text' => 'three'], ['text' => 'four']],

            [['text' => 'request contact', 'request_contact' => true]],

            [['text' => 'request location', 'request_location' => true]],
        ],
        'resize_keyboard' => true,
    ]
]);

// send message
$bot->sendMessage([
    'chat_id' => 184171927,
    'text' => 'Example Text',
    'reply_markup' => [
        'remove_keyboard' => true
    ]
]);

// send message
$bot->sendMessage([
    'chat_id' => 184171927,
    'text' => 'Example Text',
    'reply_markup' => [
        'force_reply' => true,
        'input_field_placeholder' => 'test',
    ]
]);

$response = $bot->methodName([
    // parameters
    'example' => 'test',
]); // (TelegramBotPHP\Response\Response Object( .... ))


// {
//   "ok": true,
//   "result": {
//     "message_id": 28236,
//     "from": {
//       "id": 93372553,
//       "is_bot": true,
//       "first_name": "BotFather",
//       "username": "BotFather"
//     },
//     "chat": {
//       "id": 184171927,
//       "first_name": "Erfan",
//       "type": "private"
//     },
//     "date": 1627277790,
//     "text": "Example Text"
//   }
// }

$response->isOk(); // check response ok is true (true)

$response->getResult(); // get response Result. The result is not always an object and may be an array and a bool (TelegramBotPHP\Types\Message Object([messageId] => 28236 [from] => TelegramBotPHP\Types\User Object( ... ) [date] => 1627277790[chat] => TelegramBotPHP\Types\Chat Object( ... )[text] => Example Text))

$response->getResponseData(); // get all of response as an array (Array ([ok] => 1 [result] => Array ( [message_id] => 28236 [from] => Array  ( ... ) [chat] => Array ( ... ) [date] => 1627277790 [text] => Example Text )))


$result = $response->getResult();// TelegramBotPHP\Types\Message Object( ... )

$messageId = $result->message_id; // 28236
$chatId = $result->chat->id; // 184171927
$text = $result->text; // Example Text

// or in array
$result = $response->getResponseData(); // Array ( ... )
$result = $result['result']; // Array ( ... )

$messageId = $result['message_id']; // 28236
$chatId = $result['chat']['id']; // 184171927
$text = $result['text']; // Example Text


// {
//   "ok": false,
//   "error_code": 400,
//   "description": "Bad Request: chat not found"
// }

$response->getErrorCode(); // check response error_code (400)
$response->getDescription(); // check response description ("Bad Request: chat not found")

$response->getRequestMethod(); // get request method name (sendMessage)
$response->getRequestParameters(); // get request parameters as an array (['chat_id' => '184171927', 'text' => 'Example Text'])



// downloadFile($filePath, $localFilePath)

// $fileSource = self::$config->botApiServerFileUrl . self::$token . '/' . $filePath;

$bot->downloadFile('documents/example.txt', __DIR__ . '/documents/example.txt');

// $fileSource = self::$config->botApiServerFileUrl . self::$token . '/' . 'documents/example.txt';

// or

Bot::downloadFile('documents/example.txt', __DIR__ . '/documents/example.txt');



// downloadFileByFileId($fileId, $localFilePath)

$bot->downloadFileByFileId('BQACAgQAAxkBAAJ0T2EJUDHTeXGcSBUrqFMgzZCQ0OJGAAIhCQACg2tJUEqm6016cXE9IAQ', __DIR__ . '/documents/example.txt');

// or

Bot::downloadFileByFileId('BQACAgQAAxkBAAJ0T2EJUDHTeXGcSBUrqFMgzZCQ0OJGAAIhCQACg2tJUEqm6016cXE9IAQ', __DIR__ . '/documents/example.txt');



$chatId = $bot->getHelper()->getChatId();
// or
$chatId = Helper::getChatId();
// or
$chatId = $bot->getUpdate()->message->chat->id;


$helper = new Helper({__Input_Update_Array__});

// Example:
$helper = new Helper($bot->getInput());

$helper = $bot->getHelper();

$text = Format::mention('184171927','Erfan'); // [Erfan](tg://user?id=184171927)

// escape markdownV2 style
$text = Format::markdownV2('');

// escape HTML style
$text = Format::html('');

// escape markdown style
$text = Format::markdown('');

// escape markdownV2 style
$text = Format::markdownV2('*bold \*text*'); // \*bold \\\*text\*

// escape HTML style
$text = Format::html('<b>bold</b>, <strong>bold</strong>'); // &amp;lt;b&amp;gt;bold&amp;lt;/b&amp;gt;, &amp;lt;strong&amp;gt;bold&amp;lt;/strong&amp;gt;

// escape markdown style
$text = Format::markdown('*bold text*'); // \*bold text\*


$text = Format::markdownV2('*bold \*text*');

Bot::sendMessage([
    'chat_id' => '184171927',
    'text' => "*{$text}*",
    'parse_mode' => ParseMode::MARKDOWNV2,
]);

if (Helper::updateTypeIsMessage()) {
    # code...
} elseif (Helper::updateTypeIsCallbackQuery()) {
    # code...
} elseif (Helper::updateTypeIsMyChatMember()) {
    # code...
}

// or ...
// Helper::updateTypeIs...()


$updateType = Helper::getUpdateType();

if ($updateType === UpdateType::MESSAGE) {

} elseif ($updateType === UpdateType::EDITED_MESSAGE) {

} elseif ($updateType === UpdateType::CALLBACK_QUERY) {

}


Bot::sendChatAction([
    'chat_id' => 184171927,
    'action' => ChatAction::TYPING,
]);

Bot::sendChatAction([
    'chat_id' => 184171927,
    'action' => ChatAction::RECORD_VOICE,
]);

Bot::sendChatAction([
    'chat_id' => 184171927,
    'action' => ChatAction::FIND_LOCATION,
]);


composer 

php composer.phar