dndmusicbot/bot.go

92 lines
1.8 KiB
Go
Raw Normal View History

2022-11-18 12:29:39 +00:00
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"sync"
"syscall"
"time"
"github.com/bwmarrin/discordgo"
"github.com/dpup/gohubbub"
"github.com/jackc/pgx/v5"
"github.com/julienschmidt/httprouter"
"github.com/kataras/go-events"
"github.com/r3labs/sse/v2"
"github.com/spf13/viper"
"google.golang.org/api/youtube/v3"
)
const (
channels int = 2 // 1 for mono, 2 for stereo
sampleRate int = 48000 // audio sampling rate
frameSize int = 960 // uint16 size of each audio frame
maxBytes int = (frameSize * 2) * 2 // max size of opus data
)
var (
app = new(App)
config = viper.GetViper()
)
func init() {
log.Println("bot.go loading..")
config.SetConfigName("config")
config.SetConfigType("yaml")
config.AddConfigPath(".")
err := config.ReadInConfig()
if err != nil {
log.Fatal(err)
}
app.mux = http.NewServeMux()
go http.ListenAndServe(":8826", app.mux)
log.Println("bot.go done.")
}
type App struct {
discord *discordgo.Session
voice *discordgo.VoiceConnection
youtube *youtube.Service
queue *Queue
ambiance *Queue
curamb string
events events.EventEmmiter
next bool
db *pgx.Conn
sse *sse.Server
router *httprouter.Router
active []string
plidx int
playlist *Playlist
plm *sync.RWMutex
hubbub *gohubbub.Client
mux *http.ServeMux
}
func main() {
app.plm = &sync.RWMutex{}
ticker := time.NewTicker(300 * time.Millisecond)
sc := make(chan os.Signal, 1)
signal.Notify(sc, syscall.SIGINT, syscall.SIGTERM, os.Interrupt, os.Kill)
for {
select {
case <-sc:
app.db.Close(context.Background())
app.queue.Reset()
app.voice.Close()
app.discord.Close()
return
case <-ticker.C:
app.events.Emit("tick")
}
}
}