Permalink
Cannot retrieve contributors at this time
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Python-Chatbot/quote.py
Go to fileThis commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
32 lines (23 sloc)
1.43 KB
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
################################################## | |
# Benjamin Grant | |
""" | |
Libraries: | |
- requests (http://docs.python-requests.org/en/master/) by Kenneth Reitz used for retrieving data from the web | |
- BeautifulSoup4 (bs4) (https://www.crummy.com/software/BeautifulSoup/) by Leonard Richardson used for parsing HTML entities | |
""" | |
import json | |
import requests | |
from bs4 import BeautifulSoup | |
#Edits 'message' with a random quote, courtesy of quotesondesign.com | |
async def generateQuote(): | |
url = 'http://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1' | |
with requests.Session() as r: | |
response = r.get(url).text #This returns the plaintext from quotesondesign.com | |
try: | |
data = json.loads(response) #We use 'loads' because we are loading a string instead of a file | |
quote = BeautifulSoup(data[0]["content"], features="html5lib").find("p").string.strip() # Returns the quote with HTML entities decoded | |
author = BeautifulSoup("<p>"+data[0]["title"]+ "</p>", features="html5lib").find("p").string.strip() # Returns the author with HTML entities decoded | |
return "As " + author + " once said, '" + quote + "'" | |
except ValueError as e: #Some quotes returned break the python json parser. There is no clear reason for this. As a 'temporary workaround', this will use recursion to fetch a new one if this happens! | |
return generateQuote() | |
################################################## |