In my project, I’m working on the feature where the user is able to submit a comment to a post.
Using the Reddit API, I’m successfuly able to submit a comment, I submit it through my Web App and having the post opened in another tab, I see it submitted on Reddit. However, when I request the JSON again, I receive the comments including recent ones except mine as shown below:
I’m not sure what I’m doing wrong.
Here is a Postman Collection of reproducible HTTP requests.
Minimal Reproducible Example:
// 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: Params = {
client_id: client_id,
response_type: "code",
state: state,
redirect_uri: "http://localhost:5173/",
duration: "temporary" as "temporary",
scope: "edit identity read submit vote",
}
const q = new URLSearchParams(params);
// Returns an Object with 'size': num
const qStr = q.toString();
// Returns the key:value pairs as Strings
endpoint.search = qStr;
// Assigns the 'search' Object property of "endpoint" to the string.
// Now console logging endpoint will return the URL Object with: '?' plus the parameters
window.location.href = endpoint.toString();
// Replaces the current URL the user is at with the endpoint URL as a string
}
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); // returns a number
char += numPlaces;
const validation = isValid(char);
const secondVal = isValid(validation);
const thirdVal = isValid(secondVal);
newStr.push(String.fromCharCode(thirdVal));
}
return newStr;
}
// 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. 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. 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);
}
}
Any help is very much appreciated!
PS: I don’t use Reddit PRAW because I don’t know Python, in case this information is relevant.
I made a comment to a post directly on Reddit and my comment is not returned within the JSON either.