Add pong metadata

This commit is contained in:
Tulir Asokan 2019-03-07 21:39:40 +02:00
parent 7786f03b03
commit e42a19df0f

24
echo.py
View file

@ -1,13 +1,15 @@
from typing import Optional from typing import Optional
from time import time from time import time
from mautrix.types import TextMessageEventContent, MessageType
from maubot import Plugin, MessageEvent from maubot import Plugin, MessageEvent
from maubot.handlers import command from maubot.handlers import command
class EchoBot(Plugin): class EchoBot(Plugin):
@staticmethod @staticmethod
def plural(num: int, unit: str, decimals: Optional[int] = None) -> str: def plural(num: float, unit: str, decimals: Optional[int] = None) -> str:
num = round(num, decimals) num = round(num, decimals)
if num == 1: if num == 1:
return f"{num} {unit}" return f"{num} {unit}"
@ -15,8 +17,7 @@ class EchoBot(Plugin):
return f"{num} {unit}s" return f"{num} {unit}s"
@classmethod @classmethod
def time_since(cls, ms: int) -> str: def prettify_diff(cls, diff: int) -> str:
diff = int(time() * 1000) - ms
if abs(diff) < 10 * 1_000: if abs(diff) < 10 * 1_000:
return f"{diff} ms" return f"{diff} ms"
elif abs(diff) < 60 * 1_000: elif abs(diff) < 60 * 1_000:
@ -26,13 +27,24 @@ class EchoBot(Plugin):
return f"{cls.plural(minutes, 'minute')} and {cls.plural(seconds, 'second')}" return f"{cls.plural(minutes, 'minute')} and {cls.plural(seconds, 'second')}"
hours, minutes = divmod(minutes, 60) hours, minutes = divmod(minutes, 60)
if abs(hours) < 24: if abs(hours) < 24:
return f"{cls.plural(hours, 'hour')}, {cls.plural(minutes, 'minute')} and {cls.plural(seconds, 'second')}" return (f"{cls.plural(hours, 'hour')}, {cls.plural(minutes, 'minute')}"
f" and {cls.plural(seconds, 'second')}")
days, hours = divmod(hours, 24) days, hours = divmod(hours, 24)
return f"{cls.plural(days, 'day')}, {cls.plural(hours, 'hour')}, {cls.plural(minutes, 'minute')} and {cls.plural(seconds, 'second')}" return (f"{cls.plural(days, 'day')}, {cls.plural(hours, 'hour')}, "
f"{cls.plural(minutes, 'minute')} and {cls.plural(seconds, 'second')}")
@command.new("ping", help="Ping") @command.new("ping", help="Ping")
async def ping_handler(self, evt: MessageEvent) -> None: async def ping_handler(self, evt: MessageEvent) -> None:
await evt.reply(f"Pong! (ping took {self.time_since(evt.timestamp)} to arrive)") 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)
@command.new("echo", help="Repeat a message") @command.new("echo", help="Repeat a message")
@command.argument("message", pass_raw=True) @command.argument("message", pass_raw=True)