PHPBot Documentation

Complete guide to building powerful Telegram bots with PHPBot

Getting Started

Welcome to PHPBot! This platform allows you to create powerful Telegram bots with ease, using either our AI-powered builder or custom PHP code.

Prerequisites:
  • A Telegram account
  • Bot token from @BotFather
  • PHPBot account (register above)

Creating Your First Bot

Step 1: Get Your Bot Token

  1. Open Telegram and search for @BotFather
  2. Send /newbot command
  3. Follow the prompts to name your bot
  4. Copy the bot token (looks like: 123456789:ABCdefGHIjklMNOpqrsTUVwxyz)

Step 2: Create Bot in PHPBot

  1. Go to Dashboard
  2. Click "Create New Bot"
  3. Enter bot name and paste your token
  4. Click "Create Bot"
Example:

Bot Name: My Awesome Bot

Token: 123456789:ABCdefGHIjklMNOpqrsTUVwxyz

Bot Commands Structure

Commands are the core of your bot. Each command responds to specific user input.

Command Components

  • Command: The trigger (e.g., /start, /help)
  • Type: Message, Callback, or Pattern
  • Response: Text or PHP code to execute
  • Description: What the command does
Note: Commands starting with / are standard Telegram commands. You can also use patterns to match any text.

Helper Functions

PHPBot provides powerful helper classes to interact with Telegram and manage data.

BotAPI - Telegram Bot API

Use BotAPI to send messages, photos, and more.

// Send a text message
BotAPI::sendMessage($chatId, "Hello, World!");

// Send a photo
BotAPI::sendPhoto($chatId, "https://example.com/image.jpg", "Caption here");

// Send a message with inline keyboard
$keyboard = [
    [
        ['text' => 'Button 1', 'callback_data' => 'btn1'],
        ['text' => 'Button 2', 'callback_data' => 'btn2']
    ]
];
BotAPI::sendMessage($chatId, "Choose an option:", $keyboard);

// Edit a message
BotAPI::editMessage($chatId, $messageId, "Updated text");

// Delete a message
BotAPI::deleteMessage($chatId, $messageId);

// Send document
BotAPI::sendDocument($chatId, "https://example.com/file.pdf");

// Answer callback query
BotAPI::answerCallbackQuery($callbackQueryId, "Button clicked!");

BotDB - Database Operations

Store and retrieve data for your bot users.

// Save user data
BotDB::set($userId, 'key', 'value');

// Get user data
$value = BotDB::get($userId, 'key');

// Get with default value
$value = BotDB::get($userId, 'key', 'default_value');

// Delete user data
BotDB::delete($userId, 'key');

// Check if key exists
if (BotDB::has($userId, 'key')) {
    // Key exists
}

// Get all user data
$allData = BotDB::getAll($userId);

Available Variables

These variables are automatically available in your PHP code:

$chatId       // Current chat ID
$userId       // User's Telegram ID
$username     // User's Telegram username
$firstName    // User's first name
$lastName     // User's last name
$messageText  // Text of the message
$messageId    // ID of the message
$callbackData // Data from callback button (if callback)
$update       // Full update object from Telegram

Command Types & Examples

1. Simple Text Response

Command: /start

Type: Message

Response:

BotAPI::sendMessage($chatId, "Welcome to my bot! 🤖\n\nUse /help to see available commands.");

2. Personalized Greeting

Command: /hello

Response:

BotAPI::sendMessage($chatId, "Hello, $firstName! 👋\n\nNice to meet you!");

3. Inline Keyboard Menu

Command: /menu

Response:

$keyboard = [
    [
        ['text' => '📊 Statistics', 'callback_data' => 'stats'],
        ['text' => '⚙️ Settings', 'callback_data' => 'settings']
    ],
    [
        ['text' => '❓ Help', 'callback_data' => 'help']
    ]
];

BotAPI::sendMessage($chatId, "Main Menu:", $keyboard);

4. Callback Handler

Command: stats

Type: Callback

Response:

// Answer the callback
BotAPI::answerCallbackQuery($callbackData, "Loading stats...");

// Send statistics
$stats = "📊 Your Statistics:\n\n";
$stats .= "Messages sent: " . BotDB::get($userId, 'msg_count', 0) . "\n";
$stats .= "Member since: " . BotDB::get($userId, 'join_date', 'Today');

BotAPI::editMessage($chatId, $messageId, $stats);

5. Pattern Matching

Command: * (matches any message)

Type: Pattern

Response:

// Echo back the message
BotAPI::sendMessage($chatId, "You said: $messageText");

// Or count messages
$count = BotDB::get($userId, 'msg_count', 0);
BotDB::set($userId, 'msg_count', $count + 1);

PHP Code in Commands

You can write any PHP code in your command responses. Here are some advanced examples:

Random Quotes

$quotes = [
    "The only way to do great work is to love what you do. - Steve Jobs",
    "Innovation distinguishes between a leader and a follower. - Steve Jobs",
    "Stay hungry, stay foolish. - Steve Jobs"
];

