天谪小红书群控系统测试版 自动生成图片自动发笔记,自动评论等功能。

空闲时间写的软件,目前正在开发中,算是写到一半了吧。发出来大家一起研究研究。

主要用途:小红书小号日常更新。

功能:自动生成图片、免接口通义生成笔记、小红书多账号管理、定时发布、审核后发布、按关键词搜索笔记后自动评论点赞收藏,自动同步小豆芽账号[可用于接任务]。

图片生成方式:自定义背景图或生成的信笺图片+自定义随机字体+随机排列=笔记图片
测试软件运行环境:win10 .net 4.7以上 Node.js 其它系统自行测试。

在这里插入图片描述
软件:小红书群控系统测试版 以下是展示图片:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
图片生成器与小红书发送接口代码如下:

from flask import Flask, request, jsonify
import jieba
import json
import os
import execjs
import requests
import random
import time
from PIL import Image, ImageDraw, ImageFont, ImageStat
from datetime import datetime
import math
import string
import random
import base64

app = Flask(__name__)

headers = {
    "accept": "application/json, text/plain, */*",
    "accept-language": "zh-CN,zh;q=0.9",
    "cache-control": "no-cache",
    "content-type": "application/json;charset=UTF-8",
    "origin": "https://www.xiaohongshu.com",
    "pragma": "no-cache",
    "referer": "https://www.xiaohongshu.com/",
    "sec-ch-ua": "\"Chromium\";v=\"112\", \"Google Chrome\";v=\"112\", \"Not:A-Brand\";v=\"99\"",
    "sec-ch-ua-mobile": "?0",
    "sec-ch-ua-platform": "\"Windows\"",
    "sec-fetch-dest": "empty",
    "sec-fetch-mode": "cors",
    "sec-fetch-site": "same-site",
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36",
}

PUNCTUATION = ",。!?:;、()“”‘’【】[]《》〈〉…—~·!@#$%^&*()_+-=<>?/\\\"'`"

# 常见符号列表用于信笺四角装饰
DECORATIVE_SYMBOLS = ["circle", "star", "heart", "zigzag", "zigzags","sun", "moon", "wave", "dashed", "lightning"]

def get_random_font(font_directory='ttf'):
    """
    随机从指定目录中选择一个字体文件
    """
    # 获取 ttf 目录下的所有文件
    font_files = [f for f in os.listdir(font_directory) if f.endswith('.ttf')]

    # 如果目录中没有字体文件,抛出错误
    if not font_files:
        raise FileNotFoundError("在指定的字体目录中没有找到任何字体文件")

    # 随机选择一个字体文件
    random_font = random.choice(font_files)
    return os.path.join(font_directory, random_font)
    
    
def segment_text(text):
    words = jieba.lcut(text)
    lines = []
    current_line = ""

    # 定义随机让词语独占一行的概率
    single_word_prob = 0.05
    two_words_prob = 0.1
    three_words_prob = 0.15
    four_words_prob = 0.2

    for word in words:
        word_length = len(word)

        if word_length == 1 and random.random() < single_word_prob:
            if current_line:
                cleaned_line = clean_punctuation(current_line)
                if cleaned_line:
                    lines.append(cleaned_line)
                current_line = ""
            lines.append(word)
        elif word_length == 2 and random.random() < two_words_prob:
            if current_line:
                cleaned_line = clean_punctuation(current_line)
                if cleaned_line:
                    lines.append(cleaned_line)
                current_line = ""
            lines.append(word)
        elif word_length == 3 and random.random() < three_words_prob:
            if current_line:
                cleaned_line = clean_punctuation(current_line)
                if cleaned_line:
                    lines.append(cleaned_line)
                current_line = ""
            lines.append(word)
        elif word_length == 4 and random.random() < four_words_prob:
            if current_line:
                cleaned_line = clean_punctuation(current_line)
                if cleaned_line:
                    lines.append(cleaned_line)
                current_line = ""
            lines.append(word)
        else:
            if len(current_line) + word_length > 8:
                cleaned_line = clean_punctuation(current_line)
                if cleaned_line:
                    lines.append(cleaned_line)
                current_line = word
            else:
                current_line += word
    
    if current_line:
        cleaned_line = clean_punctuation(current_line)
        if cleaned_line:
            lines.append(cleaned_line)

    return lines


