github.com/starshine-sys/bcr@v0.21.0/message_create.go (about)

     1  package bcr
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/diamondburned/arikawa/v3/discord"
     7  	"github.com/diamondburned/arikawa/v3/gateway"
     8  )
     9  
    10  // MessageCreate gets called on new messages
    11  // - makes sure the router has a bot user
    12  // - checks if the message matches a prefix
    13  // - runs commands
    14  func (r *Router) MessageCreate(m *gateway.MessageCreateEvent) {
    15  	r.Logger.Debug("received new message (%v) in %v by %v#%v (%v)", m.ID, m.ChannelID, m.Author.Username, m.Author.Discriminator, m.Author.ID)
    16  
    17  	// set the bot user if not done already
    18  	if r.Bot == nil {
    19  		r.mustSetBotUser(m.GuildID)
    20  		r.Prefixes = append(r.Prefixes, fmt.Sprintf("<@%v>", r.Bot.ID), fmt.Sprintf("<@!%v>", r.Bot.ID))
    21  	}
    22  
    23  	// if the author is a bot, return
    24  	if m.Author.Bot {
    25  		return
    26  	}
    27  
    28  	// if the message does not start with any of the bot's prefixes (including mentions), return
    29  	if !r.MatchPrefix(m.Message) {
    30  		return
    31  	}
    32  
    33  	// get the context
    34  	ctx, err := r.NewContext(m)
    35  	if err != nil {
    36  		ctx.Router.Logger.Error("getting context: %v", err)
    37  		return
    38  	}
    39  
    40  	err = r.Execute(ctx)
    41  	if err != nil {
    42  		ctx.Router.Logger.Error("executing command: %v", err)
    43  		return
    44  	}
    45  }
    46  
    47  // mustSetBotUser sets the bot user in the router, panicking if it fails.
    48  // This is intended to be used in MessageCreate to simplify error handling
    49  func (r *Router) mustSetBotUser(guildID discord.GuildID) {
    50  	err := r.SetBotUser(guildID)
    51  	if err != nil {
    52  		panic(err)
    53  	}
    54  }
    55  
    56  // SetBotUser sets the router's bot user, returning any errors
    57  func (r *Router) SetBotUser(guildID discord.GuildID) error {
    58  	s, _ := r.StateFromGuildID(guildID)
    59  
    60  	me, err := s.Me()
    61  	if err != nil {
    62  		return err
    63  	}
    64  
    65  	r.Bot = me
    66  	return nil
    67  }