$randomQuote = $quotes[array_rand($quotes)];
BotAPI::sendMessage($chatId, "💭 Quote of the day:\n\n$randomQuote");

Simple Calculator

// Command: /calc 5 + 3
$parts = explode(' ', $messageText);
if (count($parts) === 4) {
    $num1 = floatval($parts[1]);
    $operator = $parts[2];
    $num2 = floatval($parts[3]);
    
    $result = 0;
    switch ($operator) {
        case '+': $result = $num1 + $num2; break;
        case '-': $result = $num1 - $num2; break;
        case '*': $result = $num1 * $num2; break;
        case '/': $result = $num2 != 0 ? $num1 / $num2 : 'Error: Division by zero'; break;
    }
    
    BotAPI::sendMessage($chatId, "Result: $result");
} else {
    BotAPI::sendMessage($chatId, "Usage: /calc 5 + 3");
}

User Points System

// Get current points
$points = BotDB::get($userId, 'points', 0);

// Add points
$points += 10;
BotDB::set($userId, 'points', $points);

// Send message
BotAPI::sendMessage($chatId, "🎉 You earned 10 points!\n\nTotal points: $points");

Variables & Data Storage

Storing User State

// Save user's current state
BotDB::set($userId, 'state', 'waiting_for_name');

// Later, check the state
$state = BotDB::get($userId, 'state');
if ($state === 'waiting_for_name') {
    BotDB::set($userId, 'name', $messageText);
    BotDB::delete($userId, 'state');
    BotAPI::sendMessage($chatId, "Nice to meet you, $messageText!");
}

Storing Complex Data

// Store array as JSON
$userData = [
    'name' => 'John',
    'age' => 25,
    'city' => 'New York'
];
BotDB::set($userId, 'profile', json_encode($userData));

// Retrieve and decode
$profile = json_decode(BotDB::get($userId, 'profile'), true);
BotAPI::sendMessage($chatId, "Name: " . $profile['name']);
Important: Data is stored per user. Each user has their own isolated storage.

User Management

View and manage all users who have interacted with your bot from the bot management page.

Features:

  • View all bot users with their Telegram info
  • Ban/unban users
  • See when users first started using the bot
  • Track user activity

Checking if User is Banned

// This is handled automatically by PHPBot
// Banned users won't trigger commands
// But you can check manually if needed:
if (BotDB::get($userId, 'is_banned', false)) {
    BotAPI::sendMessage($chatId, "You are banned from using this bot.");
    return;
}

Broadcasting Messages

Send messages to all your bot users at once from the bot management page.

Use Cases:
  • Announce new features
  • Send updates or news
  • Notify users about maintenance
  • Run promotional campaigns

Webhook Configuration

Setting Up Webhook

  1. Go to your bot's management page
  2. Click "Set Webhook" button
  3. PHPBot will automatically configure the webhook with Telegram
  4. Your bot is now live!
Note: Webhooks require HTTPS. PHPBot handles this automatically.

Viewing Logs

Monitor your bot's activity in real-time:

  • See all incoming messages
  • View command executions
  • Debug errors
  • Track user interactions

Best Practices

1. Always Provide Help

// Create a /help command
$helpText = "Available Commands:\n\n";
$helpText .= "/start - Start the bot\n";
$helpText .= "/help - Show this message\n";
$helpText .= "/menu - Open main menu\n";
BotAPI::sendMessage($chatId, $helpText);

2. Handle Errors Gracefully

try {
    // Your code here
    $result = someFunction();
    BotAPI::sendMessage($chatId, "Success: $result");
} catch (Exception $e) {
    BotAPI::sendMessage($chatId, "Sorry, something went wrong. Please try again.");
    // Log error for debugging
}

3. Use Descriptive Command Names

  • /subscribe instead of /sub
  • /settings instead of /s
  • /help instead of /h

4. Provide Feedback

// Always acknowledge user actions
BotAPI::sendMessage($chatId, "✅ Settings saved successfully!");
// or
BotAPI::answerCallbackQuery($callbackData, "Processing...");

5. Test Thoroughly

  • Test all commands before deploying
  • Try edge cases and invalid inputs
  • Check callback buttons work correctly
  • Monitor logs for errors

Troubleshooting

Bot Not Responding

  • Check if webhook is set correctly
  • Verify bot token is correct
  • Check bot logs for errors
  • Ensure bot is not banned by Telegram

Commands Not Working

  • Check command syntax (must start with /)
  • Verify command type is correct (Message/Callback/Pattern)
  • Check for PHP syntax errors in response code
  • Review bot logs for error messages

Data Not Saving

  • Ensure you're using BotDB::set() correctly
  • Check that userId is valid
  • Verify key names are consistent
  • Look for errors in logs
Need Help?

If you're still having issues, check the bot logs in your dashboard or contact support.

Ready to Build Your Bot?

Start creating amazing Telegram bots with PHPBot today!

Go to Dashboard