def clean_punctuation(text):
    while text and text[0] in PUNCTUATION:
        text = text[1:]
    while text and text[-1] in PUNCTUATION:
        text = text[:-1]

    if not text or all(char in PUNCTUATION for char in text):
        return ""
    
    return text


def calculate_text_size(draw, text, font):
    bbox = draw.textbbox((0, 0), text, font=font)
    text_width = bbox[2] - bbox[0]
    text_height = bbox[3] - bbox[1]
    return text_width, text_height


def calculate_average_color(image):
    stat = ImageStat.Stat(image)
    avg_color = stat.mean[:3]
    return avg_color


def choose_text_color(background_color):
    brightness = (background_color[0] * 299 + background_color[1] * 587 + background_color[2] * 114) / 1000
    if brightness > 180:
        return (0, 0, 0)  # 黑色
    else:
        return (255, 255, 255)  # 白色


def add_shadow(draw, position, text, font, text_color, shadow_color):
    x, y = position
    draw.text((x + 2, y + 2), text, font=font, fill=shadow_color)


def generate_random_background(image_width, image_height):
    """
    随机生成信笺风格的背景
    """
    # 增加更多随机浅色系背景颜色
    background_colors = [
    (255, 250, 240), (248, 244, 232), (240, 230, 210), (255, 245, 238), (250, 240, 230),
    (255, 248, 220), (253, 245, 230), (245, 245, 220), (230, 230, 250),
    
    # 额外的淡色背景颜色
    (255, 255, 240), (250, 250, 210), (255, 239, 219), (255, 240, 245), (255, 240, 255),
    (250, 240, 255), (245, 255, 250), (240, 255, 255), (240, 255, 240), (255, 255, 224),
    (253, 245, 230), (245, 255, 250), (250, 250, 250), (255, 250, 250), (255, 255, 255),
    (250, 240, 255), (248, 248, 255), (245, 245, 245), (245, 222, 179), (255, 228, 196),
    (255, 235, 205), (250, 235, 215), (255, 250, 205), (255, 245, 225), (255, 228, 225),
    (255, 239, 213), (255, 239, 240), (253, 245, 229), (252, 245, 228), (255, 255, 245),
    (252, 252, 245), (248, 248, 240), (255, 253, 230), (250, 240, 220), (255, 248, 235)
]
    background_color = random.choice(background_colors)

    # 创建背景
    img = Image.new('RGB', (image_width, image_height), color=background_color)
    draw = ImageDraw.Draw(img)

    # 增加更多线条颜色选择
    line_colors = [
    (random.randint(150, 200), random.randint(100, 150), random.randint(100, 150)),
    (random.randint(180, 220), random.randint(150, 180), random.randint(130, 160)),
    (random.randint(190, 230), random.randint(140, 190), random.randint(110, 160)),

    # 新增更多的随机线条颜色
    (random.randint(140, 180), random.randint(100, 140), random.randint(90, 130)),
    (random.randint(170, 210), random.randint(140, 180), random.randint(120, 160)),
    (random.randint(160, 210), random.randint(120, 170), random.randint(130, 180)),
    (random.randint(180, 230), random.randint(130, 190), random.randint(110, 170)),
    (random.randint(150, 200), random.randint(120, 160), random.randint(110, 150)),
    (random.randint(170, 220), random.randint(140, 190), random.randint(100, 150)),
    (random.randint(180, 240), random.randint(130, 190), random.randint(90, 150)),
    (random.randint(160, 210), random.randint(150, 200), random.randint(110, 160)),
    (random.randint(170, 210), random.randint(130, 170), random.randint(100, 140)),
    (random.randint(150, 190), random.randint(140, 180), random.randint(120, 160)),
    (random.randint(190, 230), random.randint(160, 200), random.randint(130, 170)),
    (random.randint(140, 190), random.randint(120, 170), random.randint(100, 150)),
    (random.randint(150, 220), random.randint(130, 180), random.randint(90, 140))
]

    line_color = random.choice(line_colors)

    # 随机画横线装饰
    for _ in range(random.randint(3, 6)):
        start_x = random.randint(0, image_width)
        end_x = random.randint(0, image_width)
        y = random.randint(0, image_height)
        draw.line([(start_x, y), (end_x, y)], fill=line_color, width=2)

    # 在四周添加装饰性边框
    for _ in range(4):
        offset = random.randint(0, 10)
        draw.rectangle([offset, offset, image_width - offset, image_height - offset], outline=line_color)

    # 添加随机装饰符号到四个角
    add_decorative_symbols(draw, image_width, image_height, line_color, background_color)

    return img



