Edm0nd/edmond/plugins/wikipedia.py

84 lines
2.7 KiB
Python
Raw Normal View History

2020-10-09 13:31:00 +02:00
import time
from typing import cast
2020-10-09 13:31:00 +02:00
import wikipedia
2020-10-09 13:31:00 +02:00
from edmond.plugin import Plugin
from edmond.plugins.plus import PlusPlugin
2022-11-29 12:53:47 +01:00
from edmond.utils import limit_text_length
2020-10-09 13:31:00 +02:00
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):
2022-09-04 15:27:13 +02:00
page = None
2020-10-09 13:31:00 +02:00
retries = self.NUM_RETRIES
while retries > 0:
try:
2022-09-04 15:27:13 +02:00
page = wikipedia.page(title=wikipedia.random())
2020-10-09 13:31:00 +02:00
break
2022-09-04 15:27:13 +02:00
except Exception as exc:
# The wikipedia package can raise a lot of different stuff,
# so we sort of have to catch broadly.
self.bot.log_d(f"Wikipedia exception: {exc}")
2020-10-09 13:31:00 +02:00
retries -= 1
if page:
2022-11-29 12:53:47 +01:00
reply = limit_text_length(page.summary)
self.register_url_for_plus(page.url, event.target)
2022-11-25 18:39:11 +01:00
self.bot.say(event.target, reply)
2020-10-09 13:31:00 +02:00
def tell_definition(self, event):
2022-09-01 18:53:53 +02:00
page = None
reply = ""
2020-10-09 13:31:00 +02:00
retries = self.NUM_RETRIES
while retries > 0:
try:
2022-09-01 18:53:53 +02:00
page = wikipedia.page(title=self.command.content)
2020-10-09 13:31:00 +02:00
break
except wikipedia.exceptions.DisambiguationError:
2022-09-01 18:53:53 +02:00
reply = self.config["ambiguous_response"]
2020-10-09 13:31:00 +02:00
break
except wikipedia.exceptions.PageError:
2022-09-01 18:53:53 +02:00
reply = self.config["empty_response"]
2020-10-09 13:31:00 +02:00
break
2022-11-25 18:39:11 +01:00
except Exception:
2022-09-01 18:53:53 +02:00
reply = self.bot.config["error_message"]
2020-10-09 13:31:00 +02:00
# Keep trying after a slight delay.
time.sleep(1)
retries -= 1
2022-09-01 18:53:53 +02:00
if page:
2022-11-29 12:53:47 +01:00
reply = limit_text_length(page.summary)
self.register_url_for_plus(page.url, event.target)
2022-09-01 18:53:53 +02:00
self.bot.say(event.target, reply)
def register_url_for_plus(self, url: str, target: str):
if plus_plugin := self.bot.get_plugin("plus"):
def handler(plus_event):
self.bot.say(plus_event.target, url)
cast(PlusPlugin, plus_plugin).add_handler(target, handler)