summaryrefslogtreecommitdiff
path: root/app/internal/create_bot.go
blob: c1bea851c12f69535a1ff4b0df7f6763ef37d13a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package internal

import (
	"fmt"
	"net"
	"os"
	"os/exec"
	"syscall"
	"time"
)

type Bot struct {
	BotID     string    `json:"bot_id"`
	BotToken  string    `json:"bot_token"`
	Cmd       *exec.Cmd // Ajouter une référence à la commande
	processID int       // Stocker le PGID (Process Group ID)
}

func Start(b *Bot) (net.Conn, error) {
	socketPath := fmt.Sprintf("/tmp/%s.sock", b.BotID)

	// Nettoyage préalable du socket
	if err := os.RemoveAll(socketPath); err != nil && !os.IsNotExist(err) {
		return nil, fmt.Errorf("error cleaning socket: %w", err)
	}

	// Configuration du bot
	cmd := exec.Command("../bot/build/discord-bot", b.BotToken)
	cmd.SysProcAttr = &syscall.SysProcAttr{
		Setpgid: true, // Permet de kill le processus enfant si nécessaire
	}

	// Redirection des sorties pour le débogage
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	if err := cmd.Start(); err != nil {
		return nil, fmt.Errorf("failed to start bot: %w", err)
	}
	b.Cmd = cmd
	b.processID = cmd.Process.Pid

	// Mécanisme d'attente intelligente pour le socket
	var conn net.Conn
	maxRetries := 10
	for i := 0; i < maxRetries; i++ {
		var err error
		conn, err = net.Dial("unix", socketPath)
		if err == nil {
			break
		}
		time.Sleep(500 * time.Millisecond)
	}

	if conn == nil {
		return nil, fmt.Errorf("failed to connect to bot socket after %d attempts", maxRetries)
	}

	fmt.Printf("Bot %s started successfully\n", b.BotID)
	return conn, nil
}