File size: 12,167 Bytes
b190b45
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
"""

نمونه کدهای استفاده از API اخبار کریپتو

Crypto News API Client Examples in Python



این فایل شامل مثال‌های مختلف برای استفاده از API اخبار است

This file contains various examples for using the News API

"""

import requests
import json
from typing import List, Dict, Optional
from datetime import datetime


class CryptoNewsClient:
    """

    کلاس کلاینت برای دسترسی به API اخبار

    Client class for accessing the News API

    """
    
    def __init__(self, base_url: str = "http://localhost:3000"):
        """

        مقداردهی اولیه کلاینت

        Initialize the client

        

        Args:

            base_url: آدرس پایه سرور / Base URL of the server

        """
        self.base_url = base_url
        self.session = requests.Session()
        self.session.headers.update({
            'Accept': 'application/json',
            'User-Agent': 'CryptoNewsClient/1.0'
        })
    
    def get_all_news(self, limit: int = 100) -> List[Dict]:
        """

        دریافت تمام اخبار

        Get all news articles

        

        Example:

            >>> client = CryptoNewsClient()

            >>> articles = client.get_all_news(limit=50)

            >>> print(f"Found {len(articles)} articles")

        """
        url = f"{self.base_url}/api/news"
        params = {'limit': limit}
        
        try:
            response = self.session.get(url, params=params, timeout=10)
            response.raise_for_status()
            data = response.json()
            return data.get('articles', [])
        except requests.exceptions.RequestException as e:
            print(f"خطا در دریافت اخبار / Error fetching news: {e}")
            return []
    
    def get_news_by_sentiment(self, sentiment: str, limit: int = 50) -> List[Dict]:
        """

        دریافت اخبار بر اساس احساسات

        Get news by sentiment

        

        Args:

            sentiment: 'positive', 'negative', or 'neutral'

            limit: تعداد نتایج / Number of results

        

        Example:

            >>> client = CryptoNewsClient()

            >>> positive_news = client.get_news_by_sentiment('positive')

            >>> for article in positive_news[:5]:

            ...     print(article['title'])

        """
        url = f"{self.base_url}/api/news"
        params = {
            'sentiment': sentiment,
            'limit': limit
        }
        
        try:
            response = self.session.get(url, params=params, timeout=10)
            response.raise_for_status()
            data = response.json()
            articles = data.get('articles', [])
            
            # فیلتر سمت کلاینت / Client-side filter
            return [a for a in articles if a.get('sentiment') == sentiment]
        except requests.exceptions.RequestException as e:
            print(f"Error: {e}")
            return []
    
    def get_news_by_source(self, source: str, limit: int = 50) -> List[Dict]:
        """

        دریافت اخبار از یک منبع خاص

        Get news from a specific source

        

        Example:

            >>> client = CryptoNewsClient()

            >>> coindesk_news = client.get_news_by_source('CoinDesk')

        """
        url = f"{self.base_url}/api/news"
        params = {
            'source': source,
            'limit': limit
        }
        
        try:
            response = self.session.get(url, params=params, timeout=10)
            response.raise_for_status()
            data = response.json()
            return data.get('articles', [])
        except requests.exceptions.RequestException as e:
            print(f"Error: {e}")
            return []
    
    def search_news(self, keyword: str, limit: int = 100) -> List[Dict]:
        """

        جستجوی اخبار بر اساس کلمه کلیدی

        Search news by keyword

        

        Example:

            >>> client = CryptoNewsClient()

            >>> bitcoin_news = client.search_news('bitcoin')

            >>> print(f"Found {len(bitcoin_news)} articles about Bitcoin")

        """
        articles = self.get_all_news(limit)
        keyword_lower = keyword.lower()
        
        return [
            article for article in articles
            if keyword_lower in article.get('title', '').lower() or
               keyword_lower in article.get('content', '').lower()
        ]
    
    def get_latest_news(self, count: int = 10) -> List[Dict]:
        """

        دریافت آخرین اخبار

        Get latest news

        

        Example:

            >>> client = CryptoNewsClient()

            >>> latest = client.get_latest_news(5)

            >>> for article in latest:

            ...     print(f"{article['title']} - {article['published_at']}")

        """
        articles = self.get_all_news(limit=100)
        
        # مرتب‌سازی بر اساس تاریخ انتشار / Sort by publish date
        sorted_articles = sorted(
            articles,
            key=lambda x: x.get('published_at', ''),
            reverse=True
        )
        
        return sorted_articles[:count]
    
    def get_news_statistics(self) -> Dict:
        """

        دریافت آمار اخبار

        Get news statistics

        

        Returns:

            Dictionary containing statistics

        

        Example:

            >>> client = CryptoNewsClient()

            >>> stats = client.get_news_statistics()

            >>> print(f"Total articles: {stats['total']}")

            >>> print(f"Positive: {stats['positive']}")

            >>> print(f"Negative: {stats['negative']}")

        """
        articles = self.get_all_news()
        
        stats = {
            'total': len(articles),
            'positive': sum(1 for a in articles if a.get('sentiment') == 'positive'),
            'negative': sum(1 for a in articles if a.get('sentiment') == 'negative'),
            'neutral': sum(1 for a in articles if a.get('sentiment') == 'neutral'),
            'sources': len(set(a.get('source', {}).get('title', '') for a in articles))
        }
        
        return stats


# ==============================================================================
# مثال‌های استفاده / Usage Examples
# ==============================================================================

