Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import re
- import logging
- import sqlite3
- from datetime import datetime, timedelta, timezone
- from telegram import Update
- from telegram.ext import Application, CommandHandler, MessageHandler, ContextTypes, filters
- # ==================== CONFIGURATION ====================
- TOKEN = "8218725801:AAEz3zZYChRwPNhSCUDlE1psOiVAAg6oT4U"
- CHANNEL_ID = -1003540313095
- # =======================================================
- # Enable logging
- logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
- # Regex filter to capture variations of: e, E, even, EVEN, o, O, odd, ODD (including mixed cases with numbers e.g., e24, o19)
- CHAT_FILTER_REGEX = re.compile(r'(even|odd|e|o)', re.IGNORECASE)
- # --- DATABASE SETUP ---
- def init_db():
- conn = sqlite3.connect('palaro.db')
- cursor = conn.cursor()
- cursor.execute('''
- CREATE TABLE IF NOT EXISTS chats (
- id INTEGER PRIMARY KEY AUTOINCREMENT,
- user_identifier TEXT,
- timestamp DATETIME
- )
- ''')
- conn.commit()
- conn.close()
- # Background Listener: Logs every qualified channel chat into the database
- async def track_messages(update: Update, context: ContextTypes.DEFAULT_TYPE):
- # Ensure messages are processed only from your designated channel
- if update.effective_chat.id != CHANNEL_ID:
- return
- msg = update.effective_message
- if msg.text or msg.caption:
- text = msg.text or msg.caption
- # If text matches our game criteria (even if mixed with numbers), log it
- if CHAT_FILTER_REGEX.search(text):
- if msg.author_signature:
- user_identifier = f"✍️ {msg.author_signature}"
- elif msg.from_user:
- user = msg.from_user
- user_identifier = f"@{user.username}" if user.username else f"ID: `{user.id}`"
- elif msg.sender_chat:
- user_identifier = f"📢 {msg.sender_chat.title}"
- else:
- return
- now = datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M:%S')
- conn = sqlite3.connect('palaro.db')
- cursor = conn.cursor()
- cursor.execute('INSERT INTO chats (user_identifier, timestamp) VALUES (?, ?)', (user_identifier, now))
- conn.commit()
- conn.close()
- # Command Processor: Triggers when someone sends /active
- async def check_active(update: Update, context: ContextTypes.DEFAULT_TYPE):
- if update.effective_chat.id != CHANNEL_ID:
- return
- # 1. Capture exact execution time (in UTC)
- command_time = update.effective_message.date.astimezone(timezone.utc)
- # Get the start of the current day (00:00:00 UTC) to handle the daily history reset
- start_of_day_str = command_time.strftime('%Y-%m-%d 00:00:00')
- # 2. Subtract exactly 1 hour and round down minutes/seconds to :00
- cutoff_time = (command_time - timedelta(hours=1)).replace(minute=0, second=0, microsecond=0)
- cutoff_str = cutoff_time.strftime('%H:%M:%S')
- command_str = command_time.strftime('%H:%M:%S')
- cutoff_db_format = cutoff_time.strftime('%Y-%m-%d %H:%M:%S')
- # Send temporary progress indicator
- loading_msg = await context.bot.send_message(
- chat_id=CHANNEL_ID,
- text=f"⏳ **Filtering message data...**\nCounting qualified chats sent before {cutoff_str} UTC..."
- )
- # 3. Clean up and execute query with daily reset constraint
- conn = sqlite3.connect('palaro.db')
- cursor = conn.cursor()
- # CRITICAL: Automatically purge any chat records from previous dates (Older than today 00:00:00)
- cursor.execute('DELETE FROM chats WHERE datetime(timestamp) < datetime(?)', (start_of_day_str,))
- conn.commit()
- # Query local database for users reaching >= 30 chats between 00:00:00 today and the 1-hour cutoff window
- cursor.execute('''
- SELECT user_identifier, COUNT(*)
- FROM chats
- WHERE datetime(timestamp) >= datetime(?) AND datetime(timestamp) <= datetime(?)
- GROUP BY user_identifier
- ''', (start_of_day_str, cutoff_db_format))
- rows = cursor.fetchall()
- conn.close()
- # 4. Generate winners table
- qualified_users = []
- for user, count in rows:
- if count >= 30:
- qualified_users.append(f"• {user} — **{count} chats** ✅")
- # 5. Format and dispatch final summary
- response_text = (
- f"🏆 **QUALIFIED USERS (30+ CHATS REQUIRED)** 🏆\n"
- f"━━━━━━━━━━━━━━━━━━━━\n"
- f"📅 **Date Today:** {command_time.strftime('%Y-%m-%d')}\n"
- f"⏰ **Active Command Time:** {command_str} UTC\n"
- f"⏱ **Cutoff Time (1hr Before):** {cutoff_str} UTC\n"
- f"━━━━━━━━━━━━━━━━━━━━\n\n"
- )
- if qualified_users:
- response_text += "\n".join(qualified_users)
- else:
- response_text += f"❌ No users reached 30 or more chats within today's window before the cutoff."
- await loading_msg.edit_text(response_text)
- def main():
- init_db()
- application = Application.builder().token(TOKEN).build()
- # Capture standard messages to continuous feed
- application.add_handler(MessageHandler(filters.Chat(CHANNEL_ID) & ~filters.COMMAND, track_messages))
- # Listen to command events
- application.add_handler(CommandHandler("active", check_active))
- print("=== [ONLINE] HTTP BOT IS TRACKING WITH AUTO-RESET RUNNING ===")
- application.run_polling()
- if __name__ == "__main__":
- main()
Advertisement