Ver Fonte

Added admin and hidden routes that can be hidden from help

Mathew Medoff há 3 anos atrás
pai
commit
6062b5d7fa
6 ficheiros alterados com 71 adições e 90 exclusões
  1. 12 73
      bot/event/mux/help.go
  2. 1 3
      bot/event/mux/message.go
  3. 38 14
      bot/event/mux/router.go
  4. 6 0
      go.mod
  5. 13 0
      go.sum
  6. 1 0
      session.go

+ 12 - 73
bot/event/mux/help.go

@@ -25,9 +25,20 @@ func (r *Router) helpCommandHandler(s *discordgo.Session, m *discordgo.Message,
 	catMap := make(map[string][]string)
 	var cats []string
 
+	var isAdmin = r.isAdminRoute(s, m, ctx)
+
 	for _, v := range r.categories {
 		keys := make([]string, 0, len(r.routes))
 		for _, route := range r.routes {
+			// If the route is hidde, do not add it to the help list
+			if route.Hidden {
+				continue
+			}
+
+			if route.Admin && !isAdmin {
+				continue
+			}
+
 			if route.CategoryID == v.ID {
 				l := len(route.Usage) // TODO: Add the +args part :)
 				if l > maxDisplayLen {
@@ -54,10 +65,6 @@ func (r *Router) helpCommandHandler(s *discordgo.Session, m *discordgo.Message,
 			}
 			cmdmap[route.Name] = route
 
-			if route.Name == "help" || route.Name == "about" {
-				continue
-			}
-
 			keys = append(keys, route.Name)
 		}
 	}
@@ -88,7 +95,7 @@ func (r *Router) helpCommandHandler(s *discordgo.Session, m *discordgo.Message,
 		if catKey != "" {
 			resp += fmt.Sprintf("\n%s\n", catKey)
 		} else {
-			resp += fmt.Sprint("\n\n")
+			resp += "\n\n"
 		}
 
 		routes := catMap[catKey]
@@ -100,72 +107,4 @@ func (r *Router) helpCommandHandler(s *discordgo.Session, m *discordgo.Message,
 
 	resp += "```\n"
 	s.ChannelMessageSend(m.ChannelID, resp)
-
-	return
-}
-
-func (r *Router) helpCommandHandlerOld(s *discordgo.Session, m *discordgo.Message, ctx *Context) {
-	displayPrefix := ""
-
-	switch ctx.Method {
-	case DirectMethod:
-		displayPrefix = ""
-	case PrefixMethod:
-		displayPrefix = r.prefix
-	case MentionMethod:
-		displayPrefix = fmt.Sprintf("@%s ", s.State.User.Username)
-	}
-
-	// Sort commands
-	maxDisplayLen := 0
-	keys := make([]string, 0, len(r.routes))
-	cmdmap := make(map[string]*route)
-
-	for _, v := range r.routes {
-		// Only display commands with a description
-		if v.Description == "" {
-			continue
-		}
-
-		// Calculate the max length of command+args string
-		l := len(v.Usage) // TODO: Add the +args part :)
-		if l > maxDisplayLen {
-			maxDisplayLen = l
-		}
-
-		cmdmap[v.Name] = v
-
-		// help and about are added separately below.
-		if v.Name == "help" || v.Name == "about" {
-			continue
-		}
-
-		keys = append(keys, v.Name)
-	}
-
-	sort.Strings(keys)
-
-	// TODO: Learn more link needs to be configurable
-	resp := "```autoit\n"
-
-	v, ok := cmdmap["help"]
-	if ok {
-		keys = append([]string{v.Name}, keys...)
-	}
-
-	v, ok = cmdmap["about"]
-	if ok {
-		keys = append([]string{v.Name}, keys...)
-	}
-
-	// Add sorted result to help msg
-	for _, k := range keys {
-		v := cmdmap[k]
-		resp += fmt.Sprintf("%s%-"+strconv.Itoa(maxDisplayLen)+"s # %s\n", displayPrefix, v.Usage, v.Description)
-	}
-
-	resp += "```\n"
-	s.ChannelMessageSend(m.ChannelID, resp)
-
-	return
 }

+ 1 - 3
bot/event/mux/message.go

@@ -31,9 +31,7 @@ func (r *Router) OnMessageCreate(s *discordgo.Session, m *discordgo.MessageCreat
 		channel, err = s.Channel(m.ChannelID)
 		if err != nil {
 		} else {
-			err = s.State.ChannelAdd(channel)
-			if err != nil {
-			}
+			_ = s.State.ChannelAdd(channel)
 		}
 	}
 

+ 38 - 14
bot/event/mux/router.go

@@ -15,6 +15,8 @@ type RouteOptions struct {
 	Category    string    // The category to put the route under
 	Type        RouteType // The type of route this is
 	Callback    Handler   // route handler function to call
+	Hidden      bool      // The route is hidden from the help menu'
+	Admin       bool      // The route is only visible to admins
 }
 
 type route struct {
@@ -24,6 +26,8 @@ type route struct {
 	CategoryID  int
 	Type        RouteType
 	Run         Handler
+	Hidden      bool
+	Admin       bool
 }
 
 type category struct {
@@ -42,15 +46,15 @@ const (
 
 // Handler is the function signature required for a message route handler.
 type Handler func(*discordgo.Session, *discordgo.Message, *Context)
+type IsAdminRouteHandler func(*discordgo.Session, *discordgo.Message, *Context) bool
 
 // Context holds a bit of extra data we pass along to route handlers
 // This way processing some of this only needs to happen once.
 type Context struct {
-	Fields          []string
-	Args            []string
-	Content         string
-	isDirectMessage bool // Indicates the message was sent via direct message
-	Method          Method
+	Fields  []string
+	Args    []string
+	Content string
+	Method  Method
 }
 
 // Method is the method a command was received
@@ -67,16 +71,19 @@ const (
 
 // Router is the main struct for all mux methods.
 type Router struct {
-	routes     []*route
-	helpRoute  *route
-	prefix     string
-	categories []*category
+	routes       []*route
+	helpRoute    *route
+	prefix       string
+	categories   []*category
+	isAdminRoute IsAdminRouteHandler // the admin check handler func to call
 }
 
 // New returns a new Discord message route mux
 func New() *Router {
 	r := &Router{}
 
+	r.isAdminRoute = isAdminRouteDefault
+
 	helpRoute := &route{}
 	helpRoute.Name = "help"
 	helpRoute.Usage = "help"
@@ -93,14 +100,18 @@ func (r *Router) SetCommandPrefix(cmdPrefix string) {
 	r.prefix = cmdPrefix + " "
 }
 
+func (r *Router) SetAdminRouteCallback(callback IsAdminRouteHandler) {
+	r.isAdminRoute = callback
+}
+
 // ErrRegisterRouteNameRequired is returned when registering a new route without a name
-var ErrRegisterRouteNameRequired = errors.New("All routes must have a name")
+var ErrRegisterRouteNameRequired = errors.New("all routes must have a name")
 
 // ErrRegisterInvalidRouteType is returned when registering a new route with an invalid type
-var ErrRegisterInvalidRouteType = errors.New("Invalid route type")
+var ErrRegisterInvalidRouteType = errors.New("invalid route type")
 
 // ErrRegisterCallbackRequired is returned when registering a new route without a callback
-var ErrRegisterCallbackRequired = errors.New("A valid callback must be provided")
+var ErrRegisterCallbackRequired = errors.New("a valid callback must be provided")
 
 // Register allows you to register a route
 //func (r *Router) Register(routeType RouteType, name, desc string, callback Handler) (*Route, error) {
@@ -123,6 +134,8 @@ func (r *Router) Register(name string, options RouteOptions) error {
 	route.Description = options.Description
 	route.Usage = options.Usage
 	route.Run = options.Callback
+	route.Hidden = options.Hidden
+	route.Admin = options.Admin
 
 	if options.Category != "" {
 		for _, category := range r.categories {
@@ -139,7 +152,7 @@ func (r *Router) Register(name string, options RouteOptions) error {
 }
 
 // ErrAddCategoryNameRequired is returned when registering a new route without a name
-var ErrAddCategoryNameRequired = errors.New("All categories must have a name")
+var ErrAddCategoryNameRequired = errors.New("all categories must have a name")
 
 // AddCategory allows you to a a router category
 func (r *Router) AddCategory(name, description string) error {
@@ -179,10 +192,21 @@ func (r *Router) findRoute(searchString string, routeType RouteType) (*route, []
 			continue
 		}
 
-		if strings.ToLower(commandKey) == strings.ToLower(route.Name) {
+		if strings.EqualFold(commandKey, route.Name) {
 			return route, fields[0:], fields[1:]
 		}
 	}
 
 	return nil, nil, nil
 }
+
+// Default callback for determining if the caller is an admin
+func isAdminRouteDefault(s *discordgo.Session, m *discordgo.Message, ctx *Context) bool {
+	channelPermissions, err := s.UserChannelPermissions(m.Author.ID, m.ChannelID)
+
+	if err != nil {
+		return false
+	}
+
+	return (channelPermissions&discordgo.PermissionAdministrator > 0)
+}

+ 6 - 0
go.mod

@@ -1,3 +1,9 @@
 module git.mgmcomp.net/thisnthat/discord
 
 go 1.14
+
+require (
+	git.mgmcomp.net/thisnthat/discordgo v0.0.0-20211006203217-5322d32875f4
+	github.com/gorilla/websocket v1.4.2 // indirect
+	golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 // indirect
+)

+ 13 - 0
go.sum

@@ -0,0 +1,13 @@
+git.mgmcomp.net/thisnthat/discordgo v0.0.0-20211006203217-5322d32875f4 h1:txbtCCEOuipIB0DgPubeTdw3igP+CR5Kl2gCKnYDf2M=
+git.mgmcomp.net/thisnthat/discordgo v0.0.0-20211006203217-5322d32875f4/go.mod h1:Mld4OR1WOQKeKYSMyYX3T18ilnCQCtwus+A1LoNcC50=
+github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc=
+github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
+golang.org/x/crypto v0.0.0-20210921155107-089bfa567519 h1:7I4JAnoQBe7ZtJcBaYHi5UtiO8tQHbUSXxL+pnGRANg=
+golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
+golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
+golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1 h1:SrN+KX8Art/Sf4HNj6Zcz06G7VEz+7w9tdXTPOZ7+l4=
+golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
+golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
+golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=

+ 1 - 0
session.go

@@ -5,6 +5,7 @@ import "git.mgmcomp.net/thisnthat/discordgo"
 // GetSession - Get a discord session from the provided token
 func GetSession(token string) (*discordgo.Session, error) {
 	session, err := discordgo.New("Bot " + token)
+	session.Identify.Intents = discordgo.MakeIntent(discordgo.IntentsAll)
 
 	// If we can not create the client then just fatal.
 	if err != nil {