Login sessions persist; start/stop all chat bot messages

This commit is contained in:
tyler 2024-02-09 15:35:18 -05:00
parent c090dc8654
commit 5c3fa663a1
13 changed files with 429 additions and 61 deletions

View file

@ -1,5 +1,7 @@
# Doing # Doing
Reset session information in config on logout
Show error when choosing file "chooseFile" Show error when choosing file "chooseFile"
Show filename in chat bot list Show filename in chat bot list
Add styling to choose file button Add styling to choose file button

198
app.go
View file

@ -215,10 +215,77 @@ func (a *App) UpdateChatMessage(cid string, cm config.ChatMessage) (map[string]c
return a.cfg.Channels[cid].ChatBot.Messages, nil return a.cfg.Channels[cid].ChatBot.Messages, nil
} }
func (a *App) NewChatBot(cid string, username string, password string, streamUrl string) error { type NewChatBotResponse struct {
LoggedIn bool `json:"logged_in"`
StreamUrl string `json:"stream_url"`
Username string `json:"username"`
}
func (a *App) GetChatBot(cid string) (NewChatBotResponse, error) {
if a.cb == nil {
return NewChatBotResponse{}, fmt.Errorf("Chat bot not initalized.")
}
loggedIn, err := a.cb.LoggedIn()
if err != nil {
a.logError.Println("error checking if chat bot is logged in:", err)
return NewChatBotResponse{}, fmt.Errorf("Error checking if chat bot is logged in. Try again.")
}
return NewChatBotResponse{loggedIn, a.cb.Cfg.Session.Client.StreamUrl, a.cb.Cfg.Session.Username}, nil
}
func (a *App) NewChatBot(cid string) (NewChatBotResponse, error) {
a.cbMu.Lock() a.cbMu.Lock()
defer a.cbMu.Unlock() defer a.cbMu.Unlock()
if a.cb != nil {
err := a.resetChatBot()
if err != nil {
a.logError.Println("error resetting chat bot:", err)
return NewChatBotResponse{}, fmt.Errorf("Error creating chat bot. Try Again.")
}
}
channel, exists := a.cfg.Channels[cid]
if !exists {
a.logError.Println("channel does not exist:", cid)
return NewChatBotResponse{}, fmt.Errorf("Channel does not exist.")
}
if channel.ChatBot.Session.Client.StreamUrl == "" {
return NewChatBotResponse{}, nil
}
var err error
a.cb, err = chatbot.NewChatBot(a.ctx, channel.ChatBot, a.logError)
if err != nil {
a.logError.Println("error creating new chat bot:", err)
return NewChatBotResponse{}, fmt.Errorf("Error creating new chat bot. Try again.")
}
loggedIn, err := a.cb.LoggedIn()
if err != nil {
a.logError.Println("error checking if chat bot is logged in:", err)
return NewChatBotResponse{}, fmt.Errorf("Error checking if chat bot is logged in. Try again.")
}
if loggedIn {
err = a.cb.StartChatStream()
if err != nil {
a.logError.Println("error starting chat stream:", err)
return NewChatBotResponse{}, fmt.Errorf("Error connecting to chat. Try again.")
}
}
return NewChatBotResponse{loggedIn, channel.ChatBot.Session.Client.StreamUrl, channel.ChatBot.Session.Username}, nil
}
func (a *App) LoginChatBot(cid string, username string, password string, streamUrl string) error {
a.cbMu.Lock()
defer a.cbMu.Unlock()
a.cfgMu.Lock()
defer a.cfgMu.Unlock()
if a.cb != nil { if a.cb != nil {
err := a.resetChatBot() err := a.resetChatBot()
if err != nil { if err != nil {
@ -231,35 +298,151 @@ func (a *App) NewChatBot(cid string, username string, password string, streamUrl
a.logError.Println("channel does not exist:", cid) a.logError.Println("channel does not exist:", cid)
return fmt.Errorf("Channel does not exist.") return fmt.Errorf("Channel does not exist.")
} }
channel.ChatBot.Session.Client.StreamUrl = streamUrl
var err error var err error
a.cb, err = chatbot.NewChatBot(a.ctx, streamUrl, channel.ChatBot, a.logError) a.cb, err = chatbot.NewChatBot(a.ctx, channel.ChatBot, a.logError)
if err != nil { if err != nil {
a.logError.Println("error creating new chat bot:", err) a.logError.Println("error creating new chat bot:", err)
return fmt.Errorf("Error creating new chat bot. Try again.") return fmt.Errorf("Error creating new chat bot. Try again.")
} }
err = a.cb.Login(username, password) cookies, err := a.cb.Login(username, password)
if err != nil { if err != nil {
a.logError.Println("error logging into chat bot:", err) a.logError.Println("error logging into chat bot:", err)
return fmt.Errorf("Error logging in. Try again.") return fmt.Errorf("Error logging in. Try again.")
} }
channel.ChatBot.Session = config.ChatBotSession{
Client: rumblelivestreamlib.NewClientOptions{
Cookies: cookies,
StreamUrl: streamUrl,
},
Username: username,
}
a.cfg.Channels[cid] = channel
err = a.cfg.Save()
if err != nil {
a.logError.Println("error saving config:", err)
return fmt.Errorf("Error saving session information. Try again.")
}
a.cb.Cfg.Session = channel.ChatBot.Session
err = a.cb.StartChatStream() err = a.cb.StartChatStream()
if err != nil { if err != nil {
a.logError.Println("error starting chat stream:", err) a.logError.Println("error starting chat stream:", err)
return fmt.Errorf("Error connecting to chat. Try again.") return fmt.Errorf("Error connecting to chat. Try again.")
} }
// a.cb = cb
return nil return nil
} }
func (a *App) ResetChatBot() error { func (a *App) StopAllChatBot(cid string) error {
err := a.cb.StopAllMessages()
if err != nil {
a.logError.Println("error stopping all chat bot messages:", err)
return fmt.Errorf("Error stopping messages.")
}
return nil
}
func (a *App) StartAllChatBot(cid string) error {
err := a.cb.StartAllMessages()
if err != nil {
a.logError.Println("error starting all chat bot messages:", err)
return fmt.Errorf("Error starting messages.")
}
return nil
}
func (a *App) UpdateChatBotUrl(cid string, streamUrl string) error {
a.cbMu.Lock() a.cbMu.Lock()
defer a.cbMu.Unlock() defer a.cbMu.Unlock()
a.cfgMu.Lock()
defer a.cfgMu.Unlock()
if a.cb == nil {
return fmt.Errorf("Chat bot not initalized.")
}
err := a.resetChatBot() err := a.resetChatBot()
if err != nil {
a.logError.Println("error resetting chat bot:", err)
return fmt.Errorf("Error creating chat bot. Try Again.")
}
channel, exists := a.cfg.Channels[cid]
if !exists {
a.logError.Println("channel does not exist:", cid)
return fmt.Errorf("Channel does not exist.")
}
channel.ChatBot.Session.Client.StreamUrl = streamUrl
a.cb, err = chatbot.NewChatBot(a.ctx, channel.ChatBot, a.logError)
if err != nil {
a.logError.Println("error creating new chat bot:", err)
return fmt.Errorf("Error creating new chat bot. Try again.")
}
a.cfg.Channels[cid] = channel
err = a.cfg.Save()
if err != nil {
a.logError.Println("error saving config:", err)
return fmt.Errorf("Error saving session information. Try again.")
}
a.cb.Cfg.Session.Client.StreamUrl = streamUrl
err = a.cb.StartChatStream()
if err != nil {
a.logError.Println("error starting chat stream:", err)
return fmt.Errorf("Error connecting to chat. Try again.")
}
return nil
}
func (a *App) ResetChatBot(cid string, logout bool) error {
a.cbMu.Lock()
defer a.cbMu.Unlock()
a.cfgMu.Lock()
defer a.cfgMu.Unlock()
if a.cb == nil {
return nil
}
err := a.cb.StopAllMessages()
if err != nil {
return fmt.Errorf("error stopping all chat bot messages: %v", err)
}
if logout {
err := a.cb.Logout()
if err != nil {
return fmt.Errorf("error logging out of chat bot: %v", err)
}
//TODO: reset session in config
channel, exists := a.cfg.Channels[cid]
if !exists {
a.logError.Println("channel does not exist:", cid)
return fmt.Errorf("Channel does not exist.")
}
channel.ChatBot.Session = config.ChatBotSession{}
a.cfg.Channels[cid] = channel
err = a.cfg.Save()
if err != nil {
a.logError.Println("error saving config:", err)
return fmt.Errorf("Error saving session information. Try again.")
}
}
err = a.resetChatBot()
if err != nil { if err != nil {
a.logError.Println("error resetting chat bot:", err) a.logError.Println("error resetting chat bot:", err)
return fmt.Errorf("Error resetting chat bot. Try Again.") return fmt.Errorf("Error resetting chat bot. Try Again.")
@ -284,11 +467,6 @@ func (a *App) resetChatBot() error {
return fmt.Errorf("error stopping chat stream: %v", err) return fmt.Errorf("error stopping chat stream: %v", err)
} }
err = a.cb.Logout()
if err != nil {
return fmt.Errorf("error logging out of chat bot: %v", err)
}
a.cb = nil a.cb = nil
return nil return nil

View file

@ -6,8 +6,10 @@ import heart from './heart-fill.png';
import house from './house.png'; import house from './house.png';
import pause from './pause-fill.png'; import pause from './pause-fill.png';
import play from './play-fill.png'; import play from './play-fill.png';
import play_green from './play-fill-green.png';
import plus_circle from './plus-circle-fill.png'; import plus_circle from './plus-circle-fill.png';
import star from './star-fill.png'; import star from './star-fill.png';
import stop from './stop-fill.png';
import thumbs_down from './hand-thumbs-down.png'; import thumbs_down from './hand-thumbs-down.png';
import thumbs_up from './hand-thumbs-up.png'; import thumbs_up from './hand-thumbs-up.png';
import x_lg from './x-lg.png'; import x_lg from './x-lg.png';
@ -20,8 +22,10 @@ export const Heart = heart;
export const House = house; export const House = house;
export const Pause = pause; export const Pause = pause;
export const Play = play; export const Play = play;
export const PlayGreen = play_green;
export const PlusCircle = plus_circle; export const PlusCircle = plus_circle;
export const Star = star; export const Star = star;
export const Stop = stop;
export const ThumbsDown = thumbs_down; export const ThumbsDown = thumbs_down;
export const ThumbsUp = thumbs_up; export const ThumbsUp = thumbs_up;
export const XLg = x_lg; export const XLg = x_lg;

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

View file

@ -45,3 +45,20 @@
resize: none; resize: none;
width: 100%; width: 100%;
} }
.chat-bot-description {
align-items: center;
display: flex;
flex-direction: row;
justify-content: start;
padding-top: 10px;
width: 100%;
}
.chat-bot-description-label {
color: white;
font-family: sans-serif;
font-size: 20px;
padding-bottom: 5px;
padding-right: 5px;
}

View file

@ -2,18 +2,19 @@ import { useEffect, useState } from 'react';
import { Modal, SmallModal } from './Modal'; import { Modal, SmallModal } from './Modal';
import { NewChatBot } from '../../wailsjs/go/main/App'; import { LoginChatBot, UpdateChatBotUrl } from '../../wailsjs/go/main/App';
import './ChatBot.css'; import './ChatBot.css';
export function ChatBotModal(props) { export function ChatBotModal(props) {
const [error, setError] = useState(''); const [error, setError] = useState('');
const [loggedIn, setLoggedIn] = useState(props.loggedIn);
const [password, setPassword] = useState(''); const [password, setPassword] = useState('');
const [saving, setSaving] = useState(false); const [saving, setSaving] = useState(false);
const updatePassword = (event) => setPassword(event.target.value); const updatePassword = (event) => setPassword(event.target.value);
const [url, setUrl] = useState(''); const [url, setUrl] = useState(props.streamUrl);
const updateUrl = (event) => setUrl(event.target.value); const updateUrl = (event) => setUrl(event.target.value);
const [username, setUsername] = useState(''); const [username, setUsername] = useState(props.username);
const updateUsername = (event) => setUsername(event.target.value); const updateUsername = (event) => setUsername(event.target.value);
useEffect(() => { useEffect(() => {
@ -22,10 +23,23 @@ export function ChatBotModal(props) {
// let p = password; // let p = password;
// let u = url; // let u = url;
// props.onSubmit(user, p, u); // props.onSubmit(user, p, u);
NewChatBot(props.cid, username, password, url) // NewChatBot(props.cid, username, password, url)
if (loggedIn) {
UpdateChatBotUrl(props.cid, url)
.then(() => { .then(() => {
reset(); reset();
props.onClose(); props.onUpdate(url);
})
.catch((error) => {
setSaving(false);
setError(error);
console.log('Error updating chat bot:', error);
});
} else {
LoginChatBot(props.cid, username, password, url)
.then(() => {
reset();
props.onLogin();
}) })
.catch((error) => { .catch((error) => {
setSaving(false); setSaving(false);
@ -33,10 +47,12 @@ export function ChatBotModal(props) {
console.log('Error creating new chat bot:', error); console.log('Error creating new chat bot:', error);
}); });
} }
}
}, [saving]); }, [saving]);
const reset = () => { const reset = () => {
setError(''); setError('');
setLoggedIn(false);
setPassword(''); setPassword('');
setSaving(false); setSaving(false);
setUrl(''); setUrl('');
@ -48,13 +64,18 @@ export function ChatBotModal(props) {
props.onClose(); props.onClose();
}; };
const logout = () => {
reset();
props.onLogout();
};
const submit = () => { const submit = () => {
if (username === '') { if (username === '') {
setError('Add username'); setError('Add username');
return; return;
} }
if (password === '') { if (password === '' && !loggedIn) {
setError('Add password'); setError('Add password');
return; return;
} }
@ -78,8 +99,10 @@ export function ChatBotModal(props) {
onClose={close} onClose={close}
show={props.show} show={props.show}
style={{ minWidth: '300px', maxWidth: '400px' }} style={{ minWidth: '300px', maxWidth: '400px' }}
cancelButton={'Cancel'} cancelButton={loggedIn ? '' : 'Cancel'}
onCancel={close} onCancel={close}
deleteButton={loggedIn ? 'Logout' : ''}
onDelete={logout}
submitButton={saving ? 'Saving' : 'Save'} submitButton={saving ? 'Saving' : 'Save'}
onSubmit={ onSubmit={
saving saving
@ -91,7 +114,17 @@ export function ChatBotModal(props) {
title={'Chat Bot'} title={'Chat Bot'}
> >
<div className='chat-bot-modal'> <div className='chat-bot-modal'>
{/* {error && <span className='chat-bot-error'>{error}</span>} */} {loggedIn ? (
<div className='chat-bot-description'>
<span className='chat-bot-description-label'>Logged in:</span>
<span
className='chat-bot-description-label'
style={{ fontWeight: 'bold' }}
>
{username}
</span>
</div>
) : (
<div className='chat-bot-setting'> <div className='chat-bot-setting'>
<span className='chat-bot-setting-label'>Username</span> <span className='chat-bot-setting-label'>Username</span>
<input <input
@ -102,6 +135,8 @@ export function ChatBotModal(props) {
value={username} value={username}
/> />
</div> </div>
)}
{!loggedIn && (
<div className='chat-bot-setting'> <div className='chat-bot-setting'>
<span className='chat-bot-setting-label'>Password</span> <span className='chat-bot-setting-label'>Password</span>
<input <input
@ -112,6 +147,7 @@ export function ChatBotModal(props) {
value={password} value={password}
/> />
</div> </div>
)}
<div className='chat-bot-setting'> <div className='chat-bot-setting'>
<span className='chat-bot-setting-label'>Stream URL</span> <span className='chat-bot-setting-label'>Stream URL</span>
<input <input

View file

@ -1,7 +1,7 @@
import { useEffect, useState } from 'react'; import { useEffect, useState } from 'react';
import { FilepathBase, StartChatBotMessage, StopChatBotMessage } from '../../wailsjs/go/main/App'; import { FilepathBase, StartChatBotMessage, StopChatBotMessage } from '../../wailsjs/go/main/App';
import { EventsOn } from '../../wailsjs/runtime/runtime'; import { EventsOn } from '../../wailsjs/runtime/runtime';
import { GearFill, Pause, Play, PlusCircle } from '../assets/icons'; import { GearFill, Pause, Play, PlayGreen, PlusCircle, Stop } from '../assets/icons';
import './StreamChatBot.css'; import './StreamChatBot.css';
import { SmallModal } from './Modal'; import { SmallModal } from './Modal';
@ -19,6 +19,20 @@ function StreamChatBot(props) {
<div className='stream-chatbot'> <div className='stream-chatbot'>
<div className='stream-chatbot-header'> <div className='stream-chatbot-header'>
<span className='stream-chatbot-title'>{props.title}</span> <span className='stream-chatbot-title'>{props.title}</span>
<div className='stream-chatbot-controls'>
<button
className='stream-chatbot-button stream-chatbot-button-title'
onClick={props.onPlayAll}
>
<img className='stream-chatbot-icon' src={PlayGreen} />
</button>
<button
className='stream-chatbot-button stream-chatbot-button-title'
onClick={props.onStopAll}
>
<img className='stream-chatbot-icon' src={Stop} />
</button>
</div>
<div className='stream-chatbot-controls'> <div className='stream-chatbot-controls'>
<button <button
className='stream-chatbot-button stream-chatbot-button-title' className='stream-chatbot-button stream-chatbot-button-title'

View file

@ -4,11 +4,15 @@ import {
AddChatMessage, AddChatMessage,
ChatBotMessages, ChatBotMessages,
DeleteChatMessage, DeleteChatMessage,
GetChatBot,
NewChatBot, NewChatBot,
ResetChatBot, ResetChatBot,
StartAllChatBot,
StartApi, StartApi,
StopAllChatBot,
StopApi, StopApi,
StopChatBotMessage, StopChatBotMessage,
UpdateChatBotUrl,
UpdateChatMessage, UpdateChatMessage,
} from '../../wailsjs/go/main/App'; } from '../../wailsjs/go/main/App';
@ -35,6 +39,9 @@ function Dashboard() {
const [openChatBot, setOpenChatBot] = useState(false); const [openChatBot, setOpenChatBot] = useState(false);
const [chatBotMessages, setChatBotMessages] = useState({}); const [chatBotMessages, setChatBotMessages] = useState({});
const [chatBotMessagesActive, setChatBotMessagesActive] = useState({}); const [chatBotMessagesActive, setChatBotMessagesActive] = useState({});
const [chatBotSessionLoggedIn, setChatBotSessionLoggedIn] = useState(false);
const [chatBotSessionStreamUrl, setChatBotSessionStreamUrl] = useState('');
const [chatBotSessionUsername, setChatBotSessionUsername] = useState('');
const [chatAsChannel, setChatAsChannel] = useState(false); const [chatAsChannel, setChatAsChannel] = useState(false);
const [chatCommand, setChatCommand] = useState(''); const [chatCommand, setChatCommand] = useState('');
const [chatOnCommand, setChatOnCommand] = useState(false); const [chatOnCommand, setChatOnCommand] = useState(false);
@ -78,6 +85,12 @@ function Dashboard() {
setChatBotMessages(messages); setChatBotMessages(messages);
}); });
NewChatBot(cid).then((response) => {
setChatBotSessionLoggedIn(response.logged_in);
setChatBotSessionStreamUrl(response.stream_url);
setChatBotSessionUsername(response.username);
});
EventsOn('QueryResponse', (response) => { EventsOn('QueryResponse', (response) => {
// console.log('query response received'); // console.log('query response received');
setRefresh(!refresh); setRefresh(!refresh);
@ -115,7 +128,7 @@ function Dashboard() {
StopApi() StopApi()
.then(() => setActive(false)) .then(() => setActive(false))
.then(() => { .then(() => {
ResetChatBot(); ResetChatBot(cid, false);
}) })
.then(() => { .then(() => {
navigate(NavSignIn); navigate(NavSignIn);
@ -244,6 +257,7 @@ function Dashboard() {
}); });
}; };
// TODO: this never gets called - delete
const saveChatBot = (username, password, url) => { const saveChatBot = (username, password, url) => {
NewChatBot(cid, username, password, url) NewChatBot(cid, username, password, url)
.then(() => { .then(() => {
@ -252,6 +266,64 @@ function Dashboard() {
.catch((error) => console.log('Error creating new chat bot:', error)); .catch((error) => console.log('Error creating new chat bot:', error));
}; };
const updateChatBot = (url) => {
setChatBotSessionStreamUrl(url);
setOpenChatBot(false);
};
const loginChatBot = () => {
GetChatBot(cid)
.then((response) => {
setChatBotSessionLoggedIn(response.logged_in);
setChatBotSessionStreamUrl(response.stream_url);
setChatBotSessionUsername(response.username);
})
.catch((error) => {
setError(error);
console.log('Error getting chat bot:', error);
})
.finally(() => {
setOpenChatBot(false);
});
};
const logoutChatBot = () => {
ResetChatBot(cid, true)
.then(() => {
NewChatBot(cid).then((response) => {
console.log('NewChatBot response:', response);
setChatBotSessionLoggedIn(response.logged_in);
setChatBotSessionStreamUrl(response.stream_url);
setChatBotSessionUsername(response.username);
});
})
.catch((error) => {
setError(error);
console.log('Error resetting chat bot:', error);
})
.finally(() => {
setOpenChatBot(false);
});
};
const chatBotStartAll = () => {
StartAllChatBot(cid).catch((error) => {
setError(error);
console.log('Error starting all chat bot messages:', error);
});
};
const chatBotStopAll = () => {
StopAllChatBot(cid)
.then(() => {
setChatBotMessagesActive({});
})
.catch((error) => {
setError(error);
console.log('Error stopping all chat bot messages:', error);
});
};
const activateMessage = (id, active) => { const activateMessage = (id, active) => {
// console.log('Dashboard activateMessage:', id, active); // console.log('Dashboard activateMessage:', id, active);
chatBotMessagesActive[id] = active; chatBotMessagesActive[id] = active;
@ -290,9 +362,15 @@ function Dashboard() {
{openChatBot && ( {openChatBot && (
<ChatBotModal <ChatBotModal
cid={cid} cid={cid}
loggedIn={chatBotSessionLoggedIn}
onClose={() => setOpenChatBot(false)} onClose={() => setOpenChatBot(false)}
onLogin={loginChatBot}
onLogout={logoutChatBot}
onSubmit={saveChatBot} onSubmit={saveChatBot}
onUpdate={updateChatBot}
show={openChatBot} show={openChatBot}
streamUrl={chatBotSessionStreamUrl}
username={chatBotSessionUsername}
/> />
)} )}
<div id='Dashboard'> <div id='Dashboard'>
@ -327,7 +405,9 @@ function Dashboard() {
chats={chatBotMessages} chats={chatBotMessages}
onAdd={newChat} onAdd={newChat}
onEdit={editChat} onEdit={editChat}
onPlayAll={chatBotStartAll}
onSettings={() => setOpenChatBot(true)} onSettings={() => setOpenChatBot(true)}
onStopAll={chatBotStopAll}
title={'Chat Bot'} title={'Chat Bot'}
isMessageActive={isMessageActive} isMessageActive={isMessageActive}
/> />

2
go.mod
View file

@ -4,7 +4,7 @@ go 1.19
require ( require (
github.com/tylertravisty/go-utils v0.0.0-20230524204414-6893ae548909 github.com/tylertravisty/go-utils v0.0.0-20230524204414-6893ae548909
github.com/tylertravisty/rumble-livestream-lib-go v0.2.2 github.com/tylertravisty/rumble-livestream-lib-go v0.3.4
github.com/wailsapp/wails/v2 v2.7.1 github.com/wailsapp/wails/v2 v2.7.1
) )

4
go.sum
View file

@ -57,8 +57,8 @@ github.com/tkrajina/go-reflector v0.5.6 h1:hKQ0gyocG7vgMD2M3dRlYN6WBBOmdoOzJ6njQ
github.com/tkrajina/go-reflector v0.5.6/go.mod h1:ECbqLgccecY5kPmPmXg1MrHW585yMcDkVl6IvJe64T4= github.com/tkrajina/go-reflector v0.5.6/go.mod h1:ECbqLgccecY5kPmPmXg1MrHW585yMcDkVl6IvJe64T4=
github.com/tylertravisty/go-utils v0.0.0-20230524204414-6893ae548909 h1:xrjIFqzGQXlCrCdMPpW6+SodGFSlrQ3ZNUCr3f5tF1g= github.com/tylertravisty/go-utils v0.0.0-20230524204414-6893ae548909 h1:xrjIFqzGQXlCrCdMPpW6+SodGFSlrQ3ZNUCr3f5tF1g=
github.com/tylertravisty/go-utils v0.0.0-20230524204414-6893ae548909/go.mod h1:2W31Jhs9YSy7y500wsCOW0bcamGi9foQV1CKrfvfTxk= github.com/tylertravisty/go-utils v0.0.0-20230524204414-6893ae548909/go.mod h1:2W31Jhs9YSy7y500wsCOW0bcamGi9foQV1CKrfvfTxk=
github.com/tylertravisty/rumble-livestream-lib-go v0.2.2 h1:gWmw44gSNOK37UQIEWS0GVxFJABt/8np9ArhFSSZj1o= github.com/tylertravisty/rumble-livestream-lib-go v0.3.4 h1:VPKelrC3hesJlbqdByMkUhbEubFx80T5FNC60JKrEfw=
github.com/tylertravisty/rumble-livestream-lib-go v0.2.2/go.mod h1:CACpHQV9xQqBKB7C13tUkL7O8Neb35+dJzRV1N211s4= github.com/tylertravisty/rumble-livestream-lib-go v0.3.4/go.mod h1:rUET5uInouMfB4ekqdGiYeoN5ibOdzU9cCgRE0i57Wg=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ= github.com/valyala/fasttemplate v1.2.1/go.mod h1:KHLXt3tVN2HBp8eijSv/kGJopbvo7S+qRAEEKiv+SiQ=

View file

@ -9,6 +9,7 @@ import (
"html/template" "html/template"
"log" "log"
"math/big" "math/big"
"net/http"
"os" "os"
"strings" "strings"
"sync" "sync"
@ -45,8 +46,10 @@ type message struct {
textFromFile []string textFromFile []string
} }
func NewChatBot(ctx context.Context, streamUrl string, cfg config.ChatBot, logError *log.Logger) (*ChatBot, error) { func NewChatBot(ctx context.Context, cfg config.ChatBot, logError *log.Logger) (*ChatBot, error) {
client, err := rumblelivestreamlib.NewClient("", validUrl(streamUrl)) // client, err := rumblelivestreamlib.NewClient("", validUrl(streamUrl))
client, err := rumblelivestreamlib.NewClient(cfg.Session.Client)
if err != nil { if err != nil {
return nil, fmt.Errorf("chatbot: error creating new client: %v", err) return nil, fmt.Errorf("chatbot: error creating new client: %v", err)
} }
@ -131,9 +134,11 @@ func (cb *ChatBot) startCommand(ctx context.Context, m *message) {
var prev time.Time var prev time.Time
for { for {
runtime.EventsEmit(cb.ctx, "ChatBotCommandActive-"+m.id, m.id)
// TODO: if error, emit error to user, stop loop? // TODO: if error, emit error to user, stop loop?
select { select {
case <-ctx.Done(): case <-ctx.Done():
runtime.EventsEmit(cb.ctx, "ChatBotMessageError-"+m.id, m.id)
return return
case cv := <-ch: case cv := <-ch:
if m.onCommandFollower && !cv.IsFollower { if m.onCommandFollower && !cv.IsFollower {
@ -173,7 +178,7 @@ func (cb *ChatBot) startCommand(ctx context.Context, m *message) {
return return
} else { } else {
prev = now prev = now
runtime.EventsEmit(cb.ctx, "ChatBotCommandActive-"+m.id, m.id) // runtime.EventsEmit(cb.ctx, "ChatBotCommandActive-"+m.id, m.id)
} }
} }
} }
@ -196,6 +201,7 @@ func (cb *ChatBot) startMessage(ctx context.Context, m *message) {
select { select {
case <-ctx.Done(): case <-ctx.Done():
timer.Stop() timer.Stop()
runtime.EventsEmit(cb.ctx, "ChatBotMessageError-"+m.id, m.id)
return return
case <-timer.C: case <-timer.C:
} }
@ -270,6 +276,17 @@ func (cb *ChatBot) chat(m *message) error {
return nil return nil
} }
func (cb *ChatBot) StartAllMessages() error {
for _, msg := range cb.Cfg.Messages {
err := cb.StartMessage(msg.ID)
if err != nil {
return fmt.Errorf("error starting message: %v", err)
}
}
return nil
}
func (cb *ChatBot) StopAllMessages() error { func (cb *ChatBot) StopAllMessages() error {
cb.messagesMu.Lock() cb.messagesMu.Lock()
defer cb.messagesMu.Unlock() defer cb.messagesMu.Unlock()
@ -280,12 +297,12 @@ func (cb *ChatBot) StopAllMessages() error {
if m.command != "" && m.onCommand { if m.command != "" && m.onCommand {
cb.commandsMu.Lock() cb.commandsMu.Lock()
defer cb.commandsMu.Unlock()
ch, exists := cb.commands[m.command] ch, exists := cb.commands[m.command]
if exists { if exists {
close(ch) close(ch)
delete(cb.commands, m.command) delete(cb.commands, m.command)
} }
cb.commandsMu.Unlock()
} }
} }
@ -323,17 +340,30 @@ func (m *message) stop() {
m.cancelMu.Unlock() m.cancelMu.Unlock()
} }
func (cb *ChatBot) Login(username string, password string) error { func (cb *ChatBot) LoggedIn() (bool, error) {
if cb.client == nil { if cb.client == nil {
return fmt.Errorf("chatbot: client is nil") return false, fmt.Errorf("chatbot: client is nil")
} }
err := cb.client.Login(username, password) loggedIn, err := cb.client.LoggedIn()
if err != nil { if err != nil {
return fmt.Errorf("chatbot: error logging in: %v", err) return false, fmt.Errorf("chatbot: error checking if chat bot is logged in: %v", err)
} }
return nil return loggedIn, nil
}
func (cb *ChatBot) Login(username string, password string) ([]*http.Cookie, error) {
if cb.client == nil {
return nil, fmt.Errorf("chatbot: client is nil")
}
cookies, err := cb.client.Login(username, password)
if err != nil {
return nil, fmt.Errorf("chatbot: error logging in: %v", err)
}
return cookies, nil
} }
func (cb *ChatBot) Logout() error { func (cb *ChatBot) Logout() error {

View file

@ -9,6 +9,7 @@ import (
"time" "time"
"github.com/tylertravisty/go-utils/random" "github.com/tylertravisty/go-utils/random"
rumblelivestreamlib "github.com/tylertravisty/rumble-livestream-lib-go"
) )
const ( const (
@ -85,8 +86,14 @@ type ChatMessage struct {
TextFile string `json:"text_file"` TextFile string `json:"text_file"`
} }
type ChatBotSession struct {
Client rumblelivestreamlib.NewClientOptions `json:"client"`
Username string `json:"username"`
}
type ChatBot struct { type ChatBot struct {
Messages map[string]ChatMessage `json:"messages"` Messages map[string]ChatMessage `json:"messages"`
Session ChatBotSession `json:"session"`
// Commands []ChatCommand // Commands []ChatCommand
} }
@ -106,7 +113,7 @@ func (a *App) NewChannel(url string, name string) (string, error) {
} }
if _, exists := a.Channels[id]; !exists { if _, exists := a.Channels[id]; !exists {
a.Channels[id] = Channel{id, url, name, DefaultInterval, ChatBot{map[string]ChatMessage{}}} a.Channels[id] = Channel{id, url, name, DefaultInterval, ChatBot{Messages: map[string]ChatMessage{}}}
return id, nil return id, nil
} }
} }