1. Tạo 1 file goolge sheet
2. Tạo app script trong google sheet -> dán đoạn code dưới đây
const TELEGRAM_API_TOKEN = '7459862651:AAE5ITVfc5JIiKLFOkE0IEwURvnrkJKtPJ8'; // Thay bằng token của bạn
const SHEET_NAME = 'Sheet1'; // Tên sheet bạn muốn lưu tin nhắn vào
function doPost(e) {
const json = JSON.parse(e.postData.contents); // Lấy dữ liệu từ Telegram
const chatId = json.message.chat.id;
const user = json.message.from.first_name;
const message = json.message.text;
// Kiểm tra nếu tin nhắn không rỗng
if (!message) {
sendTelegramMessage(chatId, 'Bạn chưa gửi tin nhắn văn bản!');
return; // Nếu không có tin nhắn văn bản, thoát luôn
}
// Lấy sheet và lưu dữ liệu vào
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME);
sheet.appendRow([new Date(), user, message]);
// Đáp lại Telegram
sendTelegramMessage(chatId, 'Tin nhắn của bạn đã được nhận!');
}
function sendTelegramMessage(chatId, message) {
if (!message || !chatId) return; // Đảm bảo không gửi tin nhắn rỗng hoặc không có chatId
const url = `https://api.telegram.org/bot${TELEGRAM_API_TOKEN}/sendMessage`;
const payload = {
method: 'post',
payload: {
chat_id: chatId,
text: message
}
};
try {
UrlFetchApp.fetch(url, payload);
} catch (error) {
Logger.log('Lỗi khi gửi tin nhắn: ' + error);
}
}
3. Chạy đường dẫn sau để gọi API Telegram setWebhook
để đảm bảo bot nhận tin nhắn từ Telegram.
https://api.telegram.org/bot<your_bot_token>/setWebhook?url=<your_deployed_url>
Nhận xét
Đăng nhận xét