Установка и настройка телеграм-бота для отправки HTTP-запросов в 1с
📘 Инструкция по установке и обслуживанию Telegram JSON File Bot
🧩 Зависимости
- Python 3.9+
python3-venv
,pip
- Рабочий Telegram-бот (токен от @BotFather)
- URL HTTP-сервиса на стороне 1С
- Пользователь
god
на сервере
📁 1. Установка
sudo apt updatesudo apt install python3 python3-pip python3-venv -y
Создаём директорию для проекта:
mkdir -p ~/telegram_botcd ~/telegram_bot
Создаём виртуальное окружение и активируем:
python3 -m venv venvsource venv/bin/activate
Устанавливаем зависимости:
pip install python-telegram-bot requests
🧠 2. Создание bot.py
Создай файл bot.py
:
nano ~/telegram_bot/bot.py
Вставь код (адаптируй токен и URL):
import loggingimport requestsfrom io import BytesIOfrom telegram import Updatefrom telegram.ext import ApplicationBuilder, MessageHandler, ContextTypes, filters
# НастройкиBOT_TOKEN = 'ТВОЙ_ТОКЕН'TARGET_URL = 'http://IP_ИЛИ_ДОМЕН_1С/endpoint'ALLOWED_USERS = {123456789} # замени на свой Telegram IDHTTP_USERNAME = '1c_user' # если требуется Basic AuthHTTP_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-сервиса
Создай файл:
sudo nano /etc/systemd/system/telegram-bot.service
Содержимое:
[Unit]Description=Telegram JSON File BotAfter=network.target
[Service]Type=simpleWorkingDirectory=/home/god/telegram_botExecStart=/home/god/telegram_bot/venv/bin/python /home/god/telegram_bot/bot.pyRestart=alwaysRestartSec=5User=godEnvironment=PYTHONUNBUFFERED=1
[Install]WantedBy=multi-user.target
🚀 4. Запуск и автозапуск
sudo systemctl daemon-reexecsudo systemctl daemon-reloadsudo systemctl enable telegram-bot.servicesudo systemctl start telegram-bot.service
🧩 5. Обслуживание
▶ Запуск / остановка
sudo systemctl start telegram-bot.servicesudo systemctl stop telegram-bot.servicesudo systemctl restart telegram-bot.service
📋 Статус
sudo systemctl status telegram-bot.service
📜 Просмотр логов
journalctl -u telegram-bot.service -f
(Для выхода из journalctl
нажми Ctrl+C
)
🔐 Telegram ID
Чтобы узнать свой Telegram ID, отправь боту /start
.
Бот ответит:
👋 Привет! Твой Telegram ID: 123456789
Добавь этот ID в список ALLOWED_USERS
.