|
| 1 | +package twitterbot |
| 2 | + |
| 3 | +import ( |
| 4 | + "errors" |
| 5 | + "fmt" |
| 6 | + "io/ioutil" |
| 7 | + "log" |
| 8 | + "net/http" |
| 9 | + |
| 10 | + "github.com/Azure/go-autorest/autorest" |
| 11 | +) |
| 12 | + |
| 13 | +// BotClient is a simple wrapper for writing messages on GroupMe |
| 14 | +type BotClient struct { |
| 15 | + botID string |
| 16 | +} |
| 17 | + |
| 18 | +// NewBotClient returns a configured BotClient suitable for use |
| 19 | +func NewBotClient(botID string) (*BotClient, error) { |
| 20 | + if botID == "" { |
| 21 | + return nil, errors.New("Can't instantiate a bot client with no botID") |
| 22 | + } else { |
| 23 | + return &BotClient{ |
| 24 | + botID: botID, |
| 25 | + }, nil |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +// botMessage is a simplified message body for some text sent on behalf of a bot. |
| 30 | +type botMessage struct { |
| 31 | + BotID string `json:"bot_id"` |
| 32 | + Text string `json:"text"` |
| 33 | +} |
| 34 | + |
| 35 | +// SendMessage posts a message on behalf of a bot. If the message is empty, an error will be returned |
| 36 | +func (bc *BotClient) SendMessage(message string) error { |
| 37 | + req, err := autorest.Prepare(&http.Request{}, |
| 38 | + autorest.WithBaseURL("https://api.groupme.com/v3/bots/post"), |
| 39 | + autorest.WithMethod("POST"), |
| 40 | + autorest.WithHeader("Content-Type", "application/json"), |
| 41 | + autorest.WithJSON(botMessage{ |
| 42 | + BotID: bc.botID, |
| 43 | + Text: message, |
| 44 | + }), |
| 45 | + ) |
| 46 | + if err != nil { |
| 47 | + return fmt.Errorf("Unable to construct request to send message on behalf of bot: %w", err) |
| 48 | + } |
| 49 | + |
| 50 | + resp, err := autorest.Send(req) |
| 51 | + if err != nil { |
| 52 | + return fmt.Errorf("Error sending request to create a message: %w", err) |
| 53 | + } |
| 54 | + |
| 55 | + if resp.StatusCode != http.StatusAccepted { |
| 56 | + bytes, _ := ioutil.ReadAll(resp.Body) |
| 57 | + log.Fatal("Bad response code from GroupMe:", string(bytes)) |
| 58 | + err := fmt.Errorf("Unexpected HTTP status code when creating message: %d", resp.StatusCode) |
| 59 | + return err |
| 60 | + } |
| 61 | + |
| 62 | + return nil |
| 63 | +} |
0 commit comments