File size: 10,533 Bytes
ad50c8c
aad7415
 
 
 
662698c
 
aad7415
662698c
 
 
aad7415
 
 
 
 
662698c
 
 
 
 
 
aad7415
 
 
 
 
 
 
 
 
 
 
 
 
662698c
aad7415
 
 
 
 
662698c
aad7415
662698c
 
aad7415
662698c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aad7415
 
 
 
 
 
 
 
 
662698c
 
aad7415
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
662698c
 
 
 
 
 
 
 
 
aad7415
 
662698c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aad7415
 
 
 
662698c
aad7415
662698c
aad7415
 
 
 
 
 
 
662698c
 
aad7415
 
 
 
 
 
 
 
 
 
662698c
aad7415
662698c
aad7415
 
 
 
662698c
 
 
 
 
aad7415
 
662698c
 
 
 
aad7415
 
 
 
 
 
 
 
662698c
aad7415
 
 
 
662698c
 
 
 
aad7415
 
 
 
662698c
aad7415
 
 
662698c
aad7415
 
 
662698c
 
aad7415
 
 
 
856dd06
662698c
aad7415
 
 
 
 
856dd06
 
 
aad7415
856dd06
aad7415
 
 
 
 
 
 
 
 
856dd06
 
 
aad7415
 
 
856dd06
 
 
 
aad7415
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# sentiment_news.py (محدث بالكامل)
import os, asyncio
import httpx
from gnews import GNews
import feedparser
from datetime import datetime, timedelta, timezone
import time

# 
# 🔴 تم التعديل: توسيع قائمة مصادر RSS لتشمل تغطية أوسع للعملات البديلة
#
CRYPTO_RSS_FEEDS = {
    "Cointelegraph": "https://cointelegraph.com/rss",
    "CoinDesk": "https://www.coindesk.com/arc/outboundfeeds/rss/",
    "CryptoSlate": "https://cryptoslate.com/feed/",
    "NewsBTC": "https://www.newsbtc.com/feed/",
    "Bitcoin.com": "https://news.bitcoin.com/feed/",
    "The Block": "https://www.theblock.co/rss.xml",
    "Decrypt": "https://decrypt.co/feed",
    "AMBCrypto": "https://ambcrypto.com/feed/",
    "CryptoPotato": "https://cryptopotato.com/feed/",
    "U.Today": "https://u.today/rss"
}

