跳到正文

个人记录

第二代自动灼灼器(自用)

松绒灼茁桌捉浊卓焯琢约 16 分钟
原文
文章信息与版本

文章信息

发布
2026年7月17日
收录
2026年7月17日
更新
2026年8月5日
篇幅
约 16 分钟

版本

  1. v1当前

叠甲:AI写的,自用,不建议使用,一定要用就自行承担后果,其他用户滥用和我无关。

搭配 systemd 和 timer 使用更佳。

/usr/local/bin/send_benben
Python
#!/usr/bin/env python3
import requests
import re
import json
import os
import time
import random
import datetime
t = random.randint(1, 15)
print("随机 sleep...", t)
time.sleep(t)
print("sleep ok")
# 硬编码完整 Cookie(从浏览器复制全部)
COOKIE = "_uid=你的uid; uid=你的uid; __client_id=你的cid; C3VK=你的C3VK; login_referer=https://www.luogu.com.cn/"

current_time = datetime.datetime.now()
# 发送内容
CONTENT = f"灼灼 _{current_time}_"

# 队列最大容量限制(可根据需要修改)
QUEUE_LIMIT = 5

# 本地队列存储文件路径(建议配合 systemd 时使用绝对路径,例如 "/home/username/luogu_bot/sent_benbens.json")
QUEUE_FILE = "~/.sent_benbens.json"


# 加载本地队列
def load_queue(file_path):
    if not os.path.exists(file_path):
        return []
    try:
        with open(file_path, "r", encoding="utf-8") as f:
            data = json.load(f)
            if isinstance(data, list):
                return data
    except Exception as e:
        print(f"读取队列文件失败(可能是文件损坏或权限问题): {e}")
    return []


# 保存本地队列
def save_queue(file_path, queue):
    try:
        with open(file_path, "w", encoding="utf-8") as f:
            json.dump(queue, f, indent=4)
    except Exception as e:
        print(f"保存队列文件失败: {e}")


# 1. 建立 Session 会话
session = requests.Session()

# 2. 配置符合洛谷要求的全局请求头
CUSTOM_UA = "ZhuoZhuo/128.84"
# CUSTOM_UA = "Mozilla/5.0"
session.headers.update({
    "User-Agent": CUSTOM_UA,
    "Referer": "https://www.luogu.com.cn/",
})

# 将 COOKIE 字符串解析并写入 Session 中
cookie_dict = {}
for item in COOKIE.split(';'):
    if '=' in item:
        key, value = item.strip().split('=', 1)
        cookie_dict[key] = value
session.cookies.update(cookie_dict)

# 3. 获取 CSRF Token
try:
    resp = session.get("https://www.luogu.com.cn/")
    if resp.status_code != 200:
        raise Exception(f"请求主页失败,状态码: {resp.status_code}")
    
    token_match = re.search(r'csrf-token" content="([^"]+)"', resp.text)
    if not token_match:
        raise Exception("未找到 CSRF Token,请确认 Cookie 格式或是否触发了人机验证。")
    
    csrf = token_match.group(1)
    print(f"成功获取 CSRF Token: {csrf}")
except Exception as e:
    print(f"获取 CSRF 失败: {e}")
    exit(1)

# 4. 发送新犇犇
headers = {
    "X-CSRF-Token": csrf,
    "X-Requested-With": "XMLHttpRequest",
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
}
data = {"content": CONTENT}

post_success = False
try:
    r = session.post("https://www.luogu.com.cn/api/feed/postBenben", data=data, headers=headers)
    if r.status_code == 200:
        try:
            res_json = r.json()
            print(f"发送成功,服务器返回: {res_json}")
            post_success = True
        except ValueError:
            print("发送成功,但未能解析返回的 JSON 数据")
            post_success = True
    else:
        print(f"发送失败: {r.status_code} {r.text}")
except Exception as e:
    print(f"请求异常: {e}")

# 5. 如果发送成功,进行队列管理和删除逻辑
if post_success:
    new_benben_id = None
    try:
        # 获取自己的第一页犇犇列表,以此抓取最新发出的犇犇 ID
        my_feeds_resp = session.get("https://www.luogu.com.cn/feed/my?page=1")
        if my_feeds_resp.status_code == 200:
            # 第一个匹配到的 data-feed-id 对应的就是刚才发出的那只犇犇
            id_match = re.search(r'data-feed-id="(\d+)"', my_feeds_resp.text)
            if id_match:
                new_benben_id = id_match.group(1)
                print(f"获取到刚发送的犇犇 ID: {new_benben_id}")
            else:
                print("获取犇犇 ID 失败,未能匹配到 data-feed-id")
        else:
            print(f"获取个人犇犇页面失败,状态码: {my_feeds_resp.status_code}")
    except Exception as e:
        print(f"获取犇犇 ID 时发生异常: {e}")

    # 如果成功拿到了新 ID,更新本地队列并触发删除
    if new_benben_id:
        queue = load_queue(QUEUE_FILE)
        
        # 避免由于异常运行产生重复的 ID 记录
        if new_benben_id not in queue:
            queue.append(new_benben_id)
        
        # 当队列大小超出预设限制时,开始调用接口删除旧犇犇
        while len(queue) > QUEUE_LIMIT:
            # 弹出最老的一条
            oldest_id = queue.pop(0)
            print(f"队列已满(超出上限 {QUEUE_LIMIT}),准备删除旧犇犇 ID: {oldest_id}...")
            
            try:
                # 调用洛谷删除犇犇的 POST 接口
                del_url = f"https://www.luogu.com.cn/api/feed/delete/{oldest_id}"
                del_resp = session.post(del_url, headers=headers)
                
                if del_resp.status_code == 200:
                    print(f"旧犇犇 {oldest_id} 删除成功")
                else:
                    print(f"旧犇犇 {oldest_id} 删除失败,状态码: {del_resp.status_code},响应: {del_resp.text}")
            except Exception as e:
                print(f"发送删除请求时发生异常: {e}")
        
        # 将最新状态写回本地
        save_queue(QUEUE_FILE, queue)
