Web Design IES
Web Design in Easy Steps, now in its 7th Edition, shows you how to make effective websites that work on any device.
Sean McManus shows how to download random jokes from the icanhazdadjoke website in Python, and have them spoken out loud using a text-to-speech module.
I love a good joke, and quite a few bad jokes, too. So I was excited when I saw that icanhazdadjoke.com offers an API for downloading what are often called Dad jokes.
It seems like a natural addition to my Raspberry Radio project, which reads out the news and weather and then announces your songs with a snippet of trivia before playing them. That project was documented in issues 121 and 122 of The MagPi magazine.
Below you can see a simple code example for downloading jokes. It contains the following elements:
You'll need to install the required libraries. Open a terminal window and then enter the following instructions:
pip install pyttsx3
pip install requests
Here's the Python program that downloads a random joke, and then speaks it out loud. It's also displayed to the screen so if you don't have speakers you can still see what's going on. This program should work wherever Python runs and the libraries are available.
# Program to download a joke from icanhazdadjoke.com
# And say it out loud using text-to-speech
# by Sean McManus - www.sean.co.uk
import requests
import pyttsx3
from datetime import datetime
def output(text):
print(text)
voice.say(text)
voice.runAndWait()
headers = {
'User-Agent': 'YOUR_AGENT_NAME', # ADD YOUR OWN HERE
'Accept': 'application/json'
}
try:
data = requests.get("https://icanhazdadjoke.com/", headers=headers)
joke = data.json().get('joke')
except:
# standard joke here for if the random joke lookup fails
joke = "What do clouds wear under their clothes? Thunderwear."
voice = pyttsx3.init()
voice.setProperty('rate', 170)
today = datetime.now()
day_of_week = today.strftime('%A')
output(f"This will brighten your {day_of_week}")
output(joke)
© Sean McManus. All rights reserved.
Visit www.sean.co.uk for free chapters from Sean's coding books (including Mission Python, Scratch Programming in Easy Steps and Coder Academy) and more!
Web Design in Easy Steps, now in its 7th Edition, shows you how to make effective websites that work on any device.
Power up your Microsoft Excel skills with this powerful pocket-sized book of tips that will save you time and help you learn more from your spreadsheets.
This book, now fully updated for Scratch 3, will take you from the basics of the Scratch language into the depths of its more advanced features. A great way to start programming.
Code a space adventure game in this Python programming book published by No Starch Press.
Discover how to make 3D games, create mazes, build a drum machine, make a game with cartoon animals and more!
In this entertaining techno-thriller for adults, Sean McManus takes a slice through the music industry: from the boardroom to the stage; from the studio to the record fair.