You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Reddit API问题:提交的评论为何未出现在后续获取的JSON中?

Reddit API提交评论后无法通过接口获取的问题

开发用户向帖子提交评论的功能时,遇到以下问题:通过Reddit API成功提交评论后,在Reddit网页端能正常看到该评论,但后续请求帖子评论JSON接口时,返回结果包含其他最新评论,唯独缺少自己提交的评论(包括直接在Reddit网页端发布的评论,也未出现在接口返回的JSON中)。

1. 获取用户授权

// 1. Get User Authorization
export default async function getAuthorization () {
    const cipher  = generateStr(16);
    const state = encrypt(cipher).join('');
    window.localStorage.setItem("state", state);

    const endpoint = new URL("https://www.reddit.com/api/v1/authorize");
    const client_id = import.meta.env['VITE_CLIENT_ID'];

    const params = {
        client_id: client_id,
        response_type: "code",
        state: state,
        redirect_uri: "http://localhost:5173/",
        duration: "temporary",
        scope: "edit identity read submit vote",
    }
    
    const q = new URLSearchParams(params);
    const qStr = q.toString();
    endpoint.search = qStr;

    window.location.href = endpoint.toString();
}

function generateStr (length) {
    const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~-_';
    const values = crypto.getRandomValues(new Uint8Array(length));
    return values.reduce((acc, x) => acc + possible[x % possible.length], "");
}
function isValid (char) {
    if(char > 45 && char < 48) {
        char += 2;
    } else if(char > 57 && char < 65) {
        char += 7;
    } else if(char > 90 && char < 95) {
        char += 4;
    } else if(char > 95 && char < 97) {
        char += 1;
    } else if(char > 122 && char < 126) {
        char += 3;
    } else if(char > 126) {
        const difference = char - 126;
        char = 45;
        char += difference;
    }
    return char;
}
function encrypt (str) {
    let newStr = [];
    const len = str.length;
    const numPlaces = Math.floor(Math.random()*len+1);

    for(let i=0; i < str.length; i++) {
        let char = str.charCodeAt(i);
        char += numPlaces;
        const validation = isValid(char);
        const secondVal = isValid(validation);
        const thirdVal = isValid(secondVal);
        newStr.push(String.fromCharCode(thirdVal));
    }
    return newStr;
}

2. 获取访问令牌

// 2. Get Access token
export default async function getAccessToken (stateSent, stateReceived, code) {
    const client_id = import.meta.env['VITE_CLIENT_ID'];
    const client_secret = import.meta.env['VITE_CLIENT_SECRET'];
    const encode = window.btoa(client_id + ':' + client_secret);

    const payload = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            Authorization: `Basic ${encode}`
        },
        body: new URLSearchParams({
            grant_type: "authorization_code",
            code,
            redirect_uri: "http://localhost:5173/"
        })
    }

    if (stateSent === stateReceived) {
        const body = await fetch("https://www.reddit.com/api/v1/access_token", payload);
        const response = await body.json();
        window.localStorage.setItem("access_token", response.access_token)
        return response.access_token;
    } else {
        return null;
    }
} 

3. 提交评论

// 3. Submit Comment
const base = "https://oauth.reddit.com/api";
const access_token = window.localStorage.getItem("access_token");

export async function comment (thing_id = "t3_1dyxu5j", text = "Test comment") {
    const url = `${base}/comment`;
    const payload = {
        method: 'POST',
        headers: {
            Authorization: `Bearer ${access_token}`,
            "Content-Type": "application/x-www-form-urlencoded"
        },
        body: new URLSearchParams({
            api_type: "json",
            recaptcha_token: "",
            return_rtjson: "true",
            richtext_json: "",
            text: `${text}`,
            thing_id: `${thing_id}`,
        })
    }
    
    try {
        const body = await fetch(url, payload);
        const response = await body.json();

        if (response) {
            return response;
        }
    } catch (e) {
        console.error(e);
    }
}

4. 获取帖子评论

// 4. Get Post comments
export default async function getComments () {
    try {
        const body = await fetch("https://www.reddit.com/r/gaming/comments/1dyxu5j/gaming_in_your_30s.json");
        const response = await body.json();
        if (response) {
            return response[1].data.children;
        }
    } catch (e) {
        console.error(e);
    }
}

补充说明:直接在Reddit网页端发布的评论,同样未出现在接口返回的JSON中,急需相关技术帮助。
注:因不懂Python,未使用Reddit PRAW。

内容的提问来源于stack exchange,提问作者Jossy Solá

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 05:26:17