notify

package module
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2022 License: Apache-2.0 Imports: 11 Imported by: 0

README

Notify-Go

Notify Go is a free command line / API that allows you to easily send (bot style) messages to a recipient . This features a base implementation for all your favourite messaging platforms

like :

  • telegram
  • discord
  • slack

Note: this is not a 2 way messaging protocol . This project only publishes messages

Also , I would like to mention , Slack and Discord both use webhooks . So if you just want to use those and have simple needs . NO NEED TO USE THIS SOLUTION it's overkill. Just Send an http request to the webhook route with the body. ie curl it.

It's aimed to be super minimal and simple to configure. This solution is great for the following scenarios :

  • Command Line Notifications
  • System Notifications
  • IOT Devices
  • Home Automation
  • Anything that can run linux .

Contents

Table of contents


Installation

A) API Mode Installation

To use the API in your existing go code simply run the following

go get -u github.com/baderkha/notify-go

B) Command Line Installation

  1. go to release page

  2. download the binary that matches your system

  3. [windows instrructions]

  • if on windows , then just download the .msi file
  • install it on your computer
  1. [unix instructions] move to path

    Linux

    move binary to /usr/local/bin

    sudo mv ~/Downloads/notify-go-linux-x86 /usr/local/bin/notify-go
    sudo chmod +x /usr/local/bin/notify-go
    

    Mac

    move binary to /usr/local/bin

    sudo mv ~/Downloads/notify-go-linux-x86 /usr/local/bin/notify-go
    sudo chmod +x /usr/local/bin/notify-go
    

Authorization Setup

*Note you must do this in order to use the cli/api*

This section will cover how to setup authorization for each of the message senders . Note that

  • Slack
    • you need to create an app
    • give it permissions
    • create a webhook
    • use that webhook with this cli / api
  • Discord
    • go to your server settings
    • under integrations (create a webhook)
    • call it a cool name
    • use that webhook with this cli / api
  • Telegram
    • // todo

API Usage

This section will cover how to use the api.

Note You Need Go v1.18+ Since The API uses generics

MessageSender

notify.MessageSender is an interface which has implementations for slack,discord,and telegram. If your usage is simple and you only want to message Discord for example . Then attaching this interface is perfect for you.

Slack Instructions
  1. init
slackSender := notify.NewSlackSender()
  1. send a message to a webhook
err := slackSender.Send("https://slack.channel.com/your/other/channel/webhook",[]byte("some_message"))
if err != nil {
    log.Fatal(err)
}

Discord Instructions

Discord is very similar to slack since it also uses webhooks to send messages to a chat . So the init logic is the same .

  1. init
discSender := notify.NewDiscordSender()
  1. send a message to a different webhook
err := discSender.Send("https://slack.channel.com/your/other/channel/webhook",[]byte("somemessage"))
if err != nil {
    log.Fatal(err)
}



Manager

notify.Manager enables you to orchestrate sending messages to multiple social platforms . This should be used only if you expect your application to use more than 1 notification platform .

Otherwise see

  1. init
// default contains all the clients
msgMgr := notify.Default()
  1. send a message to a specific client (discord , slack , telegram)
// send to a specific client like discord
err := msgMgr.SendToSpecificType(
    notify.DiscordSenderType,
    "https://www.some-webhook.url.com",
    []byte("hi mom"),
)
  1. broadcast same message to all clients
// 1 - create a mapping
ralias := notify.NewEmptyRecieverAlias()
// returns an error 
_ = ralias.Add(notfy.DiscordSenderType,"https://www.google.com")
_ = ralias.Add(notify.SlackSenderType,"https://www.google.com")

// 2 - send msg
msgMgr.SendAll(ralias,[]byte("hi mom "))



Implement your own sender

To implement your own Message publisher client you have to implement the notify.Sender Method and then add your sender to the manager

Send(reciever string, bodyContent []byte) error

Example :

  1. Implement the interface
// equivalent of implements keyword
var _ notify.Sender = &WhatsappSender{}

type WhatsappSender struct {}

func (w *WhatsappSender) Send(reciver string , bodyContent[]byte) error {
    return nil
}
  1. [Optional] Enroll it to the manager if you're using it in tandum with other services
// your main go
func main() {
    mgr := notify.Default()
    mgr.AddSender("whatsapp",new(WhatsappSender))

    _ = msgMgr.SendToSpecificType(
        "whatsapp",
        "chat_id",
        []byte("hi mom"),
    )

}

Cli Usage

Help
notify-go --help

Managing Contacts

Contacts allow you to map channels / entities to different social profiles . IE you can map your 1 channel to discord , slack , telegram

This is powerful , because you can leverage the broadcast functionality of the cli to send to all those channel with 1 alias

Example :

  • Add Contact Entry

    notify-go newcon crypto_channel
    
  • Add Contact Social Mapping

    this will make it easy for you to reference by name rather than have to repaste the webhook everytime

    notify-go apcon crypto_channel discord https://www.google.com
    notify-go apcon crypto_channel slack https://www.google.com
    
  • List Contacts

    Allows you to list all / 1 contact

    • all
      notify-go cons 
      
    • specific
      notify-go cons crypto_channel
      


Sending Messages
  • with webhook
    notify-go msg discord https://webhook.com "hi mom"
    
  • through contact alias (see above section for how to create contacts)
    notify-go msg discord crypto_channel "hi mom"
    
  • to all social platforms via contact mapping* in this scenario we setup mapping for crypto_channel to discord and slack . So this will send to both channels concurrently
    notify-go msgcon crypto_channel "hi mom"
    
