github.com/status-im/status-go@v1.1.0/protocol/messenger_auto_message.go (about)

     1  package protocol
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"time"
     7  
     8  	"go.uber.org/zap"
     9  
    10  	"github.com/status-im/status-go/protocol/common"
    11  	"github.com/status-im/status-go/protocol/protobuf"
    12  	"github.com/status-im/status-go/signal"
    13  )
    14  
    15  // autoMessageInterval is how often we should send a message
    16  const autoMessageInterval = 120 * time.Second
    17  
    18  const autoMessageChatID = "status-bot"
    19  
    20  func (m *Messenger) AutoMessageEnabled() (bool, error) {
    21  	return m.settings.AutoMessageEnabled()
    22  }
    23  
    24  func (m *Messenger) startAutoMessageLoop() error {
    25  	enabled, err := m.AutoMessageEnabled()
    26  	if err != nil {
    27  		m.logger.Error("[auto message] failed to start auto message loop", zap.Error(err))
    28  		return err
    29  	}
    30  
    31  	if !enabled {
    32  		return nil
    33  	}
    34  
    35  	m.logger.Info("[auto message] starting auto message loop")
    36  	ticker := time.NewTicker(autoMessageInterval)
    37  	count := 0
    38  	go func() {
    39  		for {
    40  			select {
    41  			case <-ticker.C:
    42  				count++
    43  				timestamp := time.Now().Format(time.RFC3339)
    44  
    45  				msg := common.NewMessage()
    46  				msg.Text = fmt.Sprintf("%d\n%s", count, timestamp)
    47  				msg.ChatId = autoMessageChatID
    48  				msg.LocalChatID = autoMessageChatID
    49  				msg.ContentType = protobuf.ChatMessage_TEXT_PLAIN
    50  				resp, err := m.SendChatMessage(context.Background(), msg)
    51  				if err != nil {
    52  					m.logger.Error("[auto message] failed to send message", zap.Error(err))
    53  					continue
    54  				}
    55  				signal.SendNewMessages(resp)
    56  
    57  				err = m.UpdateMessageOutgoingStatus(msg.ID, common.OutgoingStatusDelivered)
    58  				if err != nil {
    59  					m.logger.Error("[auto message] failed to mark message as delivered", zap.Error(err))
    60  					continue
    61  				}
    62  
    63  				//send signal to client that message status updated
    64  				if m.config.messengerSignalsHandler != nil {
    65  					m.config.messengerSignalsHandler.MessageDelivered(autoMessageChatID, msg.ID)
    66  				}
    67  			case <-m.quit:
    68  				ticker.Stop()
    69  				return
    70  			}
    71  		}
    72  	}()
    73  
    74  	return nil
    75  }