Allow slack bots to initiate conversations

Signed-off-by: Ettore Di Giacinto <mudler@localai.io>
This commit is contained in:
Ettore Di Giacinto
2025-03-25 22:58:59 +01:00
parent fa12dba7c2
commit fb20bbe5bf
2 changed files with 31 additions and 6 deletions

View File

@@ -41,6 +41,7 @@ type Agent struct {
mcpActions types.Actions mcpActions types.Actions
subscriberMutex sync.Mutex
newMessagesSubscribers []func(openai.ChatCompletionMessage) newMessagesSubscribers []func(openai.ChatCompletionMessage)
} }
@@ -118,7 +119,10 @@ func (a *Agent) startNewConversationsConsumer() {
return return
case msg := <-a.newConversations: case msg := <-a.newConversations:
for _, s := range a.newMessagesSubscribers { a.subscriberMutex.Lock()
subs := a.newMessagesSubscribers
a.subscriberMutex.Unlock()
for _, s := range subs {
s(msg) s(msg)
} }
} }
@@ -126,6 +130,12 @@ func (a *Agent) startNewConversationsConsumer() {
}() }()
} }
func (a *Agent) AddSubscriber(f func(openai.ChatCompletionMessage)) {
a.subscriberMutex.Lock()
defer a.subscriberMutex.Unlock()
a.newMessagesSubscribers = append(a.newMessagesSubscribers, f)
}
// StopAction stops the current action // StopAction stops the current action
// if any. Can be called before adding a new job. // if any. Can be called before adding a new job.
func (a *Agent) StopAction() { func (a *Agent) StopAction() {

View File

@@ -642,6 +642,11 @@ func (t *Slack) handleMention(
} }
func (t *Slack) Start(a *agent.Agent) { func (t *Slack) Start(a *agent.Agent) {
postMessageParams := slack.PostMessageParameters{
LinkNames: 1,
Markdown: true,
}
api := slack.New( api := slack.New(
t.botToken, t.botToken,
// slack.OptionDebug(true), // slack.OptionDebug(true),
@@ -649,12 +654,22 @@ func (t *Slack) Start(a *agent.Agent) {
slack.OptionAppLevelToken(t.appToken), slack.OptionAppLevelToken(t.appToken),
) )
t.apiClient = api if t.channelID != "" {
// handle new conversations
postMessageParams := slack.PostMessageParameters{ a.AddSubscriber(func(ccm openai.ChatCompletionMessage) {
LinkNames: 1, _, _, err := api.PostMessage(t.channelID,
Markdown: true, slack.MsgOptionLinkNames(true),
slack.MsgOptionEnableLinkUnfurl(),
slack.MsgOptionText(ccm.Content, true),
slack.MsgOptionPostMessageParameters(postMessageParams),
)
if err != nil {
xlog.Error(fmt.Sprintf("Error posting message: %v", err))
} }
})
}
t.apiClient = api
client := socketmode.New( client := socketmode.New(
api, api,