Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.venv/
venv/
.env
__pycache__/
*.pyc
107 changes: 69 additions & 38 deletions bot.py
Original file line number Diff line number Diff line change
@@ -1,58 +1,89 @@
#!/usr/bin/env python
# pylint: disable=C0116,W0613
# This program is dedicated to the public domain under the CC0 license.
# bot.py - Версія для роботи в групі

import os
import logging
from dotenv import load_dotenv
from os import environ
from telegram import Update, ForceReply
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext, ContextTypes
from threading import Thread

load_dotenv()
from dotenv import load_dotenv
from telegram import Update, Bot
from telegram.ext import Updater, CommandHandler, CallbackContext
from flask import Flask, request, jsonify

# Enable logging
# Налаштування логування
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)

logger = logging.getLogger(__name__)

# Define a few command handlers. These usually take the two arguments update and
# context.
def start(update: Update, context: CallbackContext) -> None:
"""Send a message when the command /start is issued."""
user = update.effective_user
chat = update.effective_chat
update.message.reply_markdown_v2(
f"Вітаю {user.mention_markdown_v2()}\!\nВаш код для сповіщень: **{chat.id}**",
#reply_markup=ForceReply(selective=True),
)
# Завантажуємо змінні з .env файлу
load_dotenv()
BOT_TOKEN = os.getenv("BOT_TOKEN")
SECRET_KEY = os.getenv("SECRET_KEY")
GROUP_CHAT_ID = os.getenv("GROUP_CHAT_ID") # Завантажуємо ID групи

# --- Веб-сервер для прийому команд від сигналізації ---

BOT_TOKEN=environ.get("BOT_TOKEN")
app = Flask(__name__)

def main() -> None:
"""Start the bot."""
# Create the Updater and pass it your bot's token.
updater = Updater(BOT_TOKEN)
@app.route('/notify', methods=['POST'])
def notify():
"""
Ця функція приймає POST-запит від сигналізації
"""
# 1. Перевірка безпеки
if request.headers.get('X-Secret-Key') != SECRET_KEY:
logger.warning("Notify request with wrong secret key.")
return jsonify({"status": "error", "message": "Invalid secret key"}), 403

# Get the dispatcher to register handlers
dispatcher = updater.dispatcher
# 2. Отримання тексту повідомлення
data = request.json
if not data or 'message' not in data:
return jsonify({"status": "error", "message": "'message' field is required"}), 400

# on different commands - answer in Telegram
dispatcher.add_handler(CommandHandler("start", start))
message_text = data['message']
logger.info(f"Received message to send: '{message_text}'")

# on non command i.e message - echo the message on Telegram
#dispatcher.add_handler(MessageHandler(Filters.text & ~Filters.command, echo))
# 3. Надсилання повідомлення в групу
bot = Bot(token=BOT_TOKEN)
try:
# Просто надсилаємо повідомлення на один ID групи
bot.send_message(chat_id=GROUP_CHAT_ID, text=message_text)
logger.info(f"Message sent to group {GROUP_CHAT_ID}")
except Exception as e:
logger.error(f"Failed to send message to group {GROUP_CHAT_ID}: {e}")

# Start the Bot
updater.start_polling()
return jsonify({"status": "ok", "message": "Message sent"}), 200

# Run the bot until you press Ctrl-C or the process receives SIGINT,
# SIGTERM or SIGABRT. This should be used most of the time, since
# start_polling() is non-blocking and will stop the bot gracefully.
updater.idle()
def run_flask():
"""Запускає веб-сервер Flask на порту 5000."""
app.run(host='0.0.0.0', port=5000)

def main() -> None:
"""Основна функція запуску бота."""
# Перевірка, чи всі потрібні змінні завантажились
if not all([BOT_TOKEN, SECRET_KEY, GROUP_CHAT_ID]):
logger.error("FATAL: BOT_TOKEN, SECRET_KEY or GROUP_CHAT_ID not found in .env file!")
return

# Запускаємо веб-сервер в окремому потоці
flask_thread = Thread(target=run_flask)
flask_thread.daemon = True
flask_thread.start()
logger.info("Flask server started on port 5000.")

# Створюємо та запускаємо Telegram-бота
# Нам більше не потрібні обробники команд /start і /stop
updater = Updater(BOT_TOKEN)

# Можна додати команду /id для зручності
def show_id(update: Update, context: CallbackContext):
update.message.reply_text(f"ID цього чату: {update.effective_chat.id}")

updater.dispatcher.add_handler(CommandHandler("id", show_id))

updater.start_polling()
logger.info("Telegram bot started polling.")
updater.idle()

if __name__ == '__main__':
main()
main()