upd
This commit is contained in:
80
main.py
80
main.py
@@ -4,10 +4,12 @@ import subprocess
|
||||
import email
|
||||
import tempfile
|
||||
import html2text
|
||||
import asyncio
|
||||
from email import policy
|
||||
from email.parser import BytesParser
|
||||
from telegram import Update, InlineKeyboardButton, InlineKeyboardMarkup
|
||||
from telegram.ext import Application, CommandHandler, MessageHandler, CallbackQueryHandler, filters, ContextTypes
|
||||
from telegram.error import TelegramError
|
||||
|
||||
# Enable logging
|
||||
logging.basicConfig(
|
||||
@@ -22,6 +24,13 @@ TOKEN = os.getenv('TELEGRAM_BOT_TOKEN')
|
||||
# Allowed user IDs (add your Telegram user ID here for security)
|
||||
ALLOWED_USERS = os.getenv('ALLOWED_USER_IDS', '').split(',')
|
||||
|
||||
# Notification settings
|
||||
CHECK_INTERVAL = int(os.getenv('EMAIL_CHECK_INTERVAL', '60')) # Check every 60 seconds by default
|
||||
NOTIFY_USER_ID = os.getenv('NOTIFY_USER_ID', '') # User ID to send notifications to
|
||||
|
||||
# Store last known email count
|
||||
last_email_count = 0
|
||||
|
||||
def check_authorization(update: Update) -> bool:
|
||||
"""Check if user is authorized to use admin commands."""
|
||||
if not ALLOWED_USERS or ALLOWED_USERS == ['']:
|
||||
@@ -334,6 +343,64 @@ async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
||||
"""Echo the user message."""
|
||||
await update.message.reply_text(f"You said: {update.message.text}")
|
||||
|
||||
async def check_new_emails(context: ContextTypes.DEFAULT_TYPE):
|
||||
"""Background task to check for new emails and send notifications."""
|
||||
global last_email_count
|
||||
|
||||
if not NOTIFY_USER_ID or NOTIFY_USER_ID == '':
|
||||
return
|
||||
|
||||
try:
|
||||
# Execute docker command to list new emails
|
||||
result = subprocess.run(
|
||||
['docker', 'exec', 'mailserver', 'ls', '/var/mail/fymio.us/me/new/'],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10
|
||||
)
|
||||
|
||||
if result.returncode != 0:
|
||||
logger.warning(f"Error checking mail in background: {result.stderr}")
|
||||
return
|
||||
|
||||
# Parse the output
|
||||
emails = result.stdout.strip().split('\n')
|
||||
emails = [e.strip().strip("'") for e in emails if e.strip()]
|
||||
|
||||
if not emails or emails == ['']:
|
||||
current_count = 0
|
||||
else:
|
||||
current_count = len(emails)
|
||||
|
||||
# Check if there are new emails
|
||||
if current_count > last_email_count:
|
||||
new_email_count = current_count - last_email_count
|
||||
|
||||
# Send notification
|
||||
message = f"📬 You have {new_email_count} new email(s)!\n\n"
|
||||
message += f"Total unread: {current_count}"
|
||||
|
||||
keyboard = [[InlineKeyboardButton("📬 Check Mail", callback_data="checkmail")]]
|
||||
reply_markup = InlineKeyboardMarkup(keyboard)
|
||||
|
||||
try:
|
||||
await context.bot.send_message(
|
||||
chat_id=NOTIFY_USER_ID,
|
||||
text=message,
|
||||
reply_markup=reply_markup
|
||||
)
|
||||
logger.info(f"Sent notification for {new_email_count} new email(s)")
|
||||
except TelegramError as e:
|
||||
logger.error(f"Failed to send notification: {e}")
|
||||
|
||||
# Update last known count
|
||||
last_email_count = current_count
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
logger.warning("Background email check timed out")
|
||||
except Exception as e:
|
||||
logger.error(f"Error in background email check: {e}")
|
||||
|
||||
def main():
|
||||
"""Start the bot."""
|
||||
if not TOKEN:
|
||||
@@ -351,6 +418,19 @@ def main():
|
||||
application.add_handler(CallbackQueryHandler(button_callback))
|
||||
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, echo))
|
||||
|
||||
# Set up background job to check for new emails
|
||||
if NOTIFY_USER_ID and NOTIFY_USER_ID != '':
|
||||
job_queue = application.job_queue
|
||||
job_queue.run_repeating(
|
||||
check_new_emails,
|
||||
interval=CHECK_INTERVAL,
|
||||
first=10 # Start checking after 10 seconds
|
||||
)
|
||||
logger.info(f"Email notification service started. Checking every {CHECK_INTERVAL} seconds.")
|
||||
logger.info(f"Will send notifications to user ID: {NOTIFY_USER_ID}")
|
||||
else:
|
||||
logger.info("Email notifications disabled. Set NOTIFY_USER_ID to enable.")
|
||||
|
||||
# Start the Bot
|
||||
logger.info("Bot is starting...")
|
||||
application.run_polling(allowed_updates=Update.ALL_TYPES)
|
||||
|
||||
Reference in New Issue
Block a user