import os import logging import asyncio from datetime import datetime, timedelta import aiohttp import aiomysql from telegram import Bot, Update, Sticker from telegram.ext import Application, CommandHandler, CallbackContext from telegram.constants import ParseMode import pytz # लॉगिंग सेटअप logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO ) logger = logging.getLogger(__name__) # कॉन्फ़िगरेशन BOT_TOKEN = "8564049577:AAHXnLC4xVsJWwFV0l5A78fugTQfPP2F1bw" CHANNEL_ID = "@your_channel_username" # अपना चैनल यूज़रनेम डालें # डेटाबेस कॉन्फ़िग DB_CONFIG = { 'host': 'preduction.tajeemdevloper.space', 'user': 'dcgmilzx_preductionbot', 'password': 'dcgmilzx_preductionbot', 'db': 'dcgmilzx_preductionbot', 'charset': 'utf8mb4' } # स्टिकर IDs (आपको अपने स्टिकर के IDs डालने होंगे) WIN_STICKER_ID = "CAACAgIAAxkBAAIBFmda..." # जीत वाला स्टिकर ID LOSE_STICKER_ID = "CAACAgIAAxkBAAIBGGda..." # हार वाला स्टिकर ID class PredictionBot: def __init__(self): self.bot = None self.pool = None self.current_prediction = None self.is_running = False async def init_db(self): """डेटाबेस कनेक्शन इनिशियलाइज़ करें""" try: self.pool = await aiomysql.create_pool(**DB_CONFIG) async with self.pool.acquire() as conn: async with conn.cursor() as cursor: # प्रीडिक्शन टेबल बनाएं await cursor.execute(""" CREATE TABLE IF NOT EXISTS predictions ( id INT AUTO_INCREMENT PRIMARY KEY, period VARCHAR(50) NOT NULL, prediction VARCHAR(10) NOT NULL, result VARCHAR(10), created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, result_at TIMESTAMP NULL, is_active BOOLEAN DEFAULT TRUE, UNIQUE KEY unique_period (period) ) """) # हिस्ट्री टेबल बनाएं await cursor.execute(""" CREATE TABLE IF NOT EXISTS history ( id INT AUTO_INCREMENT PRIMARY KEY, period VARCHAR(50) NOT NULL, number INT NOT NULL, size VARCHAR(10) NOT NULL, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) """) # सेटिंग्स टेबल बनाएं await cursor.execute(""" CREATE TABLE IF NOT EXISTS settings ( id INT PRIMARY KEY, draw_interval INT DEFAULT 60, last_draw_time TIMESTAMP, is_auto_predict BOOLEAN DEFAULT TRUE ) """) # डिफ़ॉल्ट सेटिंग्स इन्सर्ट करें await cursor.execute(""" INSERT IGNORE INTO settings (id, draw_interval) VALUES (1, 60) """) await conn.commit() logger.info("Database initialized successfully") return True except Exception as e: logger.error(f"Database initialization failed: {e}") return False async def fetch_latest_result(self): """WinGo API से लेटेस्ट रिजल्ट फ़ेच करें""" try: url = "https://draw.ar-lottery01.com/WinGo/WinGo_1M/GetHistoryIssuePage.json" async with aiohttp.ClientSession() as session: async with session.get(url, timeout=10) as response: if response.status == 200: data = await response.json() if data.get('code') == 0 and data.get('data'): latest = data['data']['list'][0] if data['data']['list'] else None return latest return None except Exception as e: logger.error(f"Error fetching result: {e}") return None async def generate_prediction(self): """नया प्रीडिक्शन जनरेट करें""" try: async with self.pool.acquire() as conn: async with conn.cursor() as cursor: # लास्ट 5 रिजल्ट्स लें await cursor.execute(""" SELECT number, size FROM history ORDER BY created_at DESC LIMIT 5 """) results = await cursor.fetchall() if len(results) >= 3: # सिंपल पैटर्न एनालिसिस big_count = sum(1 for _, size in results if size == 'big') small_count = sum(1 for _, size in results if size == 'small') if big_count > small_count: prediction = 'small' elif small_count > big_count: prediction = 'big' else: # रैंडम प्रीडिक्शन import random prediction = random.choice(['big', 'small']) else: # रैंडम प्रीडिक्शन import random prediction = random.choice(['big', 'small']) # नेक्स्ट पीरियड निकालें await cursor.execute(""" SELECT period FROM predictions ORDER BY created_at DESC LIMIT 1 """) last_pred = await cursor.fetchone() if last_pred: last_period = last_pred[0] # पीरियड बढ़ाएं (सिंपल इंक्रीमेंट) next_period = str(int(last_period) + 1) else: # डिफ़ॉल्ट पीरियड next_period = datetime.now().strftime("%Y%m%d%H%M%S") + "001" # प्रीडिक्शन सेव करें await cursor.execute(""" INSERT INTO predictions (period, prediction, is_active) VALUES (%s, %s, TRUE) ON DUPLICATE KEY UPDATE prediction = %s, is_active = TRUE """, (next_period, prediction, prediction)) await conn.commit() return { 'period': next_period, 'prediction': prediction, 'confidence': 85 # डिफ़ॉल्ट कॉन्फिडेंस } except Exception as e: logger.error(f"Error generating prediction: {e}") return None async def post_prediction_to_channel(self, prediction_data): """चैनल में प्रीडिक्शन पोस्ट करें""" try: message = f""" 🎯 *नया प्रीडिक्शन* 📊 पीरियड: `{prediction_data['period']}` 🔮 प्रीडिक्शन: *{prediction_data['prediction'].upper()}* 📈 कॉन्फिडेंस: {prediction_data['confidence']}% ⏳ अगला ड्रॉ: 60 सेकंड में 🔄 ऑटो चेक: सक्रिय #Prediction #{prediction_data['prediction']} """ await self.bot.send_message( chat_id=CHANNEL_ID, text=message, parse_mode=ParseMode.MARKDOWN ) # करंट प्रीडिक्शन सेव करें self.current_prediction = prediction_data logger.info(f"Prediction posted: {prediction_data}") return True except Exception as e: logger.error(f"Error posting prediction: {e}") return False async def check_and_post_result(self): """रिजल्ट चेक करें और स्टिकर भेजें""" try: latest = await self.fetch_latest_result() if not latest or not self.current_prediction: return False current_period = self.current_prediction['period'] # अगर नया पीरियड आ गया है if latest['issueNumber'] != current_period: return False result_number = int(latest['number']) result_size = 'big' if result_number >= 5 else 'small' # रिजल्ट डेटाबेस में सेव करें async with self.pool.acquire() as conn: async with conn.cursor() as cursor: await cursor.execute(""" INSERT INTO history (period, number, size) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE number = %s, size = %s """, (current_period, result_number, result_size, result_number, result_size)) # प्रीडिक्शन अपडेट करें is_correct = result_size == self.current_prediction['prediction'] result_text = 'win' if is_correct else 'lose' await cursor.execute(""" UPDATE predictions SET result = %s, result_at = NOW(), is_active = FALSE WHERE period = %s """, (result_text, current_period)) await conn.commit() # स्टिकर और रिजल्ट मैसेज भेजें if is_correct: sticker_id = WIN_STICKER_ID result_msg = "✅ *जीत!* ✅\n\n🎉 बधाई हो! प्रीडिक्शन सही था!" else: sticker_id = LOSE_STICKER_ID result_msg = "❌ *हार!* ❌\n\nअगली बार जरूर जीतेंगे!" # स्टिकर भेजें await self.bot.send_sticker( chat_id=CHANNEL_ID, sticker=sticker_id ) # रिजल्ट डीटेल्स भेजें result_details = f""" {result_msg} 📊 पीरियड: `{current_period}` 🔢 नंबर: *{result_number}* 📏 साइज़: *{result_size.upper()}* 🔮 प्रीडिक्शन: *{self.current_prediction['prediction'].upper()}* 🎯 रिजल्ट: *{"सही" if is_correct else "गलत"}* ⏳ अगला प्रीडिक्शन: 60 सेकंड में... """ await self.bot.send_message( chat_id=CHANNEL_ID, text=result_details, parse_mode=ParseMode.MARKDOWN ) # करंट प्रीडिक्शन रिसेट करें self.current_prediction = None logger.info(f"Result posted: Period {current_period}, Result {result_text}") return True except Exception as e: logger.error(f"Error checking result: {e}") return False async def prediction_cycle(self): """मुख्य प्रीडिक्शन साइकिल""" while self.is_running: try: # प्रीडिक्शन जनरेट करें prediction = await self.generate_prediction() if prediction: # चैनल में पोस्ट करें await self.post_prediction_to_channel(prediction) # 60 सेकंड इंतज़ार करें (ड्रॉ टाइम) await asyncio.sleep(60) # रिजल्ट चेक करें await self.check_and_post_result() # अगले प्रीडिक्शन से पहले 5 सेकंड इंतज़ार await asyncio.sleep(5) except Exception as e: logger.error(f"Error in prediction cycle: {e}") await asyncio.sleep(10) async def start_bot(self): """बॉट स्टार्ट करें""" try: # डेटाबेस इनिशियलाइज़ करें if not await self.init_db(): logger.error("Failed to initialize database") return # टेलीग्राम बॉट बनाएं application = Application.builder().token(BOT_TOKEN).build() self.bot = application.bot # कमांड हैंडलर application.add_handler(CommandHandler("start", self.start_command)) application.add_handler(CommandHandler("predict", self.predict_command)) application.add_handler(CommandHandler("stats", self.stats_command)) application.add_handler(CommandHandler("stop", self.stop_command)) # बॉट स्टार्ट करें await application.initialize() await application.start() # प्रीडिक्शन साइकिल स्टार्ट करें self.is_running = True asyncio.create_task(self.prediction_cycle()) logger.info("Bot started successfully") # रन करते रहें await application.updater.start_polling() except Exception as e: logger.error(f"Failed to start bot: {e}") async def start_command(self, update: Update, context: CallbackContext): """स्टार्ट कमांड""" await update.message.reply_text( "🤖 *WinGo Prediction Bot*\n\n" "यह बॉट ऑटोमेटिक प्रीडिक्शन जनरेट करेगा और रिजल्ट के अनुसार स्टिकर भेजेगा।\n\n" "कमांड्स:\n" "/predict - मैन्युअल प्रीडिक्शन\n" "/stats - स्टैटिस्टिक्स देखें\n" "/stop - बॉट रोकें", parse_mode=ParseMode.MARKDOWN ) async def predict_command(self, update: Update, context: CallbackContext): """मैन्युअल प्रीडिक्शन कमांड""" prediction = await self.generate_prediction() if prediction: await update.message.reply_text( f"🔮 नया प्रीडिक्शन:\n\n" f"पीरियड: {prediction['period']}\n" f"प्रीडिक्शन: {prediction['prediction'].upper()}\n" f"कॉन्फिडेंस: {prediction['confidence']}%", parse_mode=ParseMode.MARKDOWN ) else: await update.message.reply_text("प्रीडिक्शन जनरेट करने में त्रुटि!") async def stats_command(self, update: Update, context: CallbackContext): """स्टैटिस्टिक्स कमांड""" try: async with self.pool.acquire() as conn: async with conn.cursor() as cursor: # टोटल प्रीडिक्शन्स await cursor.execute("SELECT COUNT(*) FROM predictions") total = (await cursor.fetchone())[0] # विन रेट await cursor.execute("SELECT COUNT(*) FROM predictions WHERE result = 'win'") wins = (await cursor.fetchone())[0] # करंट स्ट्रीक await cursor.execute(""" SELECT result FROM predictions WHERE result IS NOT NULL ORDER BY created_at DESC LIMIT 5 """) recent_results = await cursor.fetchall() win_rate = (wins / total * 100) if total > 0 else 0 stats_text = f""" 📊 *बॉट स्टैटिस्टिक्स* 🔢 कुल प्रीडिक्शन्स: {total} ✅ सही प्रीडिक्शन्स: {wins} 📈 जीत दर: {win_rate:.2f}% 🎯 हाल के रिजल्ट्स: """ for i, (result,) in enumerate(recent_results, 1): stats_text += f"{i}. {'✅' if result == 'win' else '❌'}\n" await update.message.reply_text(stats_text, parse_mode=ParseMode.MARKDOWN) except Exception as e: logger.error(f"Error getting stats: {e}") await update.message.reply_text("स्टैटिस्टिक्स फ़ेच करने में त्रुटि!") async def stop_command(self, update: Update, context: CallbackContext): """बॉट स्टॉप कमांड""" self.is_running = False await update.message.reply_text("बॉट रोक दिया गया है।") async def main(): """मुख्य फंक्शन""" bot = PredictionBot() await bot.start_bot() if __name__ == "__main__": # असिंक्रोनस मेन फंक्शन रन करें asyncio.run(main())