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

use permissions from database - updated bot-scripts

This commit is contained in:
2018-10-20 13:42:37 -05:00
parent 3f650e7c65
commit b004d4f29a
15 changed files with 126 additions and 57 deletions

3
.gitignore vendored
View File

@@ -3,7 +3,8 @@ dist
node_modules
yarn-error*
vendor
bot
/bot
/bot-scripts
debug
go-discord-bot
.wwp-cache

View File

@@ -15,7 +15,8 @@ RUN apk add --no-cache git alpine-sdk pkgconfig opus-dev opusfile-dev
RUN go get -u github.com/gobuffalo/packr/...
RUN go get -u github.com/golang/dep/cmd/dep
RUN dep ensure
RUN packr build -o /build/server
RUN packr build -o /build/bot
RUN go build -o /build/bot-scripts ./scripts
FROM wernight/youtube-dl
@@ -24,6 +25,6 @@ RUN apk update
RUN apk add ca-certificates opus-dev opusfile-dev
WORKDIR /bot
COPY --from=1 /build/server /
COPY --from=1 /build /server
ENTRYPOINT ["/server"]
ENTRYPOINT ["/server/bot"]

View File

@@ -7,11 +7,6 @@
"bot_prefix": "#",
"admin_emails": ["mail@example.com"],
"mod_emails": ["mail@example.com"],
"jwt_secret": "generate a random secret string here",
"server_addr": "0.0.0.0:80",
"logger": true
"server_addr": "0.0.0.0:80"
}

View File

@@ -5,6 +5,9 @@ install:
build-server:
cd ./server && packr build -o ../bot ./main.go
build-scripts:
go build -o bot-scripts ./server/scripts
build-client:
cd client && npm run build

View File

@@ -33,6 +33,22 @@ services:
- <path to your data directory>:/bot
```
#### Running Bot Scripts
Use the following scripts
- restore-messages
- used to search message history and store in database
- update-db
- used to run additional DB change scripts (will likely never have to be run)
Example:
```
docker-compose exec go-discord-bot /server/bot-scripts update-db
docker-compose exec go-discord-bot /server/bot-scripts restore-message <roomID>
```
### Commands
- `clip` - clips the past minute of audio (currently bugged if more than one user is speaking)

9
server/Gopkg.lock generated
View File

@@ -94,6 +94,14 @@
pruneopts = "UT"
revision = "0f2e0b4fc6cd5710fddbb74ba2e5e02c1c1bc22b"
[[projects]]
branch = "master"
digest = "1:5c3444689562053b027ef3b96372e306adbe0d7d109b6cdd48d01eb80f8bab14"
name = "github.com/jinzhu/copier"
packages = ["."]
pruneopts = "UT"
revision = "7e38e58719c33e0d44d585c4ab477a30f8cb82dd"
[[projects]]
digest = "1:2a21d36a5ab33e6e4ce82b3c7ba45c2330ca6e9af247382475e056b06395b8a9"
name = "github.com/jinzhu/gorm"
@@ -287,6 +295,7 @@
"github.com/go-audio/wav",
"github.com/gobuffalo/packr",
"github.com/hraban/opus",
"github.com/jinzhu/copier",
"github.com/jinzhu/gorm",
"github.com/jinzhu/gorm/dialects/sqlite",
"github.com/rylio/ytdl",

View File

@@ -64,6 +64,10 @@
name = "gopkg.in/dgrijalva/jwt-go.v3"
version = "3.2.0"
[[constraint]]
branch = "master"
name = "github.com/jinzhu/copier"
[prune]
go-tests = true
unused-packages = true

View File

@@ -16,10 +16,7 @@ func Start(token string) *discordgo.Session {
// add bot handlers
addHandler(session, bothandlers.SoundsHandler)
if config.Config.Logger {
addHandler(session, bothandlers.LoggerHandler)
}
addHandler(session, bothandlers.LoggerHandler)
// start listening for commands
startListener(session)

View File

@@ -13,17 +13,14 @@ var (
)
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"`
DefaultRoomID string `json:"default_room_id"`
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
ServerAddr string `json:"server_addr"`
JWTSecret string `json:"jwt_secret"`
DefaultRoomID string `json:"default_room_id"`
// hard coded folder paths
SoundsPath string

27
server/scripts/main.go Normal file
View File

