-
-
Notifications
You must be signed in to change notification settings - Fork 963
Create your own commands
You have to install or update composer, set your webhook and check if preset commands work correctly before trying to create custom commands.
- Just copy
examples/hook.php
and paste it to your hook address.
You can point to your custom command folder using your hook :
. . $COMMANDS_FOLDER = 'your/Commands/folder/'; . . try { . . $telegram->addCommandsPath($COMMANDS_FOLDER); . . }
Assume that we want to create a test command with usage /test
:
create a new .php
file named TestCommand.php in your commands folder
((The first word in filename have to be in uppercase))
First of all define namespace and use
dependencies for Command class in TestCommand.php
file :
namespace Longman\TelegramBot\Commands; use Longman\TelegramBot\Request; use Longman\TelegramBot\Command; use Longman\TelegramBot\Entities\Update;
Now create a class named testCommand
that extends Command
Class :
class testCommand extends Command {
Define properties :
protected $name = 'test'; //your command's name protected $description = 'A command for test'; //Your command description protected $usage = '/test'; // Usage of your command protected $version = '1.0.0'; protected $enabled = true; protected $public = true;
Note:
Every Command have a method named execute
that will execute your command automatically. You can create your own methods but you have to call them inside execute
. execute works like constructor in normal classes
execute
Method:
public function execute() { $update = $this->getUpdate(); //get Updates $message = $this->getMessage(); // get Message info $chat_id = $message->getChat()->getId(); //Get Chat Id $message_id = $message->getMessageId(); //Get message Id //$text = $message->getText(true); // Get recieved text $data = array(); // prepapre $data $data['chat_id'] = $chat_id; //set chat Id $data['reply_to_message_id'] = $message_id; //set message Id $data['text'] = 'This is just a Test...'; //set reply message $result = Request::sendMessage($data); //send message return $result; }
Now system will automatically find your command and when user type /test
, the bot will answer her/him with : This is just a Test...