From 9f3d2070323a8e1c1c5b7a6582a93f7f9d7fb25f Mon Sep 17 00:00:00 2001 From: qwerinope Date: Thu, 3 Apr 2025 11:19:31 +0200 Subject: [PATCH] refresh (both) auth tokens on startup --- .example.env | 1 + compose.yml | 1 + src/bot.ts | 8 ++++++++ src/lib/api.ts | 5 +++-- src/lib/auth.ts | 2 +- 5 files changed, 14 insertions(+), 3 deletions(-) diff --git a/.example.env b/.example.env index d3b870c..6315c96 100644 --- a/.example.env +++ b/.example.env @@ -1,3 +1,4 @@ +BOT_NAME= CHANNEL= CLIENT_ID= CLIENT_SECRET= diff --git a/compose.yml b/compose.yml index fb8ce8d..6d5ef2c 100644 --- a/compose.yml +++ b/compose.yml @@ -28,6 +28,7 @@ services: - action: rebuild path: ./src environment: + - BOT_NAME=$BOT_NAME - CHANNEL=$CHANNEL # The following env variables can be removed once the bot has sucessfully run once - CLIENT_ID=$CLIENT_ID diff --git a/src/bot.ts b/src/bot.ts index 12a23f7..d9eafa7 100644 --- a/src/bot.ts +++ b/src/bot.ts @@ -2,6 +2,7 @@ import { Bot } from '@twurple/easy-bot' import authProvider from './lib/auth'; import commands from './commands' +import api, { broadcasterAuthProvider } from './lib/api'; const channel = process.env.CHANNEL ?? '' @@ -13,6 +14,13 @@ const bot = new Bot({ bot.onConnect(async () => { // await authProvider.refreshAccessTokenForUser(238377856) + const name = await api.users.getUserByName(process.env.BOT_NAME!) + await authProvider.refreshAccessTokenForUser(name?.id!) + if (broadcasterAuthProvider) { + const broadcastername = await api.users.getUserByName(channel) + await broadcasterAuthProvider.refreshAccessTokenForUser(broadcastername?.id!) + } + setTimeout(() => { console.log('Bot is ready to accept commands!') }, 1000 * 5) diff --git a/src/lib/api.ts b/src/lib/api.ts index a0a5657..69ce5eb 100644 --- a/src/lib/api.ts +++ b/src/lib/api.ts @@ -2,5 +2,6 @@ import authProvider, { broadcasterAuthProvider as BCAuthFunction } from "../lib/ import { ApiClient } from "@twurple/api"; const api = new ApiClient({ authProvider }) export default api -const broadcasterApi = BCAuthFunction !== undefined ? new ApiClient({ authProvider: await BCAuthFunction() }) : undefined -export { broadcasterApi } +const broadcasterAuthProvider = BCAuthFunction !== undefined ? await BCAuthFunction() : undefined +const broadcasterApi = broadcasterAuthProvider !== undefined ? new ApiClient({ authProvider: broadcasterAuthProvider }) : undefined +export { broadcasterApi, broadcasterAuthProvider } diff --git a/src/lib/auth.ts b/src/lib/auth.ts index 6a2c7b5..0e1ae49 100644 --- a/src/lib/auth.ts +++ b/src/lib/auth.ts @@ -80,7 +80,7 @@ authProvider.onRefresh(async (_id, newTokenData) => { const ttvauthid = await pb.collection('ttvauth').getFirstListItem('main=true') await pb.collection('ttvauth').update(ttvauthid.id, { auth }) - console.log("Refreshed OAuth tokens.") + console.log("Refreshed Bot OAuth tokens.") }) export default authProvider