Skip to content

Commit

Permalink
feat(bot): khl proxy service binding
Browse files Browse the repository at this point in the history
  • Loading branch information
shayypy committed Dec 9, 2024
1 parent e6ce62d commit 22909b3
Show file tree
Hide file tree
Showing 12 changed files with 47 additions and 19 deletions.
6 changes: 3 additions & 3 deletions packages/bot/src/commands/calendar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,7 @@ const sendScheduleMessage = async (

export const scheduleDayCallback: ChatInputAppCommandCallback = async (ctx) => {
const league = ctx.getStringOption("league").value as League;
const client = getHtClient(league);
const client = getHtClient(ctx.env, league);
const teamId = ctx.getStringOption("team")?.value;

const dateVal = ctx.getStringOption("date")?.value;
Expand Down Expand Up @@ -228,7 +228,7 @@ export const scheduleMonthCallback: ChatInputAppCommandCallback = async (
) => {
const league = ctx.getStringOption("league").value as League;

const client = getHtClient(league);
const client = getHtClient(ctx.env, league);
const teamId = ctx.getStringOption("team")?.value || undefined;
const monthVal = ctx.getStringOption("month")?.value || undefined;
const seasonId = ctx.getStringOption("season")?.value || undefined;
Expand Down Expand Up @@ -288,7 +288,7 @@ export const htGamedayCallback: ChatInputAppCommandCallback = async (ctx) => {
const today = getNow();
today.setUTCHours(6, 0, 0, 0);
const league = ctx.getStringOption("league").value as HockeyTechLeague;
const client = getHtClient(league);
const client = getHtClient(ctx.env, league);
const teamId = ctx.getStringOption("team")?.value;
const team = teamId
? leagueTeams[league].find((t) => t.id === teamId)
Expand Down
6 changes: 3 additions & 3 deletions packages/bot/src/commands/pickemsLeaderboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ export const seasonAutocompleteWithAll: AppCommandAutocompleteCallback = async (

const league = ctx.getStringOption("league").value as HockeyTechLeague;
const query = ctx.getStringOption("season").value;
const client = getHtClient(league);
const client = getHtClient(ctx.env, league);
const seasons = (await client.getSeasonList()).SiteKit.Seasons;

return [
Expand Down Expand Up @@ -69,7 +69,7 @@ export const pickemsLeaderboardCallback: ChatInputAppCommandCallback = async (
| string
| undefined;

const client = getHtClient(league);
const client = getHtClient(ctx.env, league);
const seasons = (await client.getSeasonList()).SiteKit.Seasons;
if (seasons.length === 0) {
return ctx.reply({
Expand Down Expand Up @@ -157,7 +157,7 @@ export const pickemsMeCallback: ChatInputAppCommandCallback = async (ctx) => {

const league = ctx.getStringOption("league").value as HockeyTechLeague;

const client = getHtClient(league);
const client = getHtClient(ctx.env, league);
const db = getDb(ctx.env.DB);
const votes = await db
.select({
Expand Down
6 changes: 3 additions & 3 deletions packages/bot/src/commands/player.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ const getPlayerEmbed = async (
db?: DBWithSchema,
) => {
const locale = getHtLocale(ctx);
const client = getHtClient(league, locale);
const client = getHtClient(ctx.env, league, locale);
const player =
typeof playerInput === "number"
? (await client.getPlayerProfileBio(playerInput)).SiteKit.Player
Expand Down Expand Up @@ -351,7 +351,7 @@ export const playerCallback: ChatInputAppCommandCallback = async (ctx) => {
ctx.defer(),
async () => {
const locale = getHtLocale(ctx);
const client = getHtClient(league, locale);
const client = getHtClient(ctx.env, league, locale);
const data = await client.searchPerson(query);
const players = data.SiteKit.Searchplayers.filter(
(p) => p.role_name === "Player",
Expand Down Expand Up @@ -414,7 +414,7 @@ export const whoisCallback: ChatInputAppCommandCallback = async (ctx) => {
return [
ctx.defer({ ephemeral: true }),
async () => {
const client = getHtClient(league, getHtLocale(ctx));
const client = getHtClient(ctx.env, league, getHtLocale(ctx));
const seasons = (await client.getSeasonList()).SiteKit.Seasons;
// All star seasons can behave weirdly
const season = seasons.find((s) => s.career === "1") ?? seasons[0];
Expand Down
2 changes: 1 addition & 1 deletion packages/bot/src/commands/seasonAutocomplete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export const seasonAutocomplete: AppCommandAutocompleteCallback = async (
if (!leagues.includes(league)) return [];

const query = ctx.getStringOption("season").value;
const client = getHtClient(league);
const client = getHtClient(ctx.env, league);
const seasons = (await client.getSeasonList()).SiteKit.Seasons;

return seasons
Expand Down
2 changes: 1 addition & 1 deletion packages/bot/src/commands/standings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ export const standingsCallback: ChatInputAppCommandCallback = async (ctx) => {
const sort = ctx.getStringOption("sort").value || undefined;
const seasonId = ctx.getStringOption("season").value || undefined;

const client = getHtClient(league, getHtLocale(ctx));
const client = getHtClient(ctx.env, league, getHtLocale(ctx));
const standings = await getHtStandings(
client,
sort,
Expand Down
2 changes: 1 addition & 1 deletion packages/bot/src/commands/thread.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export const threadCloseCallback: ChatInputAppCommandCallback = async (ctx) => {
return [
ctx.defer({ ephemeral: false, thinking: true }),
async () => {
const client = getHtClient(league, getHtLocale(ctx));
const client = getHtClient(ctx.env, league, getHtLocale(ctx));
const summary = (await client.getGameSummary(gameId)).GC.Gamesummary;

await ctx.followup.editOriginalMessage({
Expand Down
2 changes: 1 addition & 1 deletion packages/bot/src/cron.ts
Original file line number Diff line number Diff line change
Expand Up @@ -532,7 +532,7 @@ export const dailyInitNotifications = async (

// Pickems (7 days from now)
try {
const client = getHtClient(league);
const client = getHtClient(env, league);
const leagueEntries = premiumEntries.filter(
(e): e is typeof e & { channelId: Snowflake } =>
e.league === league && e.channelId !== null,
Expand Down
31 changes: 28 additions & 3 deletions packages/bot/src/ht/client.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import fetchAdapter from "@haverstack/axios-fetch-adapter";
import { createFetchAdapter } from "@haverstack/axios-fetch-adapter";
import HockeyTech from "hockeytech";

export type HockeyTechLeague =
Expand Down Expand Up @@ -129,10 +129,35 @@ export const hockeyTechLeagues: Record<
},
};

export const getHtClient = (league: HockeyTechLeague, locale?: "en" | "fr") => {
export const getHtClient = (
env: Env,
league: HockeyTechLeague,
locale?: "en" | "fr",
) => {
const config = hockeyTechLeagues[league];

let adapter: ReturnType<typeof createFetchAdapter>;
if (isKhl(league) && env.KHL) {
// We use a service binding for our first-party KHL hockeytech proxy
// because Cloudflare was causing issues with intra-zone requests. This
// should be faster and reduce costs. If you aren't also hosting a KHL
// proxy on your CF zone, this will adapt automatically and use the
// public instance.
adapter = createFetchAdapter({
// @ts-expect-error technically incompatible due to missing `webSocket`
// Instead of doing this, I wanted to just pass `env.KHL.fetch`. While
// type-valid, it caused network errors and wouldn't send the request
// to the worker.
fetch(input, init) {
return fetch(input, { ...init, fetcher: env.KHL });
},
});
} else {
adapter = createFetchAdapter();
}

return new HockeyTech(config.key, config.clientCode, locale, config.proxy, {
adapter: fetchAdapter,
adapter,
});
};

Expand Down
2 changes: 1 addition & 1 deletion packages/bot/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -247,7 +247,7 @@ router
})
// .get("/t", async (request, env: Env) => {
// const gameId = Number(new URL(request.url).searchParams.get("game"));
// const client = getHtClient("pwhl");
// const client = getHtClient(env, "pwhl");
// const plays = (await client.getGamePlayByPlay(gameId)).GC.Pxpverbose;
// return json(
// plays
Expand Down
4 changes: 2 additions & 2 deletions packages/bot/src/notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1095,7 +1095,7 @@ const runNotifications = async ({
switch (league) {
case "ahl":
case "pwhl": {
const client = getHtClient(league);
const client = getHtClient(env, league);
const games = (await client.getDailySchedule(day)).SiteKit.Gamesbydate;

for (const game of games) {
Expand Down Expand Up @@ -1517,7 +1517,7 @@ export class DurableNotificationManager implements DurableObject {
return new Response("Invalid `league`", { status: 400 });
}

const client = getHtClient(data.league);
const client = getHtClient(this.env, data.league);
const games = (await client.getDailySchedule(data.day)).SiteKit.Gamesbydate;
console.log(
data.league,
Expand Down
1 change: 1 addition & 0 deletions packages/bot/worker-configuration.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ interface Env {
NOTIFICATIONS: DurableObjectNamespace;
MONTHLY_SKU?: string;
LIFETIME_SKU?: string;
KHL?: Fetcher;
}
2 changes: 2 additions & 0 deletions packages/bot/wrangler.toml
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ compatibility_date = "2023-12-18"
# season takes place during NA's standard time period
triggers.crons = ["0 17 * * *"]

services = [{ binding = "KHL", service = "khl" }]

[[durable_objects.bindings]]
name = "NOTIFICATIONS"
class_name = "DurableNotificationManager"
Expand Down

0 comments on commit 22909b3

Please sign in to comment.