github.com/sharovik/devbot@v1.0.1-0.20240308094637-4a0387c40516/events/examplescenario/event.go (about)

     1  package examplescenario
     2  
     3  import (
     4  	"fmt"
     5  	"regexp"
     6  	"time"
     7  
     8  	"github.com/sharovik/devbot/internal/service/message/conversation"
     9  
    10  	"github.com/sharovik/devbot/internal/database"
    11  	"github.com/sharovik/devbot/internal/helper"
    12  
    13  	"github.com/sharovik/devbot/internal/log"
    14  
    15  	"github.com/sharovik/devbot/internal/container"
    16  	"github.com/sharovik/devbot/internal/dto"
    17  )
    18  
    19  const (
    20  	//EventName the name of the event
    21  	EventName = "examplescenario"
    22  
    23  	//EventVersion the version of the event
    24  	EventVersion = "1.0.0"
    25  
    26  	helpMessage = "Ask me `write a message` and you will see the answer."
    27  
    28  	regexChannel = `(?im)(?:[<#@]|(?:&lt;))(\w+)(?:[|>]|(?:&gt;))`
    29  
    30  	stepMessage = "What I need to write?"
    31  	stepChannel = "Where I need to post this message? If it's channel, the channel should be public."
    32  )
    33  
    34  // EventStruct the struct for the event object. It will be used for initialisation of the event in defined-events.go file.
    35  type EventStruct struct {
    36  }
    37  
    38  // Event - object which is ready to use
    39  var Event = EventStruct{}
    40  
    41  // Help retrieves the help message
    42  func (e EventStruct) Help() string {
    43  	return helpMessage
    44  }
    45  
    46  // Alias retrieves the event alias
    47  func (e EventStruct) Alias() string {
    48  	return EventName
    49  }
    50  
    51  // Execute method which is called by message processor
    52  func (e EventStruct) Execute(message dto.BaseChatMessage) (dto.BaseChatMessage, error) {
    53  	currentConversation := conversation.GetConversation(message.Channel)
    54  
    55  	whatToWrite := ""
    56  	whereToWrite := ""
    57  
    58  	//If we don't have all variables for our conversation, that means, we didn't receive answers for all questions of our scenario
    59  	if len(currentConversation.Scenario.RequiredVariables) != 2 {
    60  		message.Text = "Not all variables are defined."
    61  
    62  		return message, nil
    63  	}
    64  
    65  	if currentConversation.Scenario.RequiredVariables[0].Value != "" {
    66  		whatToWrite = removeCurrentUserFromTheMessage(currentConversation.Scenario.RequiredVariables[0].Value)
    67  	}
    68  
    69  	if currentConversation.Scenario.RequiredVariables[1].Value != "" {
    70  		whereToWrite = extractChannelName(currentConversation.Scenario.RequiredVariables[1].Value)
    71  
    72  		if whereToWrite == "" {
    73  			message.Text = "Something went wrong and I can't parse properly the channel name."
    74  			return message, nil
    75  		}
    76  	}
    77  
    78  	_, _, err := container.C.MessageClient.SendMessage(dto.BaseChatMessage{
    79  		Channel:           whereToWrite,
    80  		Text:              whatToWrite,
    81  		AsUser:            true,
    82  		Ts:                time.Now(),
    83  		DictionaryMessage: dto.DictionaryMessage{},
    84  		OriginalMessage:   dto.BaseOriginalMessage{},
    85  	})
    86  
    87  	if err != nil {
    88  		log.Logger().AddError(err).Msg("Failed to send post-answer for selected event")
    89  		message.Text = fmt.Sprintf("Failed to send the message to the channel %s.\nReason: ```%s```", currentConversation.Scenario.RequiredVariables[1].Value, err.Error())
    90  		return message, err
    91  	}
    92  
    93  	//This answer will be show once the event get triggered.
    94  	//Leave message.Text empty, once you need to not show the message, once this event get triggered.
    95  	message.Text = "Done"
    96  
    97  	return message, nil
    98  }
    99  
   100  func extractChannelName(text string) string {
   101  	matches := helper.FindMatches(regexChannel, text)
   102  	if len(matches) == 0 {
   103  		return ""
   104  	}
   105  
   106  	if matches["1"] == "" {
   107  		return ""
   108  	}
   109  
   110  	return matches["1"]
   111  }
   112  
   113  // Install method for installation of event
   114  func (e EventStruct) Install() error {
   115  	log.Logger().Debug().
   116  		Str("event_name", EventName).
   117  		Str("event_version", EventVersion).
   118  		Msg("Triggered event installation")
   119  
   120  	if err := container.C.Dictionary.InstallNewEventScenario(database.EventScenario{
   121  		EventName:    EventName,
   122  		EventVersion: EventVersion,
   123  		Questions: []database.Question{
   124  			{
   125  				Question:      "write a message",
   126  				QuestionRegex: "(?i)(write a message)",
   127  			},
   128  			{
   129  				Question:      "write message",
   130  				QuestionRegex: "(?i)(write message)",
   131  			},
   132  		},
   133  		RequiredVariables: []database.ScenarioVariable{
   134  			{
   135  				Question: stepMessage,
   136  			},
   137  			{
   138  				Question: stepChannel,
   139  			},
   140  		},
   141  	}); err != nil {
   142  		return err
   143  	}
   144  
   145  	return nil
   146  }
   147  
   148  // Update for event update actions
   149  func (e EventStruct) Update() error {
   150  	return nil
   151  }
   152  
   153  func removeCurrentUserFromTheMessage(message string) string {
   154  	regexString := fmt.Sprintf("(?im)(<@%s>)", container.C.Config.MessagesAPIConfig.BotUserID)
   155  	re := regexp.MustCompile(regexString)
   156  	result := re.ReplaceAllString(message, ``)
   157  
   158  	return result
   159  }