1
0
mirror of https://github.com/mgerb/go-discord-bot synced 2026-01-10 17:12:48 +00:00

added web server

This commit is contained in:
2017-01-28 19:59:20 +00:00
parent 0262bdf7eb
commit 5d2726df3e
14 changed files with 119 additions and 51 deletions

1
.gitignore vendored
View File

@@ -1 +1,2 @@
config.json
dist/config.json

View File

@@ -1,4 +1,4 @@
{
"Token": "",
"Activator": "#"
"BotPrefix": "#"
}

BIN
dist/GoBot-linux vendored

Binary file not shown.

BIN
dist/GoBot-mac vendored

Binary file not shown.

BIN
dist/GoBot-windows.exe vendored

Binary file not shown.

4
dist/config.json vendored
View File

@@ -1,4 +0,0 @@
{
"Token": "",
"Activator": "#"
}

4
dist/config.template.json vendored Normal file
View File

@@ -0,0 +1,4 @@
{
"Token": "",
"BotPrefix": "#"
}

10
index.html Normal file
View File

@@ -0,0 +1,10 @@
<html>
<head>
</head>
<body>
test 123
</body>
</html>

View File

@@ -14,7 +14,7 @@ clean:
rm -rf ./dist
copyconfig:
cp config.template.json ./dist/config.json
cp config.template.json ./dist/config.template.json
cp -r ./sounds ./dist/
all: linux mac windows copyconfig

View File

