Phước

Phước

2023-10-07 11:16:35

Xây dựng ứng dụng Golang đơn giản với Chatbot Telegram và Google API

Trong bài viết này, chúng ta sẽ tìm hiểu cách tạo một chatbot Telegram bằng ngôn ngữ lập trình Go để tương tác với Google Cloud Translation API. Chatbot này cho phép người dùng gửi các tin nhắn văn bản bằng bất kỳ ngôn ngữ nào, và bot sẽ trả lời bằng cách dịch văn bản đầu vào thành tiếng Việt thông qua Google Cloud Translation API.

Yêu cầu:

  • ​Tài khoản Google Cloud với Google Cloud Translation API đã được kích hoạt.
  • Tài khoản Telegram và quyền truy cập vào BotFather để tạo một bot mới và nhận mã thông báo của bot.

Bước 1: Thiết lập Môi trường

Trước khi bắt đầu viết mã, hãy đảm bảo bạn đã cài đặt Go trên hệ thống của mình. Bạn cũng cần cài đặt các gói Go cần thiết để tương tác với API Telegram và để thực hiện việc dịch ngôn ngữ theo trích dẫn bên dưới:

$ go get golang.org/x/text/language
$ go get github.com/go-telegram-bot-api/telegram-bot-api/v5
$ go get cloud.google.com/go/translate
$ go get google.golang.org/api/option

Bước 2: Tạo Chatbot Telegram

Sử dụng BotFather của Telegram, tạo một chatbot mới và nhận mã thông báo của bot. Mã thông báo này sẽ được sử dụng để xác thực các yêu cầu tới API Telegram. 

Bước 3: Kích hoạt Google Cloud Translation API

Nếu bạn chưa làm điều này, hãy tạo tài khoản Google Cloud và kích hoạt Google Cloud Translation API.

Ngoài ra, hãy tạo một khóa API để truy cập vào Google Cloud Translation API.

Sau khi đã thực hiện 3 bước trên, chúng ta bắt đầu viết code cho dự án với từng function sau:

func translateText(targetLanguage, text string) (string, error) {
        apiKey := "YOUR_API_KEY"
        // text := "The Go Gopher is cute"
        // targetLanguage := "vi"

        ctx := context.Background()

        opts := option.WithAPIKey(apiKey)

        lang, err := language.Parse(targetLanguage)
        if err != nil {
                return "", fmt.Errorf("language.Parse: %w", err)
        }
        client, err := translate.NewClient(ctx,opts)
        if err != nil {
                return "", err
        }
        defer client.Close()
        resp, err := client.Translate(ctx, []string{text}, lang, nil)
        if err != nil {
                return "", fmt.Errorf("Translate: %w", err)
        }
        if len(resp) == 0 {
                return "", fmt.Errorf("Translate returned empty response to text: %s", text)
        }
        return resp[0].Text, nil
}

Function translateText có chức năng gọi Google Translate API để dịch văn bản, truyền 2 tham số: targetLanguage, text. Thay thế "YOUR_API_KEY" bằng API_KEY từ Google API Credentials.

Tiếp theo trong func main(), chúng ta thiết lập cấu hình cho Telegram Chatbot và tích hợp function translateText()

func main() {
    ///Telegram Config   
    bot, err := tgbotapi.NewBotAPI("YOUR_BOT_TOKEN")
    if err != nil {        
        log.Panic(err)
    }    
    bot.Debug = true    
    log.Println("Authorized on account %s",     
    bot.Self.UserName)
   
    u := tgbotapi.NewUpdate(0)   
    u.Timeout = 60
    
    //Setup Route for Telegram Chatbot
    updates := bot.GetUpdatesChan(u)
    for update := range updates {
        if update.Message == nil { // ignore any non-Message updates
            continue
        }

        if !update.Message.IsCommand() { // ignore any non-command Messages
            continue
        }

        // Create a new MessageConfig.
        // We don't have text yet,
        // so we leave it empty.
        msg := tgbotapi.NewMessage(update.Message.Chat.ID, "")

        // Extract the command from the Message.
        switch update.Message.Command() {
           case "help":
               msg.Text = "Hello! I am a translation bot. Use /dich to translate the text."
           case "dich":
               // Translate the text to the target language.
               textToTranslate := strings.TrimSpace(update.Message.Text[len("/dich"):])
               translatedText, err := translateText("en", textToTranslate)
               if err != nil {
                  fmt.Printf("Failed to translate text: %v\n", err)
                  return
               }

               // Print the translated text.
               msg.Text = "Translated Text: "+translatedText
               fmt.Printf("Translated Text: %s\n", translatedText)
           default:
               msg.Text = "I don't know that command"
        }

        if _, err := bot.Send(msg); err != nil {
           log.Panic(err)
        }
    }
}

Sau khi đã code 2 function main()translateText() chúng ta thực hiện run code. 

$ go run main.go

Dưới đây là kết quả từ Chatbot:

Chúng ta đã hoàn thành 1 ứng dụng cơ bản sử dụng Telegram Chatbot với Google API bằng ngôn ngữ Golang.

Xây dựng ứng dụng Golang đơn giản với Chatbot Telegram và Google API
0 Likes0 Comments