|
2 | 2 | import random |
3 | 3 | import urllib.request |
4 | 4 | import json |
| 5 | +import sys |
| 6 | +import os |
| 7 | +import asyncio |
| 8 | +import aiohttp |
5 | 9 |
|
6 | 10 | # Local fallback sentences |
7 | 11 | fallback_sentences = [ |
|
22 | 26 | "The best way to predict the future is to create it" |
23 | 27 | ] |
24 | 28 |
|
| 29 | +async def fetch_url(session, url): |
| 30 | + try: |
| 31 | + async with session.get(url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=3) as resp: |
| 32 | + if resp.status == 200: |
| 33 | + data = await resp.json() |
| 34 | + phrase = data.get('quote') or data.get('content') |
| 35 | + if phrase: |
| 36 | + return phrase |
| 37 | + except Exception: |
| 38 | + pass |
| 39 | + return None |
| 40 | + |
| 41 | +async def fetch_phrase_async(): |
| 42 | + urls = [ |
| 43 | + "https://dummyjson.com/quotes/random", |
| 44 | + "https://api.quotable.io/random" |
| 45 | + ] |
| 46 | + async with aiohttp.ClientSession() as session: |
| 47 | + tasks = [fetch_url(session, url) for url in urls] |
| 48 | + # Gather them concurrently |
| 49 | + results = await asyncio.gather(*tasks) |
| 50 | + for res in results: |
| 51 | + if res: |
| 52 | + return res |
| 53 | + return None |
| 54 | + |
25 | 55 | print("\n⌨️ ===============================") |
26 | 56 | print(" WELCOME TO TYPING SPEED TESTER") |
27 | 57 | print("================================ ⌨️\n") |
28 | 58 |
|
29 | 59 | while True: |
30 | 60 | print("🌐 Fetching a fresh phrase for you...") |
31 | 61 |
|
32 | | - # Try multiple APIs for robustness |
33 | | - urls = [ |
34 | | - "https://dummyjson.com/quotes/random", |
35 | | - "https://api.quotable.io/random" |
36 | | - ] |
37 | | - |
38 | | - sentence = None |
39 | | - for url in urls: |
40 | | - try: |
41 | | - req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'}) |
42 | | - with urllib.request.urlopen(req, timeout=3) as response: |
43 | | - data = json.loads(response.read().decode()) |
44 | | - # dummyjson uses 'quote', quotable uses 'content' |
45 | | - phrase = data.get('quote') or data.get('content') |
46 | | - if phrase: |
47 | | - sentence = phrase |
48 | | - break |
49 | | - except Exception: |
50 | | - continue |
| 62 | + sentence = asyncio.run(fetch_phrase_async()) |
51 | 63 |
|
52 | 64 | if not sentence: |
53 | 65 | print("📴 Offline or API unavailable. Using a classic phrase instead.") |
|
0 commit comments