feat: Add a Telegram notification tester

This commit is contained in:
kbe
2025-07-21 01:09:18 +02:00
parent a67c9face3
commit f965020f55
7 changed files with 102 additions and 18 deletions

View File

@@ -4,7 +4,7 @@ CROSSFIT_PASSWORD=your_password
# Notification settings
ENABLE_EMAIL_NOTIFICATIONS=true
ENABLE_TELEGRAM_NOTIFICATIONS=false
ENABLE_TELEGRAM_NOTIFICATIONS=true
# Email notification credentials
SMTP_SERVER=mail.infomaniak.com

17
Dockerfile.test Normal file
View File

@@ -0,0 +1,17 @@
# Use the official Python image from the Docker Hub
FROM python:3.11-slim
# Set the working directory
WORKDIR /app
# Copy the requirements file into the container
COPY requirements.txt .
# Install the dependencies
RUN pip install --no-cache-dir -r requirements.txt
# Copy the rest of the application code
COPY . .
# Run the test script
CMD ["python", "test_telegram_notifier.py"]

View File

@@ -105,6 +105,21 @@ The application will automatically load the preferred sessions from this file. I
└── crossfit_booking.log
```
## Testing the Telegram Notifier
To manually test the Telegram notifier functionality:
1. Ensure you have configured the Telegram credentials in the `.env` file:
```ini
TELEGRAM_TOKEN=your_telegram_bot_token
TELEGRAM_CHAT_ID=your_chat_id
```
2. Run the test script:
```bash
python test_telegram_notifier.py
```
## License
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.

View File

@@ -289,7 +289,7 @@ class CrossFitBooker:
"id_user": self.user_id,
"action_by": self.user_id,
"n_guests": "0",
"booked_on": "3"
"booked_on": "3" # Target CrossFit Louvre 3 ?
}
def _make_request(self, url: str, data: Dict[str, str], success_msg: str) -> bool:

View File

@@ -11,6 +11,7 @@ python-dotenv==1.1.1
python-telegram-bot==22.2
pytz==2025.2
requests==2.32.4
ruff==0.12.4
setuptools==80.9.0
six==1.17.0
sniffio==1.3.1

View File

@@ -29,10 +29,10 @@ class SessionNotifier:
enable_email (bool): Whether to enable email notifications
enable_telegram (bool): Whether to enable Telegram notifications
"""
self.email_credentials = email_credentials
self.telegram_credentials = telegram_credentials
self.enable_email = enable_email
self.enable_telegram = enable_telegram
self.email_credentials = email_credentials
self.telegram_credentials = telegram_credentials
self.enable_email = enable_email
self.enable_telegram = enable_telegram
def send_email_notification(self, message):
"""
@@ -49,11 +49,11 @@ class SessionNotifier:
email.set_content(message)
# Set the email sender and recipient
email['From'] = self.email_credentials['from']
email['To'] = self.email_credentials['to']
email["From"] = self.email_credentials["from"]
email["To"] = self.email_credentials["to"]
# Set the email subject
email['Subject'] = 'Session Booking Notification'
email["Subject"] = "Session Booking Notification"
# Send the email using smtplib
try:
@@ -64,7 +64,7 @@ class SessionNotifier:
with smtplib.SMTP_SSL(smtp_server, 465) as smtp:
logging.debug(f"Connecting to SMTP server: {smtp_server}")
smtp.login(self.email_credentials['from'], self.email_credentials['password'])
smtp.login(self.email_credentials["from"], self.email_credentials['password'])
logging.debug("Logged in to SMTP server")
smtp.send_message(email)
logging.debug("Email sent successfully")
@@ -72,7 +72,7 @@ class SessionNotifier:
logging.error(f"Failed to send email: {str(e)}")
raise
def send_telegram_notification(self, message):
async def send_telegram_notification(self, message):
"""
Send a Telegram notification with the given message.
@@ -80,11 +80,11 @@ class SessionNotifier:
message (str): The message content to be sent in the Telegram chat
"""
# Create a Bot instance with the provided token
bot = Bot(token=self.telegram_credentials['token'], base_url=self.telegram_credentials.get('base_url', 'https://api.telegram.org'))
# Send the message to the specified chat ID
bot.send_message(chat_id=self.telegram_credentials['chat_id'], text=message)
bot = Bot(token=self.telegram_credentials["token"])
# Send the message to the specified chat ID and await the result
await bot.send_message(chat_id=self.telegram_credentials["chat_id"], text=message)
def notify_session_booking(self, session_details):
async def notify_session_booking(self, session_details):
"""
Notify about a session booking via email and Telegram.
@@ -100,9 +100,9 @@ class SessionNotifier:
self.send_email_notification(email_message)
if self.enable_telegram:
self.send_telegram_notification(telegram_message)
await self.send_telegram_notification(telegram_message)
def notify_upcoming_session(self, session_details, days_until):
async def notify_upcoming_session(self, session_details, days_until):
"""
Notify about an upcoming session via email and Telegram.
@@ -119,4 +119,4 @@ class SessionNotifier:
self.send_email_notification(email_message)
if self.enable_telegram:
self.send_telegram_notification(telegram_message)
await self.send_telegram_notification(telegram_message)

51
tools/test_telegram_notifier.py Executable file
View File

@@ -0,0 +1,51 @@
#!/usr/bin/env python3
"""
Test script to manually test the Telegram notifier functionality.
This script sends a test message using the SessionNotifier class.
"""
import os
import logging
from dotenv import load_dotenv
import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from session_notifier import SessionNotifier
# Load environment variables from .env file
load_dotenv()
# Configure logging
logging.basicConfig(level=logging.DEBUG)
def main():
"""
Main function to test the Telegram notifier.
"""
# Get Telegram credentials from environment variables
telegram_credentials = {
'token': os.getenv('TELEGRAM_TOKEN'),
'chat_id': os.getenv('TELEGRAM_CHAT_ID')
}
# Create a SessionNotifier instance with only Telegram enabled
notifier = SessionNotifier(
email_credentials={},
telegram_credentials=telegram_credentials,
enable_email=False,
enable_telegram=True
)
# Test message
test_message = "This is a test message from the Telegram notifier test script."
# Send the test message
try:
import asyncio
asyncio.run(notifier.send_telegram_notification(test_message))
print("Test message sent successfully!")
except Exception as e:
print(f"Failed to send test message: {str(e)}")
if __name__ == "__main__":
main()