pushover

package module
v0.1.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 31, 2020 License: MIT Imports: 18 Imported by: 0

README

Pushover API for Go

Actions Status

This library allows programmatic access to the Pushover API with Go.

In a nutshell

Here are a few code snippets of how to use the Pushover API with Go.

Create a client
import (
    "github.com/olivere/pushover-api-go"
)

client, err := pushover.NewClient(
    pushover.WithAppToken("..."),
    pushover.WithUserKey("..."),
)
if err != nil {
    return fmt.Errorf("unable to create client: %w", err)
}
defer client.Close()
Send a message
msg := pushover.Message{
    Title:   "Invitation",
    Message: "Please come over to ...",
}
err := client.Messages.Send(context.Background(), msg)
if err != nil {
    return err
}

Command-line client

There is a simple command line client included to illustrate the usage of the client. To build it, run:

go build ./cmd/pushover

To get a list of all supported commands and sub-commands, run:

$ ./pushover help
Usage of ./pushover:

Global defaults:
  -d	Raw output of HTTP request/response to stderr
  -k	Accept insecure connections
  -v	Verbose output to stderr

Commands:
  env          Print environment
  send         Send a message

Here's an example of how to send a message with an attachment:

export APP_TOKEN=...
export USER_KEY=...
./pushover send -t "Introduction" -m "Here's an avatar of mine." -a ~/Pictures/Avatar.png

To get a list of all options of a command, add -h to the command, e.g.:

$ ./pushover send -h
Usage of ./pushover send:
  -a string
    	File to attach (optional)
  -d string
    	Device (optional)
  -expire duration
    	Expire duration (if priority is emergency) (default 5m0s)
  -html
    	Message is formatted as HTML
  -m string
    	Message to send
  -mono
    	Use monospace font for message
  -p string
    	Priority (lowest,low,normal,high, or emergency)
  -retry duration
    	Retry duration (if priority is emergency) (default 30s)
  -sound string
    	Sound to play (optional)
  -t string
    	Title (optional)
  -tags string
    	Tags (optional)
  -url string
    	URL (optional)
  -url-title string
    	URL title (optional)

License

MIT.

Documentation

Overview

Example
// Configure and create the client
client, err := pushover.NewClient()
if err != nil {
	panic(err)
}
defer client.Close()

// Run commands on the client
resp, err := client.Messages.Send(context.Background(), pushover.Message{
	Message: "Hello world!",
})
if err != nil {
	panic(err)
}
_ = resp
Output:

Index

Examples

Constants

View Source
const (
	// Version of the Pushover API for Go.
	Version = "0.1.1"
)

Variables

This section is empty.

Functions

func IsContextErr

func IsContextErr(err error) bool

IsContextErr returns true if the error is from a context that was canceled or its deadline exceeded.

func IsNotFound

func IsNotFound(err interface{}) bool

IsNotFound returns true if the given error indicates that a record could not be found.

func IsStatusCode

func IsStatusCode(err interface{}, code int) bool

IsStatusCode returns true if the given error indicates a specific HTTP status code. The err parameter can be of type *http.Response, an internal error, or int (indicating the HTTP status code).

Types

type Client

type Client struct {

	// Messages allows e.g. sending a notification.
	Messages *messagesAPI
	// contains filtered or unexported fields
}

Client represents a Pushover client.

func NewClient

func NewClient(options ...ClientOption) (*Client, error)

NewClient initializes and returns a configured Pushover client.

The client can be configured by options and will pick up the defaults from these environment variables (options override the environment):

APP_TOKEN      (default: "")
USER_KEY       (default: "")
PUSHOVER_URL   (default: "https://api.pushover.net")
Example (Default)
// NewClient will use these environment variables to construct the configuration
// - PUSHOVER_URL
// - APP_TOKEN
// - USER_KEY
client, err := pushover.NewClient()
if err != nil {
	panic(err)
}
defer client.Close()
Output:

Example (WithLogger)
// Log HTTP request and response to stderr
client, err := pushover.NewClient(
	pushover.WithLogger(pushover.NewRawLogger(os.Stderr)),
)
if err != nil {
	panic(err)
}
defer client.Close()
Output:

Example (WithTokenAndUser)
client, err := pushover.NewClient(
	pushover.WithAppToken("..."),
	pushover.WithUserKey("..."),
)
if err != nil {
	panic(err)
}
defer client.Close()
Output:

func (*Client) Close

func (c *Client) Close() error

Close the client.

func (*Client) Do

func (c *Client) Do(req *http.Request) (*http.Response, error)

Do executes the HTTP request.

func (*Client) Limits added in v0.1.1

func (c *Client) Limits() Limits

Limits returns the API limits as reported by the last API call. If you want to know the current limits without relying on the last API call, use Messages.Limits instead.

See https://pushover.net/api#limits for details.

type ClientOption

type ClientOption func(*Client)

ClientOption for configuring Client settings.

func WithAppToken

func WithAppToken(appToken string) ClientOption

WithAppToken sets the App Token (or API token) to use for this client.

func WithLogger

