signalmgr

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2024 License: MIT Imports: 8 Imported by: 0

README

Signal Manager

GoDoc

signalmgr is a Go library designed to interact with the bbernhard/signal-cli-rest-api to manage Signal accounts more easily. This library provides a wrapper for the various signal-cli-rest-api endpoints covered in signal-cli-rest-api swagger docs.

Installation

You can install the signalmgr library using go get:

go get github.com/DonovanDiamond/signalmgr

Usage

package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strings"
	"time"

	"github.com/DonovanDiamond/signalmgr"
)

func main() {
	signalmgr.API_URL = "http://localhost:8080"

	scanner := bufio.NewScanner(os.Stdin)
	fmt.Print("Enter the number to register to signal: ")
	scanner.Scan()
	number := scanner.Text()

	account := signalmgr.Account{
		Number: number,
	}

	fmt.Print("Enter 'voice' if you want to use a phone call for verification (note this will take longer than SMS verification): ")
	scanner.Scan()
	voice := strings.ToLower(scanner.Text())

	fmt.Println("Go to https://signalcaptchas.org/registration/generate.html, complete the captcha, open the development console and find the line that looks like: 'Prevented navigation to “signalcaptcha://{captcha value}” due to an unknown protocol.' and copy the entire captcha value.")
	fmt.Print("Enter the captcha value including “signalcaptcha://”: ")
	scanner.Scan()
	captcha := scanner.Text()

	if voice == "voice" {
		err := account.PostRegister(captcha, false)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println("Waiting 61 seconds before requesting voice call...")
		time.Sleep(time.Second * 61)

		fmt.Println("Go to https://signalcaptchas.org/registration/generate.html and complete a new captcha like before.")
		fmt.Print("Enter the captcha value including “signalcaptcha://”: ")
		scanner.Scan()
		captcha := scanner.Text()
	
		err = account.PostRegister(captcha, true)
		if err != nil {
			log.Fatal(err)
		}
	} else {
		err := account.PostRegister(captcha, voice == "voice")
		if err != nil {
			log.Fatal(err)
		}
	}

	fmt.Print("Please enter the token sent via SMS/call to the number provided:")
	scanner.Scan()
	token := scanner.Text()
	fmt.Print("Please enter the PIN for signal (if you have one) or leave this blank:")
	scanner.Scan()
	pin := scanner.Text()

	err := account.PostRegisterVerify(token, pin)
	if err != nil {
		log.Fatal(err)
	}

	log.Println("Successfully registered!")

	fmt.Print("Enter a number to send a test message to (formatted +123456789):")
	scanner.Scan()
	numberTo := scanner.Text()
	fmt.Print("Enter a message to send:")
	scanner.Scan()
	message := scanner.Text()

	if _, err := signalmgr.PostSend(signalmgr.SendMessageV2{
		Number:     account.Number,
		Recipients: []string{numberTo},
		Message:    message,
	}); err != nil {
		log.Fatal(err)
	}

	fmt.Print("Send a message to this number and press enter to receive it:")
	scanner.Scan()

	messages, err := account.GetMessages()
	if err != nil {
		log.Fatal(err)
	}

	for _, m := range messages {
		fmt.Printf(" - %s: %s\n", m.Envelope.SourceNumber, m.Envelope.DataMessage.Message)
	}
}

Methods

Each method is based on the methods in signal-cli-rest-api swagger docs, below is a summary of them:

Account Management
  • GetAccounts(): Lists all Signal accounts linked to the service.
  • PostRegister(captcha string, useVoice bool): Register a phone number with the Signal network.
  • PostRegisterVerify(token string, pin string): Verify a registered phone number.
  • PostUnregistert(data struct{ DeleteAccount bool; DeleteLocalData bool }): Unregister a phone number and optionally delete its data.
  • PostUsername(data struct{ Username string }): Set a username for the account.
