PHP code example of letoceiling-coder / telegram

1. Go to this page and download the library: Download letoceiling-coder/telegram 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/ */

    

letoceiling-coder / telegram example snippets


use LetoceilingCoder\Telegram\Telegram;

// Простое сообщение
Telegram::send(123456789, 'Привет! 👋');

// С форматированием
Telegram::bot()->sendMessage(123456789, '<b>Жирный</b> текст', [
    'parse_mode' => 'HTML'
]);

use LetoceilingCoder\Telegram\Telegram;

$keyboard = Telegram::inlineKeyboard()
    ->row()
    ->callback('Кнопка 1', 'btn1')
    ->callback('Кнопка 2', 'btn2')
    ->row()
    ->url('Открыть сайт', 'https://example.com')
    ->webApp('Открыть Mini App', 'https://t.me/your_bot/app')
    ->toArray();

Telegram::bot()->sendMessage(123456789, 'Выберите действие:', [
    'reply_markup' => json_encode($keyboard)
]);

use LetoceilingCoder\Telegram\MiniApp;

$miniApp = new MiniApp();
$initData = $request->header('X-Telegram-Init-Data');

if ($miniApp->validateInitData($initData)) {
    $user = $miniApp->getUser($initData);
    $userId = $user['id'];
    $username = $user['username'] ?? null;
}

use LetoceilingCoder\Telegram\Telegram;

// Фото
Telegram::bot()->sendPhoto(123456789, 'https://example.com/photo.jpg', [
    'caption' => 'Красивое фото!'
]);

// Документ
Telegram::bot()->sendDocument(123456789, 'https://example.com/file.pdf');

// Видео
Telegram::bot()->sendVideo(123456789, 'https://example.com/video.mp4', [
    'caption' => 'Видео'
]);

// Голосовое сообщение
Telegram::bot()->sendVoice(123456789, 'https://example.com/voice.ogg');

// Опрос
Telegram::bot()->sendPoll(123456789, 'Какой фреймворк лучше?', [
    'Laravel', 'Symfony', 'Yii2'
], ['is_anonymous' => false]);

use LetoceilingCoder\Telegram\Channel;

$channel = new Channel();

// Проверить подписку
$isMember = $channel->isMember('@channel_username', 123456789);

// Получить администраторов
$admins = $channel->getChatAdministrators('@channel_username');

// Забанить пользователя
$channel->banChatMember('@channel_username', 123456789);

// Создать ссылку-приглашение
$inviteLink = $channel->createChatInviteLink('@channel_username', [
    'member_limit' => 100
]);

use LetoceilingCoder\Telegram\Bot;

$bot = new Bot();

// Установить webhook
$bot->setWebhook('https://your-domain.com/api/telegram/webhook', [
    'secret_token' => 'your_secret_token',
    'allowed_updates' => ['message', 'callback_query']
]);

// Получить информацию о webhook
$info = $bot->getWebhookInfo();

// Удалить webhook
$bot->deleteWebhook();

use LetoceilingCoder\Telegram\Telegram;

// Редактировать текст
Telegram::bot()->editMessageText('Новый текст', [
    'chat_id' => 123456789,
    'message_id' => 456
]);

// Удалить сообщение
Telegram::bot()->deleteMessage(123456789, 456);

use LetoceilingCoder\Telegram\Bot;

$bot = new Bot();

// Установить описание бота (показывается до нажатия "Старт")
$bot->setMyDescription('Что может делать этот бот?

🤖 Я бот для обработки чеков.
📸 Отправьте мне фото чека или PDF.
💰 Я извлеку сумму и дату платежа.');

// Установить краткое описание (показывается в профиле)
$bot->setMyShortDescription('Бот для распознавания чеков и извлечения суммы платежа');

// Установить имя бота
$bot->setMyName('Мой Чек Бот');

// Получить текущее описание
$description = $bot->getMyDescription();
echo $description['result']['description'];

// Установить описание для конкретного языка
$bot->setMyDescription('What this bot can do?', 'en');
$bot->setMyShortDescription('Receipt recognition bot', 'en');

// Установить команды бота
$bot->setMyCommands([
    ['command' => 'start', 'description' => 'Начать работу с ботом'],
    ['command' => 'help', 'description' => 'Показать справку'],
    ['command' => 'settings', 'description' => 'Настройки'],
]);

namespace App\Http\Controllers\Api;

use Illuminate\Http\Request;
use LetoceilingCoder\Telegram\Telegram;

class TelegramWebhookController extends Controller
{
    public function handle(Request $request)
    {
        $update = $request->all();
        
        if (isset($update['message'])) {
            $this->handleMessage($update['message']);
        }
        
        if (isset($update['callback_query'])) {
            $this->handleCallback($update['callback_query']);
        }
        
        return response()->json(['ok' => true]);
    }
    
    protected function handleMessage($message)
    {
        $chatId = $message['chat']['id'];
        $text = $message['text'] ?? '';
        
        if ($text === '/start') {
            Telegram::send($chatId, 'Добро пожаловать!');
        }
    }
    
    protected function handleCallback($callback)
    {
        $callbackId = $callback['id'];
        $data = $callback['data'];
        
        Telegram::callback()->answerWithNotification($callbackId, 'Обработано!');
    }
}

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;
use LetoceilingCoder\Telegram\MiniApp;
use LetoceilingCoder\Telegram\Exceptions\TelegramValidationException;

class ValidateTelegramInitData
{
    public function handle(Request $request, Closure $next)
    {
        $initData = $request->header('X-Telegram-Init-Data');
        
        if (!$initData) {
            return response()->json(['error' => 'Unauthorized'], 401);
        }
        
        try {
            $miniApp = new MiniApp();
            $user = $miniApp->validateAndGetUser($initData);
            $request->merge(['telegram_user' => $user]);
        } catch (TelegramValidationException $e) {
            return response()->json(['error' => 'Invalid signature'], 401);
        }
        
        return $next($request);
    }
}

use LetoceilingCoder\Telegram\Exceptions\TelegramValidationException;

try {
    // Если текст длиннее 4096 символов - выбросит исключение
    Telegram::send(123456789, str_repeat('A', 5000));
} catch (TelegramValidationException $e) {
    echo $e->getMessage();
}
bash
php artisan vendor:publish --tag=telegram-config