---
description: >-
  Learn how to write PHP code in the Bots Mother code editor to create
  interactive Telegram bots. This guide covers accessing the editor, using
  Telegram webhook variables
---

# Writing PHP Code in Bots Mother Code Editor

## Writing PHP Code in Bots Mother Code Editor

This guide explains how to write PHP code in the Bots Mother platform’s code editor after adding a command for your Telegram bot. It covers accessing the code editor, using the Telegram webhook payload variables (`$update`, `$TGUser`, `$updateType`, `$message`, `$chatId`), and leveraging the BotAPI library to create dynamic bot interactions. With the "Wait for Answer" feature, your code executes when users reply, allowing you to build powerful, interactive bot logic.

### Accessing the Code Editor

After adding a command in Bots Mother, you can write custom PHP code to handle user replies. Follow these steps to reach the code editor:

1. **Navigate to Bots Mother**: Log in to the Bots Mother platform.
2. **Go to My Bots**: From the dashboard, click “My Bots.”
3. **Select Your Bot**: Find your bot and click “View.”
4. **Open Commands Tab**: Go to the “Commands” tab to see your bot’s commands.
5. **Add or Edit a Command**:
   * To add a new command, click “Add Command,” fill out the form (e.g., set `/start` as the command, enable “Wait for Answer”), and save.
   * To edit an existing command, click “Edit Settings” next to the command.
6. **Enter the Code Editor**: Click “Edit Code” for the command. This opens the PHP code editor, where you can write logic that runs when a user replies to the command.

In the code editor, you have access to the full Telegram webhook payload via the `$update` variable, along with helper variables like `$TGUser`, `$updateType`, `$message`, and `$chatId`. These variables allow you to process user input and interact with the Telegram API using BotAPI methods.

### Understanding Telegram Webhook Variables

The Bots Mother code editor provides several variables derived from the Telegram webhook payload. These variables simplify access to key data about the user’s interaction. Below is a detailed description of each:

* **`$update` (array)**\
  The complete Telegram webhook payload, containing all details about the update. It includes fields like `message`, `callback_query`, `chat`, `from`, and more, depending on the update type. Use this for advanced logic requiring full access to Telegram’s data.\
  **Example**: `$update['message']['text']` retrieves the text of a user’s message.
* **`$TGUser` (array)**\
  The user object from the Telegram update, representing the user who triggered the command or sent a reply. It typically includes fields like `id`, `first_name`, `username`, and `language_code`.\
  **Example**: `$TGUser['first_name']` gets the user’s first name.
* **`$updateType` (string)**\
  The type of the Telegram update, indicating the kind of interaction (e.g., `message`, `callback_query`, `chat_member`). Use this to conditionally handle different update types.\
  **Example**: Check if `$updateType === 'message'` to process text messages.
* **`$message` (string)**\
  The plain text message sent by the user. This is useful for commands that wait for user input after an auto-answer.\
  **Example**: If a user replies “Hello,” `$message` contains “Hello.”
* **`$chatId` (int|string)**\
  The Telegram chat ID where the interaction occurred. This could be a private chat, group, or channel ID. Use it to send responses to the correct chat.\
  **Example**: `$chatId` might be `123456789` for a private chat.

These variables are automatically available in the code editor when your command’s PHP code runs, triggered by a user’s reply (if “Wait for Answer” is enabled).

### Writing PHP Code with BotAPI

In the code editor, you can write PHP code to process user input and interact with Telegram using the **BotAPI** library. The library provides methods like `BotAPI::sendMessage`, `BotAPI::sendPhoto`, and others to send responses, manage chats, and more. Below are examples demonstrating how to use the webhook variables and BotAPI methods to create interactive bot logic.

#### Example 1: Simple Reply to User Input

This example sends a personalized response based on the user’s reply to a `/greet` command.

```php
// Check if the update is a message
if ($updateType === 'message') {
    // Get the user's first name and message
    $userName = $TGUser['first_name'] ?? 'User';
    $userMessage = $message;

    // Create a response
    $response = "Hello, $userName! You said: $userMessage";

    // Send the response to the chat
    BotAPI::sendMessage([
        'chat_id' => $chatId,
        'text' => $response,
        'parse_mode' => 'HTML'
    ]);
}
```

**Setup**: Add a `/greet` command with “Wait for Answer” enabled and an auto-answer like “Please tell me something!” When the user replies, the code runs, using `$TGUser['first_name']` for the name, `$message` for their input, and `$chatId` to send the response.

#### Example 2: Handling Specific User Input

This example checks the user’s reply and sends a photo if they type “photo.”

