Skip to content

Commit

Permalink
add option to pass custom http.Client to tb.NewBot() in case of proxy…
Browse files Browse the repository at this point in the history
…ing and other needs
  • Loading branch information
sigurniv committed Apr 18, 2018
1 parent 2a7e904 commit 5f938b2
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 4 deletions.
4 changes: 2 additions & 2 deletions api.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ func (b *Bot) Raw(method string, payload interface{}) ([]byte, error) {
return []byte{}, wrapSystem(err)
}

resp, err := http.Post(url, "application/json", &buf)
resp, err := b.client.Post(url, "application/json", &buf)
if err != nil {
return []byte{}, errors.Wrap(err, "http.Post failed")
}
Expand Down Expand Up @@ -85,7 +85,7 @@ func (b *Bot) sendFiles(

req.Header.Add("Content-Type", writer.FormDataContentType())

resp, err := http.DefaultClient.Do(req)
resp, err := b.client.Do(req)
if err != nil {
return nil, errors.Wrap(err, "http.Post failed")
}
Expand Down
10 changes: 10 additions & 0 deletions bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ func NewBot(pref Settings) (*Bot, error) {
pref.Updates = 100
}

client := pref.Client
if client == nil {
client = http.DefaultClient
}

bot := &Bot{
Token: pref.Token,
Updates: make(chan Update, pref.Updates),
Expand All @@ -28,6 +33,7 @@ func NewBot(pref Settings) (*Bot, error) {
handlers: make(map[string]interface{}),
stop: make(chan struct{}),
reporter: pref.Reporter,
client:client,
}

user, err := bot.getMe()
Expand All @@ -49,6 +55,7 @@ type Bot struct {
handlers map[string]interface{}
reporter func(error)
stop chan struct{}
client *http.Client
}

// Settings represents a utility struct for passing certain
Expand All @@ -66,6 +73,9 @@ type Settings struct {
// Reporter is a callback function that will get called
// on any panics recovered from endpoint handlers.
Reporter func(error)

// HTTP Client used to make requests to telegram api
Client *http.Client
}

// Update object represents an incoming update.
Expand Down
17 changes: 15 additions & 2 deletions telebot_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,21 @@ func TestBot(t *testing.T) {
}
}

func TestRecipient(_ *testing.T) {
bot := Bot{}
func TestRecipient(t *testing.T) {
token := os.Getenv("TELEBOT_SECRET")
if token == "" {
fmt.Println("ERROR: " +
"In order to test telebot functionality, you need to set up " +
"TELEBOT_SECRET environmental variable, which represents an API " +
"key to a Telegram bot.\n")
t.Fatal("Could't find TELEBOT_SECRET, aborting.")
}

bot, err := NewBot(Settings{Token: token})
if err != nil {
t.Fatal("couldn't create bot:", err)
}

bot.Send(&User{}, "")
bot.Send(&Chat{}, "")
}
Expand Down

0 comments on commit 5f938b2

Please sign in to comment.