~/.config/systemd/user/send-benben.timer
代码
[Unit]
Description=Timer for Luogu Benben every even hour

[Timer]
OnCalendar=*-*-* 00/2:00:00
Persistent=true

[Install]
WantedBy=timers.target
~/.config/systemd/user/send-benben.service
代码
[Unit]
Description=Send Luogu Benben

[Service]
Type=oneshot
ExecStart=/usr/local/bin/send_benben

反自动灼灼器

其实就是删犇器

/usr/local/bin/del_benben
Python
#!/usr/bin/env python3
import requests
import re
import time

# 硬编码完整 Cookie(从浏览器复制全部)
COOKIE = "_uid=?; uid=?; __client_id=?; C3VK=?; login_referer=https://www.luogu.com.cn/"

# 每次删除请求之间的延迟时间(秒),防止请求过快触发系统限制
REQUEST_DELAY = 2.0 # 小于该数值大概率会飞碟(403)

# 1. 建立 Session 会话并配置请求头
session = requests.Session()
CUSTOM_UA = "ZhuoZhuo/128.84"
session.headers.update({
    "User-Agent": CUSTOM_UA,
    "Referer": "https://www.luogu.com.cn/",
})

# 解析 Cookie
cookie_dict = {}
for item in COOKIE.split(';'):
    if '=' in item:
        key, value = item.strip().split('=', 1)
        cookie_dict[key] = value
session.cookies.update(cookie_dict)

# 2. 获取 CSRF Token
try:
    resp = session.get("https://www.luogu.com.cn/")
    if resp.status_code != 200:
        raise Exception(f"请求主页失败,状态码: {resp.status_code}")
    
    token_match = re.search(r'csrf-token" content="([^"]+)"', resp.text)
    if not token_match:
        raise Exception("未找到 CSRF Token,请确认 Cookie 格式或是否触发了人机验证。")
    
    csrf = token_match.group(1)
    print(f"成功获取 CSRF Token: {csrf}")
except Exception as e:
    print(f"获取 CSRF 失败: {e}")
    exit(1)

headers = {
    "X-CSRF-Token": csrf,
    "X-Requested-With": "XMLHttpRequest",
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
}

# 3. 循环获取第一页并删除
last_attempted_ids = []
no_progress_count = 0

print("开始清空犇犇流程...")

while True:
    try:
        # 始终请求第一页
        my_feeds_resp = session.get("https://www.luogu.com.cn/feed/my?page=1") # 如果发现读到的犇犇变少了可以改 page
        if my_feeds_resp.status_code != 200:
            print(f"获取个人犇犇页面失败,状态码: {my_feeds_resp.status_code}")
            break
        
        # 提取当前页面的所有犇犇 ID
        # 使用 dict.fromkeys 进行去重并保持原有顺序
        feed_ids = list(dict.fromkeys(re.findall(r'data-feed-id="(\d+)"', my_feeds_resp.text)))
        
        if not feed_ids:
            print("第一页未检测到任何犇犇 ID,清空任务完成。")
            break
            
        print(f"\n当前页面扫描到 {len(feed_ids)} 条犇犇,准备依次删除: {feed_ids}")
        
        # 安全退出机制:如果连续三次获取到的待删除 ID 列表完全一致且无变化
        # 说明之前的删除请求未能生效(可能因为权限问题、已被手动删除或触发频控),此时退出防止死循环
        if feed_ids == last_attempted_ids:
            no_progress_count += 1
            if no_progress_count >= 3:
                print("警告: 连续多次尝试删除相同的犇犇失败(可能触发了洛谷的频控,或 Cookie 权限失效),为防止死循环已终止脚本。")
                break
        else:
            no_progress_count = 0
            last_attempted_ids = feed_ids

        # 遍历删除当前页的犇犇
        for feed_id in feed_ids:
            print(f"正在删除 ID: {feed_id} ...")
            
            del_url = f"https://www.luogu.com.cn/api/feed/delete/{feed_id}"
            try:
                del_resp = session.post(del_url, headers=headers)
                
                if del_resp.status_code == 200:
                    print(f"ID {feed_id} 删除成功")
                else:
                    print(f"ID {feed_id} 删除失败,状态码: {del_resp.status_code},响应: {del_resp.text}")
            except Exception as e:
                print(f"请求删除 ID {feed_id} 时发生异常: {e}")
            
            # 延迟,降低请求频率
            time.sleep(REQUEST_DELAY)
            
    except Exception as outer_e:
        print(f"主循环发生非预期异常: {outer_e}")
        break

print("删除脚本执行结束。")

2h 一条,一天不到 50 次请求,还不刷屏,我就不信能封掉我!

原文