def example_1_basic_usage():
    """مثال ۱: استفاده ساده / Example 1: Basic Usage"""
    print("=" * 60)
    print("مثال ۱: دریافت تمام اخبار / Example 1: Get All News")
    print("=" * 60)
    
    client = CryptoNewsClient()
    articles = client.get_all_news(limit=10)
    
    print(f"\nتعداد مقالات / Number of articles: {len(articles)}\n")
    
    for i, article in enumerate(articles[:5], 1):
        print(f"{i}. {article.get('title', 'No title')}")
        print(f"   منبع / Source: {article.get('source', {}).get('title', 'Unknown')}")
        print(f"   احساسات / Sentiment: {article.get('sentiment', 'neutral')}")
        print()


def example_2_sentiment_filtering():
    """مثال ۲: فیلتر بر اساس احساسات / Example 2: Sentiment Filtering"""
    print("=" * 60)
    print("مثال ۲: فیلتر اخبار مثبت / Example 2: Positive News Filter")
    print("=" * 60)
    
    client = CryptoNewsClient()
    positive_news = client.get_news_by_sentiment('positive', limit=50)
    
    print(f"\nاخبار مثبت / Positive news: {len(positive_news)}\n")
    
    for article in positive_news[:3]:
        print(f"✓ {article.get('title', 'No title')}")
        print(f"  {article.get('content', '')[:100]}...")
        print()


def example_3_keyword_search():
    """مثال ۳: جستجو با کلمه کلیدی / Example 3: Keyword Search"""
    print("=" * 60)
    print("مثال ۳: جستجوی بیت‌کوین / Example 3: Bitcoin Search")
    print("=" * 60)
    
    client = CryptoNewsClient()
    bitcoin_news = client.search_news('bitcoin')
    
    print(f"\nمقالات مرتبط با بیت‌کوین / Bitcoin articles: {len(bitcoin_news)}\n")
    
    for article in bitcoin_news[:5]:
        print(f"• {article.get('title', 'No title')}")


def example_4_statistics():
    """مثال ۴: آمار اخبار / Example 4: News Statistics"""
    print("=" * 60)
    print("مثال ۴: آمار اخبار / Example 4: Statistics")
    print("=" * 60)
    
    client = CryptoNewsClient()
    stats = client.get_news_statistics()
    
    print("\n📊 آمار / Statistics:")
    print(f"   مجموع مقالات / Total: {stats['total']}")
    print(f"   مثبت / Positive: {stats['positive']} ({stats['positive']/stats['total']*100:.1f}%)")
    print(f"   منفی / Negative: {stats['negative']} ({stats['negative']/stats['total']*100:.1f}%)")
    print(f"   خنثی / Neutral: {stats['neutral']} ({stats['neutral']/stats['total']*100:.1f}%)")
    print(f"   منابع / Sources: {stats['sources']}")


def example_5_latest_news():
    """مثال ۵: آخرین اخبار / Example 5: Latest News"""
    print("=" * 60)
    print("مثال ۵: آخرین اخبار / Example 5: Latest News")
    print("=" * 60)
    
    client = CryptoNewsClient()
    latest = client.get_latest_news(5)
    
    print("\n🕒 آخرین اخبار / Latest news:\n")
    
    for i, article in enumerate(latest, 1):
        published = article.get('published_at', '')
        if published:
            dt = datetime.fromisoformat(published.replace('Z', '+00:00'))
            time_str = dt.strftime('%Y-%m-%d %H:%M')
        else:
            time_str = 'Unknown time'
        
        print(f"{i}. {article.get('title', 'No title')}")
        print(f"   زمان / Time: {time_str}")
        print()


def example_6_advanced_filtering():
    """مثال ۶: فیلتر پیشرفته / Example 6: Advanced Filtering"""
    print("=" * 60)
    print("مثال ۶: فیلتر ترکیبی / Example 6: Combined Filters")
    print("=" * 60)
    
    client = CryptoNewsClient()
    
    # دریافت اخبار مثبت درباره اتریوم
    # Get positive news about Ethereum
    all_news = client.get_all_news(limit=100)
    
    filtered = [
        article for article in all_news
        if article.get('sentiment') == 'positive' and
           'ethereum' in article.get('title', '').lower()
    ]
    
    print(f"\nاخبار مثبت درباره اتریوم / Positive Ethereum news: {len(filtered)}\n")
    
    for article in filtered[:3]:
        print(f"✓ {article.get('title', 'No title')}")
        print(f"  منبع / Source: {article.get('source', {}).get('title', 'Unknown')}")
        print()


def main():
    """تابع اصلی / Main function"""
    print("\n" + "=" * 60)
    print("نمونه‌های استفاده از API اخبار کریپتو")
    print("Crypto News API Usage Examples")
    print("=" * 60 + "\n")
    
    try:
        # اجرای تمام مثال‌ها / Run all examples
        example_1_basic_usage()
        print("\n")
        
        example_2_sentiment_filtering()
        print("\n")
        
        example_3_keyword_search()
        print("\n")
        
        example_4_statistics()
        print("\n")
        
        example_5_latest_news()
        print("\n")
        
        example_6_advanced_filtering()
        
    except Exception as e:
        print(f"\nخطا / Error: {e}")
        print("لطفاً مطمئن شوید که سرور در حال اجرا است")
        print("Please make sure the server is running")


if __name__ == "__main__":
    main()