@@ -12,12 +12,54 @@ const songs = {
1212const activeSongs = new Map ( )
1313let currentVolume = parseFloat ( localStorage . getItem ( 'tts_volume' ) ) ?? 0.4
1414
15+ async function askChatGPT ( question ) {
16+ const apiKey = localStorage . getItem ( 'openai_api_key' )
17+ if ( ! apiKey ) {
18+ return 'No hay API key configurada.'
19+ }
20+
21+ try {
22+ const response = await fetch ( 'https://api.openai.com/v1/chat/completions' , {
23+ method : 'POST' ,
24+ headers : {
25+ 'Content-Type' : 'application/json' ,
26+ 'Authorization' : `Bearer ${ apiKey } `
27+ } ,
28+ body : JSON . stringify ( {
29+ model : 'gpt-3.5-turbo' ,
30+ messages : [ {
31+ role : 'user' ,
32+ content : question
33+ } ] ,
34+ max_tokens : 150 ,
35+ temperature : 0.7
36+ } )
37+ } )
38+
39+ if ( ! response . ok ) {
40+ const error = await response . json ( )
41+ return `Error: ${ error . error ?. message || 'Error al consultar ChatGPT' } `
42+ }
43+
44+ const data = await response . json ( )
45+ const answer = data . choices ?. [ 0 ] ?. message ?. content
46+
47+ if ( ! answer ) {
48+ return 'Error: No se recibió respuesta de ChatGPT'
49+ }
50+
51+ return answer . length > 500 ? answer . substring ( 0 , 497 ) + '...' : answer
52+ } catch ( error ) {
53+ console . error ( 'Error al consultar ChatGPT:' , error )
54+ return `Error: ${ error . message } `
55+ }
56+ }
57+
1558function detectLanguage ( text ) {
1659 return languageDetector . detect ( text )
1760 . then ( r => r . find ( ( { detectedLanguage} ) =>
1861 languageDetector . expectedInputLanguages . includes ( detectedLanguage ) ) )
1962}
20-
2163function playSong ( audio , duration = 15000 ) {
2264 if ( activeSongs . has ( audio ) ) return
2365
@@ -57,6 +99,10 @@ function processMessageText(text) {
5799 return null
58100 }
59101
102+ if ( lowerText . startsWith ( '!pregunta ' ) || lowerText . startsWith ( '!openai-key ' ) ) {
103+ return null
104+ }
105+
60106 const volumeMatch = lowerText . match ( / ^ ! v o l u m e \s + ( \d + ) $ / )
61107 if ( volumeMatch ) {
62108 setVolume ( parseInt ( volumeMatch [ 1 ] ) )
@@ -97,7 +143,7 @@ client.addEventListener('notification', ({data}) => {
97143 if ( data . metadata . subscription_type !== 'channel.chat.message' ) return
98144 const { text} = data . payload . event . message
99145 const chatter_user_id = data . payload . event . chatter_user_id
100-
146+
101147 if ( chatter_user_id === client . user_id ) return
102148
103149 const lowerText = text . toLowerCase ( ) . trim ( )
@@ -111,14 +157,45 @@ client.addEventListener('notification', ({data}) => {
111157 return
112158 }
113159
160+ const openaiKeyMatch = text . match ( / ^ ! o p e n a i - k e y \s + ( .+ ) $ / i)
161+ if ( openaiKeyMatch ) {
162+ const apiKey = openaiKeyMatch [ 1 ] . trim ( )
163+ localStorage . setItem ( 'openai_api_key' , apiKey )
164+ const broadcaster_id = client . user_id
165+ client . sendMessage ( broadcaster_id , 'API key de OpenAI configurada correctamente' ) . catch ( err => {
166+ console . error ( 'Error al enviar mensaje:' , err )
167+ } )
168+ return
169+ }
170+
171+ const chatgptMatch = text . match ( / ^ ! p r e g u n t a \s + ( .+ ) $ / i)
172+ if ( chatgptMatch ) {
173+ const question = chatgptMatch [ 1 ] . trim ( )
174+ const broadcaster_id = client . user_id
175+ const username = data . payload . event . chatter_user_name || data . payload . event . chatter_user_login || 'Usuario'
176+
177+ client . sendMessage ( broadcaster_id , `🤔 ${ username } , déjame pensar...` ) . catch ( err => {
178+ console . error ( 'Error al enviar mensaje:' , err )
179+ } )
180+
181+ askChatGPT ( question ) . then ( answer => {
182+ client . sendMessage ( broadcaster_id , `💬 ${ username } : ${ answer } ` ) . catch ( err => {
183+ console . error ( 'Error al enviar mensaje:' , err )
184+ } )
185+ } ) . catch ( err => {
186+ client . sendMessage ( broadcaster_id , `Error: ${ err . message } ` ) . catch ( sendErr => {
187+ console . error ( 'Error al enviar mensaje:' , sendErr )
188+ } )
189+ } )
190+ return
191+ }
192+
114193 const processedText = processMessageText ( text )
115194
116195 if ( processedText )
117196 detectLanguage ( processedText ) . then ( r => TTS ( processedText , r ?. detectedLanguage ) )
118197} )
119-
120198import * as OAuth2 from './twitch/oauth2'
121-
122199if ( ! client . token )
123200 try {
124201 if ( client . token = OAuth2 . response ( ) )
@@ -132,21 +209,15 @@ if (!client.token)
132209 )
133210 )
134211 } catch ( error ) {
135- // TODO UI
136212 console . error ( `${ error . name } - ${ error . message } ` )
137213 }
138214if ( client . token )
139215 OAuth2 . validate ( client )
140216 . then ( validation => client . connect ( client . user_id = validation . user_id ) )
141- . catch ( e => {
142- localStorage . removeItem ( 'tts_twitch_token' )
143- location . replace (
144- OAuth2 . authorize (
145- location . href ,
146- client . client_id ,
147- client . scopes
148- )
217+ . catch ( e => location . replace (
218+ OAuth2 . authorize (
219+ location . href ,
220+ client . client_id ,
221+ client . scopes
149222 )
150- } )
151-
152-
223+ ) )
0 commit comments