```php
if ($updateType === 'message') {
    // Check the user's message
    if (strtolower($message) === 'photo') {
        // Send a photo
        BotAPI::sendPhoto([
            'chat_id' => $chatId,
            'photo' => 'https://example.com/sample.jpg',
            'caption' => 'Here’s a cool photo!',
            'parse_mode' => 'HTML'
        ]);
    } else {
        // Send a default response
        BotAPI::sendMessage([
            'chat_id' => $chatId,
            'text' => 'Please type "photo" to see an image!',
            'parse_mode' => 'HTML'
        ]);
    }
}
```

**Setup**: Add a command (e.g., `/show`) with “Wait for Answer” enabled. The code checks `$message` and uses `BotAPI::sendPhoto` or `BotAPI::sendMessage` based on the input.

#### Example 3: Using the Full `$update` Payload

This example processes a callback query from an inline keyboard using the `$update` payload.

```php
if ($updateType === 'callback_query') {
    // Extract callback data and user info
    $callbackData = $update['callback_query']['data'];
    $userName = $TGUser['first_name'] ?? 'User';

    // Respond to the callback query
    BotAPI::answerCallbackQuery([
        'callback_query_id' => $update['callback_query']['id'],
        'text' => "Thanks for clicking, $userName!",
        'show_alert' => false
    ]);

    // Send a follow-up message
    BotAPI::sendMessage([
        'chat_id' => $chatId,
        'text' => "You selected: $callbackData",
        'parse_mode' => 'HTML'
    ]);
}
```

**Setup**: Add a command with an inline keyboard (configured in the “Keyboards” field) and “Wait for Answer” enabled. The code uses `$update['callback_query']` to access callback data and responds with `BotAPI::answerCallbackQuery` and `BotAPI::sendMessage`.

#### Example 4: Managing Chat Members

This example bans a user if an admin types their user ID in a group chat.

```php
if ($updateType === 'message' && $message) {
    // Assume the message contains a user ID to ban
    $userIdToBan = (int)$message;

    // Ban the user for 24 hours
    BotAPI::banChatMember([
        'chat_id' => $chatId,
        'user_id' => $userIdToBan,
        'until_date' => time() + 86400
    ]);

    // Confirm the action
    BotAPI::sendMessage([
        'chat_id' => $chatId,
        'text' => "User $userIdToBan has been banned for 24 hours.",
        'parse_mode' => 'HTML'
    ]);
}
```

**Setup**: Add a `/ban` command with “Wait for Answer” enabled and “Chat Type” set to “Group.” The code uses `$message` as the user ID and calls `BotAPI::banChatMember`.

### Tips for Writing Effective Code

* **Validate Inputs**: Always check `$updateType` and validate `$message` or `$TGUser` to avoid errors (e.g., `if (isset($TGUser['id']))`).
* **Use `$update` for Advanced Logic**: Access nested fields like `$update['message']['reply_to_message']` for replies or `$update['chat']['type']` to check chat type.
* **Leverage BotAPI Methods**: Combine methods like `BotAPI::sendPoll`, `BotAPI::sendLocation`, or `BotAPI::editMessageText` for rich interactions. Refer to the [BotAPI Library Functions](https://grok.com/chat/1ba43157-e06b-4a17-bb86-65ba6dfb1cd6?referrer=website) for all available methods.
* **Debugging**: Use `BotAPI::sendMessage` to log variable values (e.g., `BotAPI::sendMessage(['chat_id' => $chatId, 'text' => print_r($update, true)])`) for debugging.
* **Handle "Wait for Answer"**: Since the code runs only after a user reply (when “Wait for Answer” is enabled), ensure your logic processes `$message` or `$update` appropriately.
* **Error Handling**: Wrap BotAPI calls in try-catch blocks if the library supports it, or check return values to handle API errors.

### Available BotAPI Methods

The BotAPI library provides a wide range of methods to interact with Telegram. Some commonly used methods include:

* `BotAPI::sendMessage($params)`: Send text messages.
* `BotAPI::sendPhoto($params)`: Send photos.
* `BotAPI::sendPoll($params)`: Create polls.
* `BotAPI::editMessageText($params)`: Edit sent messages.
* `BotAPI::banChatMember($params)`: Manage chat members.

For a complete list, refer to the [BotAPI Library Functions](https://grok.com/chat/1ba43157-e06b-4a17-bb86-65ba6dfb1cd6?referrer=website) documentation.

### Example Workflow

1. Add a `/feedback` command with:
   * Auto Answer: “Please share your feedback!”
   * Wait for Answer: Enabled
   * Chat Type: Private
2. In the code editor, write:

```php
if ($updateType === 'message') {
    $userName = $TGUser['first_name'] ?? 'User';
    $feedback = $message;

    BotAPI::sendMessage([
        'chat_id' => $chatId,
        'text' => "Thank you, $userName! Your feedback: $feedback",
        'parse_mode' => 'HTML'
    ]);
}
```

3. When a user types `/feedback` and replies with “Great bot!”, the bot responds with “Thank you, \[User]! Your feedback: Great bot!”
