diff --git a/documentation/01-getting-started.md b/documentation/01-getting-started.md new file mode 100644 index 00000000..8b5de70e --- /dev/null +++ b/documentation/01-getting-started.md @@ -0,0 +1,69 @@ +# Getting Started + +This guide will walk you through the initial steps to get your PHP Telegram Bot up and running. + +## Requirements + +- PHP 8.1 or higher +- The following PHP extensions: + - `pdo` + - `curl` + - `json` + - `mbstring` +- [Composer](https://getcomposer.org/) for dependency management. + +## 1. Create a New Bot with BotFather + +The first step is to register your new bot with Telegram. This is done by talking to a special bot called `@BotFather`. + +1. **Start a conversation:** Open Telegram and search for the contact `@BotFather`. +2. **Send `/newbot`:** Type and send the `/newbot` command. +3. **Choose a name:** BotFather will ask for a name for your bot. This is the display name, e.g., "My Awesome Bot". +4. **Choose a username:** Next, choose a unique username for your bot. It must end in `bot`, for example: `MyAwesomeBot` or `my_awesome_bot`. +5. **Receive your API Token:** BotFather will confirm the creation of your bot and provide you with an **API Token**. This token is essential for controlling your bot. Keep it safe and do not share it publicly. + +**Example API Token:** `123456789:AAG90e14-0f8-40183D-18491dDE` + +## 2. Install the Library + +Once you have your API token, you can install the `longman/telegram-bot` library into your PHP project using Composer. + +Navigate to your project directory and run the following command: + +```bash +composer require longman/telegram-bot +``` + +This will download the library and its dependencies, and set up the autoloader. + +## 3. Basic Configuration + +To start using the library, you need to instantiate the main `Telegram` class with your API key and bot username. + +Create a new PHP file (e.g., `bot.php`) and add the following code: + +```php +getMessage()); +} +``` + +Replace `YOUR_API_KEY` and `YOUR_BOT_USERNAME` with the credentials you received from BotFather. + +You are now ready to start receiving updates and handling commands! Move on to the [Basic Usage](./02-basic-usage.md) guide to learn how. diff --git a/documentation/02-basic-usage.md b/documentation/02-basic-usage.md new file mode 100644 index 00000000..26562d75 --- /dev/null +++ b/documentation/02-basic-usage.md @@ -0,0 +1,125 @@ +# Basic Usage + +There are two ways to receive updates from Telegram for your bot: the `getUpdates` method and the `webhook` method. + +| Method | Description | Requirements | +| :--- | :--- | :--- | +| **getUpdates** | You manually fetch updates from Telegram by running a script. | Simple to set up, no HTTPS required. | +| **Webhook** | Telegram sends updates directly to your server via an HTTPS POST request. | Requires an HTTPS-enabled server. More efficient. | + +--- + +## Method 1: getUpdates + +This method is simpler for development and testing. You run a script that actively asks Telegram for new messages. For this method to be effective, it's recommended to enable MySQL integration to keep track of processed updates. + +### `getUpdates` Example + +Create a file named `getUpdates.php`: + +```php + 'localhost', + 'user' => 'db_user', + 'password' => 'db_password', + 'database' => 'telegram_bot_db', +]; + +try { + // Create Telegram API object + $telegram = new Longman\TelegramBot\Telegram($api_key, $bot_username); + + // Enable MySQL (recommended) + $telegram->enableMySql($mysql_credentials); + + // Handle telegram getUpdates request + $telegram->handleGetUpdates(); + +} catch (Longman\TelegramBot\Exception\TelegramException $e) { + // Log Telegram errors + error_log($e->getMessage()); +} +``` + +To fetch updates, you need to execute this script periodically. You can do this manually for testing, or set up a cron job to run it automatically (e.g., every minute). + +```bash +# Run the script manually +php getUpdates.php + +# Run in a loop (for development) +while true; do php getUpdates.php; sleep 1; done +``` + +--- + +## Method 2: Webhook + +This is the recommended method for production bots. You set a URL, and Telegram will send a POST request with the update data to that URL as soon as it arrives. + +### Step 1: Set the Webhook + +You only need to do this once. Create a file named `setWebhook.php`: + +```php +setWebhook($hook_url); + if ($result->isOk()) { + echo 'Webhook was set successfully!'; + } +} catch (Longman\TelegramBot\Exception\TelegramException $e) { + error_log($e->getMessage()); +} +``` + +Run this script once from your browser or command line to register your webhook with Telegram. + +### Step 2: Handle Incoming Updates + +Now, create the `hook.php` file that will receive the updates from Telegram. + +```php +handle(); + +} catch (Longman\TelegramBot\Exception\TelegramException $e) { + // Silence is golden! + // Optionally, log the error + // error_log($e->getMessage()); +} +``` + +Now, your bot is set up to receive updates in real-time. The next step is to learn how to handle these updates with [Commands](./03-commands.md). diff --git a/documentation/03-commands.md b/documentation/03-commands.md new file mode 100644 index 00000000..ca20bf05 --- /dev/null +++ b/documentation/03-commands.md @@ -0,0 +1,148 @@ +# Commands + +The command system is the core of your bot's functionality. The library makes it easy to create and manage commands that your bot will respond to. + +## How Commands Work + +When your bot receives a message that starts with a `/`, it interprets it as a command. For example, `/start` or `/help`. The library automatically matches the command name to a corresponding command class that you have defined. + +There are three types of commands: + +- **User Commands:** Standard commands that any user can execute. +- **Admin Commands:** Commands that can only be executed by a bot admin. +- **System Commands:** Internal commands that handle non-command updates, like new users joining a chat (`new_chat_members`) or inline queries. You generally don't need to create these unless you want to override default behavior. + +## Creating a Custom Command + +Let's create a simple command that replies with "Hello, World!". + +1. **Create a commands directory:** It's good practice to store your custom commands in a dedicated directory. + ```bash + mkdir MyCommands + ``` + +2. **Create the command file:** Inside `MyCommands`, create a new file named `HelloWorldCommand.php`. + + ```php + getMessage(); + $chat_id = $message->getChat()->getId(); + + $data = [ + 'chat_id' => $chat_id, + 'text' => 'Hello, World!', + ]; + + return \Longman\TelegramBot\Request::sendMessage($data); + } + } + ``` + +### Key Properties of a Command: + +- `$name`: The command name without the `/` (e.g., `start`, `help`, `helloworld`). +- `$description`: A short description, used by the `/help` command. +- `$usage`: How to use the command (e.g., `/weather `). +- `$version`: The version of your command. +- `execute()`: The main method that runs when the command is called. + +## Registering Your Commands + +For the library to find your new command, you must tell it where to look. You do this by adding the path to your commands directory. + +In your main bot file (`getUpdates.php` or `hook.php`), add the following line after instantiating the `Telegram` object: + +```php +//... +$telegram = new Longman\TelegramBot\Telegram($api_key, $bot_username); + +// Add your custom commands path +$telegram->addCommandsPath(__DIR__ . '/MyCommands'); + +//... +``` + +Now, your bot will automatically load and execute your `HelloWorldCommand` when a user sends `/helloworld`. + +## Admin Commands + +To create a command that only admins can use, simply extend `AdminCommand` instead of `UserCommand`. + +```php +enableAdmin(123456789); // Replace with your Telegram User ID + +// Or set multiple admins +$telegram->enableAdmins([123456789, 987654321]); + +//... +``` + +## Command Configuration + +You can pass specific configuration options to your commands using `setCommandConfig()`. For example, if your command needs an API key: + +```php +$telegram->setCommandConfig('mycommand', ['api_key' => 'SOME_API_KEY']); +``` + +Inside your command, you can access this config like this: + +```php +$api_key = $this->getConfig('api_key'); +``` diff --git a/documentation/04-advanced-features.md b/documentation/04-advanced-features.md new file mode 100644 index 00000000..7a3fe434 --- /dev/null +++ b/documentation/04-advanced-features.md @@ -0,0 +1,154 @@ +# Advanced Features + +This section covers some of the more advanced features of the PHP Telegram Bot library that allow you to build more complex and interactive bots. + +## 1. Database Integration (MySQL) + +For features like conversations, tracking users, and remembering chat history, enabling MySQL is highly recommended. + +### Setup + +1. **Create a Database:** Create a new MySQL database for your bot. Ensure it uses the `utf8mb4` character set to support all Telegram characters and emojis. +2. **Import the Schema:** The library provides a `structure.sql` file that contains the necessary table structure. Import this file into your newly created database. + ```bash + mysql -u your_user -p your_database < structure.sql + ``` +3. **Enable in your code:** In your main bot file (`getUpdates.php` or `hook.php`), provide your database credentials to the `enableMySql()` method. This should be done *before* handling updates. + + ```php + 'localhost', + 'port' => 3306, // optional + 'user' => 'your_user', + 'password' => 'your_password', + 'database' => 'your_database', + ]; + + $telegram->enableMySql($mysql_credentials); + + // ... handle updates + ``` + +With the database enabled, the library will automatically log all incoming updates, messages, users, and chats. + +## 2. Conversations + +The conversation feature allows your bot to have multi-step interactions with users. For example, you can ask a user for their name, then their age, and then their location, all within a single command. + +A conversation is essentially a command that remains "active" across multiple messages. + +### Creating a Conversation Command + +A conversation command is similar to a regular command but extends the `Conversation` class. + +```php +getMessage(); + $chat_id = $message->getChat()->getId(); + $user_id = $message->getFrom()->getId(); + + // Prepare the conversation + $this->conversation = new Conversation($user_id, $chat_id, $this->getName()); + + // ... conversation logic ... + } +} +``` + +The key is the `Conversation` object, which stores the state of the conversation in the database. You can add notes to the conversation to track the user's progress and store their answers. + +For a detailed guide and examples, please refer to the [official example in the example-bot repository](https://github.com/php-telegram-bot/example-bot/blob/master/Commands/ConversationCommand.php). + +## 3. Logging + +The library uses the [PSR-3](https://www.php-fig.org/psr/psr-3/) standard for logging, allowing you to use any compatible logger, such as [Monolog](https://github.com/Seldaek/monolog). + +Logs are separated into three streams: +- `error`: For exceptions and errors within the library. +- `debug`: For detailed debugging information, including API requests and responses. +- `update`: For the raw JSON updates received from Telegram. This is very useful for re-importing missed updates. + +### Initializing the Logger + +You should initialize the logger at the beginning of your script. + +```php +use Longman\TelegramBot\TelegramLog; +use Monolog\Logger; +use Monolog\Handler\StreamHandler; + +TelegramLog::initialize( + // Main logger for debug and error logs + new Logger('telegram_bot', [ + (new StreamHandler(__DIR__ . '/logs/debug.log', Logger::DEBUG)), + (new StreamHandler(__DIR__ . '/logs/error.log', Logger::ERROR)), + ]), + // Optional logger for raw updates + new Logger('telegram_bot_updates', [ + (new StreamHandler(__DIR__ . '/logs/updates.log', Logger::INFO)), + ]) +); +``` + +## 4. Sending Messages and Media + +The `Request` class provides static methods for all available Telegram Bot API methods. + +### Sending a Text Message + +```php +use Longman\TelegramBot\Request; + +Request::sendMessage([ + 'chat_id' => $chat_id, + 'text' => 'This is a test message.', +]); +``` + +### Sending a Local Photo + +To send a file from your local server, you must encode it first. + +```php +use Longman\TelegramBot\Request; + +Request::sendPhoto([ + 'chat_id' => $chat_id, + 'photo' => Request::encodeFile('/path/to/your/image.jpg'), + 'caption' => 'This is a cool photo!', +]); +``` + +### Sending a Photo by URL or File ID + +You can also send a photo by providing a public URL or a `file_id` of a photo that is already on Telegram's servers. + +```php +// By URL +Request::sendPhoto(['chat_id' => $chat_id, 'photo' => 'https://example.com/photo.jpg']); + +// By File ID +Request::sendPhoto(['chat_id' => $chat_id, 'photo' => 'FILE_ID_OF_EXISTING_PHOTO']); +``` + +The same principles apply to sending other types of media, such as `sendDocument`, `sendAudio`, `sendVideo`, etc. diff --git a/documentation/05-contributing.md b/documentation/05-contributing.md new file mode 100644 index 00000000..5e18c7b7 --- /dev/null +++ b/documentation/05-contributing.md @@ -0,0 +1,59 @@ +# Contributing + +The easiest way to contribute is to work on a checkout of your own fork. +When working on the `core` repository, it makes sense to rename your fork to `php-telegram-bot`. + +Before you contribute code, please make sure it conforms to the PSR-12 coding standard and that the unit tests still pass. +You can run the following commands to check if everything is ready to submit: + +```bash +cd php-telegram-bot +composer install +composer check-code +``` + +Which should give you no output, indicating that there are no coding standard errors. +And then (remember to set up your test database!): + +```bash +composer test +``` + +Which should give you no failures or errors. You can ignore any skipped tests as these are for external tools. + +## Pushing + +Development is based on the git flow branching model (see http://nvie.com/posts/a-successful-git-branching-model/) +If you fix a bug please push in hotfix branch. +If you develop a new feature please create a new branch. + +## Version + +Version number: 0.#version.#hotfix + +## Further code convention adopted + +- Each method and class is documented with a docblock + +Example for a function or method: +```php +/** + * Get formatted date + * + * @param string $location + * + * @return string + */ +``` + +- Each file is provided with the following header: +```php +/** + * This file is part of the TelegramBot package. + * + * (c) Avtandil Kikabidze aka LONGMAN + * + * For the full copyright and license information, please view the LICENSE + * file that was distributed with this source code. + */ +``` diff --git a/documentation/index.md b/documentation/index.md new file mode 100644 index 00000000..62ef67e6 --- /dev/null +++ b/documentation/index.md @@ -0,0 +1,11 @@ +# PHP Telegram Bot Documentation + +Welcome to the documentation for the PHP Telegram Bot library. This library provides a pure PHP interface for the Telegram Bot API. + +## Table of Contents + +1. [Getting Started](./01-getting-started.md) +2. [Basic Usage](./02-basic-usage.md) +3. [Commands](./03-commands.md) +4. [Advanced Features](./04-advanced-features.md) +5. [Contributing](./05-contributing.md)