Integration of SeaTable 5.1 (Docker) with Telegram: Task Notifications

Hello, SeaTable community!

I am using SeaTable 5.1, deployed on an Ubuntu server via Docker. Access to SeaTable is available through a domain.

I want to set up automatic Telegram notifications whenever a new task is created in a specific table and assigned to a user. My task table includes the following columns: “Task”, “Description”, “Due Date”, and “Assignee” (of type “User”).

Is it possible to achieve this using SeaTable’s built-in automation? Thank you! :raised_hands:

Hi @Spongebob, and welcome to the SeaTable forum!

As far as I know, the answer is… yes AND no :sweat_smile:! Let me explain a bit farther…
SeaTable’s built-in automation feature won’t be able to directly send a Telegram notification by itself without any extra setting and configuration. First of all, whatever solution you use, you’ll probably have to create a Telegram bot. Then, you can:

  • write a python script that will be able to send the Telegram notification, and use the automation feature tu run this script. Using a specific library could eventually be easier than dealing yourself with lower-level http requests, you can find several step-by-step tutorials on the internet such as this one (using pyTelegramBotAPI) or this other one (using python-telegram-bot) for example. However, you’ll have to install the library so your python pipeline will be able to use it, and I dodn’t know if there is something easier than building your own custom python runner image… As far as I understand, depending on the chat you’d like to send the notifications (always the same or depending on the row triggering the automation), you eventually will have to store the chat ids in your table (if the chat depends on the row)
  • use a more complex workflow automation tool. Lot of them seems to have a Telegram integration like Make, Zapier or n8n. If the trigger is straightforward (which seems to be the case for you: filling the user column should trigger the automation), you’ll be able to deal with it directly in the workflow automation tool (so you won’t need SeaTable’s built-in automation) but for some specific cases, you can mix the two approaches by using the SeaTable’s built-in automation to run a python script sending an HTTP request to a webhook trigger in your workflow automation tool (hence the French expression why make it simple when you can make it complicated :joy:)

I imagine it’s not as easy as you were expected, but still I hope that it will help to clarify things for you…

Bests,
Benjamin


I love spending time gathering information and explaining solutions to help you solve your problems. I spend… quite a bit of time on it :sweat_smile: .If you feel grateful for the help I’ve given you, please don’t hesitate to support me. I am also available for paid services (scripts, database architecture, custom development, etc.).

bennhatton Thank you for such a detailed response!

*I already have a bot, and I’m also trying this code:

import requests*
import json*
# Фиксированный список соответствия имен пользователей и их Telegram Chat ID
CHAT_IDS = {
    "Виталий": "",  # Замените на реальный Chat ID Виталия
    "Олег": ""      # Замените на реальный Chat ID Олега
}

# Токен вашего Telegram-бота (получите его через BotFather в Telegram)
BOT_TOKEN = ""  # Замените на токен вашего бота

def send_telegram_message(chat_id, message):
    """
    Функция для отправки сообщения в Telegram
    """
    url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
    payload = {
        "chat_id": chat_id,
        "text": message
    }
    response = requests.post(url, json=payload)
    return response.json()

# Получаем данные из текущей строки
task_name = row["Задача"]  # Замените "Задача" на реальное название колонки с задачей
responsible = row["Ответственный"]  # Замените "Ответственный" на реальное название колонки
deadline = row["Срок исполнения"]  # Замените "Срок исполнения" на реальное название колонки

Blockquote

# Проверяем, есть ли ответственный в CHAT_IDS
if not responsible or responsible not in CHAT_IDS:
    print(f"Ответственный {responsible} не найден в CHAT_IDS")
    exit(1)  # Остановка скрипта с ошибкой

# Формируем сообщение
message = (
    f"🔔 Новое задание для вас:\n\n"
    f"📋 Задача: {task_name}\n"
    f"⏰ Срок исполнения: {deadline}\n"
    f"Пожалуйста, подтвердите выполнение в SeaTable."
)

# Отправляем сообщение в Telegram
chat_id = CHAT_IDS[responsible]
response = send_telegram_message(chat_id, message)