@@ -33,6 +33,7 @@ func Connect(token string) {
fmt.Println("Bot connected")
}
// Start - blocking function that starts a websocket listenting for discord callbacks
func Start() {
// Open the websocket and begin listening.
err := Session.Open()
@@ -41,7 +42,7 @@ func Start() {
return
}
fmt.Println("Bot is now running. Press CTRL-C to exit.")
fmt.Println("Bot is now running...")
// Simple way to keep program running until CTRL-C is pressed.
<-make(chan struct{})

View File

@@ -12,10 +12,10 @@ var Config configStruct
type configStruct struct {
Token string `json:"Token"`
Activator string `json:"Activator"`
BotPrefix string `json:"BotPrefix"` //prefix to use for bot commands
}
func Configure() {
func Init() {
log.Println("Reading config file...")

View File

@@ -7,22 +7,48 @@ import (
"fmt"
"github.com/bwmarrin/discordgo"
"io"
"io/ioutil"
"os"
"strings"
"time"
)
var sounds = make(map[string][][]byte, 0)
var (
sounds = make(map[string][][]byte, 0)
soundPlayingLock = false
)
const SOUNDS_DIR string = "./sounds/"
func SoundsHandler(s *discordgo.Session, m *discordgo.MessageCreate) {
if strings.HasPrefix(m.Content, config.Config.Activator) {
// exit function call if sound is playing
if soundPlayingLock {
fmt.Println("Exiting function call")
return
}
// check if valid command
if strings.HasPrefix(m.Content, config.Config.BotPrefix) {
soundName := strings.TrimPrefix(m.Content, config.Config.BotPrefix)
// check if sound exists in memory
if _, ok := sounds[soundName]; !ok {
// try to load the sound if not found in memory
err := loadFile(soundName)
if err != nil {
fmt.Println(err)
return
}
}
// Find the channel that the message came from.
c, err := s.State.Channel(m.ChannelID)
if err != nil {
// Could not find channel.
fmt.Println("User channel not found.")
return
}
@@ -36,7 +62,7 @@ func SoundsHandler(s *discordgo.Session, m *discordgo.MessageCreate) {
// Look for the message sender in that guilds current voice states.
for _, vs := range g.VoiceStates {
if vs.UserID == m.Author.ID {
err = playSound(s, g.ID, vs.ChannelID, strings.TrimPrefix(m.Content, config.Config.Activator))
err = playSound(s, g.ID, vs.ChannelID, soundName)
if err != nil {
fmt.Println("Error playing sound:", err)
}
@@ -47,36 +73,19 @@ func SoundsHandler(s *discordgo.Session, m *discordgo.MessageCreate) {
}
}
// loadSound attempts to load an encoded sound file from disk.
func LoadSounds() error {
files, _ := ioutil.ReadDir(SOUNDS_DIR)
for _, file := range files {
fmt.Println(file.Name())
err := loadFile(file.Name())
if err != nil {
fmt.Println(err.Error())
}
}
return nil
}
// load dca file into memory
func loadFile(fileName string) error {
fmt.Println("Loading file: " + fileName + ".dca")
trimmedName := strings.TrimSuffix(fileName, ".dca")
sounds[trimmedName] = make([][]byte, 0)
file, err := os.Open(SOUNDS_DIR + fileName)
file, err := os.Open(SOUNDS_DIR + fileName + ".dca")
if err != nil {
fmt.Println("Error opening dca file :", err)
return err
}
sounds[fileName] = make([][]byte, 0)
var opuslen int16
for {
@@ -84,12 +93,13 @@ func loadFile(fileName string) error {
err = binary.Read(file, binary.LittleEndian, &opuslen)
// If this is the end of the file, just return.
if err == io.EOF || err == io.ErrUnexpectedEOF {
if err != nil {
file.Close()
if err != nil {
if err == io.EOF {
return nil
} else if err == io.ErrUnexpectedEOF {
return err
}
return nil
}
if err != nil {
@@ -107,7 +117,7 @@ func loadFile(fileName string) error {
return err
}
sounds[trimmedName] = append(sounds[trimmedName], InBuf)
sounds[fileName] = append(sounds[fileName], InBuf)
}
}
@@ -119,6 +129,9 @@ func playSound(s *discordgo.Session, guildID, channelID string, sound string) (e
return errors.New("Sound not found")
}
//prevent other sounds from interrupting
soundPlayingLock = true
// Join the provided voice channel.
vc, err := s.ChannelVoiceJoin(guildID, channelID, false, false)
if err != nil {
@@ -145,5 +158,7 @@ func playSound(s *discordgo.Session, guildID, channelID string, sound string) (e
// Disconnect from the provided voice channel.
_ = vc.Disconnect()
soundPlayingLock = false
return nil
}

View File

@@ -4,26 +4,22 @@ import (
"./bot"
"./config"
"./handlers"
)
// Variables used for command line parameters
var (
BotID string
"./webserver"
)
func main() {
//read config file
config.Configure()
config.Init()
//connect bot to account with token
bot.Connect(config.Config.Token)
//load sound files into memory
handlers.LoadSounds()
//add handlers
bot.AddHandler(handlers.SoundsHandler)
//start websock to listen for messages
bot.Start()
// start new go routine for the discord websockets
go bot.Start()
// start the web server
webserver.Start()
}

45
src/webserver/server.go Normal file
View File

@@ -0,0 +1,45 @@
package webserver
import (
"fmt"
"github.com/buaazp/fasthttprouter"
"github.com/valyala/fasthttp"
"log"
)
func logger(next fasthttp.RequestHandler) fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
logger := ctx.Logger()
logger.Printf(ctx.RemoteAddr().String())
next(ctx)
}
}
func applyMiddleware(handler fasthttp.RequestHandler) fasthttp.RequestHandler {
newHandler := logger(handler)
newHandler = fasthttp.CompressHandler(newHandler)
return newHandler
}
func registerRoutes(router *fasthttprouter.Router) {
router.GET("/test", func(ctx *fasthttp.RequestCtx) {
fmt.Fprint(ctx, "routing works!")
})
router.NotFound = func(ctx *fasthttp.RequestCtx) {
fasthttp.ServeFile(ctx, "./index.html")
}
}
func Start() {
router := fasthttprouter.New()
registerRoutes(router)
// apply our middleware
handlers := applyMiddleware(router.Handler)
// start web server
log.Fatal(fasthttp.ListenAndServe("0.0.0.0:8080", handlers))
}