PHP code example of mbindi / telebridge

1. Go to this page and download the library: Download mbindi/telebridge library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mbindi / telebridge example snippets


use Mbindi\Telebridge\Models\TelegramBot;

$bot = TelegramBot::create([
    'user_id' => auth()->id(),
    'token' => env('TELEGRAM_BOT_TOKEN'),
    'name' => 'Mon Bot Assistant',
    'is_active' => true,
]);

use Mbindi\Telebridge\Services\TelegramClient;

$client = new TelegramClient();
$client->setWebhook(
    token: env('TELEGRAM_BOT_TOKEN'),
    url: route('telebridge.webhook', ['bot_token' => env('TELEGRAM_BOT_TOKEN')])
);



namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Mbindi\Telebridge\Models\TelegramBot;
use Mbindi\Telebridge\Models\TelegramMessage;
use Mbindi\Telebridge\Services\TelegramClient;

class ProcessTelegramMessage implements ShouldQueue
{
    use Dispatchable, Queueable;

    public function __construct(
        public TelegramBot $bot,
        public TelegramMessage $message,
        public int $chatId
    ) {}

    public function handle(TelegramClient $telegramClient)
    {
        // 1. Récupérer le contenu du message
        $userMessage = $this->message->content;

        // 2. 🔥 VOTRE LOGIQUE ICI (IA, base de connaissances, etc.)
        $response = $this->generateResponse($userMessage);

        // 3. Envoyer la réponse via TeleBridge
        $telegramClient->sendMessage(
            token: $this->bot->token,
            chatId: $this->chatId,
            text: $response,
            options: ['parse_mode' => 'Markdown']
        );

        // 4. Sauvegarder la réponse
        $this->message->markAsProcessed($response);
    }

    protected function generateResponse(string $message): string
    {
        // 🔥 VOTRE INTELLIGENCE ICI
        // Exemples :
        // - Appeler votre service IA
        // - Consulter votre base de connaissances
        // - Utiliser GPT/Claude/DeepSeek
        // - Logique métier personnalisée
        
        return "Réponse générée par votre logique !";
    }
}

use Mbindi\Telebridge\Services\TelegramClient;
use Mbindi\Telebridge\Services\KeyboardBuilder;

$keyboard = KeyboardBuilder::inline()
    ->row([
        KeyboardBuilder::inline()->button('Option 1', ['callback_data' => 'option_1']),
        KeyboardBuilder::inline()->button('Option 2', ['callback_data' => 'option_2']),
    ])
    ->row([
        KeyboardBuilder::inline()->button('Aide', ['callback_data' => 'help']),
    ])
    ->build();

$client = new TelegramClient();
$client->sendMessage(
    token: $bot->token,
    chatId: $chatId,
    text: 'Choisissez une option :',
    options: ['reply_markup' => $keyboard]
);

public function handle(TelegramClient $telegramClient)
{
    if ($this->message->isCallback()) {
        $action = $this->message->content; // 'option_1', 'option_2', etc.
        
        $response = match($action) {
            'option_1' => 'Vous avez choisi l\'option 1',
            'option_2' => 'Vous avez choisi l\'option 2',
            'help' => 'Voici l\'aide...',
            default => 'Action inconnue',
        };
        
        $telegramClient->sendMessage(
            token: $this->bot->token,
            chatId: $this->chatId,
            text: $response
        );
    }
}

// Photo
$client->sendPhoto(
    token: $bot->token,
    chatId: $chatId,
    photo: 'https://example.com/image.jpg',
    options: ['caption' => 'Ma photo']
);

// Document
$client->sendDocument(
    token: $bot->token,
    chatId: $chatId,
    document: 'file_id_or_url',
    options: ['caption' => 'Mon document']
);

// Vidéo
$client->sendVideo(
    token: $bot->token,
    chatId: $chatId,
    video: 'file_id_or_url'
);

// Localisation
$client->sendLocation(
    token: $bot->token,
    chatId: $chatId,
    latitude: 48.8566,
    longitude: 2.3522
);