def add_decorative_symbols(draw, image_width, image_height, color, background_color, border_margin=100):
    """
    在信笺的四个角随机绘制一些装饰符号,位置和大小随机,并确保不覆盖边框
    """

    # 定义四个角的范围,并考虑边框的安全区
    corners = [
        (border_margin, border_margin, image_width // 4, image_height // 4),  # 左上角
        (image_width * 3 // 4, border_margin, image_width - border_margin, image_height // 4),  # 右上角
        (border_margin, image_height * 3 // 4, image_width // 4, image_height - border_margin),  # 左下角
        (image_width * 3 // 4, image_height * 3 // 4, image_width - border_margin, image_height - border_margin)  # 右下角
    ]

    symbols = random.sample(DECORATIVE_SYMBOLS, random.randint(2, 3))  # 随机选择 2-3 个符号

    for symbol in symbols:
        # 随机生成形状大小,宽度和高度在 28 到 100 之间,线条类形状长可以到 800
        size = random.randint(28, 50)
        length = random.randint(100, 400) if symbol in ["circle", "star", "heart", "zigzag", "zigzags", "sun", "moon", "wave", "dashed", "lightning"] else size

        # 随机选择一个角落并在该角落内生成随机位置
        corner = random.choice(corners)
        corners.remove(corner)  # 移除已经使用的角落,确保下一个符号不会出现在同一个角落
        min_x, min_y, max_x, max_y = corner

        # 确保生成的形状不会超出角落边界,调整大小以适应可用空间
        if max_x - min_x <= length or max_y - min_y <= size:  # 如果大小超出范围,则调整为最小值
            length = (max_x - min_x) // 2
            size = (max_y - min_y) // 2

        # 生成随机位置,确保位置不会超出边框内
        x = random.randint(min_x, max_x - length)
        y = random.randint(min_y, max_y - size)
        position = (x, y)

        # 根据符号绘制
        if symbol == "circle":
            draw.ellipse([position[0], position[1], position[0] + size, position[1] + size], outline=color)
        elif symbol == "star":
            draw_star(draw, position, color, size)
        elif symbol == "zigzags":
            draw_zigzag(draw, position, color, size)
        elif symbol == "heart":
            draw_heart(draw, position, color, size)
        elif symbol == "zigzag":
            draw_flower(draw, position, color, size)
        elif symbol == "sun":
            draw_sun(draw, position, color, size)
        elif symbol == "moon":
            draw_moon(draw, position, color, size, background_color)
        elif symbol == "wave":
            draw_stamp(draw, position, color, size)
        elif symbol == "dashed":
            draw_leaf(draw, position, color, size)
        elif symbol == "lightning":
            draw_lightning(draw, position, color, length)




# 你还需要调整绘制不同形状的函数,确保它们适应这些变化


# 更新绘制各种形状的函数,接受 size 参数
def draw_star(draw, position, color, size):
    """
    绘制五角星,大小可变
    """
    x, y = position
    points = [
        (x + size // 2, y), (x + size * 2 // 3, y + size // 3),
        (x + size, y + size // 3), (x + size * 3 // 4, y + size * 2 // 3),
        (x + size * 5 // 6, y + size), (x + size // 2, y + size * 4 // 5),
        (x + size // 6, y + size), (x + size // 4, y + size * 2 // 3),
        (x, y + size // 3), (x + size // 3, y + size // 3)
    ]
    draw.polygon(points, outline=color)

def draw_heart(draw, position, color, size):
    """
    绘制心形,大小可变
    """
    x, y = position
    half_size = size // 2
    quarter_size = size // 4

    # 左边的圆弧
    draw.arc([x, y, x + half_size, y + half_size], start=180, end=360, fill=color, width=2)

    # 右边的圆弧
    draw.arc([x + half_size, y, x + size, y + half_size], start=180, end=360, fill=color, width=2)

    # 心形的底部(尖角)
    points = [(x, y + half_size // 2), (x + size, y + half_size // 2), (x + half_size, y + size)]
    draw.polygon(points, fill=color) 







def draw_zigzag(draw, position, color, length):
    """
    绘制立体线条形状的随机字母,长度可变
    """
    x, y = position

    # 随机选择一个字母
    letter = random.choice(string.ascii_uppercase)

    # 设置字体和大小
    font_size = min(100, length)  # 字体大小与长度相关,防止过大
    font = ImageFont.truetype("arial.ttf", font_size)

    # 绘制字母的立体效果,通过偏移来模拟立体感
    offset = 5  # 偏移量,用于模拟立体感

    # 先画立体效果的偏移部分
    draw.text((x + offset, y + offset), letter, font=font, fill=(100, 100, 100))  # 阴影部分

    # 然后画字母的正面
    draw.text((x, y), letter, font=font, fill=color)  # 正面部分


def draw_stamp(draw, position, color, size):
    """
    绘制简单的印章形状,大小可变
    """
    x, y = position
    radius = size // 2

    # 绘制圆形印章的外框
    draw.ellipse([x, y, x + size, y + size], outline=color, width=3)

    # 在圆形中间绘制一个简单的符号或图案
    # 比如简单的十字形或者"X"形状,代表印章内部的图案
    center_x = x + radius
    center_y = y + radius
    draw.line([(center_x - radius // 2, center_y), (center_x + radius // 2, center_y)], fill=color, width=2)
    draw.line([(center_x, center_y - radius // 2), (center_x, center_y + radius // 2)], fill=color, width=2)

def draw_flower(draw, position, color, size):
    """
    绘制小花形状,大小可变,包含随机数量的花瓣和花枝
    """
    x, y = position
    petals = random.randint(5, 7)  # 花瓣数量随机在5到7之间
    radius = size // 2  # 花瓣的半径
    petal_width = size // 3  # 花瓣的宽度
    petal_height = size // 2  # 花瓣的高度

    # 绘制花瓣,确保花瓣在中心点连起来
    for i in range(petals):
        angle = i * (360 / petals)
        # 计算每个花瓣的中心点
        petal_x = x + radius * math.cos(math.radians(angle))
        petal_y = y + radius * math.sin(math.radians(angle))
        # 绘制椭圆形花瓣
        draw.ellipse([petal_x - petal_width // 2, petal_y - petal_height // 2, petal_x + petal_width // 2, petal_y + petal_height // 2], outline=color, fill=color)

    # 绘制花心,使用一个稍小的圆
    draw.ellipse([x - radius // 4, y - radius // 4, x + radius // 4, y + radius // 4], fill=color)

   
    
def draw_moon(draw, position, color, size, background_color):
    """
    绘制不同形状的小月亮,模拟弯月、半月、凸月形状。
    :param background_color: 当前信纸的背景颜色,用于遮挡月亮的一部分。
    """
    x, y = position
    radius = size // 2

    # 随机选择月相形状
    phases = ["crescent", "half", "gibbous"]
    phase = random.choice(phases)
    
    # 绘制完整的月亮圆形
    draw.ellipse([x - radius, y - radius, x + radius, y + radius], outline=color, fill=color)

    # 根据月相叠加阴影效果
    if phase == "crescent":  # 弯月
        # 叠加一个较小且偏移的椭圆,模拟弯月
        draw.ellipse([x - radius // 2, y - radius, x + radius * 1.5, y + radius], outline=None, fill=background_color)
    elif phase == "half":  # 半月
        # 遮挡半个圆
        draw.ellipse([x - radius * 1, y - radius, x + radius * 1.4, y + radius], outline=None, fill=background_color)
    elif phase == "gibbous":  # 凸月
        # 遮挡大部分圆,留下一个稍大的亮区,形成凸月
        draw.ellipse([x - radius * 1.3, y - radius, x + radius * 0.7, y + radius], outline=None, fill=background_color)




    
def draw_sun(draw, position, color, size):
    """
    绘制小太阳形状,包含长短交替的光线
    """
    x, y = position
    radius = size // 2  # 太阳圆心的半径
    num_rays = 12  # 光线数量
    long_ray_length = size  # 长光线的长度
    short_ray_length = size // 2  # 短光线的长度

    # 绘制太阳的圆心
    draw.ellipse([x - radius, y - radius, x + radius, y + radius], outline=color, fill=color)

    # 绘制太阳的光线,长短交替
    for i in range(num_rays):
        angle = i * (360 / num_rays)
        ray_length = long_ray_length if i % 2 == 0 else short_ray_length  # 长短交替
        ray_x = x + ray_length * math.cos(math.radians(angle))
        ray_y = y + ray_length * math.sin(math.radians(angle))
        draw.line([(x, y), (ray_x, ray_y)], fill=color, width=2)


def draw_lightning(draw, position, color, length):
    """
    绘制类似于闪电的形状,通过定义起点和终点,并在中间生成四个偏移点
    """
    x, y = position
    end_x = x + length // 2  # 定义终点的X坐标
    end_y = y + length  # 定义终点的Y坐标

    # 定义两个主要点和中间的四个偏移点
    points = [
        (x, y),  # 起点
        (x + length // 4, y + length // 5),  # 第一个偏移点
        (x - length // 6, y + length * 2 // 5),  # 第二个偏移点
        (x + length // 5, y + length * 3 // 5),  # 第三个偏移点
        (x - length // 4, y + length * 4 // 5),  # 第四个偏移点
        (end_x, end_y)  # 终点
    ]

    # 绘制闪电
    draw.line(points, fill=color, width=3)





def draw_leaf(draw, position, color, size):
    """
    绘制更像树叶的形状,使用弧形边界和随机数量的侧脉,大小可变
    """
    x, y = position
    leaf_width = size
    leaf_height = size * 2  # 叶子的高度是宽度的两倍

    # 叶子的左边和右边使用弧线表示
    num_points = 20  # 用于绘制叶子的点数,数值越大,弧线越平滑
    left_points = []
    right_points = []

    # 生成左边的弧线点(从顶部到底部)
    for i in range(num_points + 1):
        t = i / num_points
        # 左侧弧线,形成曲线
        left_x = x + leaf_width // 2 * (1 - math.cos(math.pi * t))
        left_y = y + leaf_height * t
        left_points.append((left_x, left_y))

        # 右侧弧线,形成曲线
        right_x = x + leaf_width // 2 * (1 + math.cos(math.pi * t))
        right_y = y + leaf_height * t
        right_points.append((right_x, right_y))

    # 将左边和右边的点连接成一个叶子的轮廓
    leaf_outline = left_points + right_points[::-1]
    draw.polygon(leaf_outline, outline=color, fill=None)

    # 绘制主脉(中心线)
    draw.line([(x + leaf_width // 2, y), (x + leaf_width // 2, y + leaf_height)], fill=color, width=2)

    # 随机生成侧脉数量(3到5条)
    num_side_veins = random.randint(3, 5)

    # 计算侧脉的位置,并绘制侧脉
    for i in range(1, num_side_veins + 1):
        # 侧脉的y位置,从顶部到底部的等距位置
        vein_y = y + (i * leaf_height // (num_side_veins + 1))

        # 左侧侧脉,从中心线向左延伸
        draw.line([(x + leaf_width // 2, vein_y), 
                   (x + leaf_width // 4, vein_y - leaf_height // (num_side_veins * 2))], fill=color, width=1)
        
        # 右侧侧脉,从中心线向右延伸
        draw.line([(x + leaf_width // 2, vein_y), 
                   (x + leaf_width * 3 // 4, vein_y - leaf_height // (num_side_veins * 2))], fill=color, width=1)




def generate_images(text, font_path='arial.ttf', emoji_folder='emojis', bg_folder='bg', output_folder='tmp'):
    image_width = 900
    image_height = 1200
    base_font_size = 60
    min_font_size = 40
    max_font_size = 100
    line_spacing = 20

    date_folder = os.path.join(output_folder, datetime.now().strftime('%Y-%m-%d'))
    if not os.path.exists(date_folder):
        os.makedirs(date_folder)

    segmented_text = segment_text(text)

    images_text = []
    current_image_text_count = 0
    current_image_lines = []
    for line in segmented_text:
        if current_image_text_count + len(line) <= 30:
            current_image_lines.append(line)
            current_image_text_count += len(line)
        else:
            images_text.append(current_image_lines)
            current_image_lines = [line]
            current_image_text_count = len(line)
    
    if current_image_lines:
        images_text.append(current_image_lines)

    if len(images_text) > 1 and len(images_text[-1]) < 8:
        images_text[-2].extend(images_text[-1])
        images_text.pop()

    image_paths = []
    for i, lines in enumerate(images_text):
        use_background = random.choice([True, False])
        if use_background and os.path.exists(bg_folder):
            bg_files = os.listdir(bg_folder)
            if bg_files:
                bg_file = random.choice(bg_files)
                img = Image.open(os.path.join(bg_folder, bg_file)).resize((image_width, image_height))
            else:
                img = generate_random_background(image_width, image_height)
        else:
            img = generate_random_background(image_width, image_height)

        draw = ImageDraw.Draw(img)
        avg_color = calculate_average_color(img)
        text_color = choose_text_color(avg_color)

        total_height = 0
        line_heights = []
        fonts = []

        for line in lines:
            font_size = random.randint(min_font_size, max_font_size)
            font = ImageFont.truetype(font_path, font_size)
            fonts.append(font)
            line_height = font_size + random.randint(10, 30)
            line_heights.append(line_height)
            total_height += line_height

        two_word_lines = [line for line in lines if len(line) == 2]
        random_red_line = random.choice(two_word_lines) if two_word_lines and random.random() < 0.5 else None

        if total_height < image_height:
            start_y = (image_height - total_height) // 2
        else:
            start_y = 50

        for line, font, line_height in zip(lines, fonts, line_heights):
            text_width, _ = calculate_text_size(draw, line, font)
            start_x = (image_width - text_width) // 2

            current_text_color = text_color

            if line == random_red_line:
                current_text_color = (255, 0, 0)

            if random.random() < 0.5:
                if current_text_color == (255, 255, 255):
                    add_shadow(draw, (start_x, start_y), line, font, current_text_color, shadow_color=(0, 0, 0))
                elif current_text_color == (0, 0, 0):
                    add_shadow(draw, (start_x, start_y), line, font, current_text_color, shadow_color=(255, 255, 255))

            draw.text((start_x, start_y), line, font=font, fill=current_text_color)
            start_y += line_height

        timestamp = int(time.time())
        random_num = random.randint(1000, 9999)
        image_filename = f"{timestamp}_{random_num}_{i + 1}.png"
        image_path = os.path.join(date_folder, image_filename)
        img.save(image_path)
        image_paths.append(image_path)

    return {
        "image_paths": image_paths
    }


def extract_cookie_value(cookie, key):
    cookies_dict = dict(item.split('=', 1) for item in cookie.split(';'))
    return cookies_dict.get(key.strip())

def sentPostRequest(host, api, data, cookie):
    current_directory = os.path.dirname(__file__)
    file_path = os.path.join(current_directory, "xhs.js")

    # 判断 xhs.js 文件是否存在
    if not os.path.exists(file_path):
        error_message = f"错误:文件 'xhs.js' 不存在,请将该文件放在以下目录中:{current_directory}"
        print(error_message)
        return {"error": "xhs.js 文件未找到"}

    # 提取 cookie 中的 a1 值
    a1 = extract_cookie_value(cookie, 'a1')

    # 执行 JavaScript 函数并获取 X-s 和 X-t
    xs_xt = execjs.compile(open(file_path, 'r', encoding='utf-8').read()).call('getXs', api, data, a1)
    
    # 设置请求头
    headers['cookie'] = cookie
    headers['X-s'] = xs_xt['X-s']
    headers['X-t'] = str(xs_xt['X-t'])
    
    # 打印请求头
    print(f"请求头: {headers}")
    
    # 打印请求包 (请求体)
    json_data = json.dumps(data, separators=(",", ":"), ensure_ascii=False).encode("utf-8")
    print(f"请求包: {json_data.decode('utf-8')}")  # 打印前将字节类型解码为字符串

    # 发送 POST 请求
    url = host + api
    response = requests.post(url=url, data=json_data, headers=headers)
    
    # 打印响应内容
    print(f"响应内容: {response.json()}")
    
    return response.json()


def sentGetRequest(host, api, cookie):
    current_directory = os.path.dirname(__file__)
    file_path = os.path.join(current_directory, "xhs.js")
    a1 = extract_cookie_value(cookie, 'a1')
    xs_xt = execjs.compile(open(file_path, 'r', encoding='utf-8').read()).call('getXs', api, "", a1)
    
    headers['cookie'] = cookie
    headers['X-s'] = xs_xt['X-s']
    headers['X-t'] = str(xs_xt['X-t'])

    url = host + api
    response = requests.get(url=url, headers=headers)
    return response.json()


@app.route('/api/call', methods=['POST'])
def do_api():
    # 获取 JSON 数据
    data = request.json
    
    # 打印时使用 json.dumps 保留中文字符
    print(f"Received Data: {json.dumps(data, ensure_ascii=False)}")
    
    # 获取 api 和 cookie
    api = data.get("Api")  # 确保这里的 key 与 C# 端传过来的 JSON key 一致
    cookie = data.get("Cookie")
    base64_data = data.get("Data")  # 获取 Base64 编码的数据

    try:
        # 解码 Base64 为原始 JSON 字符串
        decoded_json = base64.b64decode(base64_data).decode('utf-8')

        # 手动打印解码后的内容,检查格式是否正确
        print(f"Base64 Decoded String: {decoded_json}")
        
        # 将解码的 JSON 字符串转换为 Python 字典
        post_data = json.loads(decoded_json)  # 解析 JSON
        
        # 打印转码后的内容
        print(f"转码后的字符: {post_data}")

    except Exception as e:
        print(f"Error decoding Base64 data: {e}")
        return jsonify({"error": "Invalid Base64 data"}), 400

    # 打印最后的 API 和数据
    if post_data:  # POST 请求
        result = sentPostRequest('https://edith.xiaohongshu.com', api, post_data, cookie)
    else:  # GET 请求
        result = sentGetRequest('https://edith.xiaohongshu.com', api, cookie)
    
    return jsonify(result)



# 新增状态检查接口
@app.route('/api/status', methods=['GET'])
def status():
    return jsonify({"status": "running"})
@app.route('/generate', methods=['GET'])
def generate_image():
    text = request.args.get('text', default='', type=str)
    
    if not text:
        return jsonify({"code": 404, "msg": "No text provided"}), 404

    font_path = get_random_font('ttf')  # 随机获取字体
    try:
        result = generate_images(text, font_path)  # 调用生成图片的函数
        image_paths = result["image_paths"]
        return jsonify({"code": 200, "msg": "Images generated successfully", "paths": image_paths}), 200
    except Exception as e:
        return jsonify({"code": 404, "msg": str(e)}), 404

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5023)

安装地址:https://www.tianzhe.cn/xhs/install

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱钓鱼的程序员老周

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值