To create a Telegram bot in PHP using OOP principles and following your specifications, we'll start by setting up a simple framework. This example will assume that you already have a bot token from BotFather on Telegram.
First, let's outline what we need:
- A
CommandInterface that all command classes will implement.
- A mechanism to automatically load command classes from the
cmds/ directory.
- A main bot class that handles incoming updates and dispatches them to the correct command handler.
- Use cURL for all network requests, particularly for fetching updates and sending messages.
- Long polling to continuously check for updates.
Step 1: Setup
Create a project directory and within it, create these subdirectories and files:
index.php – the entry point of our bot.
Bot.php – our main bot class.
CommandInterface.php – our command interface.
cmds/ – a directory where all specific command classes will reside.
Step 2: Define CommandInterface
<?php // CommandInterface.php
interface CommandInterface {
public function execute($chat_id, $arguments = null);
}
Step 3: Setup Bot Class
<?php // Bot.php
class Bot {
private $token = 'YOUR_BOT_TOKEN_HERE';
// Method to send requests to Telegram API
private function sendRequest($method, $params = []) {
$url = "https://api.telegram.org/bot{$this->token}/{$method}";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $params);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($curl);
curl_close($curl);
return json_decode($response, true);
}
// Method for fetching updates
public function getUpdates($offset) {
return $this->sendRequest('getUpdates', ['offset' => $offset]);
}
// Method for sending a message
public function sendMessage($chat_id, $text) {
return $this->sendRequest('sendMessage', ['chat_id' => $chat_id, 'text' => $text]);
}
// Function to load and return all command classes
private function getCommandClasses() {
$commands = [];
$files = glob(__DIR__ . '/cmds/*.php');
foreach ($files as $file) {
require_once $file;
$className = basename($file, '.php');
if (class_exists($className) && is_subclass_of($className, 'CommandInterface')) {
$commands[$className] = new $className();
}
}
return $commands;
}
// Main function to process updates
public function processUpdates() {
$offset = 0;
while (true) {
$updates = $this->getUpdates($offset);
foreach ($updates['result'] as $update) {
$offset = $update['update_id'] + 1;
$chat_id = $update['message']['chat']['id'];
$text = $update['message']['text'] ?? '';
// Simple command parsing
if (strpos($text, "/") === 0) {
$commandClasses = $this->getCommandClasses();
$commandName = explode(" ", $text)[0];
$commandName = substr($commandName, 1);
if (array_key_exists($commandName, $commandClasses)) {
$commandClasses[$commandName]->execute($chat_id);
} else {
$this->sendMessage($chat_id, "Command not found.");
}
}
}
sleep(1); // Simple delay to prevent rate limits
}
}
}
Step 4: Sample Command Class
Inside the cmds/ directory, we will create a simple command. For instance, a StartCommand.php:
<?php // cmds/StartCommand.php
require_once 'CommandInterface.php';
class StartCommand implements CommandInterface {
public function execute($chat_id, $arguments = null) {
global $bot; // Assuming $bot is an instance of Bot
$bot->sendMessage($chat_id, "Welcome to our Bot!");
}
}
Step 5: Implement index.php
<?php // index.php
require_once 'Bot.php';
require_once 'CommandInterface.php';
// Assuming autoloading commands could be handled differently or with spl_autoload_register
$bot = new Bot();
$bot->processUpdates();
This setup will:
- Use cURL for all network requests.
- Implement a basic command system with interface.
- Implement long polling to continuously fetch updates.
Please Note:
- Replace
'YOUR_BOT_TOKEN_HERE' with your actual Telegram bot token.
- This example assumes you’re familiar with setting up a local server with PHP (e.g., XAMPP, WAMP, native PHP server).
- More sophisticated command parsing and error handling may be required for production bots.