iShotaBot/modules/bsky_api.py

76 lines
2.5 KiB
Python
Raw Normal View History

2024-10-20 07:31:44 +00:00
import contextlib
from typing import Optional
from urllib.parse import urlparse
from pydantic import BaseModel
from pyrogram import Client, filters, ContinuePropagation
from pyrogram.enums import MessageEntityType, ChatType
from pyrogram.types import Message
from defs.bsky import Timeline
from init import bot
class Reply(BaseModel):
cid: int
mid: Optional[int] = None
2024-10-22 13:04:59 +00:00
async def process_url(url: str, reply: Reply, override_hidden: bool):
2024-10-20 07:31:44 +00:00
url = urlparse(url)
2024-10-24 15:45:29 +00:00
if url.hostname and url.hostname in ["bsky.app", "bsky.xtaolabs.com"]:
2024-10-20 07:31:44 +00:00
if url.path.find("profile") < 0:
return
author_handle = str(url.path[url.path.find("profile") + 8 :].split("/")[0])
if url.path.find("post") >= 0:
status_id = str(url.path[url.path.find("post") + 5 :].split("/")[0]).split(
"?"
)[0]
try:
post = await Timeline.fetch_post(author_handle, status_id)
2024-10-22 13:04:59 +00:00
await Timeline.send_to_user(reply, post, override_hidden)
2024-10-20 07:31:44 +00:00
except Exception as e:
print(e)
2024-10-21 07:25:04 +00:00
elif url.path == f"/profile/{author_handle}":
2024-10-20 07:31:44 +00:00
# 解析用户
try:
user = await Timeline.fetch_user(author_handle)
await Timeline.send_user(reply, user)
except Exception as e:
print(e)
2024-10-24 15:45:29 +00:00
@bot.on_message(filters.incoming & filters.text & filters.regex(r"bsky.*?\/profile\/"))
2024-10-20 07:31:44 +00:00
async def bsky_share(_: Client, message: Message):
2024-10-22 13:04:59 +00:00
text = message.text
if not text:
2024-10-20 07:31:44 +00:00
return
if (
message.sender_chat
and message.forward_from_chat
and message.sender_chat.id == message.forward_from_chat.id
):
# 过滤绑定频道的转发
return
2024-10-22 13:04:59 +00:00
if text.startswith("~"):
return
override_hidden = False
if "no" in text or "不隐藏" in text:
override_hidden = True
2024-10-20 07:31:44 +00:00
mid = message.id
2024-10-22 13:04:59 +00:00
if text.startswith("del") and message.chat.type == ChatType.CHANNEL:
2024-10-20 07:31:44 +00:00
with contextlib.suppress(Exception):
await message.delete()
mid = None
reply = Reply(cid=message.chat.id, mid=mid)
for num in range(len(message.entities)):
entity = message.entities[num]
if entity.type == MessageEntityType.URL:
2024-10-22 13:04:59 +00:00
url = text[entity.offset : entity.offset + entity.length]
2024-10-20 07:31:44 +00:00
elif entity.type == MessageEntityType.TEXT_LINK:
url = entity.url
else:
continue
2024-10-22 13:04:59 +00:00
await process_url(url, reply, override_hidden)
2024-10-20 07:31:44 +00:00
raise ContinuePropagation