Skip to main content

Phát Triển Bot Telegram

Tạo Bot và Cấu Hình

Bước 1: Tạo Bot Telegram

  1. Mở ứng dụng Telegram và tìm botfather
  2. Gửi tin nhắn /newbot cho BotFather để bắt đầu tạo bot
  3. Làm theo hướng dẫn để đặt tên và username cho bot
  4. Lưu lại token API mà BotFather cung cấp

Create Bot with BotFather

Bước 2: Tạo Channel và Thêm Bot

  1. Tạo một channel mới trong Telegram
  2. Thêm bot vào channel với quyền "Gửi tin nhắn"

Bước 3: Lấy Channel ID

  1. Truy cập URL sau trên trình duyệt:
https://api.telegram.org/bot<YourBOTToken>/getUpdates
  1. Tìm trường chat trong JSON response để lấy id của channel

Triển Khai Bot

Bước 4: Tạo Script Gửi Tin Nhắn

Tạo file telegram-send.sh:

#!/bin/bash

GROUP_ID=<channel_id>
BOT_TOKEN=<bot_token>

if [ "$1" == "-h" ]; then
echo "Usage: `basename $0` \"text message\""
exit 0
fi

if [ -z "$1" ]; then
echo "Add message text as the second argument"
exit 0
fi

if [ "$#" -ne 1 ]; then
echo "You can pass only one argument. For strings with spaces, put them in quotes."
exit 0
fi

curl -s --data "text=$1" --data "chat_id=$GROUP_ID" \
"https://api.telegram.org/bot$BOT_TOKEN/sendMessage" > /dev/null

Bước 5: Cấp Quyền và Kiểm Tra

# Cấp quyền thực thi
chmod +x telegram-send.sh

# Kiểm tra script
./telegram-send.sh "Test message"

Bước 6: Cài Đặt System-wide

# Di chuyển script vào /usr/bin
sudo mv telegram-send.sh /usr/bin/telegram-send

# Cấp quyền root
sudo chown root:root /usr/bin/telegram-send

Sử Dụng Bot

Gửi Tin Nhắn Đơn Giản

telegram-send "Hello from Telegram Bot"

Tích Hợp với Các Tác Vụ

Ví dụ tích hợp với backup database:

mysql --host=localhost --user=root --port=3306 --show-progress -p database \
< backup.sql && \
msg1="restore database mysql succeeded on $(date +%d-%m-%Y)" && \
telegram-send "$msg1"

Xử Lý Lỗi Thường Gặp

  1. Không gửi được tin nhắn

    • Kiểm tra token bot
    • Xác nhận channel ID
    • Kiểm tra quyền của bot trong channel
  2. Script không thực thi

    • Kiểm tra quyền thực thi của file
    • Xác nhận đường dẫn /usr/bin trong PATH

Tài Liệu Tham Khảo