class NewsFetcher:
    def __init__(self):
        self.http_client = httpx.AsyncClient(
            timeout=10.0, follow_redirects=True,
            headers={
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
                'Accept': 'application/json, text/plain, */*',
                'Accept-Language': 'en-US,en;q=0.9',
                'Cache-Control': 'no-cache'
            }
        )
        # GNews مفلترة مسبقاً لـ 3 ساعات
        self.gnews = GNews(language='en', country='US', period='3h', max_results=8)

    async def _fetch_from_gnews(self, symbol: str) -> list:
        try:
            base_symbol = symbol.split("/")[0]
            # نستخدم الكلمات المفتاحية السلبية لمحاولة عزل أخبار العملة نفسها
            query = f'"{base_symbol}" cryptocurrency -bitcoin -ethereum -BTC -ETH'
            
            # GNews تعمل بشكل متزامن، لذا نستخدم to_thread
            news_items = await asyncio.to_thread(self.gnews.get_news, query)
            
            # 
            # 🔴 تم التعديل: توحيد تنسيق الإخراج ليتضمن مفتاح 'published'
            #
            formatted_items = []
            for item in news_items:
                # GNews توفر تاريخ النشر كنص (وهو مفلتر مسبقاً لـ 3 ساعات)
                published_text = item.get('published date', 'Recent')
                formatted_items.append({
                    'title': item.get('title', 'No Title'),
                    'description': item.get('description', 'No Description'),
                    'source': item.get('source', {}).get('title', 'GNews'),
                    'published': published_text # تمرير التاريخ/الوقت
                })
            return formatted_items
            
        except Exception as e:
            print(f"Failed to fetch specific news from GNews for {symbol}: {e}")
            return []

    async def _fetch_from_rss_feed(self, feed_url: str, source_name: str, symbol: str) -> list:
        try:
            base_symbol = symbol.split('/')[0]
            max_redirects = 2
            current_url = feed_url
            
            # منطق معالجة إعادة التوجيه
            for attempt in range(max_redirects):
                try:
                    response = await self.http_client.get(current_url)
                    response.raise_for_status()
                    break
                except httpx.HTTPStatusError as e:
                    if e.response.status_code in [301, 302, 307, 308] and 'Location' in e.response.headers:
                        current_url = e.response.headers['Location']
                        continue
                    else: 
                        raise
            
            feed = feedparser.parse(response.text)
            news_items = []
            search_term = base_symbol.lower()
            
            # 
            # 🔴 تم التعديل: حساب الوقت قبل 3 ساعات (باستخدام التوقيت العالمي UTC)
            #
            three_hours_ago = datetime.now(timezone.utc) - timedelta(hours=3)

            # 
            # 🔴 تم التعديل: إزالة قيد '[:15]' والفلترة حسب الوقت
            #
            for entry in feed.entries:
                title = entry.title.lower() if hasattr(entry, 'title') else ''
                summary = entry.summary.lower() if hasattr(entry, 'summary') else entry.description.lower() if hasattr(entry, 'description') else ''
                
                # التحقق من تاريخ النشر
                published_tuple = entry.get('published_parsed')
                if not published_tuple:
                    continue # تخطي الخبر إذا لم يكن له تاريخ نشر
                
                # تحويل تاريخ النشر إلى كائن datetime مع دعم التوقيت العالمي (UTC)
                try:
                    published_time = datetime.fromtimestamp(time.mktime(published_tuple), timezone.utc)
                except Exception:
                    # في حال فشل التحويل، نفترض أنه قديم
                    continue

                # 
                # 🔴 تم التعديل: تطبيق الفلتر الزمني (آخر 3 ساعات) وفلتر اسم العملة
                #
                if (search_term in title or search_term in summary) and (published_time >= three_hours_ago):
                    news_items.append({
                        'title': entry.title, 
                        'description': summary, 
                        'source': source_name,
                        'published': published_time.isoformat() # إرسال التاريخ بتنسيق ISO
                    })
                    
            return news_items
        except Exception as e:
            print(f"Failed to fetch specific news from {source_name} RSS for {symbol}: {e}")
            return []
            
    async def get_news_for_symbol(self, symbol: str) -> str:
        base_symbol = symbol.split("/")[0]
        
        # إنشاء قائمة المهام (GNews + جميع مصادر RSS)
        tasks = [self._fetch_from_gnews(symbol)]
        for name, url in CRYPTO_RSS_FEEDS.items():
            tasks.append(self._fetch_from_rss_feed(url, name, symbol))
        
        results = await asyncio.gather(*tasks, return_exceptions=True)
        all_news_text = []
        
        for result in results:
            if isinstance(result, Exception):
                continue
                
            for item in result:
                # نستخدم الفلتر الثانوي للتأكد من أن الخبر يركز فعلاً على العملة
                if self._is_directly_relevant_to_symbol(item, base_symbol):
                    title = item.get('title', 'No Title')
                    description = item.get('description', 'No Description')
                    source = item.get('source', 'Unknown Source')
                    
                    # 
                    # 🔴 تم التعديل: هذا المنطق سيعمل الآن بفضل التعديلات السابقة
                    #
                    published = item.get('published', '') # الحصول على التاريخ/الوقت
                    
                    news_entry = f"[{source}] {title}. {description}"
                    
                    # 
                    # 🔴 تم التعديل: إضافة وقت النشر إلى النص النهائي (تنفيذاً لطلبك)
                    #
                    if published:
                        news_entry += f" (Published: {published})"
                    
                    all_news_text.append(news_entry)
        
        if not all_news_text: 
            return f"No specific news found for {base_symbol} in the last 3 hours."
        
        # أخذ أهم 5 أخبار (الأكثر حداثة أو صلة)
        important_news = all_news_text[:5]
        return " | ".join(important_news)

    def _is_directly_relevant_to_symbol(self, news_item, base_symbol):
        """
        فلتر ثانوي للتأكد من أن الخبر ليس مجرد ذكر عابر للعملة،
        بل يتعلق فعلاً بجوانب التداول أو السوق.
        """
        title = news_item.get('title', '').lower()
        description = news_item.get('description', '').lower()
        symbol_lower = base_symbol.lower()
        
        # يجب أن يكون الرمز موجوداً في العنوان أو الوصف
        if symbol_lower not in title and symbol_lower not in description:
            return False
        
        # يجب أن يحتوي الخبر على كلمات مفتاحية تدل على أنه خبر مالي/تداولي
        crypto_keywords = [
            'crypto', 'cryptocurrency', 'token', 'blockchain', 
            'price', 'market', 'trading', 'exchange', 'defi',
            'coin', 'digital currency', 'altcoin', 'airdrop', 'listing',
            'partnership', 'update', 'mainnet', 'protocol'
        ]
        
        return any(keyword in title or keyword in description for keyword in crypto_keywords)

# --- (تم تنقيح هذا الكلاس ليعكس الواقع) ---

class SentimentAnalyzer:
    def __init__(self, data_manager):
        self.data_manager = data_manager

    async def get_market_sentiment(self):
        """
        جلب سياق السوق العام (يعتمد بالكامل على DataManager).
        """
        try:
            # هذه الدالة تجلب (BTC/ETH/Fear&Greed) فقط
            market_context = await self.data_manager.get_market_context_async()
            if not market_context:
                return await self.get_fallback_market_context()
            return market_context
        except Exception as e:
            print(f"Failed to get market sentiment: {e}")
            return await self.get_fallback_market_context()

    async def get_fallback_market_context(self):
        """
        (محدث) سياق احتياطي مبسط يعكس الواقع (بدون بيانات حيتان عامة).
        """
        return {
            'timestamp': datetime.now().isoformat(),
            'btc_sentiment': 'NEUTRAL',
            'fear_and_greed_index': 50,
            'sentiment_class': 'NEUTRAL',
            'market_trend': 'UNKNOWN',
            'data_quality': 'LOW'
        }