Spaces:
Runtime error
Runtime error
Download main.py from Anoar2025/NewCoinListingsBot: direct link, hf CLI and curl.
- Browser
- Download file 5.64 kB
-
https://huggingface.co/spaces/Anoar2025/NewCoinListingsBot/resolve/main/main.py
- Command line
-
hf download hf://spaces/Anoar2025/NewCoinListingsBot/main.py
-
curl -L -o main.py https://huggingface.co/spaces/Anoar2025/NewCoinListingsBot/resolve/main/main.py
5.64 kB
| import os | |
| import logging | |
| import requests | |
| from datetime import datetime | |
| from telegram import Update | |
| from telegram.ext import Application, CommandHandler, ContextTypes | |
| from apscheduler.schedulers.asyncio import AsyncIOScheduler | |
| # --- الإعدادات --- | |
| TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN") | |
| COINMARKETCAP_API_KEY = os.environ.get("COINMARKETCAP_API_KEY") | |
| if not TELEGRAM_BOT_TOKEN or not COINMARKETCAP_API_KEY: | |
| raise ValueError("يجب تعيين TELEGRAM_BOT_TOKEN و COINMARKETCAP_API_KEY كمتغيرات بيئة.") | |
| TARGET_CHAT_ID = None | |
| # --- تسجيل الأحداث --- | |
| logging.basicConfig( | |
| format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", | |
| level=logging.INFO | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # --- جلب البيانات من CoinMarketCap --- | |
| def get_new_crypto_listings(): | |
| url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest" | |
| headers = { | |
| "Accepts": "application/json", | |
| "X-CMC_PRO_API_KEY": COINMARKETCAP_API_KEY, | |
| } | |
| parameters = { | |
| "start": "1", | |
| "limit": "10", | |
| "convert": "USD", | |
| "sort": "date_added", | |
| "sort_dir": "desc" | |
| } | |
| try: | |
| response = requests.get(url, headers=headers, params=parameters, timeout=15) | |
| data = response.json() | |
| if data["status"]["error_code"] == 0: | |
| return data["data"] | |
| else: | |
| logger.error(f"خطأ في API: {data['status']['error_message']}") | |
| return None | |
| except Exception as e: | |
| logger.error(f"استثناء في جلب البيانات: {e}") | |
| return None | |
| def format_listings_message(coins): | |
| today = datetime.now().strftime("%Y-%m-%d") | |
| message = f"📈 *العملات الرقمية الجديدة المُدرجة اليوم ({today})*\n\n" | |
| for coin in coins: | |
| name = coin.get('name', 'غير معروف') | |
| symbol = coin.get('symbol', '') | |
| price = coin['quote']['USD'].get('price', 0) | |
| volume_24h = coin['quote']['USD'].get('volume_24h', 0) | |
| market_cap = coin['quote']['USD'].get('market_cap', 0) | |
| date_added = coin.get('date_added', '')[:10] | |
| platform_info = "🖥️ *المنصات:* غير متاحة في API المجاني\n(يمكنك البحث يدوياً)" | |
| message += f"*{name} ({symbol})*\n" | |
| message += f" 💵 السعر: ${price:.6f}\n" if price < 0.01 else f" 💵 السعر: ${price:.4f}\n" | |
| message += f" 📊 حجم التداول (24س): ${volume_24h:,.2f}\n" | |
| message += f" 🏦 القيمة السوقية: ${market_cap:,.2f}\n" | |
| message += f" 🗓️ تاريخ الإضافة: {date_added}\n" | |
| message += f" {platform_info}\n\n" | |
| message += "ℹ️ *مصدر البيانات: CoinMarketCap*" | |
| return message | |
| # --- دوال البوت --- | |
| async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| global TARGET_CHAT_ID | |
| TARGET_CHAT_ID = update.effective_chat.id | |
| await update.message.reply_text( | |
| "👋 *مرحباً بك!*\n" | |
| "تم تفعيل البوت بنجاح. ستصلك رسالة يومية بأحدث العملات الرقمية المدرجة.\n\n" | |
| "🔍 يمكنك أيضاً استخدام الأوامر التالية:\n" | |
| "/latest - لعرض أحدث الإدراجات الآن.", | |
| parse_mode="Markdown" | |
| ) | |
| logger.info(f"Chat ID المسجل: {TARGET_CHAT_ID}") | |
| async def latest(update: Update, context: ContextTypes.DEFAULT_TYPE): | |
| await update.message.reply_text("⏳ جاري جلب أحدث العملات الرقمية...") | |
| coins = get_new_crypto_listings() | |
| if coins: | |
| message = format_listings_message(coins) | |
| await update.message.reply_text(message, parse_mode="Markdown") | |
| else: | |
| await update.message.reply_text("❌ عذراً، حدث خطأ أثناء جلب البيانات. يرجى المحاولة لاحقاً.") | |
| async def send_daily_update(context: ContextTypes.DEFAULT_TYPE): | |
| global TARGET_CHAT_ID | |
| if TARGET_CHAT_ID is None: | |
| logger.warning("لم يتم تعيين Chat ID بعد. انتظر حتى يتفاعل مستخدم مع البوت.") | |
| return | |
| coins = get_new_crypto_listings() | |
| if coins: | |
| message = format_listings_message(coins) | |
| await context.bot.send_message(chat_id=TARGET_CHAT_ID, text=message, parse_mode="Markdown") | |
| logger.info("تم إرسال التحديث اليومي بنجاح.") | |
| else: | |
| await context.bot.send_message(chat_id=TARGET_CHAT_ID, text="❌ حدث خطأ في الجدولة اليومية، يرجى التحقق من السجلات.") | |
| logger.error("فشل جلب البيانات للمهمة اليومية.") | |
| def main(): | |
| """تشغيل البوت""" | |
| # إنشاء التطبيق مع زيادة مهلة الاتصال | |
| application = ( | |
| Application.builder() | |
| .token(TELEGRAM_BOT_TOKEN) | |
| .connect_timeout(30) | |
| .read_timeout(30) | |
| .build() | |
| ) | |
| application.add_handler(CommandHandler("start", start)) | |
| application.add_handler(CommandHandler("latest", latest)) | |
| # جدولة المهمة اليومية الساعة 9:00 صباحاً بتوقيت UTC | |
| scheduler = AsyncIOScheduler() | |
| scheduler.add_job(send_daily_update, "cron", hour=9, minute=0, args=[application]) | |
| scheduler.start() | |
| logger.info("تم بدء المجدول اليومي.") | |
| logger.info("تم تشغيل البوت... في انتظار الرسائل.") | |
| application.run_polling() | |
| if __name__ == "__main__": | |
| main() |