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

     1  package bcr
     2  
     3  import (
     4  	"strings"
     5  
     6  	"github.com/diamondburned/arikawa/v3/discord"
     7  )
     8  
     9  // Log is an updateable log message
    10  type Log struct {
    11  	ctx    *Context
    12  	logger *Logger
    13  
    14  	msg *discord.Message
    15  
    16  	title string
    17  	color discord.Color
    18  
    19  	logs []string
    20  }
    21  
    22  // NewLog creates a new Log
    23  func (ctx *Context) NewLog(title string) *Log {
    24  	return &Log{
    25  		ctx:    ctx,
    26  		logger: ctx.Router.Logger,
    27  
    28  		title: title,
    29  		color: ColourBlue,
    30  	}
    31  }
    32  
    33  // Send ...
    34  func (log *Log) Send() {
    35  	e := discord.Embed{
    36  		Title:       log.title,
    37  		Color:       log.color,
    38  		Description: strings.Join(log.logs, "\n"),
    39  	}
    40  
    41  	if log.msg == nil {
    42  		m, err := log.ctx.Send("", e)
    43  		if err != nil {
    44  			log.logger.Error("Error sending log message: %v", err)
    45  		}
    46  		log.msg = m
    47  		return
    48  	}
    49  
    50  	_, err := log.ctx.Edit(log.msg, "", true, e)
    51  	if err != nil {
    52  		log.logger.Error("Error sending log message: %v", err)
    53  	}
    54  	return
    55  }
    56  
    57  // Log logs a normal message
    58  func (log *Log) Log(msg string) {
    59  	log.logs = append(log.logs, msg)
    60  	log.logger.Info(msg)
    61  	log.Send()
    62  }
    63  
    64  // Error logs an error message
    65  func (log *Log) Error(msg string) {
    66  	log.color = ColourRed
    67  	log.logs = append(log.logs, msg)
    68  	log.logger.Error(msg)
    69  	log.Send()
    70  }
    71  
    72  // Replace replaces the latest message
    73  func (log *Log) Replace(msg string) {
    74  	log.logger.Info(msg)
    75  
    76  	if len(log.logs) == 0 {
    77  		log.logs = append(log.logs, msg)
    78  	} else {
    79  		log.logs[len(log.logs)-1] = msg
    80  	}
    81  	log.Send()
    82  }
    83  
    84  // SetTitle ...
    85  func (log *Log) SetTitle(title string) {
    86  	log.title = title
    87  }
    88  
    89  // SetColor ...
    90  func (log *Log) SetColor(color discord.Color) {
    91  	log.color = color
    92  }