Skip to content

Commit

Permalink
Remove unnecessary log.Fatals and suboptimal os.Exits (thrasher-corp#343
Browse files Browse the repository at this point in the history
)

Engine fixes up the rest for exchange setup loading
  • Loading branch information
thrasher- authored Aug 27, 2019
1 parent c1ad765 commit c7ca29a
Show file tree
Hide file tree
Showing 7 changed files with 74 additions and 30 deletions.
59 changes: 48 additions & 11 deletions communications/telegram/telegram.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"errors"
"fmt"
"net/http"
"time"

"github.com/thrasher-corp/gocryptotrader/common"
"github.com/thrasher-corp/gocryptotrader/communications/base"
Expand Down Expand Up @@ -43,9 +44,16 @@ const (
talkRoot = "GoCryptoTrader bot"
)

var (
// ErrWaiter is the default timer to wait if an err occurs
// before retrying after successfully connecting
ErrWaiter = time.Second * 30
)

// Telegram is the overarching type across this package
type Telegram struct {
base.Base
initConnected bool
Token string
Offset int64
AuthorisedClients []int64
Expand All @@ -64,16 +72,19 @@ func (t *Telegram) Connect() error {
if err := t.TestConnection(); err != nil {
return err
}

log.Debugln("Telegram: Connected successfully!")
t.Connected = true
go t.PollerStart()
return nil
}

// PushEvent sends an event to a supplied recipient list via telegram
func (t *Telegram) PushEvent(event base.Event) error {
msg := fmt.Sprintf("Type: %s Details: %s GainOrLoss: %s",
event.Type, event.TradeDetails, event.GainLoss)
for i := range t.AuthorisedClients {
err := t.SendMessage(fmt.Sprintf("Type: %s Details: %s GainOrLoss: %s",
event.Type, event.TradeDetails, event.GainLoss), t.AuthorisedClients[i])
err := t.SendMessage(msg, t.AuthorisedClients[i])
if err != nil {
return err
}
Expand All @@ -83,20 +94,34 @@ func (t *Telegram) PushEvent(event base.Event) error {

// PollerStart starts the long polling sequence
func (t *Telegram) PollerStart() {
t.InitialConnect()
errWait := func(err error) {
log.Error(err)
time.Sleep(ErrWaiter)
}

for {
if !t.initConnected {
err := t.InitialConnect()
if err != nil {
errWait(err)
continue
}
t.initConnected = true
}

resp, err := t.GetUpdates()
if err != nil {
log.Error(err)
errWait(err)
continue
}

for i := range resp.Result {
if resp.Result[i].UpdateID > t.Offset {
if string(resp.Result[i].Message.Text[0]) == "/" {
err = t.HandleMessages(resp.Result[i].Message.Text, resp.Result[i].Message.From.ID)
if err != nil {
log.Error(err)
log.Errorf("Telegram: Unable to HandleMessages. Error: %s\n", err)
continue
}
}
t.Offset = resp.Result[i].UpdateID
Expand All @@ -107,14 +132,14 @@ func (t *Telegram) PollerStart() {

// InitialConnect sets offset, and sends a welcome greeting to any associated
// IDs
func (t *Telegram) InitialConnect() {
func (t *Telegram) InitialConnect() error {
resp, err := t.GetUpdates()
if err != nil {
log.Fatal(err)
return err
}

if !resp.Ok {
log.Fatal(resp.Description)
return errors.New(resp.Description)
}

warmWelcomeList := make(map[string]int64)
Expand All @@ -127,17 +152,25 @@ func (t *Telegram) InitialConnect() {
for userName, ID := range warmWelcomeList {
err = t.SendMessage(fmt.Sprintf("GoCryptoTrader bot has connected: Hello, %s!", userName), ID)
if err != nil {
log.Fatal(err)
log.Errorf("Telegram: Unable to send welcome message. Error: %s\n", err)
continue
}
}

if len(resp.Result) == 0 {
return
return nil
}

t.Offset = resp.Result[len(resp.Result)-1].UpdateID
return nil
}

// HandleMessages handles incoming message from the long polling routine
func (t *Telegram) HandleMessages(text string, chatID int64) error {
if t.Verbose {
log.Debugf("Telegram: Received message: %s\n", text)
}

switch {
case common.StringContains(text, cmdHelp):
return t.SendMessage(fmt.Sprintf("%s: %s", talkRoot, cmdHelpReply), chatID)
Expand All @@ -161,7 +194,7 @@ func (t *Telegram) HandleMessages(text string, chatID int64) error {
return t.SendMessage(fmt.Sprintf("%s: %s", talkRoot, t.GetPortfolio()), chatID)

default:
return t.SendMessage(fmt.Sprintf("command %s not recognized", text), chatID)
return t.SendMessage(fmt.Sprintf("Command %s not recognized", text), chatID)
}
}

Expand Down Expand Up @@ -214,6 +247,10 @@ func (t *Telegram) SendMessage(text string, chatID int64) error {
if !resp.Ok {
return errors.New(resp.Description)
}

if t.Verbose {
log.Debugf("Telegram: Sent '%s'\n", text)
}
return nil
}

Expand Down
16 changes: 6 additions & 10 deletions currency/coinmarketcap/coinmarketcap.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ package coinmarketcap
import (
"errors"
"fmt"
"log"
"net/http"
"net/url"
"strconv"
Expand Down Expand Up @@ -80,18 +79,15 @@ func (c *Coinmarketcap) SetDefaults() {
}

// Setup sets user configuration
func (c *Coinmarketcap) Setup(conf Settings) {
func (c *Coinmarketcap) Setup(conf Settings) error {
if !conf.Enabled {
c.Enabled = false
} else {
c.Enabled = true
c.Verbose = conf.Verbose
c.APIkey = conf.APIkey
err := c.SetAccountPlan(conf.AccountPlan)
if err != nil {
log.Fatal(err)
}
}

c.Enabled = true
c.Verbose = conf.Verbose
c.APIkey = conf.APIkey
return c.SetAccountPlan(conf.AccountPlan)
}

// GetCryptocurrencyInfo returns all static metadata for one or more
Expand Down
9 changes: 8 additions & 1 deletion currency/coinmarketcap/coinmarketcap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,14 @@ func TestSetup(t *testing.T) {
cfg.Enabled = true
cfg.AccountPlan = "basic"

c.Setup(cfg)
if err := c.Setup(cfg); err != nil {
t.Error(err)
}

cfg.AccountPlan = "meow"
if err := c.Setup(cfg); err == nil {
t.Error("expected err when invalid account plan is specified")
}
}

func TestCheckAccountPlan(t *testing.T) {
Expand Down
11 changes: 8 additions & 3 deletions currency/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,15 +116,20 @@ func (s *Storage) RunUpdater(overrides BotOverrides, settings *MainConfiguration
log.Debugf("Setting up currency analysis system with Coinmarketcap...")
c := &coinmarketcap.Coinmarketcap{}
c.SetDefaults()
c.Setup(coinmarketcap.Settings{
err := c.Setup(coinmarketcap.Settings{
Name: settings.CryptocurrencyProvider.Name,
Enabled: true,
AccountPlan: settings.CryptocurrencyProvider.AccountPlan,
APIkey: settings.CryptocurrencyProvider.APIkey,
Verbose: settings.CryptocurrencyProvider.Verbose,
})

s.currencyAnalysis = c
if err != nil {
log.Errorf("Unable to setup CoinMarketCap analysis. Error: %s", err)
c = nil
settings.CryptocurrencyProvider.Enabled = false
} else {
s.currencyAnalysis = c
}
}

if filePath == "" {
Expand Down
3 changes: 0 additions & 3 deletions exchange.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,4 @@ func SetupExchanges() {
)
}
wg.Wait()
if len(bot.exchanges) == 0 {
log.Fatalf("No exchanges were able to be loaded. Exiting")
}
}
3 changes: 1 addition & 2 deletions exchanges/mock/recording.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"errors"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
Expand Down Expand Up @@ -163,7 +162,7 @@ func HTTPRecord(res *http.Response, service string, respContents []byte) error {

mockRespVals, urlErr := url.ParseQuery(mockResponses[i].BodyParams)
if urlErr != nil {
log.Fatal(urlErr)
return urlErr
}

if MatchURLVals(respQueryVals, mockRespVals) {
Expand Down
3 changes: 3 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,9 @@ func main() {
log.Debugf("Global HTTP request timeout: %v.\n", common.HTTPClient.Timeout)

SetupExchanges()
if len(bot.exchanges) == 0 {
log.Fatal("No exchanges were able to be loaded. Exiting")
}

log.Debugf("Starting communication mediums..")
cfg := bot.config.GetCommunicationsConfig()
Expand Down

0 comments on commit c7ca29a

Please sign in to comment.