javascript:(function(){ const MAX_IMAGES_PER_POST = 10; function replaceDomain(e){return e.replace(/^(https?:\/\/)([^\/]+)/,"$1bsky.app")} function cleanText(e){ return e ? e.replace(/]*>([^<]+)<\/a>/g, (match, url, text) => (url.startsWith('/') ? `[U][URL=https://bsky.app${url}]${text}[/URL][/U]` : `[U][URL=${url}]${text}[/URL][/U]`)).replace(//g, "\n").replace(/<[^>]+>/g, "").trim() : "" } function extractMedia(element, excludeSelectors = []) { let images = Array.from(element.querySelectorAll('img[src*="cdn.bsky.app"]')); if (excludeSelectors.length > 0) { excludeSelectors.forEach(selector => { element.querySelectorAll(selector).forEach(excludedContainer => { images = images.filter(img => !excludedContainer.contains(img)); }); }); } images = images.map(e => e.src).filter(e => !e.includes("/avatar_thumbnail/")); let videoSourcesQuery = "video source[src], video[src]"; if (excludeSelectors.length > 0) { excludeSelectors.forEach(selector => { }); } const videoSources = new Set([...Array.from(element.querySelectorAll(videoSourcesQuery)).map(e => e.src)]); return {images, videos: Array.from(videoSources)} } function showToast(e){ const t = document.createElement("div"); t.style.cssText = "position:fixed;bottom:20px;left:20px;padding:10px 20px;background:#333;color:#fff;border-radius:4px;z-index:10000;font-family:Arial,sans-serif;font-size:14px;opacity=1;transition:opacity 1s;box-shadow:0 2px 5px rgba(0,0,0,0.3)"; t.innerText = e; document.body.appendChild(t); setTimeout(() => {t.style.opacity = "0"; setTimeout(() => document.body.removeChild(t), 1e3)}, 2e3) } function createPostCountPrompt(e){ const t = document.createElement("div"); t.style.cssText = "position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.7);z-index:9999;display:flex;justify-content:center;align-items:center"; const r = document.createElement("div"); r.style.cssText = "background:white;padding:20px;border-radius:8px;box-shadow:0 0 10px rgba(0,0,0,0.3);text-align:center"; const n = document.createElement("input"); n.type = "text"; n.value = "12"; n.style.cssText = "font-size:30px;width:100px;text-align:center;margin-bottom:20px"; const o = document.createElement("div"); o.style.cssText = "display:grid;grid-template-columns:repeat(3,1fr);gap:10px"; "1234567890".split("").forEach(e => {const t = document.createElement("button"); t.textContent = e; t.style.cssText = "font-size:20px;padding:10px;cursor:pointer"; t.onclick = () => n.value += e; o.appendChild(t)}); const p = document.createElement("div");p.style.cssText="display:flex;gap:10px;margin-bottom:20px";[1,2,10,25,35,50].forEach(num=>{const b=document.createElement("button");b.textContent=num;b.style.cssText="font-size:16px;padding:8px;cursor:pointer";b.onclick=()=>n.value=num;p.appendChild(b)}); const s = document.createElement("button"); s.textContent = "Clear"; s.style.cssText = "font-size:18px;margin-top:10px;padding:10px 20px;cursor:pointer"; s.onclick = () => n.value = ""; const a = document.createElement("button"); a.textContent = "Set Number of Posts"; a.style.cssText = "font-size:18px;margin-top:20px;padding:10px 20px;cursor:pointer"; a.onclick = () => {const o = parseInt(n.value, 10); isNaN(o) || o <= 0 ? showToast("Please enter a valid number.") : (document.body.removeChild(t), e(o))}; r.append(n,p,o, s, a); t.appendChild(r); document.body.appendChild(t) } async function getEmbedUrl(threadData){ let url = null; const post = threadData?.thread?.post; if (post?.embed?.$type === "app.bsky.embed.video#view" && post.embed.playlist) {url = post.embed.playlist;} else if (post?.record?.embed?.$type === "app.bsky.embed.video" && post.author?.did && post.record.embed.video?.ref?.$link) { url = constructVideoUrl(post.author.did, post.record.embed.video); } return url } function constructVideoUrl(did, videoEmbed){ if (videoEmbed.mimeType === "video/webm") return `https://bsky.social/xrpc/com.atproto.sync.getBlob?did=${encodeURIComponent(did)}&cid=${encodeURIComponent(videoEmbed.ref.$link)}`; return `https://video.bsky.app/watch/${encodeURIComponent(did)}/${encodeURIComponent(videoEmbed.ref.$link)}/playlist.m3u8` } function cleanHandle(handle) { if (!handle) return "Unknown"; let cleaned = handle.replace(/[\u202a-\u202f\u00AD\u200B-\u200D\uFEFF\s]/g, ""); cleaned = cleaned.trim(); cleaned = cleaned.replace(/^@+/, ""); return cleaned.trim(); } async function extractPost(postElement, isActivePost = false){ if (!(postElement instanceof Element)) return console.error("Invalid post element:", postElement), {text: "", author: "", url: "", threadData: null, quotedUrl: null}; let thisPostsAuthorHandleFromTestId = postElement.getAttribute("data-testid")?.match(/postThreadItem-by-(.+)/)?.[1]; let thisPostsUrl = null; let thisPostsId = null; const quoteEmbedSelector = '[role="link"][aria-label*="Post by"]'; if (thisPostsAuthorHandleFromTestId) { thisPostsAuthorHandleFromTestId = cleanHandle(thisPostsAuthorHandleFromTestId); const timestampLinks = Array.from(postElement.querySelectorAll('[data-testid="postTimestamp"] a[href*="/post/"], a[href*="/post/"]')); let foundLinkForThisPost = null; for (const link of timestampLinks) { if (!link.closest(quoteEmbedSelector)) { foundLinkForThisPost = link; break; } } if (!foundLinkForThisPost && timestampLinks.length > 0 && !postElement.querySelector(quoteEmbedSelector)) { foundLinkForThisPost = timestampLinks[0]; } if (foundLinkForThisPost) { thisPostsId = foundLinkForThisPost.href.split('/').pop().split('?')[0]; thisPostsUrl = `https://bsky.app/profile/${thisPostsAuthorHandleFromTestId}/post/${thisPostsId}`; console.log(`extractPost: DOM URL for self (postElement): ${thisPostsUrl}`); } else { console.warn(`extractPost: Could not find reliable DOM URL for self (postElement). TestID handle: ${thisPostsAuthorHandleFromTestId}`); } } let threadDataForThisPost = null; if (thisPostsAuthorHandleFromTestId && (thisPostsId || isActivePost)) { const postIdForApi = thisPostsId || (isActivePost ? window.location.href.split('/').pop().split('?')[0] : null); if (postIdForApi) { const apiUri = `at://${thisPostsAuthorHandleFromTestId}/app.bsky.feed.post/${postIdForApi}`; const apiUrl = `https://public.api.bsky.app/xrpc/app.bsky.feed.getPostThread?uri=${encodeURIComponent(apiUri)}&depth=0`; try { const res = await fetch(apiUrl); threadDataForThisPost = res.ok ? await res.json() : null; if (threadDataForThisPost?.thread?.post?.uri) { const apiUriParts = threadDataForThisPost.thread.post.uri.split('/'); thisPostsId = apiUriParts.pop(); const apiAuthorHandle = cleanHandle(threadDataForThisPost.thread.post.author.handle); thisPostsAuthorHandleFromTestId = apiAuthorHandle; thisPostsUrl = `https://bsky.app/profile/${apiAuthorHandle}/post/${thisPostsId}`; console.log(`extractPost: API OVERRIDE/CONFIRMED URL for self: ${thisPostsUrl}`); } else if (threadDataForThisPost) { console.log("extractPost: API data fetched but no post.uri for self:", thisPostsUrl, threadDataForThisPost); } else { console.warn("extractPost: No API data or error for self:", thisPostsUrl || `at://${thisPostsAuthorHandleFromTestId}/app.bsky.feed.post/${postIdForApi}`); } } catch (err) { console.warn("extractPost: API fetch failed for self:", thisPostsUrl, err); } } } if (!thisPostsUrl && isActivePost && thisPostsAuthorHandleFromTestId) { thisPostsUrl = `https://bsky.app/profile/${thisPostsAuthorHandleFromTestId}/post/${window.location.href.split('/').pop().split('?')[0]}`; console.log("extractPost: Fallback URL for active post (no API/DOM ID):", thisPostsUrl); } const textContentElem = postElement.querySelector('div[data-word-wrap="1"]:not([data-testid="quoteEmbed"]) div[data-word-wrap="1"], [data-testid="postText"]:not([data-testid="quoteEmbed"]) [data-testid="postText"]'); const mainTextContentElement = postElement.querySelector(':scope > div > [data-testid="postText"], :scope > div > div > [data-testid="postText"], :scope > div > div > div[data-word-wrap="1"]'); let postOutputText = ""; if (mainTextContentElement) { const clonedTextContainer = mainTextContentElement.cloneNode(true); clonedTextContainer.querySelector(quoteEmbedSelector)?.remove(); postOutputText = cleanText(clonedTextContainer.innerHTML || clonedTextContainer.textContent); } else { const tempDiv = document.createElement('div'); tempDiv.innerHTML = postElement.innerHTML; tempDiv.querySelector(quoteEmbedSelector)?.remove(); const mainTextOnlyElem = tempDiv.querySelector('div[data-word-wrap="1"], [data-testid="postText"]'); postOutputText = mainTextOnlyElem ? cleanText(mainTextOnlyElem.innerHTML || mainTextOnlyElem.textContent) : ""; } const mediaForThisPost = extractMedia(postElement, [quoteEmbedSelector]); mediaForThisPost.images.slice(0, MAX_IMAGES_PER_POST).forEach(imgUrl => postOutputText += `\n[img]${imgUrl}[/img]`); if (threadDataForThisPost) { const videoUrl = await getEmbedUrl(threadDataForThisPost); if (videoUrl) postOutputText += `\n[U][URL]${videoUrl}[/URL][/U]`; } let urlOfQuotedPostByThis = null; const quoteEmbedElement = postElement.querySelector(quoteEmbedSelector); const apiQuoteRecordInfo = threadDataForThisPost?.thread?.post?.record?.embed?.record; if (apiQuoteRecordInfo?.uri && (apiQuoteRecordInfo?.$type === "app.bsky.feed.defs#postView" || apiQuoteRecordInfo?.$type === "app.bsky.embed.record#viewRecord" || apiQuoteRecordInfo?.$type === "app.bsky.embed.recordWithMedia#viewRecord")) { let actualQuotedRecord = apiQuoteRecordInfo.value ? apiQuoteRecordInfo : apiQuoteRecordInfo.record || apiQuoteRecordInfo; if (actualQuotedRecord?.uri) { const qAuthorHandleRaw = actualQuotedRecord.author?.handle || actualQuotedRecord.uri.split('/')[2]; const qAuthorHandleClean = cleanHandle(qAuthorHandleRaw); const qPostId = actualQuotedRecord.uri.split('/')[4]; const qTextRaw = actualQuotedRecord.value?.text || ""; const qTextClean = cleanText(qTextRaw); urlOfQuotedPostByThis = `https://bsky.app/profile/${qAuthorHandleClean}/post/${qPostId}`; postOutputText += `\n\n[QUOTED POST]\nšŸ†” ${qAuthorHandleClean}\n${qTextClean}`; console.log(`extractPost: API Quoted Post BY post ${thisPostsId}: URL='${urlOfQuotedPostByThis}'`); const quotedEmbeds = actualQuotedRecord.embeds || actualQuotedRecord.value?.embeds; if (quotedEmbeds?.length > 0) { quotedEmbeds.forEach(emb => { if (emb.$type === "app.bsky.embed.images#view" && emb.images) { emb.images.slice(0, MAX_IMAGES_PER_POST).forEach(img => postOutputText += `\n[img]${img.thumb}[/img]`); } else if (emb.$type === "app.bsky.embed.video#view" && emb.playlist) { postOutputText += `\n[U][URL]${emb.playlist}[/URL][/U]`; } else if (emb.$type === "app.bsky.embed.images" && emb.images && actualQuotedRecord.author?.did) { emb.images.slice(0, MAX_IMAGES_PER_POST).forEach(img => postOutputText += `\n[img]${img.image.ref?.$link ? `https://cdn.bsky.app/img/feed_fullsize/plain/${actualQuotedRecord.author.did}/${img.image.ref.$link}@${img.image.mimeType.split('/')[1]}` : 'fallback.jpg'}[/img]`); } }); } } } else if (quoteEmbedElement) { const qTextContentElem = quoteEmbedElement.querySelector('div[data-word-wrap="1"]'); const qTextRaw = qTextContentElem?.innerHTML || ""; if (qTextRaw) { const qTextClean = cleanText(qTextRaw); let qAuthorHandleRaw = quoteEmbedElement.querySelector(".css-146c3p1.r-dnmrzs.r-1udh08x.r-1udbk01.r-3s2u2q.r-1iln25a")?.textContent?.trim() || "Unknown"; const qAuthorHandleClean = cleanHandle(qAuthorHandleRaw); let qPostId = null; const qPostLink = quoteEmbedElement.querySelector('a[href*="/post/"]'); if (qPostLink) { qPostId = qPostLink.href.split('/').pop().split('?')[0]; } postOutputText += `\n\n[QUOTED POST]\nšŸ†” ${qAuthorHandleClean}\n${qTextClean}`; if (qAuthorHandleClean !== "Unknown" && qPostId) { urlOfQuotedPostByThis = `https://bsky.app/profile/${qAuthorHandleClean}/post/${qPostId}`; console.log(`extractPost: DOM Quoted Post BY post ${thisPostsId}: URL='${urlOfQuotedPostByThis}' (ID='${qPostId}')`); } const mediaForTheQuotedPost = extractMedia(quoteEmbedElement); mediaForTheQuotedPost.images.slice(0, MAX_IMAGES_PER_POST).forEach(imgUrl => postOutputText += `\n[img]${imgUrl}[/img]`); let quotedVideoUrlDOM = null; if (quoteEmbedElement.querySelector('video[poster]')) { /* ... video logic ... */ } if (quotedVideoUrlDOM) postOutputText += `\n[U][URL]${quotedVideoUrlDOM}[/URL][/U]`; } } const normalizeUrl = (url) => (url.startsWith('/') ? `https://bsky.app${url}` : url).replace(/\/+$/, "").toLowerCase(); const externalLinks = new Set( Array.from(postElement.querySelectorAll("a[href]")) .filter(link => !link.closest(quoteEmbedSelector)) .map(link => normalizeUrl(link.href)) .filter(href => href.startsWith("http") && !href.includes("/post/") && !href.includes("/profile/") && !postOutputText.includes(href)) ); externalLinks.forEach(linkUrl => postOutputText += `\n[U][URL]${linkUrl}[/URL][/U]`); const finalAuthorString = thisPostsAuthorHandleFromTestId && thisPostsAuthorHandleFromTestId !== "Unknown" ? `šŸ†” ${thisPostsAuthorHandleFromTestId}` : `šŸ†” ${cleanHandle(postElement.querySelector(".css-146c3p1.r-dnmrzs.r-1udh08x.r-1udbk01.r-3s2u2q.r-1iln25a")?.textContent?.trim() || "Unknown")}`; return { text: postOutputText, author: finalAuthorString, url: thisPostsUrl, threadData: threadDataForThisPost, quotedUrl: urlOfQuotedPostByThis }; } async function extractPosts(e_count){ const allPosts = Array.from(document.querySelectorAll('[data-testid^="postThreadItem-by-"], [data-testid="postThreadItem"]')); if (!allPosts.length) return void showToast("No posts found on this page."); const quoteEmbedSelector = '[role="link"][aria-label*="Post by"]'; let activePostElement = allPosts.find(p => { const link = p.querySelector('a[href*="/post/' + window.location.href.split('/').pop().split('?')[0] + '"]'); return link && !link.closest(quoteEmbedSelector); }) || allPosts.find(p => !p.closest(quoteEmbedSelector)); if (!activePostElement && allPosts.length > 0) activePostElement = allPosts[0]; const activeIndex = allPosts.indexOf(activePostElement); const activeData = await extractPost(activePostElement, true); const activeUrl = activeData.url; const activeText = activeData.text; const activeAuthor = activeData.author; const activeThreadData = activeData.threadData; const activeQuotedUrl = activeData.quotedUrl; console.log("extractPosts: Active Post URL for main output:", activeUrl); if (!activeUrl) { showToast("Critical error: Could not determine URL for the active post. Aborting."); return; } let mainAuthorCleanedHandle = ""; const activeAuthorMatch = activeAuthor.match(/šŸ†” (.*)/); if (activeAuthorMatch && activeAuthorMatch[1] !== "Unknown") { mainAuthorCleanedHandle = activeAuthorMatch[1]; } else { mainAuthorCleanedHandle = cleanHandle(document.querySelector('[data-testid="profileHandle"]')?.textContent?.trim() || ""); } if (!mainAuthorCleanedHandle || mainAuthorCleanedHandle === "Unknown") return void showToast("Could not determine main username."); console.log("extractPosts: Main Author Cleaned Handle:", mainAuthorCleanedHandle); let postsToFormat = []; let parentUrl = null, parentText = null, parentAuthor = null; let topLevelQuotedPostUrlForSpoiler = activeQuotedUrl; const apiParentInfo = activeThreadData?.thread?.post?.reply?.parent; if (apiParentInfo?.uri) { } else if (activeIndex > 0) { /* DOM parent */ } postsToFormat.push({author: activeAuthor, text: activeText}); const repliesElements = allPosts.slice(activeIndex + 1, activeIndex + e_count - postsToFormat.length + 1); for (const replyElement of repliesElements) { if (postsToFormat.length >= e_count) break; const replyData = await extractPost(replyElement, false); if (replyData.text || (replyData.text && replyData.text.includes("[img]"))) { postsToFormat.push({author: replyData.author, text: replyData.text}); if (replyData.url && replyData.author && replyData.author.includes(mainAuthorCleanedHandle)) { } } } let mainPostUrls = new Set([activeUrl]); if (parentUrl && parentAuthor && parentAuthor.includes(mainAuthorCleanedHandle)) mainPostUrls.add(parentUrl); let outputChunks = []; let currentChunkPostsData = postsToFormat; let totalPostsFormatted = postsToFormat.length; const hasThreadsInfo = (parentUrl && parentAuthor && parentAuthor.includes(mainAuthorCleanedHandle) && parentUrl !== activeUrl) || ([...mainPostUrls].filter(u => u !== activeUrl && u !== parentUrl).length > 0) || (topLevelQuotedPostUrlForSpoiler && topLevelQuotedPostUrlForSpoiler !== activeUrl && !mainPostUrls.has(topLevelQuotedPostUrlForSpoiler) && (parentUrl ? topLevelQuotedPostUrlForSpoiler !== parentUrl : true) ); let chunkString = `${activeUrl}`; if (hasThreadsInfo) { chunkString += `\n[SPOILER="Threads Continued"]`; if (parentUrl && parentAuthor && parentAuthor.includes(mainAuthorCleanedHandle) && parentUrl !== activeUrl) { chunkString += `\n${parentUrl}`; } [...mainPostUrls].filter(u => u !== activeUrl && u !== parentUrl).forEach(u => chunkString += `\n${u}`); if (topLevelQuotedPostUrlForSpoiler && topLevelQuotedPostUrlForSpoiler !== activeUrl && !mainPostUrls.has(topLevelQuotedPostUrlForSpoiler) && (parentUrl ? topLevelQuotedPostUrlForSpoiler !== parentUrl : true)) { chunkString += `\n${topLevelQuotedPostUrlForSpoiler}`; } chunkString += `\n[/SPOILER]`; } chunkString += `\n[SPOILER="full text & large images"]\n\n${currentChunkPostsData.map((p, idx) => `${idx + 1}/${currentChunkPostsData.length}\n${p.author}\n${p.text}`).join("\n\n")}`; chunkString += `\n\n[COLOR=rgb(184,49,47)][B][SIZE=5]To post tweets in this format, more info here: [URL]https://www.thecoli.com/threads/tips-and-tricks-for-posting-the-coli-megathread.984734/post-52211196[/URL][/SIZE][/B][/COLOR]\n[/SPOILER]`; outputChunks.push(chunkString); const finalOutput = outputChunks.join("\n\n[threads continued]\n\n"); const d = document.createElement("textarea"); d.value = finalOutput; document.body.appendChild(d); d.select(); document.execCommand("copy"); document.body.removeChild(d); showToast(`Copied: ${totalPostsFormatted} posts`) } createPostCountPrompt(extractPosts) })();