-
Notifications
You must be signed in to change notification settings - Fork 112
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #351 from IshuSinghSE/add-random-joke-generator
added random joke generator
- Loading branch information
Showing
1 changed file
with
40 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,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()) |