Messaging
  • GetMessages(): Receive Signal Messages, when bbernhard/signal-cli-rest-api is running in normal or native mode.
  • GetMessagesSocket(messages chan<- MessageResponse): Opens a socket to receive Signal Messages and sends them to the messages channel, when bbernhard/signal-cli-rest-api is running in json-rpc mode.
  • PostSend(data SendMessageV2): Send a message (supports text, mentions, attachments, etc.).
  • PostReaction(data struct{ Reaction string; Recipient string; Timestamp int64 }): Send a reaction to a message.
  • PostReceipt(data struct{ ReceiptType string; Recipient string; Timestamp int64 }): Send a read/viewed receipt for a message.
Contacts
  • GetContacts(): List all contacts for the account.
  • PostContact(data struct{ Name string; Recipient string }): Add or update contact information.
  • PutContactsSync(): Sync contacts across devices.
Groups
  • GetGroups(): List all Signal groups associated with the account.
  • PostCreateGroup(data struct{ Name string; Members []string; Permissions struct{ AddMembers string } }): Create a new group with specified members.
  • PostGroupAdmins(groupID string, data struct{ Admins []string }): Add admins to a group.
  • DeleteGroupAdmins(groupID string, data struct{ Admins []string }): Remove admins from a group.
  • PostGroupMembers(groupID string, data struct{ Members []string }): Add members to a group.
Attachments
  • GetAttachments(): List all attachments stored in the system.
  • GetAttachment(id string): Serve an attachment by its ID.
  • DeleteAttachment(id string): Delete an attachment by its ID.
Device Linking
  • GetLinkAccountQRCode(deviceName string): Generate a QR code to link a new device.
Configuration & Health
  • GetHealth(): Check the health of the Signal API.
  • GetConfiguration(): Retrieve the current API configuration.
  • PostConfiguration(data Configuration): Update the API configuration.

Acknowledgements

Thanks to the contributors of signal-cli and signal-cli-rest-api for providing the underlying API and documentation. This project does not replace any functionality of these projects, and is just a wrapper for easy implementation in Go.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var API_URL = "http://127.0.0.1:8080"

Functions

func DeleteAttachment

func DeleteAttachment(id string) (err error)

Remove attachment.

Remove the attachment with the given id from filesystem.

func GetAttachment

func GetAttachment(id string) (raw []byte, err error)

Serve Attachment.

Serve the attachment with the given id.

func GetAttachments

func GetAttachments() (attachments []string, err error)

List all attachments.

List all downloaded attachments.

func GetHealth

func GetHealth() (resp string, err error)

API Health Check.

Internally used by the docker container to perform the health check.

func GetLinkAccountQRCode

func GetLinkAccountQRCode(deviceName string) (link string, err error)

Link device and generate QR code.

func PostConfiguration

func PostConfiguration(data Configuration) (err error)

Set the REST API configuration.

func PostSend

func PostSend(data SendMessageV2) (resp struct {
	Timestamp string `json:"timestamp"`
}, err error)

Send a signal message.

Send a signal message. Set the text_mode to 'styled' in case you want to add formatting to your text message. Styling Options: *italic text*, **bold text**, ~strikethrough text~.

Types

type Account

type Account struct {
	Number string
}

func GetAccounts

func GetAccounts() (accounts []Account, err error)

List all accounts

Lists all of the accounts linked or registered

func (*Account) DeleteGroup

func (a *Account) DeleteGroup(groupID string) (err error)

Delete the specified Signal Group.

func (*Account) DeleteGroupAdmins

func (a *Account) DeleteGroupAdmins(groupID string, data struct {
	Admins []string `json:"admins"`
}) (err error)

Remove one or more admins from an existing Signal Group.

func (*Account) DeleteGroupMembers

func (a *Account) DeleteGroupMembers(groupID string, data struct {
	Members []string `json:"members"`
}) (err error)

Remove one or more members from an existing Signal Group.

func (*Account) DeleteReaction

func (a *Account) DeleteReaction(data struct {
	Reaction     string `json:"reaction"`
	Recipient    string `json:"recipient"`
	TargetAuthor string `json:"target_author"`
	Timestamp    int64  `json:"timestamp"`
}) (err error)

