import discord
import requests
import asyncio
import json

intents = discord.Intents.default()
client = discord.Client(intents=intents)

BASE_URL = "https://show.anony.asia/hchs/post/"
last_checked_post_id = 0

# 讀取或創建保存機器人token的文件
try:
    with open("config.json", "r") as config_file:
        config = json.load(config_file)
        TOKEN = config["token"]
        CHANNEL_ID = config.get("channel_id")
except FileNotFoundError:
    print("請輸入機器人token和頻道ID：")
    TOKEN = input("機器人token(請在https://discord.com/developers/applications 新增一個自己的機器人): ")
    CHANNEL_ID = input("頻道ID: ")
    with open("config.json", "w") as config_file:
        json.dump({"token": TOKEN, "channel_id": CHANNEL_ID}, config_file)
    response = requests.get("https://hchs.anony.asia/hchs/last_checked_post_id.txt")
    if response.status_code == 200:
        with open("last_checked_post_id.txt", "w") as file:
            file.write(response.text.strip())  # 更新最新貼文ID

# 讀取保存上次的貼文ID
try:
    with open("last_checked_post_id.txt", "r") as file:
        last_checked_post_id = int(file.read())
except FileNotFoundError:
    pass

async def get_post(post_id):
    response = requests.get(BASE_URL + f"{post_id:04d}")
    if response.status_code == 200:
        return response.text.strip()
    else:
        print(f"檢查新貼文")
        return None

@client.event
async def on_ready():
    print(f'{client.user.name} 已上線！')
    await send_latest_post()
    client.loop.create_task(check_posts())

async def send_latest_post():
    global last_checked_post_id
    global CHANNEL_ID
    if last_checked_post_id == 0:
        post = await get_post(last_checked_post_id + 1)
        if post and CHANNEL_ID:  # 確保頻道ID有效
            channel = client.get_channel(int(CHANNEL_ID))  # 把CHANNEL_ID轉換為整數
            post_content = f"#匿名恆毅{last_checked_post_id + 1}\n{post}"
            embed = discord.Embed(color=discord.Color.gold(), title="\u200b匿名恆毅貼文", description=post_content)
            embed.set_thumbnail(url="https://hchs.anony.asia/hchs/hchs.jpg")
            await channel.send(embed=embed)
            last_checked_post_id = 1  # 更新最後檢查的 post_id
            save_last_checked_post_id()  # 保存最後檢查的 post_id
        else:
            print("無法獲取貼文或頻道ID未提供，忽略發送貼文")
    else:
        print("將會從下一篇貼文開始推送")

async def check_posts():
    global last_checked_post_id
    global CHANNEL_ID
    await client.wait_until_ready()
    channel = client.get_channel(int(CHANNEL_ID))  # 將CHANNEL_ID轉換為整數
    while not client.is_closed():
        post = await get_post(last_checked_post_id + 1)
        if post:
            post_content = f"#匿名恆毅{last_checked_post_id + 1}\n{post}"
            embed = discord.Embed(color=discord.Color.gold(), title="\u200b匿名恆毅貼文", description=post_content)
            embed.set_thumbnail(url="https://hchs.anony.asia/hchs/hchs.jpg")
            await channel.send(embed=embed)
            last_checked_post_id += 1
            save_last_checked_post_id()  # 保存最後檢查的 post_id
        else:
            print("成功檢查")
            await asyncio.sleep(60)

# 保存最後檢查的 post_id 到本地文件
def save_last_checked_post_id():
    with open("last_checked_post_id.txt", "w") as file:
        file.write(str(last_checked_post_id))

client.run(TOKEN)

