wikipedia: fix messages too long

For now it's only used by the Wikipedia plugin but it should probably be
moved elsewhere quickly!
This commit is contained in:
dece 2022-11-25 01:25:54 +01:00
parent 83d92d0a4d
commit 146db88ed3
2 changed files with 43 additions and 12 deletions

View file

@ -0,0 +1,14 @@
import unittest
from ..wikipedia import WikipediaPlugin
class TestWikipediaPlugin(unittest.TestCase):
def test_limit_text_length(self):
text = "lorem ipsum blah blah."
result = WikipediaPlugin.limit_text_length(text, max_length=10)
self.assertEqual(result, "lorem…")
result = WikipediaPlugin.limit_text_length(text, max_length=15)
self.assertEqual(result, "lorem ipsum…")
result = WikipediaPlugin.limit_text_length(text, max_length=30)
self.assertEqual(result, "lorem ipsum blah blah.")

View file

@ -1,4 +1,5 @@
import time
from typing import cast
try:
import wikipedia
@ -8,6 +9,7 @@ except ImportError:
DEPENDENCIES_FOUND = False
from edmond.plugin import Plugin
from edmond.plugins.plus import PlusPlugin
class WikipediaPlugin(Plugin):
@ -50,11 +52,9 @@ class WikipediaPlugin(Plugin):
self.bot.log_d(f"Wikipedia exception: {exc}")
retries -= 1
if page:
if plus_plugin := self.bot.get_plugin("plus"):
def handler(plus_event):
self.bot.say(plus_event.target, page.url)
plus_plugin.add_handler(event.target, handler)
self.bot.say(event.target, page.summary)
reply = WikipediaPlugin.limit_text_length(page.summary)
self.register_url_for_plus(page.url, event.target)
self.bot.say(event.target, summary)
def tell_definition(self, event):
page = None
@ -76,11 +76,28 @@ class WikipediaPlugin(Plugin):
time.sleep(1)
retries -= 1
if page:
reply = page.summary.split(". ", maxsplit=1)[0]
if len(reply) > 200:
reply = reply[:196] + " […]"
if plus_plugin := self.bot.get_plugin("plus"):
def handler(plus_event):
self.bot.say(plus_event.target, page.url)
plus_plugin.add_handler(event.target, handler)
reply = WikipediaPlugin.limit_text_length(page.summary)
self.register_url_for_plus(page.url, event.target)
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)
@staticmethod
def limit_text_length(text, max_length=200):
"""Limit text size to 200 characters max."""
words = text.split(" ")
cut_text = ""
while words:
next_word = words.pop(0)
if len(cut_text) + len(next_word) + 1 >= max_length:
break
cut_text += next_word + " "
if len(cut_text) < len(text):
cut_text = cut_text[:-1] + ""
else:
cut_text = cut_text.rstrip()
return cut_text