Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions documentation/01-getting-started.md
Original file line number Diff line number Diff line change
@@ -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
<?php

// Load Composer's autoloader
require __DIR__ . '/vendor/autoload.php';

// Your Bot API Key and Username
$api_key = 'YOUR_API_KEY';
$bot_username = 'YOUR_BOT_USERNAME';

try {
// Create a new Telegram instance
$telegram = new Longman\TelegramBot\Telegram($api_key, $bot_username);

// Your bot's logic will go here

} catch (Longman\TelegramBot\Exception\TelegramException $e) {
// Log error
error_log($e->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.
125 changes: 125 additions & 0 deletions documentation/02-basic-usage.md
Original file line number Diff line number Diff line change
@@ -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
<?php

require __DIR__ . '/vendor/autoload.php';

$api_key = 'YOUR_API_KEY';
$bot_username = 'YOUR_BOT_USERNAME';

// Optional: MySQL credentials for storing update states
$mysql_credentials = [
'host' => '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
<?php

require __DIR__ . '/vendor/autoload.php';

$api_key = 'YOUR_API_KEY';
$bot_username = 'YOUR_BOT_USERNAME';

// The URL of your hook.php file
$hook_url = 'https://your-domain.com/path/to/hook.php';

try {
// Create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($api_key, $bot_username);

// Set webhook
$result = $telegram->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
<?php

require __DIR__ . '/vendor/autoload.php';

$api_key = 'YOUR_API_KEY';
$bot_username = 'YOUR_BOT_USERNAME';

try {
// Create Telegram API object
$telegram = new Longman\TelegramBot\Telegram($api_key, $bot_username);

// Handle incoming webhook request
$telegram->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).
148 changes: 148 additions & 0 deletions documentation/03-commands.md
Original file line number Diff line number Diff line change
@@ -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
<?php

namespace Longman\TelegramBot\Commands\UserCommands;

use Longman\TelegramBot\Commands\UserCommand;
use Longman\TelegramBot\Entities\ServerResponse;
use Longman\TelegramBot\Exception\TelegramException;

class HelloWorldCommand extends UserCommand
{
/**
* @var string
*/
protected $name = 'helloworld';

/**
* @var string
*/
protected $description = 'A simple command that replies with Hello, World!';

/**
* @var string
*/
protected $usage = '/helloworld';

/**
* @var string
*/
protected $version = '1.0.0';

/**
* Main command execution
*
* @return ServerResponse
* @throws TelegramException
*/
public function execute(): ServerResponse
{
$message = $this->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 <city>`).
- `$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
<?php
namespace Longman\TelegramBot\Commands\AdminCommands;

use Longman\TelegramBot\Commands\AdminCommand;
// ...

class MyAdminCommand extends AdminCommand
{
// ...
}
```

You also need to specify who the admins are. You can do this with `enableAdmin()` or `enableAdmins()`:

```php
//...
$telegram = new Longman\TelegramBot\Telegram($api_key, $bot_username);

// Set a single admin
$telegram->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');
```
Loading