You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在Laravel中实现可回复用户文本的Telegram Bot?解决空响应问题

Hey there! Let's troubleshoot why your Laravel-powered Telegram Bot is sending empty responses and get it replying to user messages smoothly. Here's a step-by-step breakdown to fix this:

1. Verify Your Webhook Setup

First, make sure you have a dedicated route to receive Telegram's updates. Add this to your routes/api.php:

Route::post('/telegram/webhook', [TelegramBotController::class, 'handleUpdate']);

Then, tell Telegram where to send updates by running this curl command (replace <YOUR_BOT_TOKEN> and your domain):

curl -F "url=https://your-production-domain.com/api/telegram/webhook" https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook

You can check if the webhook is active with:

curl https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getWebhookInfo

Look for any errors in the response—this will tell you if Telegram can reach your endpoint.

2. Fix the Update Handling Logic

The most common issue is either not parsing the Telegram update correctly, forgetting to send a reply, or failing to return a valid response to Telegram. Here's a corrected controller example:

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Log;

class TelegramBotController extends Controller
{
    public function handleUpdate(Request $request)
    {
        // Extract the raw update data from Telegram
        $update = $request->json()->all();

        // Skip non-text messages (like photos, stickers, etc.)
        if (!isset($update['message']['text'], $update['message']['chat']['id'])) {
            // Always return 200 OK to Telegram, even if we don't process the update
            return response()->json(['status' => 'ok'], 200);
        }

        // Grab the key details we need
        $chatId = $update['message']['chat']['id'];
        $userInput = $update['message']['text'];

        // Craft your reply—customize this logic to your needs
        $reply = "Got it! You said: *{$userInput}*";

        // Send the reply back to the user
        $this->sendTelegramMessage($chatId, $reply);

        // Critical: Telegram requires a 200 response to stop retrying the update
        return response()->json(['status' => 'ok'], 200);
    }

    private function sendTelegramMessage(int $chatId, string $text)
    {
        $botToken = env('TELEGRAM_BOT_TOKEN');
        $client = new Client();

        try {
            $client->post("https://api.telegram.org/bot{$botToken}/sendMessage", [
                'form_params' => [
                    'chat_id' => $chatId,
                    'text' => $text,
                    'parse_mode' => 'Markdown' // Optional: enables bold/italics
                ]
            ]);
        } catch (\Exception $e) {
            // Log errors for debugging—check storage/logs/laravel.log later
            Log::error("Telegram API Error: " . $e->getMessage());
        }
    }
}
3. Troubleshoot Common Pitfalls
  • Forgot to return a response: Telegram will keep resending updates if your endpoint doesn't return a 200 OK. Don't skip that final return statement!
  • Invalid Bot Token: Double-check your .env file's TELEGRAM_BOT_TOKEN—even a single typo will break API calls.
  • Webhook unreachable: Ensure your domain is publicly accessible (localhost won't work unless you use a tool like ngrok for testing) and that your server allows POST requests to the webhook route.
  • No error logging: If the reply isn't sending, check storage/logs/laravel.log for exceptions from the sendTelegramMessage method—this will tell you if there's a network issue or API error.
4. Optional: Use a Telegram SDK for Easier Development

If you want to avoid writing raw Guzzle requests, use the popular irazasyed/telegram-bot-sdk package. Install it via composer:

composer require irazasyed/telegram-bot-sdk

Add this to config/services.php:

'telegram-bot-api' => [
    'token' => env('TELEGRAM_BOT_TOKEN'),
],

Then simplify your controller:

use Telegram\Bot\Laravel\Facades\Telegram;

public function handleUpdate(Request $request)
{
    $update = Telegram::getWebhookUpdate();
    $message = $update->getMessage();

    if ($message && $message->getText()) {
        Telegram::sendMessage([
            'chat_id' => $message->getChat()->getId(),
            'text' => "You sent: " . $message->getText(),
            'parse_mode' => 'Markdown'
        ]);
    }

    return response()->json(['status' => 'ok'], 200);
}

内容的提问来源于stack exchange,提问作者Mohammad

火山引擎 最新活动