Remove a reaction.

func (*Account) DeleteTypingIndicator

func (a *Account) DeleteTypingIndicator(data struct {
	Recipient string `json:"recipient"`
}) (err error)

Hide Typing Indicator.

func (*Account) DeleteUsername

func (a *Account) DeleteUsername() (err error)

Remove a username.

Delete the username associated with this account.

func (*Account) GetConfiguration

func (a *Account) GetConfiguration() (resp Account_Configuration, err error)

List account specific settings.

func (*Account) GetContacts

func (a *Account) GetContacts() (contacts []Contact, err error)

List Contacts.

List all contacts for the given number.

func (*Account) GetGroup

func (a *Account) GetGroup(groupID string) (group Group, err error)

List a specific Signal Group.

func (*Account) GetGroups

func (a *Account) GetGroups() (groups []Group, err error)

List all Signal Groups.

func (*Account) GetIdentities

func (a *Account) GetIdentities() (identities []Identity, err error)

List all identities for the given number.

func (*Account) GetMessages

func (a *Account) GetMessages() (messages []MessageResponse, err error)

Receive Signal Messages.

Only works if the signal api is running in `normal` or `native` mode. If you are running in `json-rpc` mode, use `GetMessagesSocket`.

func (*Account) GetMessagesSocket added in v0.1.0

func (a *Account) GetMessagesSocket(messages chan<- MessageResponse) (err error)

Opens a socket to receive Signal Messages and sends them to the `messages` channel.

Will only return if there is an error or the socket closes.

Only works if the signal api is running in `json-rpc` mode. If you are running in `normal` or `native` mode, use `GetMessages`.

func (*Account) GetStickerPacks

func (a *Account) GetStickerPacks() (packs []StickerPack, err error)

List Installed Sticker Packs.

func (*Account) PostBlockGroup

func (a *Account) PostBlockGroup(groupID string) (err error)

Block the specified Signal Group.

func (*Account) PostConfiguration

func (a *Account) PostConfiguration(data Account_Configuration) (err error)

Set account specific settings.

func (*Account) PostContact

func (a *Account) PostContact(data struct {
	ExpirationInSeconds int    `json:"expiration_in_seconds"`
	Name                string `json:"name"`
	Recipient           string `json:"recipient"`
}) (contacts []Contact, err error)

Updates the info associated to a number on the contact list. If the contact doesn’t exist yet, it will be added.

func (*Account) PostCreateGroup

func (a *Account) PostCreateGroup(data struct {
	Description    string   `json:"description"`
	ExpirationTime int      `json:"expiration_time"`
	GroupLink      string   `json:"group_link"`
	Members        []string `json:"members"`
	Name           string   `json:"name"`
	Permissions    struct {
		AddMembers string `json:"add_members"`
		EditGroup  string `json:"edit_group"`
	} `json:"permissions"`
}) (resp struct {
	ID string `json:"id"`
}, err error)

Create a new Signal Group with the specified members.

func (*Account) PostGroupAdmins

func (a *Account) PostGroupAdmins(groupID string, data struct {
	Admins []string `json:"admins"`
}) (err error)

Add one or more admins to an existing Signal Group.

func (*Account) PostGroupMembers

func (a *Account) PostGroupMembers(groupID string, data struct {
	Members []string `json:"members"`
}) (err error)

Add one or more members to an existing Signal Group.

func (*Account) PostJoinGroup

func (a *Account) PostJoinGroup(groupID string) (err error)

Join the specified Signal Group.

func (*Account) PostLinkDevice

func (a *Account) PostLinkDevice(data struct {
	URI string `json:"uri"`
}) (err error)

Links another device to this device. Only works, if this is the master device.

func (*Account) PostProfile

func (a *Account) PostProfile(data struct {
	About        string `json:"about"`
	Base64Avatar string `json:"base64_avatar"`
	Name         string `json:"name"`
}) (err error)

Update Profile.

Set your name and optional an avatar.