@@ -0,0 +1,27 @@
package main
import (
"fmt"
"os"
)
func main() {
if len(os.Args) == 1 {
fmt.Print("Error - Invalid Args\n\nPossible Args:\nrestore-message\nupdate-db\n\n")
return
}
arg := os.Args[1]
switch arg {
case "update-db":
updateDB()
case "restore-messages":
if len(os.Args) < 3 {
fmt.Println("Please provide a channel id")
return
}
restoreMessages(os.Args[2])
}
}

View File

@@ -1,5 +1,9 @@
package main
/**
This script will fetch all messages for the provided channel and store them in the database.
*/
import (
"log"
@@ -10,13 +14,15 @@ import (
"github.com/mgerb/go-discord-bot/server/db"
)
const everyoneChannel = "101198129352691712"
// var everyoneChannel = "101198129352691712"
var everyoneChannel string
// this is a script to go through chat history and log old message into database
func main() {
func restoreMessages(channelID string) {
config.Init()
db.Init()
session := bot.Start(config.Config.Token)
everyoneChannel = channelID
fetchMessages(session, "")
}

View File

@@ -0,0 +1,25 @@
package main
import (
"fmt"
"github.com/mgerb/go-discord-bot/server/db"
)
// keep change script embedded in go files for ease of use
const changeScript = `
-- script to update all users default permission to a value of 1 (user)
UPDATE users SET permissions = 1 WHERE permissions IS NULL OR permissions = 0;
`
func updateDB() {
db.Init()
conn := db.GetConn()
err := conn.Exec(changeScript).Error
if err != nil {
fmt.Println(err)
}
}

View File

@@ -31,22 +31,12 @@ type CustomClaims struct {
// GetJWT - get json web token
func GetJWT(user model.User) (string, error) {
permissions := PermUser
if checkEmailPermissions(user.Email, config.Config.ModEmails) {
permissions = PermMod
}
if checkEmailPermissions(user.Email, config.Config.AdminEmails) {
permissions = PermAdmin
}
claims := CustomClaims{
user.ID,
user.Username,
user.Discriminator,
user.Email,
permissions,
*user.Permissions,
jwt.StandardClaims{
ExpiresAt: time.Now().AddDate(0, 1, 0).Unix(), // one month
Issuer: "Go Discord Bot",
@@ -57,15 +47,6 @@ func GetJWT(user model.User) (string, error) {
return token.SignedString([]byte(config.Config.JWTSecret))
}
func checkEmailPermissions(email string, emails []string) bool {
for _, e := range emails {
if email == e {
return true
}
}
return false
}
// AuthPermissions - secure end points based on auth levels
func AuthPermissions(p int) gin.HandlerFunc {
return func(c *gin.Context) {

View File

@@ -3,6 +3,7 @@ package model
import (
"time"
"github.com/jinzhu/copier"
"github.com/jinzhu/gorm"
)
@@ -20,9 +21,15 @@ type User struct {
Verified bool `json:"verified"`
MFAEnabled bool `json:"mfa_enabled"`
Bot bool `json:"bot"`
Permissions *int `gorm:"default:1;not null" json:"permissions"`
}
// UserSave -
func UserSave(conn *gorm.DB, u *User) error {
return conn.Save(u).Error
var userCopy User
copier.Copy(&userCopy, u)
// insert or update user
// need to make copy of assign object because it must mess
// with the actual object in FirstOrCreate method
return conn.Where(&User{ID: u.ID}).Assign(userCopy).FirstOrCreate(u).Error
}

View File

@@ -9,8 +9,6 @@ import (
log "github.com/sirupsen/logrus"
)
const cashGuildID = "101198129352691712"
type oauthReq struct {
Code string `json:"code"`
}
@@ -50,6 +48,15 @@ func oauthHandler(c *gin.Context) {
return
}
// save/update user in database
err = model.UserSave(db.GetConn(), &user)
if err != nil {
log.Error(err)
c.JSON(500, err)
return
}
// generate json web token
token, err := middleware.GetJWT(user)
@@ -59,12 +66,5 @@ func oauthHandler(c *gin.Context) {
return
}
// save/update user in database
err = model.UserSave(db.GetConn(), &user)
if err != nil {
log.Error(err)
}
c.JSON(200, token)
}