Skip to content

Commit

Permalink
add api client from the broadcaster to change stream
Browse files Browse the repository at this point in the history
  • Loading branch information
lluisd committed Oct 17, 2024
1 parent b074a81 commit 0bf965c
Show file tree
Hide file tree
Showing 6 changed files with 68 additions and 34 deletions.
5 changes: 2 additions & 3 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const EventSub = require('./lib/eventSub')
mongoose.connect(config.database).then(() => {
const messenger = new Messenger()
messenger.init()
.then((res) => {
.then(async (bot) => {
console.log('Connected')

const app = express()
Expand Down Expand Up @@ -124,15 +124,14 @@ mongoose.connect(config.database).then(() => {
})

const eventSub = new EventSub();
eventSub.init(res.apiClient, res.bot)
await eventSub.init(bot)
eventSub.apply(app);
const listener = app.listen(process.env.PORT, async ()=> {
console.log('Listening on port ', + listener.address().port)
await eventSub.markAsReady()
await eventSub.subscribeEvent(config.twitch.roomId)
app.get('/', (req, res) => res.redirect('/stream'))
})

})
})

Expand Down
33 changes: 33 additions & 0 deletions broadcasterApiClient.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
const config = require('./config')
const {RefreshingAuthProvider} = require("@twurple/auth");
const TokenService = require("./services/token");
const {ApiClient} = require("@twurple/api");

class BroadcasterApiClient {
constructor() {
this.apiClient = null
}

async getApiClient () {
if (this.apiClient === null) {
const authProvider = new RefreshingAuthProvider(
{
clientId: config.twitch.clientId,
clientSecret: config.twitch.clientSecret
}
)
const tokenData = await TokenService.getToken(config.twitch.roomId)

authProvider.onRefresh(async (userId, newTokenData) => {
await TokenService.updateToken(userId, newTokenData)
})

await authProvider.addUserForToken(tokenData);

this.apiClient = new ApiClient({authProvider})
}
return this.apiClient
}
}

module.exports = new BroadcasterApiClient()
8 changes: 8 additions & 0 deletions handlers/stream.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ class Stream {
await BrowserService.refreshPage().catch(() => { console.error('refreshPage on refreshPage')})
}

async changeTitle(title) {
await TwitchService.setTitle(title).catch(() => { console.error('setTitle on changeTitle')})
}

async changeCategory(name) {
await TwitchService.setGame(name).catch(() => { console.error('setGame on changeCategory')})
}

async getScreenshots(target, bot) {
bot.say(target, `Fotos del stream ${config.externalUrl}/stream`)
}
Expand Down
9 changes: 3 additions & 6 deletions lib/eventSub.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
const {EventSubMiddleware} = require("@twurple/eventsub-http");
const config = require("../config");
const broadcasterApiClient = require('../broadcasterApiClient')

class EventSub {
constructor() {}

init (apiClient, bot) {
async init (bot) {
const apiClient = await broadcasterApiClient.getApiClient()
this.bot = bot
this.middleware = new EventSubMiddleware({
apiClient,
Expand Down Expand Up @@ -56,11 +58,6 @@ class EventSub {
this.bot.say(`#${config.twitch.channels}`, `Raid a @${event.raidedBroadcasterDisplayName}!`)
})

this.middleware.onChannelRaidFrom(channelId, event => {
console.log(`${event.raidedBroadcasterDisplayName} raiding with ${event.viewers} viewers!`);
this.bot.say(`#${config.twitch.channels}`, `Raid a @${event.raidedBroadcasterDisplayName}!`)
})

this.middleware.onChannelBan(channelId, event => {
console.log(`${event.moderatorDisplayName} banned ${event.userDisplayName}!`);
if (event.isPermanent) {
Expand Down
29 changes: 5 additions & 24 deletions lib/messenger.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ class Messenger {

async init() {
await this.tokenAutoRefresh()
await this.channelTokenAutoRefresh()

const opts = {
options: { debug: true },
Expand Down Expand Up @@ -54,31 +53,14 @@ class Messenger {
this.authProvider.addUser(parseInt(config.twitch.userId), tokenData, ['chat'])
}

async channelTokenAutoRefresh () {
const authProvider = new RefreshingAuthProvider(
{
clientId: config.twitch.clientId,
clientSecret: config.twitch.clientSecret
}
)
const tokenData = await TokenService.getToken(config.twitch.roomId)

authProvider.onRefresh(async ( userId, newTokenData) => {
await TokenService.updateToken(userId, newTokenData)
})

await authProvider.addUserForToken(tokenData);
}

listen () {
const apiClient = new ApiClient({ authProvider: this.authProvider })

this.bot.on('message', this.handleText.bind(this))
this.bot.on('connected', this.handleConnect.bind(this))


this.bot.connect().catch(console.error)
return { apiClient, bot: this.bot }
return this.bot
}

async handleText (target, context, msg, self) {
Expand All @@ -99,12 +81,11 @@ class Messenger {
if (textSplit.length > 0 && inputParser.isAskingForOF(textSplit[0]) && this._isNotCooldown('of',15))
return handlers.generic.randomYoutubeLink(target, this.bot)

if (textSplit.length > 1 && inputParser.isAskingToSetTitle(textSplit[0]) && isEditor(context))
return handlers.generic.setTitle(target, textSplit.slice(1).join(' '), this.bot)

if (textSplit.length > 1 && inputParser.isAskingToSetGame(textSplit[0]) && isEditor(context))
return handlers.generic.setGame(target, textSplit.slice(1).join(' '), this.bot)
if (textSplit.length > 1 && inputParser.isAskingToSetTitle(textSplit[0]) && (isMod(context) || isBroadcaster(context) || isEditor(context)))
return handlers.stream.changeTitle(textSplit.slice(1).join(' '))

if (textSplit.length > 1 && inputParser.isAskingToSetGame(textSplit[0]) && (isMod(context) || isBroadcaster(context) || isEditor(context)))
return handlers.stream.changeCategory(textSplit.slice(1).join(' '))

// Weather
if (textSplit.length > 1 && inputParser.isAskingForSunset(textSplit[0]))
Expand Down
18 changes: 17 additions & 1 deletion services/twitch.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,22 @@
const config = require('../config')
const dbManager = require('../helpers/dbmanager')
const broadcasterApiClient = require('../broadcasterApiClient')

const endpointPrefix = 'https://api.twitch.tv/helix'

async function setTitle(title) {
const api = await broadcasterApiClient.getApiClient()
return await api.channels.updateChannelInfo(config.twitch.roomId, { title: title })
}

async function setGame(name) {
const api = await broadcasterApiClient.getApiClient()
const game = await api.games.getGameByName(name)
if (game) {
return await api.channels.updateChannelInfo(config.twitch.roomId, { gameId: game.id })
}
}

async function getStream() {
let result = { type: 'notLive'}
let liveData = null
Expand Down Expand Up @@ -175,7 +189,9 @@ module.exports = {
banUser,
unBanUser,
getUser,
sendAnnouncement
sendAnnouncement,
setTitle,
setGame
}


0 comments on commit 0bf965c

Please sign in to comment.