import { building } from "$app/environment"; import { HASH_SECRET, TWITCH_APP_CLIENT_ID, TWITCH_APP_SECRET } from "$env/static/private"; import { z } from "zod"; const authBodyValidator = z.object({ access_token: z.string(), expires_in: z.number(), token_type: z.enum(["bearer"]), }); type TwitchSubscribeBody = { type: "channel.follow"; version: 2; condition: { broadcaster_user_id: "1093261112", moderator_user_id: "1093261112", }, transport: { method: "webhook"; callback: string; secret: string; }; }; // Not the complete event, but the information we need. export const twitchFollowEvent = z.object({ subscription: z.object({ type: z.enum(['channel.follow']), }), event: z.object({ user_name: z.string(), }), }); /* *curl -X POST 'https://api.twitch.tv/helix/eventsub/subscriptions' \ -H 'Authorization: Bearer 2gbdx6oar67tqtcmt49t3wpcgycthx' \ -H 'Client-Id: wbmytr93xzw8zbg0p1izqyzzc5mbiz' \ -H 'Content-Type: application/json' \ -d '{"type":"channel.follow","version":"2","condition":{"broadcaster_user_id":"1234", "moderator_user_id": "1234"},"transport":{"method":"webhook","callback":"https://example.com/callback","secret":"s3cre77890ab"}}' */ // Webhook -> Redeem of channel reward export const createTwitchClient = () => { const getAccessToken = async () => { if (building) { return ''; } const authUrl = `https://id.twitch.tv/oauth2/authorize` + `?response_type=code` + `&client_id=${TWITCH_APP_CLIENT_ID}` + `&redirect_uri=${encodeURIComponent("https://twitch.johncosta.tech/redirect")}` + `&scope=moderator:read:followers` + `&state=mkldsamkldsamkldsamkldsa` const twitchAuthResponse = await fetch( authUrl, { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded", }, }, ); const json = await twitchAuthResponse.json(); console.log(json); const { access_token } = authBodyValidator.parse( json, ); return access_token; }; const _access_token = getAccessToken(); const subscribeToFollow = async () => { const twitchSubResponse = await fetch( "https://api.twitch.tv/helix/eventsub/subscriptions", { method: "POST", headers: { Authorization: `Bearer ${await _access_token}`, "Client-Id": TWITCH_APP_CLIENT_ID, "Content-Type": "application/json", }, body: JSON.stringify({ type: "channel.follow", version: 2, condition: { moderator_user_id: '1093261112', broadcaster_user_id: '1093261112' }, transport: { callback: "https://twitch.johncosta.tech/api/webhook", method: "webhook", secret: HASH_SECRET, }, } satisfies TwitchSubscribeBody), }, ); const res = await twitchSubResponse.json(); console.log(res); }; return { subscribeToFollow, }; };