// 👀 Reddit community sightings: reads the newest posts in UK Pokémon TCG subreddits through Reddit's official // API (free app account, read-only) and posts restock/sighting reports that name a UK shop as // "Spotted – not confirmed" in #📍┃community-store-sightings (Drew, 2026-10-08: "yes to Reddit which will go in // community sightings"). Only the post title and a link to the Reddit post are shared. One check every 5 minutes. // Keys: staff paste them into the private /reddit connect form (REDDIT_CLIENT_ID, REDDIT_CLIENT_SECRET in .env); // REDDIT_LIVE=true posts for real (otherwise #alert-testing). Since Nov 2025 Reddit approves every new API app // (Responsible Builder Policy), so the keys only work once Reddit has approved the request. import fs from 'node:fs' import path from 'node:path' import {EmbedBuilder,SlashCommandBuilder,ModalBuilder,TextInputBuilder,TextInputStyle,ActionRowBuilder,PermissionFlagsBits} from 'discord.js' import {saveEnvValue} from '../core/env-file.js' import {chKey} from './design.js' // ukOnly: the subreddit isn't UK-specific, so the post must also say it's in the UK export const SUBREDDITS=[{name:'PokemonTCG_UK'},{name:'PokemonRestocks',ukOnly:true}] export const LIVE_CHANNEL='community-store-sightings' // the members' sightings channel (/spotted posts there too) // Shop names people actually type → our channel key (null = no channel of its own, shown by name only) const SHOPS=[ [/pok[eé]mon (center|centre)|\bpc ?uk\b/i,'pokemon-center-uk','Pokémon Center'],[/smyths?/i,'smyths','Smyths'],[/argos/i,'argos','Argos'], [/\bGAME\b|game\.co\.uk|game store/,'game','GAME'],[/tesco/i,null,'Tesco'],[/asda/i,'asda','Asda'],[/sainsbury/i,'sainsburys','Sainsbury’s'], [/chaos ?cards/i,'chaos-cards','Chaos Cards'],[/entertainer/i,'the-entertainer','The Entertainer'],[/w\.?h\.? ?smith/i,'whsmith','WHSmith'], [/b ?& ?m\b|b and m\b/i,null,'B&M'],[/home bargains/i,null,'Home Bargains'],[/tk ?maxx/i,null,'TK Maxx'],[/costco/i,'costco','Costco'], [/amazon/i,'amazon-uk','Amazon'],[/john lewis/i,'john-lewis','John Lewis'],[/\bvery\.co|\bvery\b(?= has| have| restock)/i,'very','Very'], [/currys/i,'currys','Currys'],[/\bhmv\b/i,'hmv','HMV'],[/aldi/i,null,'Aldi'],[/lidl/i,null,'Lidl'],[/the range\b/i,null,'The Range'], [/magic madhouse/i,'magic-madhouse','Magic Madhouse'],[/total ?cards/i,'total-cards','Total Cards'],[/zatu/i,'zatu','Zatu'], [/waterstones/i,'waterstones','Waterstones'],[/hobbycraft/i,'hobbycraft','Hobbycraft'],[/menkind/i,'menkind','Menkind'],[/tg ?jones/i,'tg-jones','TG Jones'], ] const SIGHTING=/restock|re-stock|in stock|back in|spotted|found|in-?store|on the shelf|shelves|just (got|picked|grabbed)|dropped|drop\b|pre-?orders? (are )?(open|live|up)|queue|now live|is live|available/i const QUESTION=/\?\s*$|^(any ?one|has any|does any|do you|when|where|is there|will|should|how|what|which|why)\b/i const UK=/\buk\b|united kingdom|england|scotland|wales|northern ireland|london|manchester|birmingham|£/i export function shopsMentioned(text){return SHOPS.filter(([re])=>re.test(text)).map(([,key,name])=>({key,name}))} // Is this post a real sighting report? (pure, tested) export function isSighting(post,{ukOnly=false,now=Date.now()/1000}={}){ const title=String(post.title||''),text=`${title}\n${post.selftext||''}` if(now-(post.created_utc||0)>3*3600)return false // older than 3 hours is no use if(QUESTION.test(title.trim()))return false if(ukOnly&&!UK.test(text))return false return SIGHTING.test(text)&&shopsMentioned(text).length>0 } export function sightingEmbed(post,sub,{test=false}={}){ const shops=shopsMentioned(`${post.title}\n${post.selftext||''}`).map(s=>s.name) const mins=Math.max(1,Math.round((Date.now()/1000-post.created_utc)/60)) const lines=[`🏪 **Shop:** ${[...new Set(shops)].join(', ')}`,`🕒 Posted ${mins} min ago on r/${sub}`,'⚠️ Reported by a Reddit user, not checked by us. Stock may be local or already gone.'] if(test)lines.push(`\n🧪 **Test mode.** Would go to: #${LIVE_CHANNEL}`) const e=new EmbedBuilder().setColor(0xf59e0b).setAuthor({name:'👀 Spotted – not confirmed • Reddit'}).setTitle(String(post.title).slice(0,240)) .setURL(`https://www.reddit.com${post.permalink}`).setDescription(lines.join('\n')).setTimestamp(new Date(post.created_utc*1000)) // no picture from the post: only its title and a link back to Reddit are shared (as told to Reddit in the API request) return e } // Was a shared post deleted or removed on Reddit? Then our Discord notice goes too (re-application, 2026-10-09: // Responsible Builder Policy). Pure, tested. export const isGone=p=>!p||Boolean(p.removed_by_category)||p.author==='[deleted]'||['[removed]','[deleted]'].includes(p.selftext)||p.removed===true export const SHARED_DAYS=7 // how long we remember which Discord message shows which Reddit post // ---------- runner ---------- const STATE_FILE=path.join(process.env.DATA_DIR||'./data','reddit-state.json') const load=()=>{try{return JSON.parse(fs.readFileSync(STATE_FILE,'utf8'))}catch{return {}}} const save=s=>fs.writeFileSync(STATE_FILE,JSON.stringify(s,null,1)) // Reddit's API rules: :: (by /u/) (re-application, 2026-10-09) export const UA=`discord:galar-alerts-sightings:v1.1 (by /u/${process.env.REDDIT_USERNAME||'Galar-Alerts'})` let token={value:null,until:0} // a read-only, app-only sign-in with the app's ID and secret (no Reddit username or password involved) async function tokenFor(id,secret,fetcher=fetch){ const r=await fetcher('https://www.reddit.com/api/v1/access_token',{method:'POST',signal:AbortSignal.timeout(15000), headers:{'User-Agent':UA,'Content-Type':'application/x-www-form-urlencoded',Authorization:'Basic '+Buffer.from(`${id}:${secret}`).toString('base64')}, body:'grant_type=client_credentials'}) if(!r.ok)throw Error(`Reddit sign-in failed (HTTP ${r.status})`) const j=await r.json();if(!j.access_token)throw Error('Reddit sign-in failed (no token)');return j } async function getToken(){ if(token.value&&Date.now()c.data) } const findText=(g,k)=>g.channels.cache.find(c=>chKey(c.name)===k&&c.isTextBased()) async function checkReddit(g,{live}){ const s=load() for(const sub of SUBREDDITS){ const posts=await newPosts(sub.name) const seen=new Set(s[sub.name]||[]),first=!s[sub.name] for(const p of posts.reverse()){ // oldest first if(seen.has(p.id))continue;seen.add(p.id) if(first||p.stickied||p.over_18||!isSighting(p,sub))continue const ch=findText(g,live?LIVE_CHANNEL:'alert-testing')||(live?findText(g,'store-sightings'):null);if(!ch)continue const msg=await ch.send({embeds:[sightingEmbed(p,sub.name,{test:!live})],allowedMentions:{parse:[]}}) ;(s.shared||={})[p.id]={channel:ch.id,message:msg.id,at:Date.now()} status.posted++;console.log(`[reddit] ${live?'posted':'test-posted'} r/${sub.name} ${p.id}`) } s[sub.name]=[...seen].slice(-300);save(s) } } // Every 30 minutes: forget shares older than SHARED_DAYS, and delete our notice for any post that's gone from Reddit async function checkDeleted(g){ const s=load(),shared=s.shared||{},now=Date.now() for(const [id,x] of Object.entries(shared))if(now-x.at>SHARED_DAYS*864e5)delete shared[id] const ids=Object.keys(shared).slice(0,100) if(ids.length){ const r=await fetch(`https://oauth.reddit.com/api/info?id=${ids.map(i=>`t3_${i}`).join(',')}&raw_json=1`,{signal:AbortSignal.timeout(15000),headers:{'User-Agent':UA,Authorization:`Bearer ${await getToken()}`}}) if(!r.ok)throw Error(`Reddit info HTTP ${r.status}`) const found=new Map(((await r.json()).data?.children||[]).map(c=>[c.data.id,c.data])) for(const id of ids){ if(!isGone(found.get(id)))continue const x=shared[id],ch=g.channels.cache.get(x.channel) await ch?.messages.delete(x.message).catch(()=>{}) delete shared[id];console.log(`[reddit] post ${id} was deleted or removed on Reddit: our notice is deleted too`) } } s.shared=shared;save(s) } const status={watching:false,live:false,lastCheck:0,lastError:null,posted:0} let stopWatcher=null export function startRedditWatcher(client,guildId=process.env.DISCORD_GUILD_ID){ if(stopWatcher){stopWatcher();stopWatcher=null} if(!process.env.REDDIT_CLIENT_ID||!process.env.REDDIT_CLIENT_SECRET){status.watching=false;console.log('[reddit] off (not connected yet: /reddit connect)');return} const live=String(process.env.REDDIT_LIVE||'false').toLowerCase()==='true' token={value:null,until:0};Object.assign(status,{watching:true,live,lastError:null}) let busy=false,lastErrorPost=0,ticks=0 const tick=async()=>{ if(busy||!client.isReady())return;busy=true const g=client.guilds.cache.get(guildId)||client.guilds.cache.first() try{if(g){await checkReddit(g,{live});if(++ticks%6===0)await checkDeleted(g);status.lastCheck=Date.now();status.lastError=null}} // every 30 min: deleted posts catch(e){ console.error('[reddit]',e.message);status.lastError=e.message if(g&&Date.now()-lastErrorPost>6*3600e3){lastErrorPost=Date.now();await findText(g,'monitor-health')?.send(`⚠️ Reddit sightings: ${String(e.message).slice(0,150)}`).catch(()=>{})} }finally{busy=false} } const iv=setInterval(tick,5*60000);iv.unref?.();const first=setTimeout(tick,20000);first.unref?.() stopWatcher=()=>{clearInterval(iv);clearTimeout(first);status.watching=false} console.log(`[reddit] watching ${SUBREDDITS.map(x=>'r/'+x.name).join(', ')} ${live?`LIVE (#${LIVE_CHANNEL})`:'in TEST mode (#alert-testing)'}`) } // ---------- /reddit connect | status (staff; the keys only ever go through the private form) ---------- export const redditCommands=[ new SlashCommandBuilder().setName('reddit').setDescription('Staff: Reddit sightings').setDMPermission(false) .setDefaultMemberPermissions(PermissionFlagsBits.ManageGuild) .addSubcommand(c=>c.setName('connect').setDescription('Paste the Reddit app keys (opens a private form)')) .addSubcommand(c=>c.setName('status').setDescription('Are Reddit sightings connected and working?')), ] // What Reddit shows: the app ID under the app's name, the secret next to "secret" (pure, tested) export const looksLikeRedditId=s=>/^[A-Za-z0-9_-]{10,40}$/.test(String(s||'').trim()) export const looksLikeRedditSecret=s=>/^[A-Za-z0-9_-]{20,60}$/.test(String(s||'').trim()) const isStaff=i=>i.memberPermissions?.has(PermissionFlagsBits.ManageGuild) export async function handleRedditCommand(i,{fetcher=fetch,save=saveEnvValue}={}){ if(i.isChatInputCommand?.()&&i.commandName==='reddit'){ if(!isStaff(i)){await i.reply({content:'Staff only.',flags:64});return true} if(i.options.getSubcommand()==='status'){ const lines=[status.watching?`✅ Connected (${status.live?`**LIVE**, sightings post in #${LIVE_CHANNEL}`:'**test mode**, posts go to #alert-testing'})`:'❌ Not connected. Use `/reddit connect` once Reddit has approved the app.'] if(status.lastCheck)lines.push(`Last check: (every 5 minutes)`) if(status.lastError)lines.push(`⚠️ Last problem: ${status.lastError}`) lines.push(`Sightings posted since the bot started: ${status.posted}`) await i.reply({content:lines.join('\n'),flags:64});return true } await i.showModal(new ModalBuilder().setCustomId('cp:reddit:connect').setTitle('Connect Reddit sightings').addComponents( new ActionRowBuilder().addComponents(new TextInputBuilder().setCustomId('id').setLabel('App ID (under the app name on reddit.com)').setStyle(TextInputStyle.Short).setRequired(true).setMinLength(10).setMaxLength(40)), new ActionRowBuilder().addComponents(new TextInputBuilder().setCustomId('secret').setLabel('Secret').setStyle(TextInputStyle.Short).setRequired(true).setMinLength(20).setMaxLength(60)))) return true } if(i.isModalSubmit?.()&&i.customId==='cp:reddit:connect'){ if(!isStaff(i)){await i.reply({content:'Staff only.',flags:64});return true} const id=i.fields.getTextInputValue('id').trim(),secret=i.fields.getTextInputValue('secret').trim() if(!looksLikeRedditId(id)||!looksLikeRedditSecret(secret)){await i.reply({content:'❌ Those don’t look like Reddit app keys. The **ID** is the short code under the app’s name at reddit.com/prefs/apps, the **secret** is next to "secret". Try `/reddit connect` again.',flags:64});return true} await i.deferReply({flags:64}) // try the keys before saving anything: sign in and read one subreddit try{ const t=await tokenFor(id,secret,fetcher) const r=await fetcher(`https://oauth.reddit.com/r/${SUBREDDITS[0].name}/new?limit=1&raw_json=1`,{signal:AbortSignal.timeout(15000),headers:{'User-Agent':UA,Authorization:`Bearer ${t.access_token}`}}) if(!r.ok)throw Error(`reading r/${SUBREDDITS[0].name} failed (HTTP ${r.status})`) }catch(e){ await i.editReply(`❌ Not connected: ${e.message}. If Reddit hasn't approved the app yet (every new app needs its OK since November 2025), wait for their email and try again. Otherwise check you copied the ID and secret of the right app.`);return true } save('REDDIT_CLIENT_ID',id);save('REDDIT_CLIENT_SECRET',secret);process.env.REDDIT_CLIENT_ID=id;process.env.REDDIT_CLIENT_SECRET=secret console.log('[reddit] connected via /reddit connect') startRedditWatcher(i.client) await i.editReply(`✅ **Connected!** Reading r/${SUBREDDITS.map(x=>x.name).join(' and r/')} every 5 minutes. Sightings that name a UK shop post in #${LIVE_CHANNEL} as "👀 Spotted – not confirmed • Reddit" (title and link only)${status.live?'':' once Reddit sightings are switched live (REDDIT_LIVE)'}. \`/reddit status\` any time.`) return true } return false }