add more arguments to the sticker pack preview

This commit is contained in:
Kentai Radiquum 2024-12-25 23:02:19 +05:00
parent d8d5f56b84
commit 3954bdc520
Signed by: Radiquum
GPG key ID: 858E8EE696525EED
3 changed files with 126 additions and 13 deletions

View file

@ -75,8 +75,8 @@ class Command:
"I am the bot that imports stickers from Telegram and upload them to Matrix rooms\n\n"
"List of commands:\n"
"help - Show this help message.\n"
"import <url|pack_name> [\"import name\"] [-p | --primary] - Use this to import Telegram stickers from given link. import_name is pack_name if not provided. if -p flag is provided, pack will be uploaded as a Default Pack for this room."
"preview [pack_name] - Use this to create a preview for a Telegram stickers. If pack_name is not provided, then preview is generated for a primary pack."
"import <url|pack_name> [\"import name\"] [-p | --primary] - Use this to import Telegram stickers from given link. import_name is pack_name if not provided. if -p flag is provided, pack will be uploaded as a Default Pack for this room.\n"
"preview [pack_name] - Use this to create a preview for a Telegram stickers. If pack_name is not provided, then preview is generated for a primary pack.\n"
)
await send_text_to_room(self.client, self.room.room_id, text)
@ -120,17 +120,27 @@ class Command:
await send_text_to_room(self.client, self.room.room_id, text)
async def _generate_preview(self):
pack_name, _, _ = await _parse_args(self.args)
if not self.args:
pack_name, _, flags = await _parse_args(self.args)
if pack_name == "":
await send_text_to_room(
self.client,
self.room.room_id,
f"Previewing primary pack")
# TODO?: add --help flag
#
# Flags:
# -tu | --tg-url <telegram_url|telegram_shortname> - Use this flag if you want to include stickerpack url in the last message
# -a | --artist <artist> - Use this flag if you want to include stickerpack artist in the last message and room topic
# -au | --artist-url <artist_url> - Use this flag if you want to add artist url in to the last message and room topic
# -s | --space <#space:homeserver> - Use this flag if you want to include space name in the room topic
# -pu | --preview-url <website_url> - Use this flag if you want to include stickerpack preview url in the room topic
# -upd | --update-room - Use this flag if you want to update room avatar, name and topic
previewer = MatrixPreview(self.client, self.room)
async for status in previewer.generate_stickerset_preview_to_room(pack_name):
async for status in previewer.generate_stickerset_preview_to_room(pack_name, flags):
switch = {
MatrixPreview.STATUS_OK: "Done",
MatrixPreview.STATUS_NO_PERMISSION: (
"I do not have permissions to update this room\n"
"Please, give me mod 🙏"

View file

@ -20,6 +20,17 @@ async def send_text_to_room(client: AsyncClient, room_id: str, message: str):
content,
)
async def send_text_to_room_as_text(client: AsyncClient, room_id: str, message: str):
content = {
"msgtype": "m.text",
"body": message,
}
return await client.room_send(
room_id,
"m.room.message",
content,
)
async def send_sticker_to_room(client: AsyncClient, room_id: str, content: dict):
return await client.room_send(
room_id,
@ -58,8 +69,14 @@ async def is_stickerpack_existing(client: AsyncClient, room_id: str, pack_name:
async def upload_stickerpack(client: AsyncClient, room_id: str, stickerset: MatrixStickerset, name):
return await client.room_put_state(room_id, 'im.ponies.room_emotes', stickerset.json(), state_key=name)
async def update_room_image(client: AsyncClient, room_id: str, preview: dict):
return await client.room_put_state(room_id, 'm.room.avatar', preview)
async def update_room_image(client: AsyncClient, room_id: str, image: str):
return await client.room_put_state(room_id, 'm.room.avatar', {"url": image})
async def update_room_name(client: AsyncClient, room_id: str, name: str):
return await client.room_put_state(room_id, 'm.room.name', {"name": name})
async def update_room_topic(client: AsyncClient, room_id: str, topic: str):
return await client.room_put_state(room_id, 'm.room.topic', {"topic": topic})
async def upload_image(client: AsyncClient, image: str):
mime_type = magic.from_file(image, mime=True)

View file

@ -1,6 +1,59 @@
from nio import MatrixRoom, AsyncClient
from chat_functions import has_permission, is_stickerpack_existing, send_sticker_to_room, update_room_image
from chat_functions import has_permission, is_stickerpack_existing, send_sticker_to_room, update_room_image, update_room_name, update_room_topic, send_text_to_room_as_text
async def _parse_args(args: list) -> dict[str, str]:
parsed_args = {
"space": None,
"artist" : None,
"artist_url": None,
"tg_url": None,
"preview_url": None,
"update_room": False
}
if len(args) == 0:
return parsed_args
for index, arg in enumerate(args):
if arg in ["-tu", "--tg-url", "-a", "--artist", "-au", "--artist-url", "-s", "--space", "-pu", "--preview-url"]:
parameter = ""
value = ""
try:
parameter = args[index]
value = args[index + 1]
except IndexError:
continue
if parameter in ["-tu", "--tg-url"]:
if not value.startswith("https://t.me/addstickers/"):
value = f"https://t.me/addstickers/{value}"
parsed_args["tg_url"] = value
elif parameter in ["-a", "--artist"]:
parsed_args["artist"] = value
elif parameter in ["-au", "--artist-url"]:
if not value.startswith("http"):
continue
parsed_args["artist_url"] = value
elif parameter in ["-s", "--space"]:
if not value.startswith("#") or not ":" in value:
continue
parsed_args["space"] = value
elif parameter in ["-pu", "--preview-url"]:
if not value.startswith("http"):
continue
parsed_args["preview_url"] = value
if arg in ["-upd", "--update-room"]:
parsed_args["update_room"] = True
return parsed_args
class MatrixPreview:
@ -19,7 +72,7 @@ class MatrixPreview:
async def _has_permission_to_update(self) -> bool:
return await has_permission(self.client, self.room.room_id, 'state_default')
async def generate_stickerset_preview_to_room(self, pack_name: str):
async def generate_stickerset_preview_to_room(self, pack_name: str, flags: list):
if not await self._has_permission_to_update():
yield self.STATUS_NO_PERMISSION
return
@ -28,14 +81,47 @@ class MatrixPreview:
yield self.STATUS_PACK_NOT_EXISTS
return
parsed_args = await _parse_args(flags)
yield self.STATUS_UPDATING_ROOM_STATE
stickerpack = await self.client.room_get_state_event(self.room.room_id, 'im.ponies.room_emotes', pack_name)
first_item = dict(list(stickerpack.content["images"].items())[:1])
_first_item = first_item.popitem()
await update_room_image(self.client, self.room.room_id, {"url": _first_item[1]['url']})
topic = []
message = []
message.append(f"Stickerpack: {stickerpack.content['pack']['display_name']}")
if parsed_args["space"]:
topic.append(f"Space: {parsed_args['space']}")
if parsed_args["artist"] or parsed_args["artist_url"]:
if parsed_args["artist"] and parsed_args["artist_url"]:
topic.append(f"Stickerpack by {parsed_args['artist']}: {parsed_args['artist_url']}")
message.append(f"Artist: {parsed_args['artist']}: {parsed_args['artist_url']}")
elif parsed_args["artist"]:
topic.append(f"Stickerpack by {parsed_args['artist']}")
message.append(f"Artist: {parsed_args['artist']}")
elif parsed_args["artist_url"]:
topic.append(f"Stickerpack by {parsed_args['artist_url']}")
message.append(f"Artist: {parsed_args['artist_url']}")
if parsed_args["tg_url"]:
message.append(f"Telegram: {parsed_args['tg_url']}")
if parsed_args["preview_url"]:
topic.append(f"Preview: {parsed_args['tg_url']}")
topic = " | ".join(topic)
message = "\n".join(message)
if parsed_args["update_room"]:
await update_room_image(self.client, self.room.room_id, _first_item[1]['url'])
await update_room_name(self.client, self.room.room_id, stickerpack.content["pack"]["display_name"])
await update_room_topic(self.client, self.room.room_id, topic)
# Sending stickers. min: 1, maximum: 5
for stick in list(stickerpack.content["images"].items())[:5]:
await send_sticker_to_room(self.client, self.room.room_id, {"body": stick[0], "url": stick[1]['url'], "info": {"mimetype":"image/png"}})
yield self.STATUS_OK
await send_text_to_room_as_text(self.client, self.room.room_id, message)