pushover

package module
Version: v1.1.0 Latest Latest
Warning

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

Go to latest
Published: May 10, 2021 License: MIT Imports: 13 Imported by: 33

README

pushover

GoDoc Build Status Coverage Status Go Report Card

pushover is a wrapper around the Superblock's Pushover API written in go. Based on their documentation. It's a convenient way to send notifications from a go program with only a few lines of code.

Messages

Send a simple message

Here is a simple example for sending a notification to a recipient. A recipient can be a user or a group. There is no real difference, they both use a notification token.

package main

import (
    "log"

    "github.com/gregdel/pushover"
)

func main() {
    // Create a new pushover app with a token
    app := pushover.New("uQiRzpo4DXghDmr9QzzfQu27cmVRsG")

    // Create a new recipient
    recipient := pushover.NewRecipient("gznej3rKEVAvPUxu9vvNnqpmZpokzF")

    // Create the message to send
    message := pushover.NewMessage("Hello !")

    // Send the message to the recipient
    response, err := app.SendMessage(message, recipient)
    if err != nil {
        log.Panic(err)
    }

    // Print the response if you want
    log.Println(response)
}
Send a message with a title

There is a simple way to create a message with a title. Instead of using pushover.NewMessage you can use pushover.NewMessageWithTitle.

message := pushover.NewMessageWithTitle("My awesome message", "My title")
Send a fancy message

If you want a more detailed message you can still do it.

message := &pushover.Message{
    Message:     "My awesome message",
    Title:       "My title",
    Priority:    pushover.PriorityEmergency,
    URL:         "http://google.com",
    URLTitle:    "Google",
    Timestamp:   time.Now().Unix(),
    Retry:       60 * time.Second,
    Expire:      time.Hour,
    DeviceName:  "SuperDevice",
    CallbackURL: "http://yourapp.com/callback",
    Sound:       pushover.SoundCosmic,
}
Send a message with an attachment

You can send an image attachment along with the message.

file, err := os.Open("/some/image.png")
if err != nil {
  panic(err)
}
defer file.Close()

message := pushover.NewMessage("Hello !")
if err := message.AddAttachment(file); err != nil {
  panic(err)
}

Callbacks and receipts

If you're using an emergency notification you'll have to specify a retry period and an expiration delay. You can get the receipt details using the token in the message response.

...
response, err := app.SendMessage(message, recipient)
if err != nil {
    log.Panic(err)
}

receiptDetails, err := app.GetReceiptDetails(response.Receipt)
if err != nil {
    log.Panic(err)
}

fmt.Println("Acknowledged status :", receiptDetails.Acknowledged)

You can also cancel an emergency notification before the expiration time.

response, err := app.CancelEmergencyNotification(response.Receipt)
if err != nil {
    log.Panic(err)
}

User verification

If you want to validate that the recipient token is valid.

...
recipientDetails, err := app.GetRecipientDetails(recipient)
if err != nil {
    log.Panic(err)
}

fmt.Println(recipientDetails)

Documentation

Overview

Package pushover provides a wrapper around the Pushover API

Index

Constants

View Source
const (
	// MessageMaxLength is the max message number of characters.
	MessageMaxLength = 1024
	// MessageTitleMaxLength is the max title number of characters.
	MessageTitleMaxLength = 250
	// MessageURLMaxLength is the max URL number of characters.
	MessageURLMaxLength = 512
	// MessageURLTitleMaxLength is the max URL title number of characters.
	MessageURLTitleMaxLength = 100
	// MessageMaxAttachmentByte is the max attachment size in byte.
	MessageMaxAttachmentByte = 2621440
)

API limitations.

View Source
const (
	PriorityLowest    = -2
	PriorityLow       = -1
	PriorityNormal    = 0
	PriorityHigh      = 1
	PriorityEmergency = 2
)

Message priorities

View Source
const (
	SoundPushover     = "pushover"
	SoundBike         = "bike"
	SoundBugle        = "bugle"
	SoundCashRegister = "cashregister"
	SoundClassical    = "classical"
	SoundCosmic       = "cosmic"
	SoundFalling      = "falling"
	SoundGamelan      = "gamelan"
	SoundIncoming     = "incoming"
	SoundIntermission = "intermission"
	SoundMagic        = "magic"
	SoundMechanical   = "mechanical"
	SoundPianobar     = "pianobar"
	SoundSiren        = "siren"
	SoundSpaceAlarm   = "spacealarm"
	SoundTugBoat      = "tugboat"
	SoundAlien        = "alien"
	SoundClimb        = "climb"
	SoundPersistent   = "persistent"
	SoundEcho         = "echo"
	SoundUpDown       = "updown"
	SoundVibrate      = "vibrate"
	SoundNone         = "none"
)

Sounds

Variables

