nonsensebot/app/modules/misskey_preview.py

58 lines
2.1 KiB
Python
Raw Normal View History

2024-08-03 01:49:45 +01:00
"""
This module takes misskey links (e.g.) and provides a preview in a reply.
"""
import niobot
import httpx
import typing
import textwrap
from urllib.parse import urlparse
if typing.TYPE_CHECKING:
from ..main import TortoiseIntegratedBot
class MisskeyPreviewModule(niobot.Module):
bot: "TortoiseIntegratedBot"
@niobot.event("message")
async def on_message(self, room: niobot.MatrixRoom, event: niobot.RoomMessage):
supported_prefixes = self.bot.cfg.get("misskey_preview", {})
supported_prefixes = supported_prefixes.get("urls", ["https://fedi.transgender.ing/notes"])
if not isinstance(event, niobot.RoomMessageText):
return
sent = []
async with httpx.AsyncClient() as client:
for item in event.body.split():
if not event.body.startswith(tuple(supported_prefixes)):
return
parsed = urlparse(item)
post_id = parsed.path.split("/")[-1]
if post_id in sent:
continue
elif len(sent) >= 5:
break
2024-08-11 15:18:31 +01:00
resp = await client.get("https://%s/api/v1/statuses/%s" % (parsed.netloc, post_id))
2024-08-03 01:49:45 +01:00
if resp.status_code != 200:
continue
data = resp.json()
2024-08-11 15:18:31 +01:00
username = data["user"]["fqn"]
if not data.get("text"):
2024-08-03 01:49:45 +01:00
continue
2024-08-03 19:19:55 +01:00
text = textwrap.shorten(data["text"], width=1000)
rendered = self.bot._markdown_to_html(text)
text_body = "<blockquote>%s</blockquote>" % rendered
2024-08-03 01:57:52 +01:00
body = "<a href=\"%s\">@%s:</a><br>%s" % (
2024-08-03 01:55:38 +01:00
"https://%s/@%s" % (parsed.netloc, username),
2024-08-03 01:52:50 +01:00
username,
2024-08-03 01:57:52 +01:00
text_body,
2024-08-03 01:49:45 +01:00
)
2024-08-03 01:52:50 +01:00
await self.bot.send_message(
room,
body,
reply_to=event,
2024-08-03 01:55:38 +01:00
content_type="html.raw",
2024-08-03 01:52:50 +01:00
override={"body": f"@{username}: {data['text']!r}"}
)
2024-08-03 01:49:45 +01:00
sent.append(post_id)