Edm0nd/edmond/plugins/wikipedia.py

69 lines
2 KiB
Python
Raw Normal View History

2020-10-09 13:31:00 +02:00
import time
try:
import wikipedia
DEPENDENCIES_FOUND = True
except ImportError:
DEPENDENCIES_FOUND = False
from edmond.plugin import Plugin
class WikipediaPlugin(Plugin):
REQUIRED_CONFIGS = [
"commands", "ambiguous_response", "empty_response", "lang",
2020-10-09 13:31:00 +02:00
]
NUM_RETRIES = 3
def __init__(self, bot):
super().__init__(bot)
if not self.is_ready:
return
wikipedia.set_lang(self.config["lang"])
def on_pubmsg(self, event):
if not self.should_handle_command(event.arguments[0]):
return False
2020-10-09 23:37:54 +02:00
# "science"
if self.command.ident == self.config["commands"][0]:
2020-10-09 13:31:00 +02:00
self.tell_random_summary(event)
2020-10-09 23:37:54 +02:00
# "definition"
elif self.command.ident == self.config["commands"][1]:
2020-10-09 13:31:00 +02:00
self.tell_definition(event)
return True
def tell_random_summary(self, event):
summary = ""
retries = self.NUM_RETRIES
while retries > 0:
try:
summary = wikipedia.summary(wikipedia.random(), sentences=1)
break
2021-06-11 11:31:45 +02:00
except: # The wikipedia package can raise a lot of different stuff.
2020-10-09 13:31:00 +02:00
pass
retries -= 1
if summary:
self.bot.say(event.target, summary)
def tell_definition(self, event):
summary = ""
retries = self.NUM_RETRIES
while retries > 0:
try:
summary = wikipedia.summary(self.command.content, sentences=1)
break
except wikipedia.exceptions.DisambiguationError:
summary = self.config["ambiguous_response"]
break
except wikipedia.exceptions.PageError:
summary = self.config["empty_response"]
break
2021-06-11 11:31:45 +02:00
except:
summary = self.bot.config["error_message"]
2020-10-09 13:31:00 +02:00
# Keep trying after a slight delay.
time.sleep(1)
retries -= 1
if summary:
self.bot.say(event.target, summary)