-
-
Notifications
You must be signed in to change notification settings - Fork 958
Snippets
Feel free to add your own ;)
Sometimes we need some helping functions (like a dumper below) accessible in any command. Create your own Helpers class to keep your custom code together and easily accessible.
Create Helpers.php
anywhere inside your project, adding this code to it:
<?php
namespace Longman\TelegramBot;
class Helpers {
}
Open your hook.php
and add this code somewhere, to include it (setting your respective path):
include_once '/path/to/Helpers.php';
Now you're ready to use your Helpers
class. Open any command file and add a new use
statement to the use
section.
use Longman\TelegramBot\Helpers;
Hooray! Now you can call you custom functions stored in your Helpers
class in any command like this:
Helpers::yourFunction();
Add them to your Helpers class and use when needed.
Use this function to get the value of any variable during command execution. Very helpful for debugging purposes.
The value will be written to the debug
log (if enabled) and sent to the chat passed through the $chat_id
parameter.
Note: Alternatively, you can create a private static variable called $dump_chat_id
, which will be used if no chat ID is passed to the function. (e.g. private static $dump_chat_id = 123;
)
/**
* Dumper, to send variable contents to the passed chat_id.
*
* Used to log and send variable dump (var_export) to the developer or any Telegram chat ID provided.
* Will return ServerResponse object for later use.
*
* @param mixed $data
* @param int $chat_id
*
* @return \Longman\TelegramBot\Entities\ServerResponse
* @throws \Longman\TelegramBot\Exception\TelegramException
*/
public static function dump($data, $chat_id = null)
{
$dump = var_export($data, true);
// Write the dump to the debug log, if enabled.
TelegramLog::debug($dump);
// Send the dump to the passed chat_id.
if ($chat_id !== null || (property_exists(self::class, 'dump_chat_id') && $chat_id = self::$dump_chat_id)) {
$result = Request::sendMessage([
'chat_id' => $chat_id,
'text' => $dump,
'disable_web_page_preview' => true,
'disable_notification' => true,
]);
if ($result->isOk()) {
return $result;
}
TelegramLog::error('Var not dumped to chat_id %s; %s', $chat_id, $result->printError());
}
return Request::emptyResponse();
}