Skip to content

Commit

Permalink
Merge branch 'master' of https://github.com/dotabod/backend
Browse files Browse the repository at this point in the history
  • Loading branch information
Geczy committed Sep 22, 2024
2 parents d69df1b + d19459a commit 637b89a
Show file tree
Hide file tree
Showing 9 changed files with 133 additions and 14 deletions.
10 changes: 5 additions & 5 deletions packages/dota/locales/fa-IR/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,15 +13,15 @@
"betaTester_off": "{{channel}} دیگه قابلیت بتا نیست برای فعال سازی دوباره !beta رو بزن",
"betaTester_on": "{{channel}} is now a beta tester. Visit discord.dotabod.com to see the beta features. Type !beta to undo",
"bets": {
"error": "Unable to open bets. $t(refreshToken)",
"error": "نشد قمار را به راه کنیم. $t(refreshToken)",
"lost": "این رو که باختیم. عب نداره بعدی هم لوزه",
"notScored": "همه بازی رو دبه کردن {{emote}} بازی {{matchId}} هیچ تاثیری نداشت",
"open": "قمار کنید {{emote}}",
"remade": "Swapped hero {{emote}} Bets for {{- oldHeroName}} refunded and new gamba for {{- newHeroName}} opened {{emote2}}",
"won": "بلاخره بردیم. یک تنه بازی رو حمل کردم"
},
"bounties": {
"pickup": "+$t(bounties.totalGold, {\"count\": {{bountyValue}} }) from bounty ({{totalBounties}}/4) {{emote}} Thanks {{heroNames}} {{emote2}}",
"pickup": "+$t(bounties.totalGold, {\"count\": {{bountyValue}} })گلد از بانتی ({{totalBounties}}/4){{emote}} مرسی از {{heroNames}}{{emote2}}",
"totalGold": "{{count}} گلد"
},
"chatters": {
Expand Down Expand Up @@ -50,16 +50,16 @@
"commands": "",
"commands_everyone": "کامندهای همگانی: {{commandList}}",
"commands_mods": "کامندهای مادها {{commandList}}",
"commandsPage": "To view {{- channel}}'s commands, visit {{- url}}",
"commandsPage": "برای دیدن کامندهای {{- channel}} برین تو لینک {{- url}}",
"connections": {
"gsi_one": "{{count}} streamer connected to Dotabod GSI",
"gsi_one": "{{count}} استریمر از Dotabod GSI استفاده میکنن",
"gsi_other": "{{count}} streamers connected to Dotabod GSI",
"overlay_one": "{{count}} streamer using the overlay",
"overlay_other": "{{count}} streamers using the overlay"
},
"dota2pt": "میخوای چیز جدید واسه قهرمان {{- heroName}} یاد بگیری؟ این اینک رو چک کن {{- url}}",
"dotabod": "من یک ربات سورس باز هستم. سازنده من {{author}}. اطلاعات بیشتر: {{- url}}",
"facet": "{{- heroName}} facet {{number}}: {{- facetTitle}} · {{- facetDescription}}",
"facet": "{{- heroName}} با فست {{number}}{{- facetTitle}}{{- facetDescription}}",
"facetInvalid": "Invalid facet specified · $t(facetNotFound, {{- heroName }})",
"facetNotFound": "Use !facet {{- heroName}} 1 or !facet {{- heroName}} 2 · Dotabod only knows the actually chosen facet for the streamer's current hero",
"facetSelection": "{{- heroName}} selected facet: {{- facetTitle}} · {{- facetDescription}}",
Expand Down
14 changes: 10 additions & 4 deletions packages/dota/src/db/watcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import { server } from '../dota/index.js'
import findUser from '../dota/lib/connectedStreamers.js'
import { didTellUser, gsiHandlers } from '../dota/lib/consts.js'
import { getRankDetail } from '../dota/lib/ranks.js'
import { DBSettings, getValueOrDefault } from '../settings.js'
import { DBSettings } from '../settings.js'
import { chatClient } from '../twitch/chatClient.js'
import { twitchChat } from '../twitch/index.js'
import { updateTwurpleTokenForTwitchId } from '../twitch/lib/getTwitchAPI'
import { toggleDotabod } from '../twitch/toggleDotabod.js'
import { logger } from '../utils/logger.js'
import getDBUser from './getDBUser.js'
Expand Down Expand Up @@ -86,6 +86,12 @@ class SetupSupabase {
const client = findUser(newObj.userId)
if (client?.Account) {
client.Account.scope = newObj.scope
client.Account.access_token = newObj.access_token
client.Account.refresh_token = newObj.refresh_token
client.Account.expires_at = newObj.expires_at
client.Account.expires_in = newObj.expires_in
client.Account.obtainment_timestamp = new Date(newObj.obtainment_timestamp ?? '')
updateTwurpleTokenForTwitchId(newObj.providerAccountId)
}
}

Expand Down Expand Up @@ -128,9 +134,9 @@ class SetupSupabase {
const ONE_DAY_IN_MS = 86_400_000 // 1 day in ms
const dayAgo = new Date(Date.now() - ONE_DAY_IN_MS).toISOString()

const hasNewestScopes = client.Account?.scope?.includes('channel:bot')
// const hasNewestScopes = client.Account?.scope?.includes('channel:bot')
const requiresRefresh = client.Account?.requires_refresh
if ((!hasNewestScopes || requiresRefresh) && !didTellUser.has(client.name)) {
if (requiresRefresh && !didTellUser.has(client.name)) {
didTellUser.add(client.name)

const { data, error } = await supabase
Expand Down
2 changes: 1 addition & 1 deletion packages/dota/src/dota/lib/heroes.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { t } from 'i18next'

const heroes = {
export const heroes = {
npc_dota_hero_antimage: {
id: 1,
localized_name: 'Anti-Mage',
Expand Down
6 changes: 5 additions & 1 deletion packages/dota/src/twitch/chatClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ export const chatClient = {
twitchChat.emit('say', channel, `${prefix}${text}`)
},
whisper: (channel: string, text: string) => {
twitchChat.emit('whisper', channel, `${prefix}${text}`)
const MAX_WHISPER_LENGTH = 10000
const chunks = text.match(new RegExp(`.{1,${MAX_WHISPER_LENGTH}}`, 'g')) || []
chunks.forEach((chunk) => {
twitchChat.emit('whisper', channel, `${prefix}${chunk}`)
})
},
}
2 changes: 1 addition & 1 deletion packages/dota/src/twitch/commands/dotabod.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ commandHandler.registerCommand('dotabod', {

chatClient.say(
channel,
t('dotabod', { url: 'dotabod.com', author: '@techleed', lng: client.locale }),
t('dotabod', { url: 'dotabod.com', author: '@techleed ', lng: client.locale }),
)
},
})
78 changes: 78 additions & 0 deletions packages/dota/src/twitch/commands/test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@ import { t } from 'i18next'
import axios from 'axios'
import type { DelayedGames } from '../../../../steam/src/types/index.js'
import supabase from '../../db/supabase.js'
import { server } from '../../dota/index.js'
import { gsiHandlers } from '../../dota/lib/consts.js'
import { getAccountsFromMatch } from '../../dota/lib/getAccountsFromMatch.js'
import { heroes } from '../../dota/lib/heroes'
import MongoDBSingleton from '../../steam/MongoDBSingleton.js'
import { steamSocket } from '../../steam/ws.js'
import { getWinProbability2MinAgo } from '../../stratz/livematch'
import { logger } from '../../utils/logger.js'
import { chatClient } from '../chatClient.js'
import commandHandler, { type MessageType } from '../lib/CommandHandler.js'

Expand Down Expand Up @@ -181,6 +184,74 @@ const handle2mDataCommand = async (message: MessageType) => {
}
}

async function fixWins(token: string, twitchChatId: string, currentMatchId?: string) {
const ONE_DAY_IN_MS = 86_400_000 // 1 day in ms
const dayAgo = new Date(Date.now() - ONE_DAY_IN_MS).toISOString()

const { data: bets } = await supabase
.from('bets')
.select('id, matchId, myTeam, userId, hero_name')
.is('won', null)
.eq('userId', token)
.neq('matchId', currentMatchId)
.gte('created_at', dayAgo)
.order('created_at', { ascending: false })
.range(0, 10)

chatClient.whisper(
twitchChatId,
bets?.map((b) => b.matchId).join(', ') || 'No broken games found',
)

if (!bets) return

await Promise.all(
bets.map(async (bet) => {
const heroId = bet?.hero_name ? heroes[bet.hero_name as keyof typeof heroes]?.id || 0 : 0
const sockets = await server.io.in(bet.userId).fetchSockets()
if (!Array.isArray(sockets) || !sockets.length) return
chatClient.whisper(
twitchChatId,
`Requesting opendota match data from overlay for match "${bet.matchId}" with hero id "${heroId}"...`,
)
const lastSocket = sockets[sockets.length - 1]
try {
const response = await new Promise((resolve, reject) => {
lastSocket
.timeout(25000)
.emit(
'requestMatchData',
{ matchId: bet.matchId, heroId },
(err: any, response: any) => {
chatClient.whisper(twitchChatId, JSON.stringify(response))
if (err) reject(err)
else resolve(response)
},
)
})

if (typeof response?.radiantWin === 'boolean') {
await supabase
.from('bets')
.update({
radiant_score: response?.radiantScore,
dire_score: response?.direScore,
kda: { kills: response?.kills, deaths: response?.deaths, assists: response?.assists },
won: response.radiantWin && bet.myTeam === 'radiant',
lobby_type: response.lobbyType,
})
.eq('id', bet.id)
}
} catch (e) {
logger.error('Error fetching sockets', { e })
}
}),
)

const handler = gsiHandlers.get(token)
handler?.emitWLUpdate()
}

commandHandler.registerCommand('test', {
permission: 4,

Expand Down Expand Up @@ -213,6 +284,13 @@ commandHandler.registerCommand('test', {
case 'wp':
handleWpCommand(message, args)
break
case 'fixwins':
await fixWins(
message.channel.client.token,
message.user.userId,
message.channel.client.gsi?.map?.matchid,
)
break
default:
chatClient.whisper(message.user.userId, 'Invalid command')
}
Expand Down
4 changes: 4 additions & 0 deletions packages/dota/src/twitch/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ twitchChat.on('connect', () => {
logger.info('We alive on dotabod chat server!')
})

twitchChat.on('disconnect', (reason, details) => {
logger.warn('Disconnected from dotabod chat server', { reason, details })
})

const lastMissingUserMessageTimestamps: Record<string, number> = {}

twitchChat.on(
Expand Down
8 changes: 8 additions & 0 deletions packages/dota/src/twitch/lib/getTwitchAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,11 @@ export const getTwitchAPI = (twitchId: string): ApiClient => {

return api
}

// Remove and re-add the user to get the new tokens in Twurple cache
export function updateTwurpleTokenForTwitchId(twitchId: string) {
const authProvider = getAuthProvider()

authProvider.removeUser(twitchId)
getTwitchAPI(twitchId)
}
23 changes: 21 additions & 2 deletions packages/twitch-chat/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,27 @@ io.on('connection', (socket) => {

hasDotabodSocket = true

socket.on('disconnect', () => {
console.log('We lost the server! Respond to all messages with "server offline"')
socket.on('reconnect', () => {
console.log('Reconnecting to the server')
hasDotabodSocket = true
})

socket.on('reconnect_failed', () => {
console.log('Reconnect failed')
hasDotabodSocket = false
})

socket.on('reconnect_error', (error) => {
console.log('Reconnect error', error)
hasDotabodSocket = false
})

socket.on('disconnect', (reason, details) => {
console.log(
'We lost the server! Respond to all messages with "server offline"',
reason,
details,
)
hasDotabodSocket = false
})

Expand Down

0 comments on commit 637b89a

Please sign in to comment.