View Source
var (
	ErrHTTPPushover              = errors.New("pushover: http error")
	ErrEmptyToken                = errors.New("pushover: empty API token")
	ErrEmptyURL                  = errors.New("pushover: empty URL, URLTitle needs an URL")
	ErrEmptyRecipientToken       = errors.New("pushover: empty recipient token")
	ErrInvalidRecipientToken     = errors.New("pushover: invalid recipient token")
	ErrInvalidRecipient          = errors.New("pushover: invalid recipient")
	ErrInvalidHeaders            = errors.New("pushover: invalid headers in server response")
	ErrInvalidPriority           = errors.New("pushover: invalid priority")
	ErrInvalidToken              = errors.New("pushover: invalid API token")
	ErrMessageEmpty              = errors.New("pushover: message empty")
	ErrMessageTitleTooLong       = errors.New("pushover: message title too long")
	ErrMessageTooLong            = errors.New("pushover: message too long")
	ErrMessageAttachmentTooLarge = errors.New("pushover: message attachment is too large")
	ErrMessageURLTitleTooLong    = errors.New("pushover: message URL title too long")
	ErrMessageURLTooLong         = errors.New("pushover: message URL too long")
	ErrMissingAttachment         = errors.New("pushover: missing attachment")
	ErrMissingEmergencyParameter = errors.New("pushover: missing emergency parameter")
	ErrInvalidDeviceName         = errors.New("pushover: invalid device name")
	ErrEmptyReceipt              = errors.New("pushover: empty receipt")
)

Pushover custom errors.

View Source
var APIEndpoint = "https://api.pushover.net/1"

APIEndpoint is the API base URL for any request.

Functions

This section is empty.

Types

type Errors

type Errors []string

Errors represents the errors returned by pushover.

func (Errors) Error

func (e Errors) Error() string

Error represents the error as a string.

type Limit

type Limit struct {
	// Total number of messages you can send during a month.
	Total int
	// Remaining number of messages you can send until the next reset.
	Remaining int
	// NextReset is the time when all the app counters will be reseted.
	NextReset time.Time
}

Limit represents the limitation of the application. This information is fetched when posting a new message.

Headers example:
	X-Limit-App-Limit: 7500
	X-Limit-App-Remaining: 7496
	X-Limit-App-Reset: 1393653600

type Message

type Message struct {
	// Required
	Message string

	// Optional
	Title       string
	Priority    int
	URL         string
	URLTitle    string
	Timestamp   int64
	Retry       time.Duration
	Expire      time.Duration
	CallbackURL string
	DeviceName  string
	Sound       string
	HTML        bool
	Monospace   bool
	// contains filtered or unexported fields
}

Message represents a pushover message.

func NewMessage

func NewMessage(message string) *Message

NewMessage returns a simple new message.

func NewMessageWithTitle

func NewMessageWithTitle(message, title string) *Message

NewMessageWithTitle returns a simple new message with a title.

func (*Message) AddAttachment

func (m *Message) AddAttachment(attachment io.Reader) error

AddAttachment adds an attachment to the message it's programmer's responsibility to close the reader.

type Pushover

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

Pushover is the representation of an app using the pushover API.

func New

func New(token string) *Pushover

New returns a new app to talk to the pushover API.

func (*Pushover) CancelEmergencyNotification

func (p *Pushover) CancelEmergencyNotification(receipt string) (*Response, error)

CancelEmergencyNotification helps stop a notification retry in case of a notification with an Emergency priority before reaching the expiration time. It requires the response receipt in order to stop the right notification.

func (*Pushover) GetReceiptDetails

func (p *Pushover) GetReceiptDetails(receipt string) (*ReceiptDetails, error)

GetReceiptDetails return detailed informations about a receipt. This is used used to check the acknowledged status of an Emergency notification.

func (*Pushover) GetRecipientDetails

func (p *Pushover) GetRecipientDetails(recipient *Recipient) (*RecipientDetails, error)

GetRecipientDetails allows to check if a recipient exists, if it's a group and the devices associated to this recipient. It returns an ErrInvalidRecipient if the recipient is not valid in the Pushover API.

func (*Pushover) SendMessage

func (p *Pushover) SendMessage(message *Message, recipient *Recipient) (*Response, error)

SendMessage is used to send message to a recipient.

type ReceiptDetails

type ReceiptDetails struct {
	Status          int
	Acknowledged    bool
	AcknowledgedBy  string
	Expired         bool
	CalledBack      bool
	ID              string
	AcknowledgedAt  *time.Time
	LastDeliveredAt *time.Time
	ExpiresAt       *time.Time
	CalledBackAt    *time.Time
}

ReceiptDetails represents the receipt informations in case of emergency priority.

func (*ReceiptDetails) UnmarshalJSON

func (r *ReceiptDetails) UnmarshalJSON(data []byte) error

UnmarshalJSON is a custom unmarshal function to handle timestamps and boolean as int and convert them to the right type.

type Recipient

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

Recipient represents the a recipient to notify.

func NewRecipient

func NewRecipient(token string) *Recipient

NewRecipient is the representation of the recipient to notify.

type RecipientDetails

type RecipientDetails struct {
	Status    int      `json:"status"`
	Group     int      `json:"group"`
	Devices   []string `json:"devices"`
	RequestID string   `json:"request"`
	Errors    Errors   `json:"errors"`
}

RecipientDetails represents the receipt informations in case of emergency priority.

type Response

type Response struct {
	Status  int    `json:"status"`
	ID      string `json:"request"`
	Errors  Errors `json:"errors"`
	Receipt string `json:"receipt"`
	Limit   *Limit
}

Response represents a response from the API.

func (Response) String

func (r Response) String() string

String represents a printable form of the response.

Jump to

Keyboard shortcuts

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