if response.get("ok"):
    print(f"Сообщение успешно отправлено пользователю {responsible}")
else:
    print(f"Ошибка при отправке сообщения: {response.get('description', 'Неизвестная ошибка')}")
    exit(1)  # Остановка скрипта с ошибкой`

I launched it through automation when adding a new row and filling in the “Responsible” field, and the message was sent to Telegram.

However, in the logs, I get the error:
“An error occurred: name ‘row’ is not defined”

Could you please help me figure out what’s wrong? :grimacing: :innocent:

Hi again!
Ok, you don’t start rom scratch, that’s great!!
In your script, on lines 25, 26 and 27 you refer to a variable called row but it’s not defined anywhere. You actually miss the seatable context:

  • at the beginning of your script, import context from the seatable_api:
    from seatable_api import context
  • before using the row variable, define it:
    row = context.current_row

This should do the trick!

Bests,
Benjamin


I love spending time gathering information and explaining solutions to help you solve your problems. I spend… quite a bit of time on it :sweat_smile: .If you feel grateful for the help I’ve given you, please don’t hesitate to support me. I am also available for paid services (scripts, database architecture, custom development, etc.).

Thank you very much, everything worked! My final code turned out like this.:fist:

from seatable_api import context, Base
import requests
import json

# Токен и URL базы SeaTable 
SEATABLE_API_TOKEN = ""  # Замените на ваш API токен
SEATABLE_URL = ""  # Например, https://cloud.seatable.io

# Токен вашего Telegram-бота (получите через BotFather в Telegram)
BOT_TOKEN = ""  # Замените на токен бота

# Подключаемся к базе SeaTable
base = Base(SEATABLE_API_TOKEN, SEATABLE_URL)
base.auth()

# Фиксированный список соответствия имен пользователей и их Telegram Chat ID
CHAT_IDS = {
    "Виталий": "",  # Замените на реальный Chat ID
    "Олег": ""      # Замените на реальный Chat ID
}

def send_telegram_message(chat_id, message):
    """
    Функция для отправки сообщения в Telegram
    """
    url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
    payload = {
        "chat_id": chat_id,
        "text": message
    }
    response = requests.post(url, json=payload)
    return response.json()

# Получаем данные из текущей строки
row = context.current_row  # Получаем текущую строку из SeaTable

task_name = row.get("Задача", "Без названия")  # Название задачи
description = row.get("Описание", "").strip()  # Описание задачи (убираем пробелы)
deadline = row.get("Срок исполнения", "Не указан")  # Срок исполнения
responsible_list = row.get("Исполнитель", [])  # Список ID исполнителей

if not responsible_list:
    print("Ошибка: Исполнитель не указан!")
    exit(1)

# Преобразуем ID пользователей в реальные имена через API
responsible_names = []
for user_id in responsible_list:
    user_info = base.get_user_info(user_id)  # Получаем имя пользователя
    if "name" in user_info:
        responsible_names.append(user_info["name"])
    else:
        print(f"❌ Ошибка: Не удалось получить имя для {user_id}")

# Отфильтруем только тех, у кого есть Chat ID
valid_responsibles = [name for name in responsible_names if name in CHAT_IDS]

if not valid_responsibles:
    print(f"❌ Ошибка: Ни один из исполнителей {responsible_names} не найден в CHAT_IDS!")
    exit(1)

# Формируем сообщение
message = (
    f"🔔 Новое задание для вас:\n\n"
    f"📋 Задача: {task_name}\n"
)

# Добавляем описание, если оно есть
if description:
    message += f"📝 Описание: {description}\n"

message += f"⏰ Срок исполнения: {deadline}\n"
message += "Пожалуйста, подтвердите выполнение в SeaTable."

# Отправляем сообщения всем исполнителям
for responsible in valid_responsibles:
    chat_id = CHAT_IDS[responsible]
    response = send_telegram_message(chat_id, message)

    if response.get("ok"):
        print(f"✅ Сообщение успешно отправлено пользователю {responsible}")
    else:
        print(f"❌ Ошибка при отправке сообщения пользователю {responsible}: {response.get('description', 'Неизвестная ошибка')}")

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.