295 lines
14 KiB
PHP
295 lines
14 KiB
PHP
<?php
|
|
// bot.php - Webhook handler untuk Telegram Bot
|
|
|
|
include 'koneksi.php';
|
|
include 'run_background.php';
|
|
|
|
// === GANTI DENGAN TOKEN BOT TELEGRAM ANDA ===
|
|
$botToken = "8184881871:AAFOz6uzIgxE7rk3WttcKKrr0DtcNGIt-Ho";
|
|
$website = "https://api.telegram.org/bot" . $botToken;
|
|
|
|
// Ambil request dari Telegram
|
|
$content = file_get_contents("php://input");
|
|
$update = json_decode($content, TRUE);
|
|
|
|
if (!$update) {
|
|
exit;
|
|
}
|
|
|
|
if (isset($update["message"])) {
|
|
$chatId = $update["message"]["chat"]["id"];
|
|
|
|
// Command /start
|
|
if (isset($update["message"]["text"]) && $update["message"]["text"] === "/start") {
|
|
$text = "Halo! Saya adalah <b>Identia</b>.\n\n"
|
|
. "Penting untuk diketahui: <b>Ini bukanlah Bot otomatis yang bisa menjawab pesan secara otomatis</b>. Ini adalah <b>saluran interaksi langsung</b> untuk terhubung secara personal dengan Admin Identia.\n\n"
|
|
. "Namun, untuk memulai obrolan langsung dengan Admin, kami perlu memverifikasi data Anda terlebih dahulu.\n\n"
|
|
. "👇 <b>Silakan Bagikan Kontak Terlebih Dahulu untuk Berinteraksi Langsung dengan Admin</b>\n\n"
|
|
. "<i>Catatan: Setelah berhasil, Anda dapat mengakses menu bantuan dengan mengetik /help. Menu tersebut menyediakan akses mandiri secara ringkas untuk:</i>\n"
|
|
. "• <i>Pengelolaan Akun & Akses Mandiri</i>";
|
|
|
|
// Meminta kontak dari user menggunakan ReplyKeyboardMarkup
|
|
$keyboard = [
|
|
'keyboard' => [
|
|
[
|
|
['text' => '📱 Bagikan Kontak Saya', 'request_contact' => true]
|
|
]
|
|
],
|
|
'resize_keyboard' => true,
|
|
'is_persistent' => true
|
|
];
|
|
|
|
$postData = [
|
|
'chat_id' => $chatId,
|
|
'text' => $text,
|
|
'parse_mode' => 'HTML',
|
|
'reply_markup' => json_encode($keyboard)
|
|
];
|
|
|
|
file_get_contents($website . "/sendMessage?" . http_build_query($postData));
|
|
exit;
|
|
}
|
|
|
|
// Konfirmasi / Cek Nomor HP
|
|
if (isset($update["message"]["contact"])) {
|
|
$phoneNumber = $update["message"]["contact"]["phone_number"];
|
|
|
|
// Normalisasi nomor HP (telegram biasa mengirim format internasional, misal 628... atau +628...
|
|
// Kita ubah menjadi 08... menyesuaikan format lokal
|
|
$normalizedPhone = preg_replace('/^\+?62/', '0', $phoneNumber);
|
|
|
|
// Cek database di tabel occupant
|
|
$stmt = $pdo->prepare("SELECT id_occupant FROM occupant WHERE no_hp = ? OR no_hp = ? OR no_hp = ?");
|
|
$stmt->execute([
|
|
$phoneNumber,
|
|
$normalizedPhone,
|
|
"62" . ltrim($normalizedPhone, '0')
|
|
]);
|
|
$occupant = $stmt->fetch(PDO::FETCH_ASSOC);
|
|
|
|
if ($occupant) {
|
|
// Nomor terdaftar, simpan chat_id ke database
|
|
try {
|
|
$pdo->exec("ALTER TABLE occupant ADD COLUMN telegram_id VARCHAR(100) NULL AFTER no_hp");
|
|
} catch (PDOException $e) {
|
|
}
|
|
|
|
$updateStmt = $pdo->prepare("UPDATE occupant SET telegram_id = ? WHERE id_occupant = ?");
|
|
$updateStmt->execute([$chatId, $occupant['id_occupant']]);
|
|
|
|
$text = "✅ <b>Verifikasi Berhasil!</b>\n\n"
|
|
. "Nomor Anda telah terverifikasi sebagai Penghuni <b>Identia</b> yang sah.\n\n"
|
|
. "Saat ini, Anda sudah <b>Terhubung Langsung</b> dengan saluran pribadi Admin <b>Identia</b>.\n\n"
|
|
. "Silakan sampaikan pertanyaan, laporan kendala, atau pesan Anda di sini kapan pun Anda butuhkan. Admin akan membalas pesan Anda dari Control Panel sesegera mungkin.";
|
|
|
|
$removeKeyboard = ['remove_keyboard' => true];
|
|
|
|
$postData = [
|
|
'chat_id' => $chatId,
|
|
'text' => $text,
|
|
'parse_mode' => 'HTML',
|
|
'reply_markup' => json_encode($removeKeyboard)
|
|
];
|
|
file_get_contents($website . "/sendMessage?" . http_build_query($postData));
|
|
} else {
|
|
// Nomor tidak terdaftar
|
|
$text = "Maaf, nomor handphone Anda ($phoneNumber) tidak ditemukan pada daftar Penghuni Identia.\n\nPastikan Anda mendaftar melalui Admin terlebih dahulu.";
|
|
$postData = [
|
|
'chat_id' => $chatId,
|
|
'text' => $text
|
|
];
|
|
file_get_contents($website . "/sendMessage?" . http_build_query($postData));
|
|
}
|
|
exit;
|
|
}
|
|
|
|
// Check if the message contains media
|
|
if (
|
|
isset($update["message"]["photo"]) ||
|
|
isset($update["message"]["document"]) ||
|
|
isset($update["message"]["voice"]) ||
|
|
isset($update["message"]["audio"]) ||
|
|
isset($update["message"]["video"]) ||
|
|
isset($update["message"]["sticker"]) ||
|
|
isset($update["message"]["animation"])
|
|
) {
|
|
|
|
$messageId = $update["message"]["message_id"];
|
|
|
|
// Hapus pesan media yang dikirimkan user tersebut langsung dari Telegram
|
|
$deleteData = [
|
|
'chat_id' => $chatId,
|
|
'message_id' => $messageId
|
|
];
|
|
file_get_contents($website . "/deleteMessage?" . http_build_query($deleteData));
|
|
|
|
// Kirim pesan peringatan ke user
|
|
$text = "⚠️ <b>Pesan Ditolak</b>\n\nMaaf, Anda hanya dapat mengirim pesan berupa <b>Teks Biasa</b> ke Admin.\n\nGambar, stiker, dokumen, atau pesan suara akan otomatis dihapus oleh sistem.";
|
|
$postData = [
|
|
'chat_id' => $chatId,
|
|
'text' => $text,
|
|
'parse_mode' => 'HTML'
|
|
];
|
|
file_get_contents($website . "/sendMessage?" . http_build_query($postData));
|
|
exit;
|
|
}
|
|
|
|
// Handle Teks Biasa (Occupant membalas/chat ke Admin atau kirim command khusus)
|
|
if (isset($update["message"]["text"])) {
|
|
$textMessage = trim($update["message"]["text"]);
|
|
|
|
// Verifikasi bahwa user telegram ini ada telegram_id nya di sistem
|
|
try {
|
|
$pdo->exec("ALTER TABLE occupant ADD COLUMN telegram_id VARCHAR(100) NULL AFTER no_hp");
|
|
} catch (PDOException $e) {
|
|
}
|
|
|
|
$stmt = $pdo->prepare("SELECT id_occupant FROM occupant WHERE telegram_id = ?");
|
|
$stmt->execute([$chatId]);
|
|
$occupant = $stmt->fetch(PDO::FETCH_ASSOC);
|
|
|
|
if ($occupant) {
|
|
$id_occupant = $occupant['id_occupant'];
|
|
|
|
// Dapatkan URL dasar untuk Web App
|
|
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http";
|
|
$host = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';
|
|
$uri = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
|
|
$baseUrl = $protocol . "://" . $host . $uri;
|
|
|
|
// --- Cek Command Khusus (Tidak masuk ke database chats admin) ---
|
|
if ($textMessage === '/help') {
|
|
$manPathMng = __DIR__ . '/manifest_manage.json';
|
|
$mng = file_exists($manPathMng) ? (json_decode(file_get_contents($manPathMng), true) ?: []) : [];
|
|
|
|
// Hapus pesan lama jika ada (mencegah duplikasi)
|
|
if (isset($mng[$chatId])) {
|
|
$oldMsgData = $mng[$chatId];
|
|
if (is_array($oldMsgData)) {
|
|
$oldMsgId = $oldMsgData['msg_id'];
|
|
$oldUserMsgId = $oldMsgData['user_msg_id'] ?? null;
|
|
@file_get_contents($website . "/deleteMessage?chat_id=$chatId&message_id=$oldMsgId");
|
|
if ($oldUserMsgId) {
|
|
@file_get_contents($website . "/deleteMessage?chat_id=$chatId&message_id=$oldUserMsgId");
|
|
}
|
|
} else {
|
|
$oldMsgId = $oldMsgData;
|
|
@file_get_contents($website . "/deleteMessage?chat_id=$chatId&message_id=$oldMsgId");
|
|
}
|
|
unset($mng[$chatId]);
|
|
}
|
|
|
|
$text = "📚 <b>Pusat Bantuan & Manajemen Akun</b>\n\n"
|
|
. "Silakan klik tombol <b>Manage</b> di bawah ini untuk membuka menu pengelolaan akun Anda secara mandiri.";
|
|
|
|
$webAppUrl = $baseUrl . "/occ.php?chat_id=" . $chatId;
|
|
$btn = ['inline_keyboard' => [[['text' => 'Manage', 'web_app' => ['url' => $webAppUrl]]]]];
|
|
$postData = ['chat_id' => $chatId, 'text' => $text, 'parse_mode' => 'HTML', 'reply_markup' => json_encode($btn)];
|
|
|
|
$res = file_get_contents($website . "/sendMessage?" . http_build_query($postData));
|
|
$resData = json_decode($res, true);
|
|
|
|
if (isset($resData['result']['message_id'])) {
|
|
$msgId = $resData['result']['message_id'];
|
|
$userMsgId = $update["message"]["message_id"];
|
|
|
|
$mng[$chatId] = [
|
|
'msg_id' => $msgId,
|
|
'user_msg_id' => $userMsgId
|
|
];
|
|
file_put_contents($manPathMng, json_encode($mng));
|
|
runBackground(__DIR__ . '/auto_delete_manage.php', [$chatId]);
|
|
} else {
|
|
// Update manifest just in case we unset it above
|
|
file_put_contents($manPathMng, json_encode($mng));
|
|
}
|
|
exit;
|
|
}
|
|
|
|
// --- Simpan Pesan Normal ke Admin ---
|
|
// Account ID default biasanya di set ke 1
|
|
$id_account = 1;
|
|
|
|
// Cek apakah pesan ini adalah sebuah reply
|
|
try {
|
|
$pdo->exec("ALTER TABLE chats ADD COLUMN reply_to_chat_id INT NULL AFTER telegram_msg_id");
|
|
} catch (PDOException $e) {
|
|
}
|
|
|
|
$replyToId = null;
|
|
if (isset($update['message']['reply_to_message']) && isset($update['message']['reply_to_message']['message_id'])) {
|
|
$tgReplyId = $update['message']['reply_to_message']['message_id'];
|
|
// Temukan chat lokal berdasarkan telegram_msg_id
|
|
$qRep = $pdo->prepare("SELECT id_chat FROM chats WHERE telegram_msg_id = ? LIMIT 1");
|
|
$qRep->execute([$tgReplyId]);
|
|
$foundRep = $qRep->fetch();
|
|
if ($foundRep)
|
|
$replyToId = $foundRep['id_chat'];
|
|
}
|
|
|
|
$insertStmt = $pdo->prepare("INSERT INTO chats (id_account, id_occupant, sender, message, is_read, telegram_msg_id, reply_to_chat_id) VALUES (?, ?, 'occupant', ?, 0, ?, ?)");
|
|
$insertStmt->execute([$id_account, $occupant['id_occupant'], $textMessage, $update['message']['message_id'], $replyToId]);
|
|
|
|
// WEB PUSH NOTIFICATION DISPATCH (Notify Admins)
|
|
require_once 'PushHelper.php';
|
|
$qOcc = $pdo->prepare("SELECT name FROM occupant WHERE id_occupant = ?");
|
|
$qOcc->execute([$occupant['id_occupant']]);
|
|
$occName = $qOcc->fetchColumn() ?: "Resident";
|
|
PushHelper::broadcastToAdmins($pdo, "New Message from {$occName}", strip_tags($textMessage), '/chats.php');
|
|
|
|
// ALL PREVIOUS MESSAGES TO THIS USER ARE NOW READ
|
|
try {
|
|
$pdo->exec("UPDATE chats SET is_read = 1 WHERE id_occupant = {$occupant['id_occupant']} AND sender = 'account'");
|
|
} catch (PDOException $e) {
|
|
}
|
|
|
|
// Update last_active
|
|
try {
|
|
$pdo->exec("ALTER TABLE occupant ADD COLUMN last_active DATETIME NULL");
|
|
} catch (PDOException $e) {
|
|
}
|
|
$updateLastActive = $pdo->prepare("UPDATE occupant SET last_active = NOW() WHERE id_occupant = ?");
|
|
$updateLastActive->execute([$occupant['id_occupant']]);
|
|
|
|
} else {
|
|
// Belum terhubung & memaksa untuk kirim kontak
|
|
if (in_array($textMessage, ['/help'])) {
|
|
$text = "⚠️ <b>Akses Ditolak</b>\n\nMaaf, perintah <b>$textMessage</b> dinonaktifkan sementara.\n\nAnda <b>Wajib Membagikan Kontak</b> agar sistem dapat memverifikasi identitas Anda terlebih dahulu sebelum fitur ini dapat digunakan.";
|
|
} else {
|
|
$text = "Sesi chat Anda belum terhubung dengan Identia.\n\n👇 <b>Silakan Bagikan Kontak Terlebih Dahulu untuk Berinteraksi Langsung dengan Admin</b>";
|
|
}
|
|
$keyboard = ['keyboard' => [[['text' => '📱 Bagikan Kontak Saya', 'request_contact' => true]]], 'resize_keyboard' => true, 'is_persistent' => true];
|
|
$postData = [
|
|
'chat_id' => $chatId,
|
|
'text' => $text,
|
|
'parse_mode' => 'HTML',
|
|
'reply_markup' => json_encode($keyboard)
|
|
];
|
|
file_get_contents($website . "/sendMessage?" . http_build_query($postData));
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
// Handle Pesan Diedit (Occupant mengedit pesan di Telegram)
|
|
if (isset($update["edited_message"])) {
|
|
$chatId = $update["edited_message"]["chat"]["id"];
|
|
|
|
if (isset($update["edited_message"]["text"])) {
|
|
$editedText = $update["edited_message"]["text"];
|
|
$messageId = $update["edited_message"]["message_id"];
|
|
|
|
$stmt = $pdo->prepare("SELECT id_occupant FROM occupant WHERE telegram_id = ?");
|
|
$stmt->execute([$chatId]);
|
|
$occupant = $stmt->fetch(PDO::FETCH_ASSOC);
|
|
|
|
if ($occupant) {
|
|
// Kita tandai sebagai (Diedit) di akhir teks agar admin tahu
|
|
$newText = htmlspecialchars($editedText) . " <i class='mdi mdi-pencil-outline edit-tag' style='font-size:11px; margin-left:3px;' title='Diedit'></i>";
|
|
|
|
$updateStmt = $pdo->prepare("UPDATE chats SET message = ? WHERE telegram_msg_id = ? AND id_occupant = ?");
|
|
$updateStmt->execute([$newText, $messageId, $occupant['id_occupant']]);
|
|
}
|
|
}
|
|
}
|
|
?>
|