Skip to content
chuv1 edited this page Apr 30, 2017 · 8 revisions

Small chunks of code to help us develop bots faster and better

Feel free to add your own ;)

Helpers class (for dummies)

Sometimes we need some helping functions (like a dumper below) accessible in any command. Create your own Helpers class to keep your custom together and easy accessible.

Step 1.

Create Helpers.php in your custom Commands directory. Put this code inside:

<?php
    namespace Longman\TelegramBot;

    class Helpers{
    }

Step 2.

Open your hook.php and add this code somewhere after defining your custom commands path (and change this code accordingly).

if(file_exists($commands_path.'Helpers.php')){
    require_once $commands_path.'Helpers.php';
}

Step 3.

Now you ready to use your Helpers class. Open any command file and add new use statement to the "use" section.

use Longman\TelegramBot\Helpers;

Hooray! Now you can call you custom commands stored in Helpers class in any command.

Useful functions snippets

Add them to your Helpers class and use when needed.

Dumper

Use this function to get value of any variable during command execution. Very helpful for debugging purposes. Don't forget put your user id inside.

/**
 * Dumper. 
 * Used to send variable dump (var_export) to the developer or any Telegram ID provided.
 * Will return ServerResponse object for later usage
 *
 * @param mixed $data
 *
 * @return bool | ServerResponse
 */
static function dump($data) {

  $dump = var_export($data, true);

  $message = [
      'chat_id'                   => PUT_YOUR_USER_ID_HERE,
      'text'                      => $dump,
      'disable_web_page_preview'  => true,
      'disable_notification'      => true
  ];
   
  $result = Request::sendMessage($message);

  return $result->isOk() ? $result : self::dump('Var not dumped: '.$result->printError());
  
}