func WithLogger(logger Logger) ClientOption

WithLogger specifies a new logger.

func WithTransport

func WithTransport(tr http.RoundTripper) ClientOption

WithTransport allows to use HTTP middleware with a Client.

func WithURL

func WithURL(url string) ClientOption

WithURL specifies the base URL to use. It is primarily used in development or testing.

func WithUserKey

func WithUserKey(userKey string) ClientOption

WithUserKey sets the user key (or user/group key) to use for this client.

type JSONLogger

type JSONLogger struct {
	// contains filtered or unexported fields
}

JSONLogger logs output formatted as JSON.

func NewJSONLogger

func NewJSONLogger(w io.Writer) *JSONLogger

NewJSONLogger creates a new JSONLogger that writes to w.

func (*JSONLogger) Log

func (l *JSONLogger) Log(req *http.Request, resp *http.Response, err error, start time.Time, duration time.Duration) error

Log a roundtrip.

type Limits added in v0.1.1

type Limits struct {
	Limit     int64     `json:"limit"`
	Remaining int64     `json:"remaining"`
	Reset     int64     `json:"reset"`
	ResetTime time.Time `json:"-"`
}

Limits represents the API limits of the current application, i.e the current call limit, the number of remaining calls, and the time when the limits are reset.

See https://pushover.net/api#limits for details.

type Logger

type Logger interface {
	// Log request, response, error, start and duration of request.
	Log(*http.Request, *http.Response, error, time.Time, time.Duration) error
}

Logger specifies an interface for log output.

type Message

type Message struct {
	// Message to send. You can use up to 1024 4-byte UTF-8 characters here.
	// Longer messages are automatically truncated.
	Message string
	// HTML enables or disables HTML formatting in the Message (default: false).
	HTML bool
	// Monospace, when enabled, formats the message with a monospace font (default: false).
	Monospace bool
	// Title of the message (optional). If missing, it will use
	// the name of the app. The maximum length is 250 4-byte UTF-8 characters,
	// which will be automatically truncated.
	Title string
	// Attachment (optional) is the name of a file to be attached.
	Attachment string
	// Devices is the names of the devices (optional). By default,
	// the message is sent to all devices.
	Devices []string
	// URL to be shown as a supplement in the message (optional).
	// Use a maximum length of 512 4-byte UTF-8 characters, otherwise
	// the URL will be automatically truncated.
	URL string
	// URLTitle is a title to be shown for the URL (optional).
	// If missing, only the URL will be shown. URLTitle has a
	// maximum length of 100 4-byte UTF-8 characters and will
	// be automatically truncated.
	URLTitle string
	// Priority of the message (optional). By default, we use a Normal priority.
	//
	// If the Priority is Emergency, you must supply Retry and Expire as
	// described https://pushover.net/api#priority.
	Priority Priority
	// Sound to be played (optional).
	Sound string
	// Timestamp specifies the date/time of the message rather than the
	// time your message is received by the API servers (optional).
	Timestamp time.Time

	// Retry is used only when Priority is set to Emergency, in combination
	// with Expire. Retry specifies how often (in seconds) the Pushover
	// servers will send the same notification to the user (a minimum of 30 seconds
	// is enforced).
	//
	// For details, see https://pushover.net/api#priority.
	Retry time.Duration
	// Expire is used when Priority is set to Emergency, in combination with Retry.
	// Expire specifies how many seconds your notification will continue to be retried
	// (every Retry seconds). A maximum of 3 hours or 10800 seconds is enforced.
	//
	// For details, see https://pushover.net/api#priority.
	Expire time.Duration

	// CallbackURL, if set, specifies a publically accessible URL that is invoked
	// when the user acknowledged the message, e.g. when Priority is Emergency.
	CallbackURL string

	// Tags can be used instead of receipts when the server is unable to process
	// receipts. Tags will be stored on Pushover servers and can be used to e.g.
	// cancel receipts by tag.
	Tags []string
}

Message to send.

type Priority

type Priority int

Priority settings of a Message.

const (
	// Lowest will generate no alert/notification on the user's devices.
	Lowest Priority = -2
	// Low will send the message as a quiet notification.
	Low Priority = -1
	// Normal is the normal priority.
	Normal Priority = 0
	// High will bypass the user's quiet hours.
	High Priority = 1
	// Emergency will bypass the user's quiet hours and will require
	// a confirmation by the user.
	Emergency Priority = 2
)

type RawLogger

type RawLogger struct {
	// contains filtered or unexported fields
}

RawLogger logs output raw HTTP requests and responses.

func NewRawLogger

func NewRawLogger(w io.Writer) *RawLogger

NewRawLogger creates a new RawLogger that writes to w.

func (*RawLogger) Log

func (l *RawLogger) Log(req *http.Request, resp *http.Response, err error, start time.Time, duration time.Duration) error

Log a roundtrip.

type SendResponse

type SendResponse struct {
	Receipt string `json:"receipt,omitempty"`
	Status  int    `json:"status,omitempty"`
	Request string `json:"request,omitempty"`
}

SendResponse is the outcome of the Send method.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL