From 8b5721375f65c6fd898c11a67f62d96ea5bf9292 Mon Sep 17 00:00:00 2001 From: dece Date: Fri, 9 Oct 2020 13:31:00 +0200 Subject: [PATCH] wikipedia: add plugin --- README.md | 2 +- config.json.example | 7 ++++ edmond/plugins/wikipedia.py | 67 +++++++++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 edmond/plugins/wikipedia.py diff --git a/README.md b/README.md index 219e5ce..554d213 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,6 @@ Missing features - [ ] Music - [ ] Opinions - [ ] Translate -- [ ] Wikipedia: find definition, get random page +- [x] Wikipedia: find definition, get random page - [ ] Wolframalpha - [ ] Youtube: parsing for title, requests for channel or video diff --git a/config.json.example b/config.json.example index d832363..958988f 100644 --- a/config.json.example +++ b/config.json.example @@ -25,6 +25,13 @@ "calm": "Fine!", "pissed": "Pissed off..." } + }, + "wikipedia": { + "commands": ["science", "define"], + "lang": "en", + "ambiguous_response": "It is ambiguous.", + "empty_response": "I can't find it.", + "error_response": "An error occured ;(" } } } diff --git a/edmond/plugins/wikipedia.py b/edmond/plugins/wikipedia.py new file mode 100644 index 0000000..394559a --- /dev/null +++ b/edmond/plugins/wikipedia.py @@ -0,0 +1,67 @@ +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", "error_response", + "lang", + ] + 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 + if self.command.ident == "science": + self.tell_random_summary(event) + elif self.command.ident == "define": + 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 + except wikipedia.exceptions.WikipediaException: + 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 + except wikipedia.exceptions.WikipediaException: + summary = self.config["error_response"] + # Keep trying after a slight delay. + time.sleep(1) + retries -= 1 + if summary: + self.bot.say(event.target, summary)