Scripts/wikifortune
2022-03-30 23:20:58 +02:00

38 lines
988 B
Python
Executable File

#!/usr/bin/python3
import requests
import sys
import textwrap
def connection_error():
print("Could not contact wikipedia servers.")
sys.exit(1)
def get_random_page():
params = {
'action' : 'query',
'format' : 'json',
'list' : 'random',
'rnlimit' : 1,
'rnnamespace' : 0
}
try:
return requests.get('https://en.wikipedia.org/w/api.php', params).json()['query']['random'][0]
except ConnectionError:
connection_error()
def get_page_with_summary(title):
try:
return requests.get('https://en.wikipedia.org/api/rest_v1/page/summary/' + title).json()
except ConnectionError:
connection_error()
def main():
while True:
page = get_page_with_summary(get_random_page()['title'])
if page['type'] == 'standard':
break
print(page['title'] + ':\n\n' + textwrap.fill(page['extract'], width=80))
if __name__ == '__main__':
main()