Tạo Telegram bot để phục vụ làm việc với GoogleSheet

by LamNT59
527 views

1. Bài toán

  • Việc truy xuất các dữ liệu trên một file Excel hay GoogleSheet là rất dễ dàng với những người có kĩ năng Office cơ bản.
  • Tuy nhiên với một người không có kiến thức đủ để làm việc với Excel, GoogleSheet hoặc muốn truy xuất thông tin từ file ngay lập tức mà lại đang không có các công cụ hỗ trợ làm việc, viết các câu lệnh trên Excel, GoogleSheet, thì việc truy xuất dữ liệu này sẽ trở nên khó khăn.
  • Khi đó việc tạo một trợ lý ảo, một con bot giúp người dùng có thể truy cập đến dữ liệu trên một file Excel, GoogleSheet là một việc rất hữu ích.
  • Ở đây tôi sẽ dùng bot trên Telegram vì đây là một ứng dụng nhắn tin khá phổ biến và cho phép developer phát triển nhiều thứ trên đó.
  • Về ngôn ngữ lập trình tôi sẽ sử dụng Python vì ngôn ngữ này cho phép developer làm việc dễ dàng với Excel, GoogleSheet.

2. Tạo bot trên Telegram

  • Đầu tiên người dùng cần phải truy cập vào ứng dụng Telegram, vào thanh tìm kiếm và tìm kiếm từ khoá BotFather
  • Gõ lệnh /newbot để tạo bắt đầu tạo bot mới
  • Tiếp theo chúng ta sẽ đặt tên cho bot của mình.
  • Sau khi đặt tên BotFather sẽ yêu cầu chúng ta chọn username cho con bot, đây cũng chính là tên giúp chúng ta có thể tìm kiếm con bot ở trên Telegram như các tìm kiếm một người dùng.
Sau khi hoàn thành xong bước trên BotFather sẽ gửi lại cho chúng ta thông tin về bot
  • Link để truy cập vào bot: t.me/csv_xlsx_bot
  • Access token: developer sẽ sử dụng token để làm việc với các API từ đó phát triển các tính năng khác cho con bot của mình.

3. Sử dụng Python để truy xuất data từ GoogleSheet

  • Đầu tiên chúng ta cần tạo một project Python
  • Thêm các thư viện cần thiết: pip, pandas, numpy
  • Chạy các câu lệnh sau ở terminal để thêm các thư viện cần dùng
  • Lưu ý là link GoogleSheet cần được public access cho tất cả người dùng có thể truy cập
# Install pip
python3 get-pip.py
# Install pandas
pip install pandas
# Install numpy
pip install numpy

Tạo file .env: file này được dùng để lưu token của Telegram API developer

export BOT_TOKEN=6354775494:*************************************

Tạo một file đặt tên là utils.py: file này sẽ chứa các thuật toán làm việc với file GoogleSheet

  • Chúng ta sẽ sử dụng thư viện pandas đọc file GoogleSheet
  • Các trường thông tin truy vấn được sử dụng ở đây là
Các trường thông tin truy vấn được sử dụng:
  • download_link: đường dẫn file GoogleSheet cần truy vấn
  • sheet_name: tab trong file GoogleSheet cần truy vấn
  • usecols: các cột giá trị truy vấn
  • df = df[(df[‘City’]==’Los Angeles’)]: dùng để filter các bản ghi có trường ‘City’ là ‘Los Angeles’
Kết quả trả về sẽ được parse sang string bằng việc sử dụng thư viện numpy
import requests
import pandas as pd
import numpy as np

download_link_prefix = "https://drive.google.com/uc?export=download&id="
def read_data_from_file(file_path):
    sheet_name = 'FoodSales'
    query_cols = ['ID','Date','City']
    download_link = get_google_sheets_download_link(file_path)
    if (download_link == None): return None
    else: 
        df = pd.read_excel(download_link, sheet_name=sheet_name, usecols=query_cols)
        df = df[(df['City']=='Los Angeles')]
        mat = np.array(df)
        return np.array2string(mat)

def get_google_sheets_download_link(file_path):
    file_split= file_path.split('/')
    if len(file_split) > 5:
        return download_link_prefix + file_split[5]
    else:
        return None

Tạo file main.py: file này sẽ bao gồm các thao tác làm việc với bot Telegram

  • bot = telebot.TeleBot(BOT_TOKEN): tạo một instance của bot Telegram
  • @bot.message_handler(commands=[]): đoạn code sẽ tạo phương thức lắng nghe lệnh điều khiển từ người dùng
  • bot.reply_to(): gửi lại tin nhắn tới người dùng
  • bot.infinity_polling(): câu lệnh cho phép bot Telegram sẽ lắng nghe liên tục các thông tin, lệnh từ phía người dùng
  • bot.send_message(): gửi lại câu trả lời cho tin nhắn nhận được từ người dùng
  • bot.register_next_step_handler(): đăng ký function sẽ được thực thi ngay sau khi nhận được phản hồi từ phía người dùng
  • file_path = message.text: đọc tin nhắn, câu lệnh được gửi từ phía người dùng
import os
import telebot
from dotenv import load_dotenv
load_dotenv()
from utils import read_data_from_file, write_data_to_file

BOT_TOKEN = os.environ.get('BOT_TOKEN')

bot = telebot.TeleBot(BOT_TOKEN)

@bot.message_handler(commands=['start', 'hello'])
def send_welcome(message):
    bot.reply_to(message, "Howdy, how are you doing?")

@bot.message_handler(commands=['read_record'])
def send_welcome(message):
    sent_msg = bot.send_message(message.chat.id, "So, what link would you like to read?")
    bot.register_next_step_handler(sent_msg, read_csv_xlsx_handler)

def read_csv_xlsx_handler(message):
    file_path = message.text
    result = read_data_from_file(file_path)
    if (result == None): bot.send_message(message.chat.id, "Could not read")
    else: bot.send_message(message.chat.id, result)

bot.infinity_polling()
  • Để chạy con bot của mình ta cần gõ lệnh sau trên terminal:
python3 main.py

4. Kết quả

  • File được dùng để đọc dữ liệu: Sample Link
  • Video Demo

5. Tham khảo

  • Telegram Bot Developer API: https://core.telegram.org/bots/features
  • Pandas: https://pandas.pydata.org/docs/
  • IDE: Visual Studio Code
  • Language: Python

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

You may also like