use tempfile, test

This commit is contained in:
felinae98 2021-02-26 20:16:16 +08:00
parent b14604fd3a
commit c47b0c4425
No known key found for this signature in database
GPG Key ID: 00C8B010587FF610

View File

@ -7,6 +7,7 @@ import base64
from pyppeteer import launch from pyppeteer import launch
from html import escape from html import escape
from hashlib import sha256 from hashlib import sha256
from tempfile import NamedTemporaryFile
from .plugin_config import plugin_config from .plugin_config import plugin_config
@ -44,14 +45,14 @@ class Render(metaclass=Singleton):
return str(data) return str(data)
async def text_to_pic(self, text: str) -> str: async def text_to_pic(self, text: str) -> str:
hash_text = sha256(text.encode()).hexdigest()[:20]
lines = text.split('\n') lines = text.split('\n')
parsed_lines = list(map(lambda x: '<p>{}</p>'.format(escape(x)), lines)) parsed_lines = list(map(lambda x: '<p>{}</p>'.format(escape(x)), lines))
html_text = '<div style="width:17em;padding:1em">{}</div>'.format(''.join(parsed_lines)) html_text = '<div style="width:17em;padding:1em">{}</div>'.format(''.join(parsed_lines))
with open('/tmp/text-{}.html'.format(hash_text), 'w') as f: with NamedTemporaryFile('wt', suffix='.html', delete=False) as tmp:
f.write(html_text) tmp_path = tmp.name
data = await self.render('file:///tmp/text-{}.html'.format(hash_text), target='div') tmp.write(html_text)
os.remove('/tmp/text-{}.html'.format(hash_text)) data = await self.render('file://{}'.format(tmp_path), target='div')
os.remove(tmp_path)
return data return data
async def text_to_pic_cqcode(self, text:str) -> str: async def text_to_pic_cqcode(self, text:str) -> str:
@ -68,3 +69,8 @@ async def parse_text(text: str):
else: else:
return text return text
async def test():
ren = Render()
res = await ren.text_to_pic('12333333')
logger.debug(res)
nonebot.get_driver().on_startup(test)