1
0
mirror of https://github.com/mgerb/go-discord-bot synced 2026-01-10 09:02:49 +00:00

added server address to config

This commit is contained in:
2017-02-04 00:59:30 +00:00
parent cb19c43515
commit c08cf8a4cb
19 changed files with 108 additions and 134 deletions

View File

@@ -11,8 +11,11 @@ import (
var Config configStruct
type configStruct struct {
Token string `json:"Token"`
BotPrefix string `json:"BotPrefix"` //prefix to use for bot commands
Token string `json:"Token"`
BotPrefix string `json:"BotPrefix"` //prefix to use for bot commands
SoundsPath string `json:"SoundsPath"`
UploadPassword string `json:"UploadPassword"`
ServerAddr string `json:"ServerAddr`
}
func Init() {

View File

@@ -2,20 +2,29 @@ package handlers
import (
"../config"
"bufio"
"encoding/binary"
"errors"
"fmt"
"github.com/bwmarrin/discordgo"
"io"
"io/ioutil"
"os"
"layeh.com/gopus"
"os/exec"
"strconv"
"strings"
"time"
)
var (
sounds = make(map[string]*AudioClip, 0)
const (
channels int = 2 // 1 for mono, 2 for stereo
frameRate 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 (
sounds = make(map[string]*AudioClip, 0)
soundPlayingLock = false
)
@@ -31,7 +40,7 @@ func SoundsHandler(s *discordgo.Session, m *discordgo.MessageCreate) {
// exit function call if sound is playing
if soundPlayingLock {
fmt.Println("Exiting function call")
fmt.Println("Function in progress, exiting function call...")
return
}
@@ -82,10 +91,9 @@ func SoundsHandler(s *discordgo.Session, m *discordgo.MessageCreate) {
// load dca file into memory
func loadFile(fileName string) error {
fmt.Println("Loading file: " + fileName + ".dca")
// scan directory for file
files, _ := ioutil.ReadDir("./sounds")
files, _ := ioutil.ReadDir(config.Config.SoundsPath)
var fextension string
var fname string
for _, f := range files {
@@ -103,12 +111,30 @@ func loadFile(fileName string) error {
return errors.New("File not found")
}
// open file and load into memory
file, err := os.Open(SOUNDS_DIR + fileName + ".dca")
fmt.Println("Loading file: " + fname + fextension)
// use ffmpeg to convert file into a format we can use
cmd := exec.Command("ffmpeg", "-i", config.Config.SoundsPath+fname+fextension, "-f", "s16le", "-ar", strconv.Itoa(frameRate), "-ac", strconv.Itoa(channels), "pipe:1")
ffmpegout, err := cmd.StdoutPipe()
if err != nil {
fmt.Println("Error opening dca file :", err)
return err
return errors.New("Stdout error.")
}
ffmpegbuf := bufio.NewReaderSize(ffmpegout, 16348)
err = cmd.Start()
if err != nil {
return errors.New("CMD Start error.")
}
// crate encoder to convert audio to opus codec
opusEncoder, err := gopus.NewEncoder(frameRate, channels, gopus.Audio)
if err != nil {
return errors.New("NewEncoder error.")
}
sounds[fileName] = &AudioClip{
@@ -117,35 +143,28 @@ func loadFile(fileName string) error {
Extension: fextension,
}
var opuslen int16
for {
// Read opus frame length from dca file.
err = binary.Read(file, binary.LittleEndian, &opuslen)
// If this is the end of the file, just return.
// read data from ffmpeg stdout
audiobuf := make([]int16, frameSize*channels)
err = binary.Read(ffmpegbuf, binary.LittleEndian, &audiobuf)
if err == io.EOF || err == io.ErrUnexpectedEOF {
return nil
}
if err != nil {
file.Close()
if err == io.EOF {
return nil
} else if err == io.ErrUnexpectedEOF {
return err
}
return errors.New("Error reading from ffmpeg stdout.")
}
// Read encoded pcm from dca file.
InBuf := make([]byte, opuslen)
err = binary.Read(file, binary.LittleEndian, &InBuf)
// Should not be any end of file errors
// convert audio to opus codec
opus, err := opusEncoder.Encode(audiobuf, frameSize, maxBytes)
if err != nil {
fmt.Println("Error reading from dca file :", err)
return err
return errors.New("Encoding error.")
}
sounds[fileName].Content = append(sounds[fileName].Content, InBuf)
// append sound bytes to the content for this audio file
sounds[fileName].Content = append(sounds[fileName].Content, opus)
}
return nil
}
// playSound plays the current buffer to the provided channel.
@@ -165,7 +184,7 @@ func playSound(s *discordgo.Session, guildID, channelID string, sound string) (e
}
// Sleep for a specified amount of time before playing the sound
time.Sleep(250 * time.Millisecond)
time.Sleep(100 * time.Millisecond)
// Start speaking.
_ = vc.Speaking(true)

View File

@@ -1,15 +1,12 @@
package webserver
import (
"fmt"
"../config"
"github.com/buaazp/fasthttprouter"
"github.com/valyala/fasthttp"
"io"
"log"
"os"
"os/exec"
"strings"
"sync"
)
func logger(next fasthttp.RequestHandler) fasthttp.RequestHandler {
@@ -22,7 +19,6 @@ func logger(next fasthttp.RequestHandler) fasthttp.RequestHandler {
func applyMiddleware(handler fasthttp.RequestHandler) fasthttp.RequestHandler {
newHandler := logger(handler)
//newHandler = fasthttp.CompressHandler(newHandler)
return newHandler
}
@@ -47,128 +43,54 @@ func Start() {
handlers := applyMiddleware(router.Handler)
// start web server
log.Fatal(fasthttp.ListenAndServe("0.0.0.0:8080", handlers))
log.Fatal(fasthttp.ListenAndServe(config.Config.ServerAddr, handlers))
}
func fileUpload(ctx *fasthttp.RequestCtx) {
password := ctx.FormValue("password")
if string(password) != config.Config.UploadPassword {
ctx.Error("Invalid password.", 400)
return
}
file, err := ctx.FormFile("file")
if err != nil {
ctx.SetStatusCode(500)
fmt.Fprint(ctx, "Error reading file.")
ctx.Error("Error reading file.", 400)
return
}
src, err := file.Open()
if err != nil {
ctx.SetStatusCode(500)
fmt.Fprint(ctx, "Error opening file.")
ctx.Error("Error opening file.", 400)
return
}
defer src.Close()
// create uploads folder if it does not exist
if _, err := os.Stat("./uploads"); os.IsNotExist(err) {
os.Mkdir("./uploads", os.ModePerm)
if _, err := os.Stat(config.Config.SoundsPath); os.IsNotExist(err) {
os.Mkdir(config.Config.SoundsPath, os.ModePerm)
}
// check if file already exists
if _, err := os.Stat("./uploads/" + file.Filename); err == nil {
ctx.SetStatusCode(403)
fmt.Fprint(ctx, "File already exists.")
if _, err := os.Stat(config.Config.SoundsPath + file.Filename); err == nil {
ctx.Error("File already exists.", 400)
return
}
dst, err := os.Create("./uploads/" + file.Filename)
dst, err := os.Create(config.Config.SoundsPath + file.Filename)
if err != nil {
ctx.SetStatusCode(500)
fmt.Fprint(ctx, "Error writing file.")
ctx.Error("Error creating file.", 400)
return
}
defer dst.Close()
if _, err = io.Copy(dst, src); err != nil {
ctx.SetStatusCode(500)
fmt.Fprint(ctx, "Error writing file.")
ctx.Error("Error writing file.", 400)
return
}
err = convertFile(file.Filename)
if err != nil {
ctx.SetStatusCode(500)
fmt.Fprint(ctx, err.Error())
return
}
fmt.Fprint(ctx, "Success")
}
func convertFile(fileName string) error {
trimmedName := strings.Split(fileName, ".")[0]
outputPath := "./sounds/"
inputPath := "./uploads/"
fmt.Println(inputPath + fileName)
fmt.Println(outputPath + trimmedName + ".dca")
command := "./dca-rs " + "--raw " + "--i " + inputPath + fileName + " > " + outputPath + trimmedName + ".dca"
wg := new(sync.WaitGroup)
commands := []string{command}
for _, str := range commands {
wg.Add(1)
go exe_cmd(str, wg)
}
wg.Wait()
/*
cmd := exec.Command("./dca-rs", "--raw", "--i", inputPath+fileName+" > "+outputPath+trimmedName+".dca")
_, err := cmd.Output()
if err != nil {
fmt.Println(err.Error())
}
err = cmd.Wait()
if err == nil {
fmt.Println(err.Error())
}
*/
/*
outFile, err := os.Create(outputPath + trimmedName + ".dca")
if err != nil {
return err
}
defer outFile.Close()
stdoutPipe, err := cmd.StdoutPipe()
if err != nil {
return err
}
writer := bufio.NewWriter(outFile)
defer writer.Flush()
fmt.Println(stdoutPipe)
go io.Copy(writer, stdoutPipe)
*/
fmt.Println("working")
return nil
}
func exe_cmd(cmd string, wg *sync.WaitGroup) {
fmt.Println(cmd)
parts := strings.Fields(cmd)
out, err := exec.Command(parts[0], parts[1]).Output()
if err != nil {
fmt.Println("error occured")
fmt.Printf("%s", err)
}
fmt.Printf("%s", out)
wg.Done()
ctx.Success("application/json", []byte("Success!"))
}