// Contact
$client->sendContact(
    token: $bot->token,
    chatId: $chatId,
    phoneNumber: '+33123456789',
    firstName: 'John Doe'
);

$client->sendChatAction(
    token: $bot->token,
    chatId: $chatId,
    action: 'typing' // ou 'upload_photo', 'record_video', etc.
);

$client->editMessageText(
    token: $bot->token,
    chatId: $chatId,
    messageId: 123,
    text: 'Message mis à jour !'
);

use Mbindi\Telebridge\Models\TelegramBot;

// Créer un bot
$bot = TelegramBot::create([
    'user_id' => $userId,
    'license_id' => $licenseId, // Optionnel
    'token' => 'your-bot-token',
    'name' => 'Mon Bot',
    'is_active' => true,
]);

// Relations
$bot->user;          // Propriétaire du bot
$bot->license;       // Licence associée (si applicable)
$bot->messages;      // Messages du bot

// Helpers
$bot->hasActiveLicense();
$bot->getRemainingMessages();
$bot->getWebhookUrl();
$bot->activate();
$bot->deactivate();

use Mbindi\Telebridge\Models\TelegramMessage;

// Les messages sont créés automatiquement par TeleBridge
$message = TelegramMessage::find($id);

// Relations
$message->bot;           // Bot qui a reçu le message
$message->telegramUser;  // Utilisateur Telegram
$message->conversation;  // Conversation (si vous avez ce modèle)

// Vérifications de type
$message->isText();
$message->isPhoto();
$message->isDocument();
$message->isCallback();

// Helpers
$message->isProcessed();
$message->getDecodedContent();
$message->markAsProcessed($response, $metadata);

// Scopes
TelegramMessage::unprocessed()->get();
TelegramMessage::ofType('photo')->get();

use Mbindi\Telebridge\Models\TelegramUser;

$user = TelegramUser::where('telegram_id', $telegramId)->first();

$user->telegram_id;  // ID Telegram
$user->username;     // @username
$user->first_name;
$user->last_name;
$user->last_seen;    // Dernière activité

protected function generateResponse(string $message): string
{
    $response = Http::post('https://api.openai.com/v1/chat/completions', [
        'model' => 'gpt-4',
        'messages' => [
            ['role' => 'user', 'content' => $message]
        ],
    ]);

    return $response->json()['choices'][0]['message']['content'];
}

protected function generateResponse(string $message): string
{
    // Chercher dans votre base de connaissances
    $knowledge = KnowledgeBase::where('user_id', $this->bot->user_id)
        ->where('contenu', 'like', "%{$message}%")
        ->first();

    if ($knowledge) {
        return $knowledge->contenu;
    }

    return "Désolé, je n'ai pas trouvé de réponse à votre question.";
}

public function handle(TelegramClient $telegramClient)
{
    // Vérifier la licence
    if (!$this->bot->hasActiveLicense()) {
        $telegramClient->sendMessage(
            $this->bot->token,
            $this->chatId,
            "❌ Votre licence a expiré."
        );
        return;
    }

    // Vérifier le quota
    if ($this->bot->getRemainingMessages() <= 0) {
        $telegramClient->sendMessage(
            $this->bot->token,
            $this->chatId,
            "⚠️ Quota de messages épuisé."
        );
        return;
    }

    // Traiter le message...
    $response = $this->generateResponse($this->message->content);

    // Envoyer la réponse...
    $telegramClient->sendMessage(/*...*/);

    // Décrémenter le quota
    $license = $this->bot->user->activeLicense();
    $license->decrement('messages_remaining');
}
bash
php artisan vendor:publish --tag=telebridge-migrations
php artisan migrate
bash
php artisan vendor:publish --tag=telebridge-config
bash
php artisan telebridge:set-webhook
bash
php artisan telebridge:set-webhook
bash
php artisan telebridge:set-webhook {bot_token} --url=https://example.com/webhook
bash
php artisan telebridge:install