228 lines
8.3 KiB
PHP
228 lines
8.3 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Page;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Http;
|
|
use Illuminate\Support\Facades\Log;
|
|
|
|
class TelegramController extends Controller
|
|
{
|
|
public ?string $token = null;
|
|
public ?string $baseUrl = null;
|
|
|
|
public function __construct()
|
|
{
|
|
// Token de prueba (recuerda revocarlo después)
|
|
$this->token = '8617998449:AAFK4DNGPV3efRpmcjeMVZhdTUeErGj-ePc';
|
|
$this->baseUrl = "https://api.telegram.org/bot{$this->token}";
|
|
|
|
// Si prefieres usar config (recomendado para producción)
|
|
// $this->token = config('services.telegram.token');
|
|
// $this->baseUrl = config('services.telegram.base_url') . "/bot{$this->token}";
|
|
}
|
|
|
|
/**
|
|
* Enviar texto simple
|
|
*/
|
|
public function sendText($chatId, $text, $parseMode = null)
|
|
{
|
|
$params = [
|
|
'chat_id' => $chatId,
|
|
'text' => $text,
|
|
];
|
|
|
|
if ($parseMode) {
|
|
$params['parse_mode'] = $parseMode;
|
|
}
|
|
|
|
$response = Http::post("{$this->baseUrl}/sendMessage", $params);
|
|
|
|
return $response->json();
|
|
}
|
|
|
|
/**
|
|
* Enviar mensaje con teclado personalizado
|
|
*/
|
|
public function sendKeyboard($chatId, $text, $buttons = [])
|
|
{
|
|
$keyboard = [
|
|
'keyboard' => $buttons,
|
|
'resize_keyboard' => true,
|
|
'one_time_keyboard' => false,
|
|
];
|
|
|
|
$response = Http::post("{$this->baseUrl}/sendMessage", [
|
|
'chat_id' => $chatId,
|
|
'text' => $text,
|
|
'reply_markup' => json_encode($keyboard),
|
|
]);
|
|
|
|
return $response->json();
|
|
}
|
|
|
|
/**
|
|
* Enviar botones inline
|
|
*/
|
|
public function sendInlineKeyboard($chatId, $text, $buttons = [])
|
|
{
|
|
$inlineKeyboard = [
|
|
'inline_keyboard' => $buttons,
|
|
];
|
|
|
|
$response = Http::post("{$this->baseUrl}/sendMessage", [
|
|
'chat_id' => $chatId,
|
|
'text' => $text,
|
|
'reply_markup' => json_encode($inlineKeyboard),
|
|
]);
|
|
|
|
return $response->json();
|
|
}
|
|
|
|
/**
|
|
* Webhook principal con sistema de comandos mejorado
|
|
*/
|
|
public function webhook(Request $request)
|
|
{
|
|
$update = $request->all();
|
|
|
|
Log::info('Webhook recibido', $update);
|
|
|
|
if (isset($update['message'])) {
|
|
$chatId = $update['message']['chat']['id'];
|
|
$text = trim($update['message']['text'] ?? '');
|
|
$firstName = $update['message']['from']['first_name'] ?? 'Usuario';
|
|
|
|
// Sistema de comandos
|
|
$comandos = [
|
|
'/start' => function () use ($firstName) {
|
|
return "🎈 ¡Bienvenido a SkyBalloons, {$firstName}!\n\n" . "Somos especialistas en decoración con globos para eventos.\n\n" . "🎯 Comandos disponibles:\n" . "/help - Ver ayuda\n" . "/info - Información del bot\n" . "/contacto - Contactar soporte\n" . "/precios - Solicitar precios\n" . '/eventos - Tipos de eventos';
|
|
},
|
|
|
|
'/help' => function () {
|
|
return "📖 *Comandos disponibles:*\n\n" . "/start - Iniciar el bot\n" . "/help - Mostrar esta ayuda\n" . "/info - Información del bot\n" . "/contacto - Datos de contacto\n" . "/precios - Información de precios\n" . "/eventos - Tipos de eventos que realizamos\n\n" . '💡 *Ejemplo:* Envíame un mensaje directo y te responderé.';
|
|
},
|
|
|
|
'/info' => function () {
|
|
return "🤖 *Información del Bot*\n\n" . "📌 Nombre: SkyBalloons Bot\n" . "👤 Usuario: @skyballoons_bot\n" . '📱 Framework: Laravel ' . app()->version() . "\n" . "🔄 Versión: 2.0\n" . '📅 Estado: Activo (modo prueba)';
|
|
},
|
|
|
|
'/contacto' => function () {
|
|
return "📞 *Contacto SkyBalloons*\n\n" . "📧 Email: skyballoons@ejemplo.com\n" . "📱 Telegram: @skyballoons_soporte\n" . "📷 Instagram: @skyballoons\n" . "📍 Ubicación: Ciudad de México\n\n" . '⏰ Horario: Lunes a Viernes 9am - 6pm';
|
|
},
|
|
|
|
'/precios' => function () {
|
|
return "💰 *Precios Referenciales*\n\n" . "🎈 Globo latex (docena): $120 MXN\n" . "✨ Globo metalizado (docena): $250 MXN\n" . "🎉 Arco de globos: Desde $800 MXN\n" . "🎊 Centro de mesa: Desde $350 MXN\n" . "🎈 Globos con helio (c/u): $40 MXN\n\n" . '📩 Solicita cotización personalizada con /cotizar';
|
|
},
|
|
|
|
'/eventos' => function () {
|
|
return "🎪 *Eventos que realizamos*\n\n" . "✅ Cumpleaños\n" . "✅ Bodas\n" . "✅ Baby showers\n" . "✅ Graduaciones\n" . "✅ Eventos corporativos\n" . "✅ Aniversarios\n" . "✅ Fiestas infantiles\n\n" . '¡Pide tu presupuesto sin compromiso!';
|
|
},
|
|
|
|
'/cotizar' => function () use ($chatId) {
|
|
// Aquí podrías iniciar un flujo de conversación
|
|
return "📝 *Solicitud de cotización*\n\n" . "Por favor, responde estas preguntas:\n" . "1. ¿Qué tipo de evento será?\n" . "2. ¿Cuántos invitados aproximadamente?\n" . "3. ¿Cuándo es la fecha del evento?\n" . "4. ¿Tienes algún diseño en mente?\n\n" . 'Un asesor te contactará en breve.';
|
|
},
|
|
];
|
|
|
|
// Verificar si el comando existe
|
|
if (isset($comandos[$text])) {
|
|
$respuesta = $comandos[$text]();
|
|
$this->sendText($chatId, $respuesta, 'Markdown');
|
|
}
|
|
// Responder mensajes de texto normales
|
|
else {
|
|
$respuesta = "🎈 ¡Hola {$firstName}!\n\n" . "Recibí tu mensaje: \"{$text}\"\n\n" . "Usa /help para ver todos los comandos disponibles.\n\n" . "💡 *Tips:*\n" . "• /precios - Ver lista de precios\n" . "• /eventos - Tipos de eventos\n" . '• /cotizar - Solicitar cotización';
|
|
|
|
$this->sendText($chatId, $respuesta, 'Markdown');
|
|
}
|
|
}
|
|
// Manejar callback queries (botones inline)
|
|
elseif (isset($update['callback_query'])) {
|
|
$callbackQuery = $update['callback_query'];
|
|
$chatId = $callbackQuery['message']['chat']['id'];
|
|
$data = $callbackQuery['data'];
|
|
|
|
// Responder al callback
|
|
Http::post("{$this->baseUrl}/answerCallbackQuery", [
|
|
'callback_query_id' => $callbackQuery['id'],
|
|
'text' => "Procesando: {$data}",
|
|
'show_alert' => false,
|
|
]);
|
|
|
|
// Enviar mensaje según el callback
|
|
$this->sendText($chatId, "Has seleccionado: {$data}\n\nUn asesor te contactará pronto.");
|
|
}
|
|
|
|
return response()->json(['ok' => true], 200);
|
|
}
|
|
|
|
/**
|
|
* Obtener actualizaciones manualmente (sin webhook)
|
|
*/
|
|
public function getUpdates(Request $request)
|
|
{
|
|
$offset = $request->get('offset', 0);
|
|
$limit = $request->get('limit', 100);
|
|
$timeout = $request->get('timeout', 30);
|
|
|
|
$response = Http::get("{$this->baseUrl}/getUpdates", [
|
|
'offset' => $offset,
|
|
'limit' => $limit,
|
|
'timeout' => $timeout,
|
|
]);
|
|
|
|
return response()->json($response->json());
|
|
}
|
|
|
|
/**
|
|
* Configurar webhook
|
|
*/
|
|
public function setWebhook(Request $request)
|
|
{
|
|
$url = $request->get('url');
|
|
|
|
if (!$url) {
|
|
return response()->json(['error' => 'URL requerida'], 400);
|
|
}
|
|
|
|
$response = Http::post("{$this->baseUrl}/setWebhook", [
|
|
'url' => $url,
|
|
]);
|
|
|
|
return response()->json($response->json());
|
|
}
|
|
|
|
/**
|
|
* Eliminar webhook
|
|
*/
|
|
public function deleteWebhook()
|
|
{
|
|
$response = Http::post("{$this->baseUrl}/deleteWebhook");
|
|
|
|
return response()->json($response->json());
|
|
}
|
|
|
|
/**
|
|
* Obtener información del webhook
|
|
*/
|
|
public function getWebhookInfo()
|
|
{
|
|
$response = Http::get("{$this->baseUrl}/getWebhookInfo");
|
|
|
|
return response()->json($response->json());
|
|
}
|
|
|
|
/**
|
|
* Enviar mensaje directo (endpoint para pruebas)
|
|
*/
|
|
public function sendMessage(Request $request)
|
|
{
|
|
$chatId = $request->get('chat_id', 7981938691); // Tu chat ID por defecto
|
|
$text = $request->get('text', 'Mensaje de prueba');
|
|
|
|
return response()->json($this->sendText($chatId, $text, 'Markdown'));
|
|
}
|
|
}
|