TwitchLights/src/lib/twitch.ts
2025-06-30 18:50:02 +01:00

99 lines
3.0 KiB
TypeScript

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 () => {
const twitchAuthResponse = await fetch(
`https://id.twitch.tv/oauth2/token?client_id=${TWITCH_APP_CLIENT_ID}&client_secret=${TWITCH_APP_SECRET}&grant_type=client_credentials`,
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
},
);
const { access_token } = authBodyValidator.parse(
await twitchAuthResponse.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,
};
};