Bot PHP mẫu này trình bày những điều cơ bản về API Bot Telegram.
Nếu bạn có thắc mắc, hãy thử Câu hỏi thường gặp của chúng tôi hoặc xem trang này để biết thêm ví dụ.
= 500] {
// do not wat to DDOS server if something goes wrong
sleep[10];
return false;
} else if [$http_code != 200] {
$response = json_decode[$response, true];
error_log["Request has failed with error {$response['error_code']}: {$response['description']}\n"];
if [$http_code == 401] {
throw new Exception['Invalid access token provided'];
}
return false;
} else {
$response = json_decode[$response, true];
if [isset[$response['description']]] {
error_log["Request was successful: {$response['description']}\n"];
}
$response = $response['result'];
}
return $response;
}
function apiRequest[$method, $parameters] {
if [!is_string[$method]] {
error_log["Method name must be a string\n"];
return false;
}
if [!$parameters] {
$parameters = array[];
} else if [!is_array[$parameters]] {
error_log["Parameters must be an array\n"];
return false;
}
foreach [$parameters as $key => &$val] {
// encoding to JSON array parameters, for example reply_markup
if [!is_numeric[$val] && !is_string[$val]] {
$val = json_encode[$val];
}
}
$url = API_URL.$method.'?'.http_build_query[$parameters];
$handle = curl_init[$url];
curl_setopt[$handle, CURLOPT_RETURNTRANSFER, true];
curl_setopt[$handle, CURLOPT_CONNECTTIMEOUT, 5];
curl_setopt[$handle, CURLOPT_TIMEOUT, 60];
return exec_curl_request[$handle];
}
function apiRequestJson[$method, $parameters] {
if [!is_string[$method]] {
error_log["Method name must be a string\n"];
return false;
}
if [!$parameters] {
$parameters = array[];
} else if [!is_array[$parameters]] {
error_log["Parameters must be an array\n"];
return false;
}
$parameters["method"] = $method;
$handle = curl_init[API_URL];
curl_setopt[$handle, CURLOPT_RETURNTRANSFER, true];
curl_setopt[$handle, CURLOPT_CONNECTTIMEOUT, 5];
curl_setopt[$handle, CURLOPT_TIMEOUT, 60];
curl_setopt[$handle, CURLOPT_POST, true];
curl_setopt[$handle, CURLOPT_POSTFIELDS, json_encode[$parameters]];
curl_setopt[$handle, CURLOPT_HTTPHEADER, array["Content-Type: application/json"]];
return exec_curl_request[$handle];
}
function processMessage[$message] {
// process incoming message
$message_id = $message['message_id'];
$chat_id = $message['chat']['id'];
if [isset[$message['text']]] {
// incoming text message
$text = $message['text'];
if [strpos[$text, "/start"] === 0] {
apiRequestJson["sendMessage", array['chat_id' => $chat_id, "text" => 'Hello', 'reply_markup' => array[
'keyboard' => array[array['Hello', 'Hi']],
'one_time_keyboard' => true,
'resize_keyboard' => true]]];
} else if [$text === "Hello" || $text === "Hi"] {
apiRequest["sendMessage", array['chat_id' => $chat_id, "text" => 'Nice to meet you']];
} else if [strpos[$text, "/stop"] === 0] {
// stop now
} else {
apiRequestWebhook["sendMessage", array['chat_id' => $chat_id, "reply_to_message_id" => $message_id, "text" => 'Cool']];
}
} else {
apiRequest["sendMessage", array['chat_id' => $chat_id, "text" => 'I understand only text messages']];
}
}
define['WEBHOOK_URL', '//my-site.example.com/secret-path-for-webhooks/'];
if [php_sapi_name[] == 'cli'] {
// if run from console, set or delete webhook
apiRequest['setWebhook', array['url' => isset[$argv[1]] && $argv[1] == 'delete' ? '' : WEBHOOK_URL]];
exit;
}
$content = file_get_contents["php://input"];
$update = json_decode[$content, true];
if [!$update] {
// receive wrong update, must not happen
exit;
}
if [isset[$update["message"]]] {
processMessage[$update["message"]];
}
Ghi chú. Để bật tệp nhật ký lỗi, hãy sao chép TelegramErrorLogger. php trong cùng thư mục của Telegram. tập tin php
Cấu hình [WebHook]
Điều hướng đến https. //api. điện báo. org/bot[BOT_TOKEN]/setWebhook?url=https. // trang web của bạn. com/your_update. php Hoặc sử dụng phương thức setWebhook của lớp Telegram
ví dụ
$telegram = new Telegram['YOUR TELEGRAM TOKEN HERE']; $chat_id = $telegram->ChatID[]; $content = array['chat_id' => $chat_id, 'text' => 'Test']; $telegram->sendMessage[$content];
Nếu bạn muốn nhận một số tham số cụ thể từ phản hồi Telegram
$telegram = new Telegram['YOUR TELEGRAM TOKEN HERE']; $result = $telegram->getData[]; $text = $result['message'] ['text']; $chat_id = $result['message'] ['chat']['id']; $content = array['chat_id' => $chat_id, 'text' => 'Test']; $telegram->sendMessage[$content];
Để tải lên Ảnh hoặc một số tệp khác, bạn cần tải nó bằng CurlFile
// Load a local file to upload. If is already on Telegram's Servers just pass the resource id $img = curl_file_create['test.png','image/png']; $content = array['chat_id' => $chat_id, 'photo' => $img ]; $telegram->sendPhoto[$content];
Để tải xuống một tệp trên máy chủ của Telegram
$file = $telegram->getFile[$file_id]; $telegram->downloadFile[$file['result']['file_path'], './my_downloaded_file_on_local_server.png'];
Xem cập nhật. php hoặc cập nhật coway. php cho ví dụ hoàn chỉnh. Nếu bạn muốn xem CowSay Bot hoạt động, hãy thêm nó
Nếu bạn muốn sử dụng getUpdates thay vì WebHook, bạn cần gọi hàm
php composer.phar require eleirbag89/telegrambotphp
8 bên trong chu trình for$telegram = new Telegram['YOUR TELEGRAM TOKEN HERE']; $req = $telegram->getUpdates[]; for [$i = 0; $i < $telegram-> UpdateCount[]; $i++] { // You NEED to call serveUpdate before accessing the values of message in Telegram Class $telegram->serveUpdate[$i]; $text = $telegram->Text[]; $chat_id = $telegram->ChatID[]; if [$text == '/start'] { $reply = 'Working'; $content = array['chat_id' => $chat_id, 'text' => $reply]; $telegram->sendMessage[$content]; } // DO OTHER STUFF }
Xem getUpdates. php cho ví dụ hoàn chỉnh
Chức năng
Để có tài liệu chức năng đầy đủ và cập nhật, hãy kiểm tra http. //eleirbag89. github. io/TelegramBotPHP/
Xây dựng bàn phím
Các bot của Telegram có thể có hai loại bàn phím khác nhau. Nội tuyến và trả lời.
InlineKeyboard được liên kết với một tin nhắn cụ thể, trong khi ReplyKeyboard được liên kết với toàn bộ cuộc trò chuyện.
Chúng đều là một mảng các nút, đại diện cho các hàng và cột.
Ví dụ, bạn có thể sắp xếp ReplyKeyboard như thế này. sử dụng mã này.
php composer.phar require eleirbag89/telegrambotphp
0Khi người dùng nhấp vào nút, văn bản nút sẽ được gửi lại cho bot.
Đối với InlineKeyboard, điều này khá giống nhau [nhưng bạn cần cung cấp URL hợp lệ hoặc dữ liệu Gọi lại]
php composer.phar require eleirbag89/telegrambotphp
1Đây là danh sách tất cả các chức năng trợ giúp để tạo bàn phím dễ dàng
php composer.phar require eleirbag89/telegrambotphp
2Gửi bàn phím tùy chỉnh. $option là một mảng của mảng KeyboardButton.
Kiểm tra để biết thêm thông tin.
php composer.phar require eleirbag89/telegrambotphp
3Gửi bàn phím tùy chỉnh. $inline_keyboard là một mảng của mảng InlineKeyboardButton.
Kiểm tra để biết thêm thông tin.
php composer.phar require eleirbag89/telegrambotphp
4Tạo một InlineKeyboardButton.
Kiểm tra để biết thêm thông tin.
php composer.phar require eleirbag89/telegrambotphp
5Tạo Nút bàn phím.
Kiểm tra để biết thêm thông tin.
php composer.phar require eleirbag89/telegrambotphp
6Ẩn bàn phím tùy chỉnh.
Kiểm tra để biết thêm thông tin.
php composer.phar require eleirbag89/telegrambotphp
7Hiển thị giao diện Trả lời cho người dùng.
Kiểm tra để biết thêm thông tin.
biểu tượng cảm xúc
Để biết danh sách các biểu tượng cảm xúc sẽ sử dụng trong tin nhắn bot của bạn, vui lòng tham khảo cột Số byte của bảng này. http. // ứng dụng. timwhitlock. thông tin/biểu tượng cảm xúc/bảng/unicode
Giấy phép
Phần mềm nguồn mở này được phân phối theo Giấy phép MIT. xem PHÉP. md
Đóng góp
Tất cả các loại đóng góp đều được chào đón - mã, thử nghiệm, tài liệu, báo cáo lỗi, tính năng mới, v.v.