main
 1#!/usr/bin/env python
 2# -*- coding: utf-8 -*-
 3import asyncio
 4import re
 5from datetime import timedelta
 6
 7from glom import glom
 8from loguru import logger
 9from pyrogram.client import Client
10from pyrogram.types import Message
11
12from config import TZ, cache
13from custom.config import ACCOUNT_NAME, CHANNEL_LILAOSHI_OFFICIAL, CHANNEL_LILAOSHI_PREVIEWED
14from database.d1 import insert_d1, query_d1
15from database.r2 import get_cf_r2
16from messages.chat_history import get_history_info_list_via_telegram
17from messages.parser import parse_msg
18from messages.utils import delete_message
19from networking import match_social_media_link
20from utils import nowdt
21
22
23async def handle_lilaoshi(client: Client, message: Message):
24    if ACCOUNT_NAME != "xiaohao" or message.chat.id != CHANNEL_LILAOSHI_OFFICIAL:
25        return
26    info = parse_msg(message, silent=True)
27    if info["entity_urls"] and (matched := await match_social_media_link(info["entity_urls"][0])) and matched["platform"] in ["twitter", "x", "fxtwitter", "fixupx"]:
28        text = f"{matched['url']}\n#set_target_chat={CHANNEL_LILAOSHI_PREVIEWED} #no_show_statistics #no_twitter_comments #set_reply_msg_id=-1 #no_show_progress"
29        msg = await client.send_message("@bennydou_bot", text)
30        await asyncio.sleep(30)
31        await delete_message(msg)
32        await save2d1(matched["post_id"], info["time"])
33
34
35async def preview_lilaoshi_history_message(client: Client, hours: int = 25):
36    if cache.get("preview_lilaoshi_history_message"):
37        return
38    cache.set("preview_lilaoshi_history_message", 1, ttl=12 * 3600)  # backup every 12 hours
39    # from database.d1 import create_d1_table
40
41    # columns = "id TEXT PRIMARY KEY, handle TEXT, time TEXT"
42    # indexes = ["handle", "time"]
43    # await create_d1_table("twitter", columns, idx_cols=indexes, silent=False)
44    begin_time = nowdt(TZ) - timedelta(hours=hours)
45    d1 = await query_d1(sql=f"SELECT id FROM twitter WHERE time >= '{begin_time:%Y-%m-%d %H:%M:%S}'", silent=True)
46    d1_ids = set(glom(d1, "**.id", default=[]))
47    if not d1_ids:
48        return
49    offical_info_list = await get_history_info_list_via_telegram(client, chat_id="lilaoshibushinilaoshi", begin_time=begin_time, limit=999999)
50    for info in offical_info_list:  # old to new
51        if not info["entity_urls"]:
52            continue
53        matched = re.findall(r"https://(:?twitter|x|fxtwitter|fixupx|vxtwitter)\.com/whyyoutouzhele/status/(\d+)", info["entity_urls"][0])
54        pids = [pid for _, pid in matched]
55        for pid in pids:
56            if pid not in d1_ids:
57                url = f"https://x.com/whyyoutouzhele/status/{pid}"
58                logger.info(f"解析李老师频道链接: {url} | {info['text'][:30]}")
59                text = f"{url}\n#set_target_chat={CHANNEL_LILAOSHI_PREVIEWED} #no_show_statistics #no_twitter_comments #set_reply_msg_id=-1 #no_show_progress"
60                msg = await client.send_message("@bennydou_bot", text)
61                await asyncio.sleep(30)
62                await delete_message(msg)
63                await save2d1(pid, info["time"])
64
65
66async def save2d1(pid: str, time: str):
67    if await get_cf_r2(f"x.com/whyyoutouzhele/status/{pid}", silent=True):
68        records = {
69            "id": str(pid),
70            "handle": "whyyoutouzhele",
71            "time": time,
72        }
73        await query_d1(**insert_d1("twitter", records, update_on_conflict="id"), silent=True)