Skip to content

Установка и настройка телеграм-бота для отправки HTTP-запросов в 1с

📘 Инструкция по установке и обслуживанию Telegram JSON File Bot

🧩 Зависимости

  • Python 3.9+
  • python3-venv, pip
  • Рабочий Telegram-бот (токен от @BotFather)
  • URL HTTP-сервиса на стороне 1С
  • Пользователь god на сервере

📁 1. Установка

Terminal window
sudo apt update
sudo apt install python3 python3-pip python3-venv -y

Создаём директорию для проекта:

Terminal window
mkdir -p ~/telegram_bot
cd ~/telegram_bot

Создаём виртуальное окружение и активируем:

Terminal window
python3 -m venv venv
source venv/bin/activate

Устанавливаем зависимости:

Terminal window
pip install python-telegram-bot requests

🧠 2. Создание bot.py

Создай файл bot.py:

Terminal window
nano ~/telegram_bot/bot.py

Вставь код (адаптируй токен и URL):

import logging
import requests
from io import BytesIO
from telegram import Update
from telegram.ext import ApplicationBuilder, MessageHandler, ContextTypes, filters
# Настройки
BOT_TOKEN = 'ТВОЙ_ТОКЕН'
TARGET_URL = 'http://IP_ИЛИ_ДОМЕН_1С/endpoint'
ALLOWED_USERS = {123456789} # замени на свой Telegram ID
HTTP_USERNAME = '1c_user' # если требуется Basic Auth
HTTP_PASSWORD = '1c_pass'
logging.basicConfig(level=logging.INFO)
def is_authorized(user_id: int) -> bool:
return user_id in ALLOWED_USERS
async def handle_file(update: Update, context: ContextTypes.DEFAULT_TYPE):
user_id = update.effective_user.id
if not is_authorized(user_id):
await update.message.reply_text("⛔ Доступ запрещён.")
return
document = update.message.document
if not document.file_name.endswith('.json') and not document.file_name.endswith('.txt'):
await update.message.reply_text("Отправьте .json или .txt файл.")
return
file = await document.get_file()
buffer = BytesIO()
await file.download_to_memory(out=buffer)
content_bytes = buffer.getvalue()
content_str = content_bytes.decode('utf-8', errors='replace')
try:
response = requests.post(
TARGET_URL,
data=content_str.encode('utf-8'),
headers={"Content-Type": "application/json"},
auth=(HTTP_USERNAME, HTTP_PASSWORD)
)
await update.message.reply_text(
f"✅ Файл отправлен.\n"
f"Статус: {response.status_code}\n"
f"Ответ:\n{response.text}"
)
except Exception as e:
await update.message.reply_text(f"❌ Ошибка при отправке: {str(e)}")
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await update.message.reply_text(f"👋 Привет! Твой Telegram ID: {update.effective_user.id}")
if __name__ == '__main__':
app = ApplicationBuilder().token(BOT_TOKEN).build()
app.add_handler(MessageHandler(filters.Document.ALL, handle_file))
app.add_handler(MessageHandler(filters.TEXT & filters.Regex(r'^/start'), start))
app.run_polling()

🛠 3. Настройка systemd-сервиса

Создай файл:

Terminal window
sudo nano /etc/systemd/system/telegram-bot.service

Содержимое:

[Unit]
Description=Telegram JSON File Bot
After=network.target
[Service]
Type=simple
WorkingDirectory=/home/god/telegram_bot
ExecStart=/home/god/telegram_bot/venv/bin/python /home/god/telegram_bot/bot.py
Restart=always
RestartSec=5
User=god
Environment=PYTHONUNBUFFERED=1
[Install]
WantedBy=multi-user.target

🚀 4. Запуск и автозапуск

Terminal window
sudo systemctl daemon-reexec
sudo systemctl daemon-reload
sudo systemctl enable telegram-bot.service
sudo systemctl start telegram-bot.service

🧩 5. Обслуживание

▶ Запуск / остановка

Terminal window
sudo systemctl start telegram-bot.service
sudo systemctl stop telegram-bot.service
sudo systemctl restart telegram-bot.service

📋 Статус

Terminal window
sudo systemctl status telegram-bot.service

📜 Просмотр логов

Terminal window
journalctl -u telegram-bot.service -f

(Для выхода из journalctl нажми Ctrl+C)


🔐 Telegram ID

Чтобы узнать свой Telegram ID, отправь боту /start.

Бот ответит:

👋 Привет! Твой Telegram ID: 123456789

Добавь этот ID в список ALLOWED_USERS.