func (*Account) PostQuitGroup

func (a *Account) PostQuitGroup(groupID string) (err error)

Quit the specified Signal Group.

func (*Account) PostRateLimitChallenge

func (a *Account) PostRateLimitChallenge(data struct {
	Captcha        string `json:"captcha"`
	ChallengeToken string `json:"challenge_token"`
}) (err error)

Lift rate limit restrictions by solving a captcha.

When running into rate limits, sometimes the limit can be lifted, by solving a CAPTCHA. To get the captcha token, go to https://signalcaptchas.org/challenge/generate.html For the staging environment, use: https://signalcaptchas.org/staging/registration/generate.html. The \"challenge_token\" is the token from the failed send attempt. The \"captcha\" is the captcha result, starting with signalcaptcha://.

func (*Account) PostReaction

func (a *Account) PostReaction(data struct {
	Reaction     string `json:"reaction"`
	Recipient    string `json:"recipient"`
	TargetAuthor string `json:"target_author"`
	Timestamp    int64  `json:"timestamp"`
}) (err error)

Send a reaction.

React to a message.

func (*Account) PostReceipt

func (a *Account) PostReceipt(data struct {
	ReceiptType string `json:"receipt_type"`
	Recipient   string `json:"recipient"`
	Timestamp   int64  `json:"timestamp"`
}) (err error)

Send a receipt.

Send a read or viewed receipt.

func (*Account) PostRegister

func (a *Account) PostRegister(captcha string, useVoice bool) error

Register a phone number.

Register a phone number with the signal network.

func (*Account) PostRegisterVerify

func (a *Account) PostRegisterVerify(token string, pin string) error

Verify a registered phone number.

Verify a registered phone number with the signal network.

func (*Account) PostStickerPack

func (a *Account) PostStickerPack(data struct {
	PackID  string `json:"pack_id"`
	PackKey string `json:"pack_key"`
}) (err error)

Add Sticker Pack.

In order to add a sticker pack, browse to https://signalstickers.org/ and select the sticker pack you want to add. Then, press the \"Add to Signal\" button. If you look at the address bar in your browser you should see an URL in this format: https://signal.art/addstickers/#pack_id=XXX\u0026pack_key=YYY, where XXX is the pack_id and YYY is the pack_key.

func (*Account) PostUnregistert

func (a *Account) PostUnregistert(data struct {
	DeleteAccount   bool `json:"delete_account"`
	DeleteLocalData bool `json:"delete_local_data"`
}) (err error)

Unregister a phone number.

Disables push support for this device. **WARNING:** If *delete_account* is set to *true*, the account will be deleted from the Signal Server. This cannot be undone without loss.

func (*Account) PostUsername

func (a *Account) PostUsername(data struct {
	Username string `json:"username"`
}) (resp Account_PostUsernameResponse, err error)

Set a username.

Allows to set the username that should be used for this account. This can either be just the nickname (e.g. test) or the complete username with discriminator (e.g. test.123). Returns the new username with discriminator and the username link.

func (*Account) PutContactsSync

func (a *Account) PutContactsSync() (err error)

Send a synchronization message with the local contacts list to all linked devices. This command should only be used if this is the primary device.

func (*Account) PutGroupSettings

func (a *Account) PutGroupSettings(groupID string, data struct {
	Base64Avatar string `json:"base64_avatar"`
	Description  string `json:"description"`
	Name         string `json:"name"`
}) (err error)

Update the state of a Signal Group.

func (*Account) PutSettings

func (a *Account) PutSettings(data struct {
	DiscoverableByNumber bool `json:"discoverable_by_number"`
	ShareNumber          bool `json:"share_number"`
}) (err error)

Update the account settings.

Update the account attributes on the signal server.

func (*Account) PutTrustIdentity

func (a *Account) PutTrustIdentity(numberToTrust string, data struct {
	TrustAllKnownKeys    bool   `json:"trust_all_known_keys"`
	VerifiedSafetyNumber string `json:"verified_safety_number"`
}) (err error)

