Notion_Bot/app/utils/send_to_notion.py

93 lines
2.8 KiB
Python
Raw Permalink Normal View History

2024-04-27 21:42:08 +04:00
import os
import re
from datetime import datetime, timezone
from os import path
from imgur_python import Imgur
from aiogram.types import Message, MessageEntity, PhotoSize
from app.settings import notion, bot, secrets
2024-04-28 20:05:23 +04:00
async def send_to_notion(message: Message, album):
imgur_client = Imgur(
{"client_id": secrets.imgur_client_id.get_secret_value()}
)
2024-04-27 21:42:08 +04:00
pattern = r"(https?://[^\s]+|t\.me/[^\s]+)"
image_url = None
2024-04-28 20:05:23 +04:00
photos = []
2024-04-27 21:42:08 +04:00
if message.caption:
links2 = re.findall(pattern, message.caption)
text: str = message.caption
links: MessageEntity = [
link.url for link in message.caption_entities if link.type == "text_link"
]
2024-04-28 20:05:23 +04:00
if album:
2024-05-02 19:43:14 +04:00
photos: PhotoSize = [photo.photo[-1].file_id for photo in album]
2024-04-28 20:05:23 +04:00
elif message.photo:
2024-05-02 19:43:14 +04:00
photos: PhotoSize = [message.photo[-1].file_id]
2024-04-27 21:42:08 +04:00
else:
text: str = message.text
links2 = re.findall(pattern, message.text)
photos = []
links: MessageEntity = (
[link.url for link in message.entities if link.type == "text_link"]
if message.entities
else []
)
if links2:
links.extend(links2)
links = set(links)
properties = {
2024-04-28 20:05:23 +04:00
"Name": {"title": [{"text": {"content": text[: text.find("\n") or -1]}}]},
2024-04-27 21:42:08 +04:00
"Text": {"rich_text": [{"text": {"content": text}}]},
"Added at": {
"date": {
"start": datetime.now().astimezone(timezone.utc).isoformat(),
"end": None,
}
},
}
for i, link in enumerate(links, start=1):
if i > 4:
break
properties[f"Link{i}"] = {"url": link}
cover = None
if photos:
2024-04-28 20:05:23 +04:00
for i, photo in enumerate(photos, start=1):
if i > 9:
break
file_name = f"images/{photo}.jpg"
await bot.download(photo, destination=file_name)
image = imgur_client.image_upload(
path.realpath(file_name), "Untitled", "My first image upload"
)
image_url = image["response"]["data"]["link"]
os.remove(file_name)
if i == 1:
cover = {"type": "external", "external": {"url": image_url}}
properties[f"Image{i}"] = {
"files": [
{
"name": "image.jpg",
"type": "external",
"external": {"url": image_url},
}
]
}
2024-04-27 21:42:08 +04:00
icon = {"type": "emoji", "emoji": "🎉"}
parent = {
"type": "database_id",
"database_id": secrets.database_id.get_secret_value(),
}
return await notion.pages.create(
parent=parent, properties=properties, icon=icon, cover=cover
)