PagerMaid_Plugins_Pyro/qr/main.py

82 lines
2.6 KiB
Python
Raw Normal View History

2023-01-09 13:42:40 +00:00
""" QR Code related utilities. """
from PIL import Image
2024-09-28 14:35:08 +00:00
from pagermaid.config import Config
2023-01-09 13:42:40 +00:00
from pagermaid.enums import Client, Message
from pagermaid.listener import listener
2024-09-28 14:35:08 +00:00
from pagermaid.utils import lang, pip_install, safe_remove
from pagermaid.utils.bot_utils import log
2023-01-09 13:42:40 +00:00
pip_install("pyqrcode")
pip_install("pypng")
pip_install("pyzbar")
from pyqrcode import create
2023-07-01 12:18:58 +00:00
@listener(
is_plugin=False,
outgoing=True,
command="genqr",
description=lang("genqr_des"),
parameters="[string]",
)
2023-01-09 13:42:40 +00:00
async def gen_qr(client: Client, message: Message):
2023-07-01 12:18:58 +00:00
"""Generate QR codes."""
2023-01-09 13:42:40 +00:00
text = message.obtain_message()
if not text:
2023-07-01 12:18:58 +00:00
await message.edit(lang("error_prefix"))
2023-01-09 13:42:40 +00:00
return
if not Config.SILENT:
2023-07-01 12:18:58 +00:00
await message.edit(lang("genqr_process"))
2023-01-09 13:42:40 +00:00
try:
create(text, error="L", encoding="utf-8", mode="binary").png("qr.webp", scale=6)
2023-01-09 13:42:40 +00:00
await client.send_document(
message.chat.id,
document="qr.webp",
2024-02-04 07:56:06 +00:00
reply_to_message_id=message.reply_to_message_id,
message_thread_id=message.message_thread_id,
2023-01-09 13:42:40 +00:00
)
except UnicodeEncodeError:
await message.edit(f"{lang('error_prefix')}{lang('genqr_e_encode')}")
return
except Exception as e:
await message.edit(f"{lang('error_prefix')}\n{e}")
return
finally:
safe_remove("qr.webp")
await message.safe_delete()
await log(f"`{text}` {lang('genqr_ok')}")
2023-07-01 12:18:58 +00:00
@listener(
is_plugin=False, outgoing=True, command="parseqr", description=lang("parseqr_des")
)
2023-01-09 13:42:40 +00:00
async def parse_qr(message: Message):
2023-07-01 12:18:58 +00:00
"""Parse attachment of replied message as a QR Code and output results."""
2023-01-09 13:42:40 +00:00
try:
from pyzbar.pyzbar import decode as pyzbar_decode
except ImportError:
await message.edit(f"{lang('error_prefix')}请先在系统中安装 zbar 库。")
return
success = False
reply = message.reply_to_message
if message.document or message.photo or message.sticker:
target_file_path = await message.download()
elif reply and (reply.document or reply.photo or reply.sticker):
target_file_path = await reply.download()
else:
return await message.edit(f"{lang('error_prefix')}{lang('parseqr_nofile')}")
try:
text = str(pyzbar_decode(Image.open(target_file_path))[0].data)[2:][:-1]
success = True
2023-07-01 12:18:58 +00:00
await message.edit(f"**{lang('parseqr_content')}: **\n" f"`{text}`")
2023-01-09 13:42:40 +00:00
except Exception:
await message.edit(f"{lang('error_prefix')}{lang('parseqr_e_noqr')}")
text = None
finally:
safe_remove(target_file_path)
if success:
await log(f"{lang('parseqr_log')} `{text}`.")