Trust an identity. When 'trust_all_known_keys' is set to 'true', all known keys of this user are trusted. **This is only recommended for testing.**

func (*Account) PutTypingIndicator

func (a *Account) PutTypingIndicator(data struct {
	Recipient string `json:"recipient"`
}) (err error)

Show Typing Indicator.

type Account_Configuration

type Account_Configuration struct {
	TrustMode string `json:"trust_mode"`
}

type Account_PostUsernameResponse

type Account_PostUsernameResponse struct {
	Username     string `json:"username"`
	UsernameLink string `json:"username_link"`
}

type Configuration

type Configuration struct {
	Logging struct {
		Level string `json:"Level"`
	} `json:"logging"`
}

func GetConfiguration

func GetConfiguration() (resp Configuration, err error)

List the REST API configuration.

type Contact

type Contact struct {
	Blocked           bool   `json:"blocked"`
	Color             string `json:"color"`
	MessageExpiration string `json:"message_expiration"`
	Name              string `json:"name"`
	Number            string `json:"number"`
	ProfileName       string `json:"profile_name"`
	Username          string `json:"username"`
	UUID              string `json:"uuid"`
}

type GetAboutResponse

type GetAboutResponse struct {
	Build        int                 `json:"build"`
	Capabilities map[string][]string `json:"capabilities"`
	Mode         string              `json:"mode"`
	Version      string              `json:"version"`
	Versions     []string            `json:"versions"`
}

func GetAbout

func GetAbout() (resp GetAboutResponse, err error)

List all accounts.

Lists all of the accounts linked or registered.

type Group

type Group struct {
	Admins          []string `json:"admins"`
	Blocked         bool     `json:"blocked"`
	ID              string   `json:"id"`
	InternalID      string   `json:"internal_id"`
	InviteLink      string   `json:"invite_link"`
	Members         []string `json:"members"`
	Name            string   `json:"name"`
	PendingInvites  []string `json:"pending_invites"`
	PendingRequests []string `json:"pending_requests"`
}

type Identity

type Identity struct {
	Added        string `json:"added"`
	Fingerprint  string `json:"fingerprint"`
	Number       string `json:"number"`
	SafetyNumber string `json:"safety_number"`
	Status       string `json:"status"`
}

type MessageResponse added in v0.1.0

type MessageResponse struct {
	Envelope signaltypes.MessageEnvelope `json:"envelope"`
	Account  string                      `json:"account"`
}

type SearchResult

type SearchResult struct {
	Number     string `json:"number"`
	Registered bool   `json:"registered"`
}

func GetSearch

func GetSearch(numbers []string) (results []SearchResult, err error)

Check if one or more phone numbers are registered with the Signal Service.

type SendMessageV2

type SendMessageV2 struct {
	Number            string                         `json:"number"`
	Recipients        []string                       `json:"recipients"`
	Message           string                         `json:"message"`
	Base64Attachments []string                       `` /* 181-byte string literal not displayed */
	Sticker           string                         `json:"sticker"`
	Mentions          []SendMessageV2_MessageMention `json:"mentions"`
	QuoteTimestamp    *int64                         `json:"quote_timestamp"`
	QuoteAuthor       *string                        `json:"quote_author"`
	QuoteMessage      *string                        `json:"quote_message"`
	QuoteMentions     []SendMessageV2_MessageMention `json:"quote_mentions"`
	TextMode          *string                        `json:"text_mode" enums:"normal,styled"`
	EditTimestamp     *int64                         `json:"edit_timestamp"`
	NotifySelf        *bool                          `json:"notify_self"`
}

type SendMessageV2_MessageMention

type SendMessageV2_MessageMention struct {
	Start  int64  `json:"start"`
	Length int64  `json:"length"`
	Author string `json:"author"`
}

type StickerPack

type StickerPack struct {
	Author    string `json:"author"`
	Installed bool   `json:"installed"`
	PackID    string `json:"pack_id"`
	Title     string `json:"title"`
	URL       string `json:"url"`
}

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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