pizzabot/echo.py

53 lines
2 KiB
Python
Raw Normal View History

2019-03-06 13:15:11 +00:00
from typing import Optional
2018-11-01 23:17:23 +00:00
from time import time
2019-03-07 19:39:40 +00:00
from mautrix.types import TextMessageEventContent, MessageType
2018-12-17 22:54:33 +00:00
from maubot import Plugin, MessageEvent
from maubot.handlers import command
2018-11-01 23:17:23 +00:00
class EchoBot(Plugin):
@staticmethod
2019-03-07 19:39:40 +00:00
def plural(num: float, unit: str, decimals: Optional[int] = None) -> str:
2019-03-06 13:15:11 +00:00
num = round(num, decimals)
if num == 1:
return f"{num} {unit}"
else:
return f"{num} {unit}s"
@classmethod
2019-03-07 19:39:40 +00:00
def prettify_diff(cls, diff: int) -> str:
2018-11-01 23:17:23 +00:00
if abs(diff) < 10 * 1_000:
return f"{diff} ms"
elif abs(diff) < 60 * 1_000:
2019-03-06 13:15:11 +00:00
return cls.plural(diff / 1_000, 'second', decimals=1)
2018-11-01 23:17:23 +00:00
minutes, seconds = divmod(diff / 1_000, 60)
if abs(minutes) < 60:
2019-03-06 13:15:11 +00:00
return f"{cls.plural(minutes, 'minute')} and {cls.plural(seconds, 'second')}"
2018-11-01 23:17:23 +00:00
hours, minutes = divmod(minutes, 60)
if abs(hours) < 24:
2019-03-07 19:39:40 +00:00
return (f"{cls.plural(hours, 'hour')}, {cls.plural(minutes, 'minute')}"
f" and {cls.plural(seconds, 'second')}")
2018-11-01 23:17:23 +00:00
days, hours = divmod(hours, 24)
2019-03-07 19:39:40 +00:00
return (f"{cls.plural(days, 'day')}, {cls.plural(hours, 'hour')}, "
f"{cls.plural(minutes, 'minute')} and {cls.plural(seconds, 'second')}")
2018-11-01 23:17:23 +00:00
2018-12-17 22:54:33 +00:00
@command.new("ping", help="Ping")
2018-11-01 23:17:23 +00:00
async def ping_handler(self, evt: MessageEvent) -> None:
2019-03-07 19:39:40 +00:00
diff = int(time() * 1000) - evt.timestamp
content = TextMessageEventContent(msgtype=MessageType.NOTICE,
body="Pong! (ping took "
f"{self.prettify_diff(diff)} to arrive)")
content["pong"] = {
"ms": diff,
"from": evt.sender.split(":", 1)[1],
"ping": evt.event_id,
}
await evt.reply(content)
2018-11-01 23:17:23 +00:00
2018-12-17 22:54:33 +00:00
@command.new("echo", help="Repeat a message")
@command.argument("message", pass_raw=True)
2018-12-17 22:54:33 +00:00
async def echo_handler(self, evt: MessageEvent, message: str) -> None:
await evt.respond(message)