Simplified

This commit is contained in:
2024-01-10 00:28:31 -07:00
parent bc3b61c148
commit 6122cafd44
4 changed files with 45 additions and 63 deletions

View File

@ -5,6 +5,11 @@ import (
"time"
)
var (
mu sync.Mutex
instance *CooldownManager
)
type CooldownManager struct {
cooldowns map[string]time.Time
mu sync.Mutex
@ -16,26 +21,47 @@ func NewCooldownManager() *CooldownManager {
}
}
func (m *CooldownManager) StartCooldown(key string, duration time.Duration) {
m.mu.Lock()
defer m.mu.Unlock()
func GetInstance() *CooldownManager {
mu.Lock()
defer mu.Unlock()
m.cooldowns[key] = time.Now().Add(duration)
if instance == nil {
instance = &CooldownManager{
cooldowns: make(map[string]time.Time),
}
}
return instance
}
func (m *CooldownManager) IsOnCooldown(key string) bool {
func (m *CooldownManager) StartCooldown(userID string, key string, duration time.Duration) {
m.mu.Lock()
defer m.mu.Unlock()
cooldownEnd, exists := m.cooldowns[key]
m.cooldowns[userID+":"+key] = time.Now().Add(duration)
}
func (m *CooldownManager) IsOnCooldown(userID string, key string) bool {
m.mu.Lock()
defer m.mu.Unlock()
cooldownEnd, exists := m.cooldowns[userID+":"+key]
if !exists {
return false
}
if time.Now().After(cooldownEnd) {
delete(m.cooldowns, key)
delete(m.cooldowns, userID+":"+key)
return false
}
return true
}
func CancelCooldown(userID string, key string) {
manager := GetInstance()
manager.mu.Lock()
defer manager.mu.Unlock()
delete(manager.cooldowns, userID+":"+key)
}

View File

@ -78,10 +78,10 @@ func CooldownHandler(event discord.InteractionEvent, key string, duration time.D
}
}
if manager.IsOnCooldown(key) {
if manager.IsOnCooldown(user.ID().String(), key) {
return false
}
manager.StartCooldown(key, duration)
manager.StartCooldown(user.ID().String(), key, duration)
return true
}

View File

@ -3,9 +3,9 @@ package lib
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
@ -47,16 +47,15 @@ func OpenAITextGeneration(prompt string) (string, error) {
return resp.Choices[0].Message.Content, nil
}
func OpenAIImageGeneration(prompt string) (*bytes.Buffer, error) {
// Send the generation request to DALL·E 3
func OpenAIImageGeneration(prompt string) (imageFile *bytes.Buffer, err error) {
resp, err := client.CreateImage(context.Background(), openai.ImageRequest{
Prompt: prompt,
Model: "dall-e-3",
Size: "1024x1024",
})
if err != nil {
log.Printf("Image creation error: %v\n", err)
return nil, fmt.Errorf("failed to generate image")
return nil, errors.New("there was an error generating the image based on this prompt... this usually happens when the generated image violates safety requirements")
}
imageRes, err := http.Get(resp.Data[0].URL)
@ -73,6 +72,5 @@ func OpenAIImageGeneration(prompt string) (*bytes.Buffer, error) {
return nil, err
}
imageFile := bytes.NewBuffer(imageBytes)
return imageFile, nil
return bytes.NewBuffer(imageBytes), nil
}