Broadcasting messages

Note this will message everyone in the contact list and all platforms. use this with caution :)

notify-go msgbrod "hi mom"

[^1]: By Ahmad Baderkhan

[^2]: License Apache-V2

Documentation

Overview

Package notify: a notificaion publishing package that allows you to send messages to different social platforms

Index

Constants

View Source
const (
	// DiscordType : senderType of discord
	DiscordSenderType = "discord"
	// SlackSenderType : senderType of Slack
	SlackSenderType = "slack"
	// TelegramSenderType : senderType of telegram
	TelegramSenderType = "telegram"
	// TestSenderType : sender Type for testing
	TestSenderType = "test"
)
View Source
const (

	// EnvHTTPDebugging : setting this environment
	// enables debugging http logs to stdout
	EnvHTTPDebugging = "NOTIFY_GO_HTTP_DEBUGGING"
)

Variables

View Source
var (
	SupportedTypes = []string{
		DiscordSenderType,
		SlackSenderType,
		TelegramSenderType,
		TestSenderType,
	}
	SupportedTypesString = strings.Join(SupportedTypes, " , ")
)

Functions

func SetDebug

func SetDebug(val bool)

SetDebug : turn debug on or off

Otherwise it will default to the environment variable see : EnvHTTPDebugging for the env var key

Types

type DiscordBody

type DiscordBody struct {
	Content string `json:"content"`
}

DiscordBody : Discord body

func (DiscordBody) WithBody

func (s DiscordBody) WithBody(b []byte) DiscordBody

type DiscordSender

type DiscordSender = WebhookSender[DiscordBody]

DiscordSender : slack message sender

func NewDiscordSender

func NewDiscordSender() *DiscordSender

NewDiscordSender : creat a new discord notification sender

type Manager

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

Manager : A manager for all the sender type implementations

func Default

func Default() *Manager

func (*Manager) AddSender

func (m *Manager) AddSender(senderType string, s MessageSender)

AddSender : add a sender service Try to use this only during your app's init phase preferably

func (*Manager) SendAll

func (m *Manager) SendAll(alias *RecieverAlias, bodyContent []byte) error

SendAll : concurrently sends messages to all the senders given a reciver alias address map

func (*Manager) SendToSpecificType

func (m *Manager) SendToSpecificType(senderType, reciever string, bodyContent []byte) error

SendToSpecificType : allows you to access the Send Method

type MessageSender

type MessageSender interface {
	// Send send to someone not in your default configs
	Send(reciever string, bodyContent []byte) error
}

MessageSender : a base contract that all other message senders need to fullfill

type RecieverAlias

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

RecieverAlias : a map of a sender and reciver, it's a good way to group similar recivers but different channels

In plain english : let's say you had the same group in discord , slack , telegram this struct will provide you with functionality to be able to map the same group for different channels

It's go routine safe !

forexample :

// from primitive data
var s map[string]string = make(map[string]string)
s[notify.DiscordSenderType] = "https://somechannelwebhook.com"
s[notify.TestSenderType] = "some_channel_id"
// will throw an error if sender type is not supported or if reciver is empty for sender
coolCryptoChannel,err := notify.NewReciverAlias(s)

// using the ReciverAlias struct (it's go routine safe)
// getting reciver
DiscordChannelWebhook := coolCryptoChannel.Get(notify.DiscordSenderType)

// enrolling new reciver
coolCryptoChannel.Add(notify.SlackSenderType,"https://someslackchannelwebooh.com")

func NewEmptyRecieverAlias

func NewEmptyRecieverAlias() *RecieverAlias

func NewRecieverAlias

func NewRecieverAlias(senderTypeToReciverMap map[string]string) (*RecieverAlias, error)

NewRecieverAlias : returns a reciver alias A reciever alias is basically a map of sender type -> reciever

func (*RecieverAlias) Add

func (r *RecieverAlias) Add(senderType string, reciver string) error

Add : add a sender -> reciver mapping will throw error if sender type is not supported / reciver is empty

func (*RecieverAlias) Get

func (r *RecieverAlias) Get(senderType string) string

Get : get a reciver for a sender type

type SenderMock

type SenderMock struct {
	mock.Mock
}

SenderMock : mock implementation you can use in your testing

func (*SenderMock) Send

func (s *SenderMock) Send(reciever string, bodyContent []byte) error

Send send to someone not in your default configs

type SlackBody

type SlackBody struct {
	Text string `json:"text"`
}

func (SlackBody) WithBody

func (s SlackBody) WithBody(b []byte) SlackBody

type SlackSender

type SlackSender = WebhookSender[SlackBody]

SlackSender : slack message sender

func NewSlackSender

func NewSlackSender() *SlackSender

NewSlackSender : creat a new slack notification sender

type WebhookSender

type WebhookSender[T interface{ WithBody(b []byte) T }] struct {
	// contains filtered or unexported fields
}

WebhookSender : Generic message sender using webhooks

func NewWebhookSender

func NewWebhookSender[T interface{ WithBody(b []byte) T }](errPrefix string) (w *WebhookSender[T])

func (*WebhookSender[T]) Send

func (s *WebhookSender[T]) Send(reciever string, bodyContent []byte) error

Send send to someone not in your default configs

Directories

Path Synopsis
cmd
cli
internal
pkg

Jump to

Keyboard shortcuts

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