forked from suryanshsk/Python-Voice-Assistant-Suryanshsk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
random_joke_generator.py
40 lines (33 loc) · 1.01 KB
/
random_joke_generator.py
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
import requests
from textblob import TextBlob
def get_random_joke():
joke_url = "https://icanhazdadjoke.com/"
emoji_map = {
"positive": "😊",
"neutral": "😐",
"negative": "😢"
}
headers = {
"Accept": "application/json",
"User-Agent": "Mozilla/5.0"
}
def get_sentiment(joke):
analysis = TextBlob(joke)
if analysis.sentiment.polarity > 0:
return "positive"
elif analysis.sentiment.polarity == 0:
return "neutral"
else:
return "negative"
try:
joke_response = requests.get(joke_url, headers=headers)
joke_response.raise_for_status()
joke_data = joke_response.json()
joke = joke_data["joke"]
sentiment = get_sentiment(joke)
emoji = emoji_map.get(sentiment, "")
return f"{joke} {emoji}"
except requests.exceptions.RequestException as e:
return f"Error fetching joke: {e}"
if __name__ == "__main__":
print(get_random_joke())