tusharkhan / chatbot
๐ค Modern PHP chatbot framework with multi-platform support (Telegram, Slack, Web). Build intelligent conversational bots with pattern matching, state management, and middleware. Works with any PHP framework or standalone.
Requires
- php: >=8.0
- irazasyed/telegram-bot-sdk: ^3.9
- jolicode/slack-php-api: ^4.8
- nyholm/psr7: ^1.8
- symfony/http-client: ^6.0|^7.0
Requires (Dev)
- phpunit/phpunit: ^9.0
- squizlabs/php_codesniffer: ^3.6
This package is auto-updated.
Last update: 2025-08-22 08:23:36 UTC
README
TusharKhan Chatbot Package
A framework-agnostic PHP chatbot package that works seamlessly with plain PHP, Laravel, or any custom PHP application. Build powerful chatbots with multi-platform support including Web, Telegram, and Slack.
Package details
- PHP: >=8.0
- License: MIT
Note: The downloads badge above is provided by Packagist/Shields.io and will display live download counts after the package is published on Packagist. If you prefer to show a static number, replace the badge with the value from Packagist.
๐ Features
- Framework Agnostic: Works with any PHP framework or plain PHP
- Multi-Platform Support: Web, Telegram, and Slack drivers included
- Pattern Matching: Flexible message routing with parameters, wildcards, and regex
- Multi-turn Conversations: Stateful conversations with context management
- Storage Options: File-based or in-memory storage (easily extensible)
- Middleware Support: Add custom processing logic
- Fallback Handling: Graceful handling of unmatched messages
- Easy Setup: No complex configuration required
- Rich Messaging: Support for buttons, keyboards, attachments, and interactive components
- Modern Platform Features: Events API, slash commands, and interactive components
- Fully Tested: Comprehensive unit test coverage (79 tests, 202 assertions)
๐ฆ Installation
Install via Composer:
composer require tusharkhan/chatbot
๐ฏ Quick Start
Basic Web Chatbot
<?php require_once 'vendor/autoload.php'; use TusharKhan\Chatbot\Core\Bot; use TusharKhan\Chatbot\Drivers\WebDriver; use TusharKhan\Chatbot\Storage\FileStore; // Initialize bot $driver = new WebDriver(); $storage = new FileStore(__DIR__ . '/storage'); $bot = new Bot($driver, $storage); // Add message handlers $bot->hears('hello', function($context) { return 'Hello! How can I help you?'; }); $bot->hears('my name is {name}', function($context) { $name = $context->getParam('name'); $context->getConversation()->set('name', $name); return "Nice to meet you, $name!"; }); // Set fallback handler $bot->fallback(function($context) { return "I don't understand. Try saying 'hello'."; }); // Listen for messages $bot->listen(); // Output responses $driver->outputJson(); // For AJAX // or $driver->outputHtml(); // For form submissions ?>
Telegram Bot
<?php use TusharKhan\Chatbot\Core\Bot; use TusharKhan\Chatbot\Drivers\TelegramDriver; use TusharKhan\Chatbot\Storage\FileStore; // Configuration $botToken = $_ENV['TELEGRAM_BOT_TOKEN'] ?? 'your-telegram-bot-token-here'; // Initialize bot $driver = new TelegramDriver($botToken); $storage = new FileStore(__DIR__ . '/storage'); $bot = new Bot($driver, $storage); // Handle /start command $bot->hears(['/start', 'start'], function($context) { $name = $context->getData()['from']['first_name'] ?? 'there'; return "Welcome to our bot, $name! ๐ค\n\nType /help to see what I can do."; }); // Handle /help command $bot->hears(['/help', 'help'], function($context) { return "๐ค *Bot Commands:*\n\nโข /start - Start the bot\nโข /help - Show this help\nโข order - Start food ordering"; }); // Start food ordering $bot->hears(['order', '/order'], function($context) { $context->getConversation()->setState('ordering_category'); return "๐ฝ๏ธ *Food Ordering*\n\nWhat would you like?\nโข Pizza ๐\nโข Burger ๐\nโข Salad ๐ฅ"; }); $bot->listen(); ?>
Slack Bot
<?php use TusharKhan\Chatbot\Core\Bot; use TusharKhan\Chatbot\Drivers\SlackDriver; use TusharKhan\Chatbot\Storage\FileStore; // Configuration $botToken = $_ENV['SLACK_BOT_TOKEN'] ?? 'xoxb-your-bot-token-here'; $signingSecret = $_ENV['SLACK_SIGNING_SECRET'] ?? 'your-signing-secret-here'; // Initialize bot $driver = new SlackDriver($botToken, $signingSecret); $storage = new FileStore(__DIR__ . '/storage'); $bot = new Bot($driver, $storage); $bot->hears('hello', function($context) { return 'Hello! ๐ How can I help you today?'; }); // Handle slash commands $bot->hears('/weather {city}', function($context) { $city = $context->getParam('city'); return "Weather for {$city}: 22ยฐC, Sunny โ๏ธ"; }); $bot->listen(); ?>
๐ง Pattern Matching
The bot supports various pattern matching types:
Exact Match
$bot->hears('hello', $handler);
Wildcards
$bot->hears('hello*', $handler); // Matches "hello world", "hello there", etc.
Parameters
$bot->hears('my name is {name}', function($context) { $name = $context->getParam('name'); return "Hello, $name!"; });
Multiple Patterns
$bot->hears(['hello', 'hi', 'hey'], $handler);
Regular Expressions
$bot->hears('/^\d+$/', $handler); // Matches numbers only
Custom Functions
$bot->hears(function($message) { return strpos($message, 'urgent') !== false; }, $handler);
๐ฌ Conversation Management
Handle multi-turn conversations with ease:
// Start a conversation flow $bot->hears('order pizza', function($context) { $context->getConversation()->setState('ordering'); return 'What size pizza? (small/medium/large)'; }); // Handle the next step $bot->hears(['small', 'medium', 'large'], function($context) { $conversation = $context->getConversation(); if ($conversation->isInState('ordering')) { $size = $context->getMessage(); $conversation->set('pizza_size', $size); $conversation->setState('toppings'); return "Great! What toppings for your $size pizza?"; } }); // Continue the flow... $bot->hears('*', function($context) { $conversation = $context->getConversation(); if ($conversation->isInState('toppings')) { $toppings = $context->getMessage(); $size = $conversation->get('pizza_size'); $conversation->clear(); // End conversation return "Order confirmed: $size pizza with $toppings!"; } });
๐ Middleware
Add custom processing logic:
// Logging middleware $bot->middleware(function($context) { error_log("Message: " . $context->getMessage()); return true; // Continue processing }); // Authentication middleware $bot->middleware(function($context) { $userId = $context->getSenderId(); if (!isUserAuthenticated($userId)) { $context->getDriver()->sendMessage('Please login first'); return false; // Stop processing } return true; });
๐๏ธ Storage Options
File Storage (Persistent)
use TusharKhan\Chatbot\Storage\FileStore; $storage = new FileStore('/path/to/storage/directory'); $bot = new Bot($driver, $storage);
Array Storage (In-Memory)
use TusharKhan\Chatbot\Storage\ArrayStore; $storage = new ArrayStore(); $bot = new Bot($driver, $storage);
Custom Storage
Implement the StorageInterface
for custom storage solutions:
use TusharKhan\Chatbot\Contracts\StorageInterface; class DatabaseStore implements StorageInterface { public function store(string $key, array $data): bool { /* ... */ } public function retrieve(string $key): ?array { /* ... */ } public function exists(string $key): bool { /* ... */ } public function delete(string $key): bool { /* ... */ } }
๐ Framework Integration
Laravel Integration
// In a Laravel Controller use TusharKhan\Chatbot\Core\Bot; use TusharKhan\Chatbot\Drivers\WebDriver; class ChatbotController extends Controller { public function handle(Request $request) { $bot = new Bot(new WebDriver(), new FileStore(storage_path('chatbot'))); $bot->hears('hello', function($context) { return 'Hello from Laravel!'; }); $bot->listen(); return response()->json([ 'responses' => $bot->getDriver()->getResponses() ]); } }
Plain PHP Integration
// For AJAX requests if (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])) { $driver->outputJson(); } else { $driver->outputHtml(); }
๐งช Testing
Run the test suite:
# Run all tests composer test # Run with coverage ./vendor/bin/phpunit --coverage-html coverage # Check code style composer cs-check # Fix code style composer cs-fix
๐ Examples & Documentation
Working Examples
examples/web_driver.php
- Complete web chatbot with ordering systemexamples/telegram.php
- Full Telegram bot with commands and conversationsexamples/slack.php
- Slack bot with interactive components
Comprehensive Guides
doc/web-driver-bot.md
- WebDriver guide (plain PHP and Laravel)doc/telegram.md
- Complete Telegram bot implementation guidedoc/slack-bot-example.md
- Slack bot setup and real-world examples
๐ง Advanced Usage
Custom Drivers
Create custom drivers by implementing DriverInterface
:
use TusharKhan\Chatbot\Contracts\DriverInterface; class CustomDriver implements DriverInterface { public function getMessage(): ?string { /* ... */ } public function getSenderId(): ?string { /* ... */ } public function sendMessage(string $message, ?string $senderId = null): bool { /* ... */ } public function getData(): array { /* ... */ } public function hasMessage(): bool { /* ... */ } }
Error Handling
$bot->middleware(function($context) { try { return true; } catch (Exception $e) { error_log('Chatbot error: ' . $e->getMessage()); $context->getDriver()->sendMessage('Sorry, something went wrong.'); return false; } });
๐ API Reference
Bot Class
hears($pattern, $handler)
- Add message handlerfallback($handler)
- Set fallback handlermiddleware($middleware)
- Add middlewarelisten()
- Process incoming messagessay($message, $senderId)
- Send messageconversation()
- Get current conversationdriver()
- Get driver instancestorage()
- Get storage instance
Context Class
getMessage()
- Get incoming messagegetSenderId()
- Get sender IDgetConversation()
- Get conversation instancegetDriver()
- Get driver instancegetParams()
- Get extracted parametersgetParam($key, $default)
- Get specific parametergetData()
- Get raw platform data
Conversation Class
setState($state)
- Set conversation stategetState()
- Get current stateisInState($state)
- Check if in specific stateset($key, $value)
- Set variableget($key, $default)
- Get variablehas($key)
- Check if variable existsremove($key)
- Remove variableclear()
- Clear all data
๐ Supported Platforms
Web Driver
- HTTP/AJAX requests
- Form submissions
- Session-based conversations
- JSON/HTML responses
- Laravel and plain PHP integration
Telegram API
- Bot Commands:
/start
,/help
, custom commands - Message Types: Text, photos, documents, stickers
- Keyboards: Inline and reply keyboards
- Webhook Support: Real-time message processing
- Rich Formatting: Markdown and HTML support
Slack API
- Events API: Real-time message events
- Slash Commands: Custom bot commands
- Interactive Components: Buttons, menus, and forms
- Rich Messaging: Block Kit for rich layouts
- Mentions & DMs: App mentions and direct messages
- Webhook Verification: Signature verification for security
๐ Security Features
- Input Validation: Built-in message sanitization
- Webhook Verification: Signature verification for Slack
- Rate Limiting: Middleware support for rate limiting
- Error Handling: Comprehensive error logging
- Storage Security: Secure file-based storage
๐ Package Statistics
- Total Tests: 79 tests with 193 assertions
- Code Coverage: Comprehensive coverage of all core features
- PHP Version: Requires PHP 8.0+
- Dependencies: Modern, actively maintained packages
- Package Size: Lightweight with minimal dependencies
๐ค Contributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature
) - Commit your changes (
git commit -m 'Add amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
๐ License
This project is licensed under the MIT License - see the LICENSE file for details.
๐โโ๏ธ Support
- Create an Issue for bug reports
- Email: tushar.khan0122@gmail.com
- Documentation: See
/doc
folder for comprehensive guides
๐ Acknowledgments
- Built with modern PHP 8.0+ features
- Uses established libraries for platform integrations
- Framework-agnostic design for maximum compatibility
- Community-driven development
Made with โค๏ธ by Tushar Khan Portfolio: tusharkhan.me