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

added docker support

This commit is contained in:
2018-05-30 21:23:03 -05:00
parent af8448e028
commit 3d05a49a3e
20 changed files with 125 additions and 196 deletions

2
.dockerignore Normal file
View File

@@ -0,0 +1,2 @@
./client/node_modules
./server/vendor

1
.gitignore vendored
View File

@@ -11,3 +11,4 @@ youtube
go-discord-bot
data.db
.wwp-cache
data

View File

@@ -1,48 +1,28 @@
FROM ubuntu
FROM node:8.11.1-alpine
WORKDIR /home/temp
WORKDIR /home/client
ADD ./client .
RUN npm install
RUN npm run build
RUN apt-get -qq update
# install git
RUN apt-get install -y git
FROM golang:1.10.2-alpine3.7
# install Golang
RUN apt-get install --yes curl
RUN curl https://storage.googleapis.com/golang/go1.8.3.linux-amd64.tar.gz | tar xvz
RUN cp -r ./go /usr/local/
RUN cp ./go/bin/* /usr/bin
RUN mkdir -p /home/go/src
RUN mkdir /home/go/bin
RUN mkdir /home/go/pkg
ENV GOPATH=/home/go
ENV GOBIN=$GOPATH/bin
RUN go env
# install nodejs and npm
RUN curl --silent --location https://deb.nodesource.com/setup_6.x | bash -
RUN apt-get install -y nodejs
RUN apt-get install -y build-essential
# install yarn
RUN curl -sS https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -
RUN echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list
RUN apt-get update && apt-get install yarn
RUN yarn --version
# set working directory
RUN mkdir -p /home/go/src/github.com/mgerb/go-discord-bot
ADD . /home/go/src/github.com/mgerb/go-discord-bot
# build client app
WORKDIR /home/go/src/github.com/mgerb/go-discord-bot/client
RUN yarn install
RUN yarn run build
WORKDIR /home/go/src/github.com/mgerb/go-discord-bot
# build server
WORKDIR /go/src/github.com/mgerb/go-discord-bot/server
COPY --from=0 /home/dist /go/src/github.com/mgerb/go-discord-bot/dist
ADD ./server .
RUN apk add --no-cache git alpine-sdk
RUN go get -u github.com/gobuffalo/packr/...
RUN go get
RUN go build -o bot ./main.go
RUN packr build -o /build/server
# Run the app
CMD ["./bot"]
FROM wernight/youtube-dl
RUN apk update
RUN apk add ca-certificates
WORKDIR /bot
COPY --from=1 /build/server /
ENTRYPOINT ["/server"]

View File

@@ -1,13 +0,0 @@
# use docker container to build client
docker run -it -d --name node1 node:8.9.4-alpine;
docker exec -it node /bin/sh -c "mkdir /home/client";
docker cp ./client node1:/home/client;
docker exec -it node1 /bin/sh -c "cd /home/client && yarn install";
docker exec -it node1 /bin/sh -c "cd /home/client && yarn run build";
docker cp node1:/home/dist ./dist;
docker kill node1;
docker rm node1;

View File

@@ -1,6 +1,6 @@
{
"name": "go-discord-bot",
"version": "1.0.0",
"version": "0.4.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {

View File

@@ -1,6 +1,6 @@
{
"name": "go-discord-bot",
"version": "1.0.0",
"version": "0.4.0",
"description": "Client for go-discord-bot",
"scripts": {
"build": "NODE_ENV=prod webpack -p --progress --colors",

View File

@@ -2,19 +2,15 @@
"token": "",
"client_id": "",
"client_secret": "",
"redirect_uri": "",
"redirect_uri": "https://localhost/oauth",
"bot_prefix": "#",
"admin_emails": ["mail@example.com"],
"mod_emails": ["mail@example.com"],
"jwt_key": "generate a random secret string here",
"jwt_secret": "generate a random secret string here",
"server_addr": "0.0.0.0:80",
"logger": true,
"database": "data.db",
"sounds_path": "./sounds/",
"clips_path": "./clips/"
"logger": true
}

1
docker-build.sh Executable file
View File

@@ -0,0 +1 @@
docker build -t mgerb/go-discord-bot .

9
docker-compose.yml Normal file
View File

@@ -0,0 +1,9 @@
version: "2"
services:
go-discord-bot:
image: mgerb/go-discord-bot:latest
ports:
- 8080:8080
volumes:
- ./data:/bot

View File

@@ -2,10 +2,10 @@ run:
go run ./main.go
install:
go get && cd client && npm install
go get ./server && cd client && npm install
build-server:
packr build -o bot ./main.go && packr install
cd ./server && packr build -o ../bot ./main.go
build-client:
cd client && npm run build

View File

@@ -11,10 +11,30 @@ A soundboard bot for discord with a Go back end and React front end.
* Install [ffmpeg](https://www.ffmpeg.org/download.html)
* edit your config.json file
* run the executable
* visit http://localhost:8080
### With docker-compose
Make sure to create a `config.json` file in your data volume.
Take a look at `config.template.json` for example congurations.
docker-compose.yml
```
version: "2"
services:
go-discord-bot:
image: mgerb/go-discord-bot:latest
ports:
- 8080:8080
volumes:
- <path to your data directory>:/bot
```
### Commands
* `clip` - clips the past minute of audio
* `clip` - clips the past minute of audio (currently bugged if more than one user is speaking)
* `summon` - summons the bot to your current channel
* `dismiss` - dismisses the bot from the server
* `<audio clip>` - play a named audio clip
@@ -48,12 +68,6 @@ https://<your domain name> {
}
```
### Clipping audio
If the bot is in a channel it listens to all audio. Use the `clip` command
to record the past minute of conversation. Access all clips in the "Clips"
section of the site.
### Stats
If logging is enabled the bot will log all messages and store in a database file. Currently the bot keeps track of
@@ -83,7 +97,3 @@ Use these commands to compile the project. The client must be built first.
* `packr build`
* `packr install`
### Windows
I only run this on linux. I'm not sure if it will work on windows, but it should without too much work.

View File

@@ -229,12 +229,12 @@ func (conn *AudioConnection) loadFile(fileName string) error {
log.Debug("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(sampleRate), "-ac", strconv.Itoa(channels), "pipe:1")
cmd := exec.Command("ffmpeg", "-i", config.Config.SoundsPath+"/"+fname+fextension, "-f", "s16le", "-ar", strconv.Itoa(sampleRate), "-ac", strconv.Itoa(channels), "pipe:1")
ffmpegout, err := cmd.StdoutPipe()
if err != nil {
return errors.New("Unable to execute ffmpeg. To set permissions on this file run chmod +x ffmpeg_linux (or ffmpeg_mac depending which operating system you are on)")
return err
}
ffmpegbuf := bufio.NewReaderSize(ffmpegout, 16348)
@@ -242,7 +242,7 @@ func (conn *AudioConnection) loadFile(fileName string) error {
err = cmd.Start()
if err != nil {
return errors.New("Unable to execute ffmpeg. To set permissions on this file run chmod +x ffmpeg_linux (or ffmpeg_mac depending which operating system you are on)")
return err
}
// crate encoder to convert audio to opus codec
@@ -299,7 +299,7 @@ func writePacketsToFile(username string, packets chan *discordgo.Packet) {
// construct filename
timestamp := time.Now().UTC().Format("2006-01-02") + "-" + strconv.Itoa(int(time.Now().Unix()))
filename := config.Config.ClipsPath + timestamp + "-" + username + ".wav"
filename := config.Config.ClipsPath + "/" + timestamp + "-" + username + ".wav"
// grab everything from the voice packet channel and dump it to the file
// close when there is nothing left

View File

@@ -2,7 +2,6 @@ package config
import (
"encoding/json"
"flag"
"io/ioutil"
log "github.com/sirupsen/logrus"
@@ -10,40 +9,34 @@ import (
// Variables used for command line parameters
var (
Config configFile
Flags configFlags
Config configType
)
type configFile struct {
Token string `json:"token"`
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
RedirectURI string `json:"redirect_uri"`
type configType struct {
Token string `json:"token"`
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
RedirectURI string `json:"redirect_uri"`
BotPrefix string `json:"bot_prefix"` //prefix to use for bot commands
AdminEmails []string `json:"admin_emails"`
ModEmails []string `json:"mod_emails"`
ServerAddr string `json:"server_addr"`
JWTSecret string `json:"jwt_secret"`
Logger bool `json:"logger"`
GuildID string `json:"guild_id"`
BotPrefix string `json:"bot_prefix"` //prefix to use for bot commands
SoundsPath string `json:"sounds_path"`
ClipsPath string `json:"clips_path"`
AdminEmails []string `json:"admin_emails"`
ModEmails []string `json:"mod_emails"`
ServerAddr string `json:"server_addr"`
JWTKey string `json:"jwt_key"`
Logger bool `json:"logger"`
Database string `json:"database"`
}
type configFlags struct {
Prod bool
// hard coded folder paths
SoundsPath string
ClipsPath string
YoutubePath string
}
// Init -
func Init() {
parseConfig()
parseFlags()
Config.SoundsPath = "./sounds"
Config.ClipsPath = "./clips"
Config.YoutubePath = "./youtube"
}
func parseConfig() {
@@ -61,22 +54,6 @@ func parseConfig() {
err := json.Unmarshal(file, &Config)
if err != nil {
log.Error(err)
log.Fatal(err)
}
}
func parseFlags() {
Flags.Prod = false
prod := flag.Bool("p", false, "Run in production")
flag.Parse()
Flags.Prod = *prod
if Flags.Prod {
log.Warn("Running in production mode")
}
}

View File

@@ -2,7 +2,6 @@ package db
import (
"github.com/jinzhu/gorm"
"github.com/mgerb/go-discord-bot/server/config"
// database driver for sqlite
_ "github.com/jinzhu/gorm/dialects/sqlite"
@@ -14,7 +13,7 @@ var Conn *gorm.DB
// Init - initialize database
func Init() {
var err error
Conn, err = gorm.Open("sqlite3", config.Config.Database)
Conn, err = gorm.Open("sqlite3", "data.db")
if err != nil {
panic("failed to connect database")

View File

@@ -3,7 +3,6 @@ package main
import (
"os"
"github.com/gin-gonic/gin"
"github.com/mgerb/go-discord-bot/server/bot"
"github.com/mgerb/go-discord-bot/server/config"
"github.com/mgerb/go-discord-bot/server/db"
@@ -20,13 +19,6 @@ func init() {
//read config file
config.Init()
if config.Flags.Prod {
// prod
gin.SetMode(gin.ReleaseMode)
// Only log the warning severity or above.
log.SetLevel(log.WarnLevel)
}
if config.Config.Logger {
db.Init()
db.Conn.AutoMigrate(&logger.Message{}, &logger.Attachment{}, &logger.User{})

View File

@@ -7,6 +7,7 @@ import (
"regexp"
"github.com/gin-gonic/gin"
"github.com/mgerb/go-discord-bot/server/config"
log "github.com/sirupsen/logrus"
)
@@ -16,8 +17,8 @@ func Downloader(c *gin.Context) {
fileType := c.Query("fileType")
// create youtube folder if it does not exist
if _, err := os.Stat("youtube"); os.IsNotExist(err) {
os.Mkdir("youtube", os.ModePerm)
if _, err := os.Stat(config.Config.YoutubePath); os.IsNotExist(err) {
os.Mkdir(config.Config.YoutubePath, os.ModePerm)
}
// get the video title
@@ -41,7 +42,7 @@ func Downloader(c *gin.Context) {
cleanTitle := cleanseTitle(titleOut.String())
log.Debug(cleanTitle)
cmd := exec.Command("youtube-dl", "-x", "--audio-format", "mp3", "-o", "./youtube/"+cleanTitle+".%(ext)s", url)
cmd := exec.Command("youtube-dl", "-x", "--audio-format", "mp3", "-o", config.Config.YoutubePath+"/"+cleanTitle+".%(ext)s", url)
var out bytes.Buffer
cmd.Stdout = &out

View File

@@ -11,8 +11,6 @@ import (
log "github.com/sirupsen/logrus"
)
var soundList []sound
type sound struct {
Prefix string `json:"prefix"`
Name string `json:"name"`
@@ -22,26 +20,39 @@ type sound struct {
// SoundList -
func SoundList(c *gin.Context) {
if len(soundList) < 1 {
err := PopulateSoundList()
if err != nil {
c.JSON(http.StatusInternalServerError, err)
return
}
soundList, err := readSoundsDir(config.Config.SoundsPath)
if err != nil {
log.Error(err)
c.JSON(http.StatusInternalServerError, err)
return
}
c.JSON(200, soundList)
}
// PopulateSoundList -
func PopulateSoundList() error {
// ClipList -
func ClipList(c *gin.Context) {
soundList = []sound{}
files, err := ioutil.ReadDir(config.Config.SoundsPath)
clipList, err := readSoundsDir(config.Config.ClipsPath)
if err != nil {
return err
log.Error(err)
c.JSON(http.StatusInternalServerError, err)
return
}
c.JSON(200, clipList)
}
func readSoundsDir(dir string) ([]sound, error) {
soundList := []sound{}
files, err := ioutil.ReadDir(dir)
if err != nil {
return soundList, err
}
for _, f := range files {
@@ -57,33 +68,5 @@ func PopulateSoundList() error {
soundList = append(soundList, listItem)
}
return nil
}
// ClipList -
func ClipList(c *gin.Context) {
clipList := []sound{}
files, err := ioutil.ReadDir(config.Config.ClipsPath)
if err != nil {
log.Error(err)
c.JSON(http.StatusInternalServerError, err)
return
}
for _, f := range files {
fileName := strings.Split(f.Name(), ".")[0]
extension := strings.Split(f.Name(), ".")[1]
listItem := sound{
Name: fileName,
Extension: extension,
}
clipList = append(clipList, listItem)
}
c.JSON(200, clipList)
return soundList, nil
}

View File

@@ -35,13 +35,13 @@ func FileUpload(c *gin.Context) {
file.Filename = strings.Replace(file.Filename, " ", "", -1)
// check if file already exists
if _, err := os.Stat(config.Config.SoundsPath + file.Filename); err == nil {
if _, err := os.Stat(config.Config.SoundsPath + "/" + file.Filename); err == nil {
c.JSON(http.StatusInternalServerError, "File already exists.")
return
}
err = c.SaveUploadedFile(file, config.Config.SoundsPath+file.Filename)
log.Debug("Saving file", config.Config.SoundsPath+file.Filename)
err = c.SaveUploadedFile(file, config.Config.SoundsPath+"/"+file.Filename)
log.Debug("Saving file", config.Config.SoundsPath+"/"+file.Filename)
if err != nil {
log.Error(err)
@@ -49,14 +49,5 @@ func FileUpload(c *gin.Context) {
return
}
// repopulate sound list
err = PopulateSoundList()
if err != nil {
log.Error(err)
c.JSON(http.StatusInternalServerError, "Error populating sound list.")
return
}
c.JSON(200, "Success")
}

View File

@@ -54,7 +54,7 @@ func GetJWT(user discord.User) (string, error) {
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(config.Config.JWTKey))
return token.SignedString([]byte(config.Config.JWTSecret))
}
func checkEmailPermissions(email string, emails []string) bool {
@@ -96,7 +96,7 @@ func AuthorizedJWT() gin.HandlerFunc {
// parse and verify token
token, err := jwt.ParseWithClaims(tokenString[1], &CustomClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(config.Config.JWTKey), nil
return []byte(config.Config.JWTSecret), nil
})
if err != nil {

View File

@@ -16,7 +16,7 @@ func getRouter() *gin.Engine {
router.StaticFS("/static", box)
router.Static("/public/sounds", config.Config.SoundsPath)
router.Static("/public/youtube", "./youtube")
router.Static("/public/youtube", config.Config.YoutubePath)
router.Static("/public/clips", config.Config.ClipsPath)
router.NoRoute(func(c *gin.Context) {