sqwiggle

package module
v0.0.0-...-e6cd448 Latest Latest
Warning

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

Go to latest
Published: Feb 8, 2015 License: MIT Imports: 10 Imported by: 0

README

Sqwiggle Go Client

Build Status Coverage Status Go Report Card

A Golang client library for the Sqwiggle API.

Supports
  • Attachments
  • Conversations
  • Info
  • Invites
  • Messages
  • Organizations
  • Streams
  • Users
Installation
go get github.com/hermanschaaf/sqwiggle
Example usage

The following example lists the 50 most recent messages across all streams, and prints them out.

package main

import (
	"fmt"
	"github.com/hermanschaaf/sqwiggle"
)

// The following code instantiates a client, then calls the
// ListMessages method to return a slice of Messages. If no error occurred, it
// iterates through the messages and prints them out one by one.
func main() {
	client := sqwiggle.NewClient("YOUR-API-KEY")

	page, limit := 0, 50
	msgs, err := client.ListMessages(page, limit)
	if err != nil {
		panic(err)
	}

	for _, m := range msgs {
		fmt.Printf("%s: %s\n", m.Author.Name, m.Text)
	}
}

When instantiating a new client, it is also possible to use your own HTTPClient:

client := Client{
	APIKey:     "YOUR-API-KEY",
	RootURL:    "https://api.sqwiggle.com/", // customize the URL
	HTTPClient: &http.Client{}, // your own custom http.Client
}

This is useful in testing environments, for example (and is used in the tests for this package).

Full Docs

https://godoc.org/github.com/hermanschaaf/sqwiggle

There are plenty more usage examples in the docs and also in sqwiggle_test.go.


MIT License

Documentation

Overview

Package sqwiggle provides a simplified interface to the Sqwiggle API

Index

Examples

Constants

View Source
const (
	TypeImage         AttachmentType = "image"
	TypeLink                         = "link"
	TypeFile                         = "file"
	TypeTwitterStatus                = "twitter_status"
	TypeTwitterUser                  = "twitter_user"
	TypeVideo                        = "video"
	TypeCode                         = "code"
	TypeGist                         = "gist"
)

Validation Token Types

View Source
const (
	ErrAuthentication ErrorType = "authentication"
	ErrAuthorization            = "authorization"
	ErrInvalidParam             = "invalid_param"
	ErrUnknownParam             = "unknown_param"
	ErrLimitReached             = "limit_reached"
	ErrValidation               = "validation"
	ErrUnknown                  = "unknown"
)

These errors define the types of errors expected to be returned by the Sqwiggle API.

View Source
const (
	RoleUser    UserRole = "user"
	RoleOwner            = "owner"
	RoleManager          = "manager"
	RoleBanned           = "banned"
)

These UserRole constants define the possible user roles that can be returned by the API.

View Source
const (
	StatusBusy      UserStatus = "busy"
	StatusAvailable            = "available"
	StatusOffline              = "offline"
)

The below UserStatus constants define the typical states a user may be in, i.e. "busy", "available" or "offline"

View Source
const (
	TypeUser    UserType = "user"
	TypeClient           = "client"
	TypeSupport          = "support"
)

The below UserType constants define the known UserTypes that may be returned by the API.

Variables

This section is empty.

Functions

This section is empty.

Types

type Attachment

type Attachment struct {
	ID          int            `json:"id"`          // ID of the attachment
	Type        AttachmentType `json:"type"`        // image, link, file, twitter_status, twitter_user, video, code, gist
	URL         string         `json:"url"`         // URL where the attachment content can be accessed
	Title       string         `json:"title"`       // A title for the attachment, for example a filename or webpage title
	Description string         `json:"description"` // A description of the attachment, for example a web page summary
	Image       string         `json:"image"`       // URL of an image representing the attachment, this may not reside on Sqwiggle's servers
	Status      string         `json:"status"`      // If an upload, denotes the uploade status ('pending' or 'uplodaed')
	Animated    bool           `json:"animated"`    // If an image, denotes whether animated
	CreatedAt   time.Time      `json:"created_at"`  // The time that this attachment was created
	UpdatedAt   time.Time      `json:"updated_at"`  // The time that this attachment was last updated or edited

	// undocumented:
	Width  int `json:"width,omitempty"`
	Height int `json:"height,omitempty"`
}

Attachment is a piece of media that belongs to a message. It may represent a link, image, video, file upload or more. Sqwiggle often adds new attachment types based on demand so it is important to filter using the type parameter.

type AttachmentType

type AttachmentType string

AttachmentType represents the type of attachment in a message

func (AttachmentType) String

func (t AttachmentType) String() string

type Client

type Client struct {
	APIKey     string
	RootURL    string
	HTTPClient *http.Client
}

Client is the main struct used to interface with the API. API methods are implemented as methods on this struct, and so the first step of any interaction with the API client must be to insantiate this struct. This can be done using the NewClient function.

func NewClient

func NewClient(APIKey string) *Client

NewClient returns a new Client with sensible defaults, which can be used to interface with the API. It takes only an APIKey string as single argument.

func (*Client) DeleteAttachment

func (c *Client) DeleteAttachment(id int) error

DeleteAttachment removes the specified attachment from the parent message. If this is the only attachment in the message then the parent message will also be removed.

func (*Client) DeleteInvite

func (c *Client) DeleteInvite(id int) error

DeleteInvite removes the specified invite from the organization. This will result in the invite no longer working should the recipient click on the link contained in the invite email.

func (*Client) DeleteMessage

func (c *Client) DeleteMessage(id int) error

DeleteMessage removes the specified message from the stream. So that conversation flow is preserved the message will be replaced with a "This message has been removed" note in the stream.

Example

The following code instantiates a client, then calls the DeleteMessage method to delete a single message.

package main

import (
	"github.com/hermanschaaf/sqwiggle"
)

func main() {
	client := sqwiggle.NewClient("YOUR-API-KEY")

	messageID := 48914
	err := client.DeleteMessage(messageID)
	if err != nil {
		panic(err)
	}
}
Output:

func (*Client) DeleteStream

func (c *Client) DeleteStream(id int) error

DeleteStream removes the chat stream from the organisation.

func (*Client) GetAttachment

func (c *Client) GetAttachment(id int) (Attachment, error)

GetAttachment retrieves the details of a message attachment. There are many different types of attachments and each type may return different fields in the response.

func (*Client) GetConversation

func (c *Client) GetConversation(id int) (Conversation, error)

GetConversation retrieves the details of a specific conversation provided it is accessible via the provided token.

func (*Client) GetInfo

func (c *Client) GetInfo() ([]byte, error)

GetInfo returns the reponse for GET /info. This is an unstructured response, so this endpoint just returns the raw byte slice.

func (*Client) GetInvite

func (c *Client) GetInvite(id int) (Invite, error)

GetInvite retrieves the details of any invite that has been previously created. Supply an invite ID to get details of the invite.

func (*Client) GetMessage

func (c *Client) GetMessage(id int) (Message, error)

GetMessage returns the reponse for GET /message. It retrieves the details of a message and any nested attachments.

Example

The following code instantiates a client, then calls the GetMessage method to return a single message. If no error occurred, it prints out the author name and text of the message.

package main

import (
	"fmt"

	"github.com/hermanschaaf/sqwiggle"
)

func main() {
	client := sqwiggle.NewClient("YOUR-API-KEY")

	id := 1000
	m, err := client.GetMessage(id)
	if err != nil {
		panic(err)
	}

	fmt.Printf("%s: %s\n", m.Author.Name, m.Text)
}
Output:

func (*Client) GetOrganization

func (c *Client) GetOrganization(id int) (Organization, error)

GetOrganization returns the reponse for GET /organizations/:id. It retrieves the details of any user that the token has access to. Supply an ID and Sqwiggle will return the corresponding chat user object.

func (*Client) GetStream

func (c *Client) GetStream(id int) (Stream, error)

GetStream returns the reponse for GET /streams/:id. It retrieves the details of any stream that the token has access to. Supply an ID and Sqwiggle will return the corresponding chat stream object.

func (*Client) GetUser

func (c *Client) GetUser(id int) (User, error)

GetUser returns the reponse for GET /users/:id. It retrieves the details of any user that the token has access to. Supply an ID and Sqwiggle will return the corresponding chat user object.

func (*Client) ListAttachments

func (c *Client) ListAttachments(page, limit int) ([]Attachment, error)

ListAttachments returns a list of all attachments in the current organization. The attachments are returned in reverse date order by default.

func (*Client) ListConversations

func (c *Client) ListConversations(page, limit int) ([]Conversation, error)

ListConversations returns a list of all conversations the current token has access to.

func (*Client) ListInvites

func (c *Client) ListInvites(page, limit int) ([]Invite, error)

ListInvites returns a list of all outstanging invites in the current organization.

func (*Client) ListMessages

func (c *Client) ListMessages(page, limit int) ([]Message, error)

ListMessages returns the reponse for GET /messages. It returns all messages in the current organization across all streams. The messages are returned in reverse date order by default. If page or limit is set to zero, the defaults are used.

Example

The following code instantiates a client, then calls the ListMessages method to return a slice of Messages. If no error occurred, it iterates through the messages and prints them out one by one.

package main

import (
	"fmt"

	"github.com/hermanschaaf/sqwiggle"
)

func main() {
	client := sqwiggle.NewClient("YOUR-API-KEY")

	page, limit := 0, 50
	msgs, err := client.ListMessages(page, limit)
	if err != nil {
		panic(err)
	}

	for _, m := range msgs {
		fmt.Printf("%s: %s\n", m.Author.Name, m.Text)
	}
}
Output:

func (*Client) ListOrganizations

func (c *Client) ListOrganizations(page, limit int) ([]Organization, error)

ListOrganizations returns a list of all organizations the current token has access to. At this time each user can only belong to a single organization and all API requests are scoped by a single organization.

func (*Client) ListStreams

func (c *Client) ListStreams(page, limit int) ([]Stream, error)

ListStreams returns the reponse for GET /streams. It returns a list of all streams in the current organization. The streams are returned in sorted alphabetical order by default.

func (*Client) ListUsers

func (c *Client) ListUsers(page, limit int) ([]User, error)

ListUsers returns the reponse for GET /users. It returns a list of all users in the current organization.

func (*Client) PostAttachment

func (c *Client) PostAttachment(name string) (Attachment, error)

PostAttachment creates a new attachment for the organization. Attachments can be created from the app interfaces, or programatically via the API. Sqwiggle currently has no restrictions on the number of chat attachments you can create within an organization.

func (*Client) PostInvite

func (c *Client) PostInvite(email string) (Invite, error)

PostInvite creates a new invite for the organization. When an invite is created an email is automatically sent to the recipients address asking them to join your organization. Please bear this in mind when creating invites for test purposes, abuse of this API may result in your account becoming blocked.

func (*Client) PostMessage

func (c *Client) PostMessage(streamID int, text string, options *PostMessageOptions) (Message, error)

PostMessage creates a new message in the chat stream, which will be pushed to connected clients. If a link is detected in the message then it will be parsed and appropriate attachments will be automatically generated - for example a link to a youtube video would generate an attachment of type 'Video' with corresponding fields.

You can also "@mention" a user by including a specially formatted string in the message text. The format is illustrated below, simply replace user_name and user_id with a given users name and id.

@(user_name)[user:user_id]
Example

The following code instantiates a client, then calls the PostMessage method to create a single message. If no error occurred, it prints out the author name and text of the new message.

package main

import (
	"fmt"

	"github.com/hermanschaaf/sqwiggle"
)

func main() {
	client := sqwiggle.NewClient("YOUR-API-KEY")

	streamID := 48914
	text := "Hello from the <b>Go Sqwiggle API Client</b>!"
	options := sqwiggle.PostMessageOptions{
		Format: "html", // allow the use of certain HTML tags in the message
		Parse:  false,  // don't parse rich attachments in the message
	}
	m, err := client.PostMessage(streamID, text, &options) // it is also okay to pass in nil for options
	if err != nil {
		panic(err)
	}

	fmt.Printf("[%d] %s: %s\n", m.ID, m.Author.Name, m.Text)
}
Output:

func (*Client) PostStream

func (c *Client) PostStream(name string) (Stream, error)

PostStream creates a new stream for the organization. Streams can be created from the app interfaces, or programatically via the API. Sqwiggle currently has no restrictions on the number of chat streams you can create within an organization.

func (*Client) UpdateAttachment

func (c *Client) UpdateAttachment(id int, form url.Values) (Attachment, error)

UpdateAttachment updates the specified attachment by setting the values of the parameters passed. Note that changes made via the API will be immediately reflected in the interface of all connected clients.

Supported values are all optional:

title	A title for the attachment, for example a filename or webpage title
description	A description of the attachment, for example a web page summary
url	The URL of the attachment, this may not reside on Sqwiggle's servers
image	The URL for an optional preview image
status	If an upload, this string denotes whether the upload is 'pending' or 'uploaded'. (Null if not an upload E.G. a link attachment)

func (*Client) UpdateMessage

func (c *Client) UpdateMessage(id int, text string) (Message, error)

UpdateMessage updates the specified message by setting the values of the parameters passed. Note that changes made via the API will be immediately reflected in the interface of all connected clients.

Example

The following code instantiates a client, then calls the UpdateMessage method to update a single message. If no error occurred, it prints out the author name and text of the new message.

package main

import (
	"fmt"

	"github.com/hermanschaaf/sqwiggle"
)

func main() {
	client := sqwiggle.NewClient("YOUR-API-KEY")

	messageID := 48914
	text := "Hello again from the <b>Go Sqwiggle API Client</b>!"
	m, err := client.UpdateMessage(messageID, text)
	if err != nil {
		panic(err)
	}

	fmt.Printf("[%d] %s: %s\n", m.ID, m.Author.Name, m.Text)
}
Output:

func (*Client) UpdateOrganization

func (c *Client) UpdateOrganization(id int, values url.Values) (Organization, error)

UpdateOrganization updates the specified organization by setting the values of the parameters passed. At this time the only parameter that can be changed is the organization name, paths will be automatically generated.

Optional parameters are:

name	The oranizations name

func (*Client) UpdateStream

func (c *Client) UpdateStream(id int, name string) (Stream, error)

UpdateStream updates the specified stream by setting the values of the parameters passed. At this time the only parameter that can be changed is the name, paths will be automatically generated.

func (*Client) UpdateUser

func (c *Client) UpdateUser(id int, values url.Values) (User, error)

UpdateUser updates the specified user by setting the values of the parameters passed. Any parameters not provided will be left unchanged, and unrecognised parameters will result in the request returning an error response.

The parameters that may be set are:

name	The users full display name
email	The users email address
time_zone	The users time zone (in rails format)
avatar	A URL pointing to the users avatar, this must reside on Sqwiggle's servers
status	Status enum may be set to one of 'busy', 'available' or 'offline'
message	A custom message which will be displayed to other users
snapshot	A URL pointing to the users current snapshot
snapshot_interval	An integer specifying how often an automatic snapshot should be taken, must be set to 0 or greater than 59

All parameters are optional.

type Conversation

type Conversation struct {
	ID            int                `json:"id"`
	Status        ConversationStatus `json:"status"`        // open, closed
	Duration      int                `json:"duration"`      // The number of seconds this conversation lasted, or if open has been ongoing.
	CreatedAt     time.Time          `json:"created_at"`    // The time this conversation was started
	Participating []User             `json:"participating"` // A list of User objects that are currently participating in the conversation
	Participated  []User             `json:"participated"`  // A list of User objects that have been and or are currently in the conversation

	// undocumented
	ColorID   int  `json:"color_id"`
	MCU       bool `json:"mcu"`
	MCUServer bool `json:"mcu_server"`
	Locked    bool `json:"locked"`
}

Conversation represents an ephemeral media connection between two or more people.

type ConversationStatus

type ConversationStatus string

ConversationStatus describes the status of a conversation

const (
	ConversationOpen   ConversationStatus = "open"
	ConversationClosed                    = "closed"
)

These ConversationStatus constants describe the possible statuses of a conversation, i.e. open or closed.

type Error

type Error struct {
	Type    ErrorType `json:"type"`
	Message string    `json:"message"`
	Details string    `json:"details"`
	Param   string    `json:"param"`
}

Error represents an error that could be returned by the Sqwiggle API

func (Error) Error

func (err Error) Error() string

Error is an implementation of the error interface

type ErrorType

type ErrorType string

ErrorType is a type that describes the type of error returned by the Sqwiggle API. The constants below are defined to use this type.

func (ErrorType) String

func (e ErrorType) String() string

type Invite

type Invite struct {
	ID        int       `json:"id"`
	FromID    int       `json:"from_id"`    // ID of the user that created the invite
	Email     string    `json:"email"`      // The email address that this invite was sent to
	Avatar    string    `json:"avatar"`     // URL to a static avatar representing the email address
	URL       string    `json:"url"`        // URL to redeem the invite
	CreatedAt time.Time `json:"created_at"` // The time that this invite was created
}

Invite describes an invitation sent out to a user to join the organization

type Mention

type Mention struct {
	ID          int      `json:"id"`
	MessageID   int      `json:"message_id"`
	Name        string   `json:"name"`
	Indices     []int    `json:"indices"`
	Text        string   `json:"text"`
	SubjectType UserType `json:"subject_type"`
	SubjectID   int      `json:"subject_id"`
}

Mention represents a mention as part of a message in any chat stream.

type Message

type Message struct {
	ID          int          `json:"id"`          // ID of the message
	StreamID    int          `json:"stream_id"`   // ID of the chat stream that this message belongs to
	Text        string       `json:"text"`        // The plain text content of the message, HTML will be escaped
	Author      User         `json:"author"`      // An object representing the user or API client that created the message
	Attachments []Attachment `json:"attachments"` // A list of Attachment objects to be displayed with this message
	Mentions    []Mention    `json:"mentions"`    // A list of users tagged / mentioned in this message
	CreatedAt   time.Time    `json:"created_at"`  // The time that this message was created
	UpdatedAt   time.Time    `json:"updated_at"`  // The time that this message was last updated or edited

	// Undocumented
	ConversationID *int `json:"conversation_id,omitempty"`
}

Message represents an item in any chat stream. They may be created by humans, bots or the Sqwiggle servers.

type OrgBilling

type OrgBilling struct {
	Plan       string `json:"plan"`        // undocumented
	Status     string `json:"status"`      // undocumented, but can be "trial"
	ActiveCard bool   `json:"active_card"` // whether the organization has an active credit card
	Receipts   bool   `json:"receipts"`    // whether the organization wants receipts
	Email      string `json:"email"`       // the organization billing email address
}

OrgBilling represents the billing information for an organization.

type OrgSecurity

type OrgSecurity struct {
	MediaAccept     bool `json:"media_accept"`
	DomainRestrict  bool `json:"domain_restrict"`
	DomainSignup    bool `json:"domain_signup"`
	OpenInvites     bool `json:"open_invites"`
	UploadsDisabled bool `json:"uploads_disabled"`
	ManualDisabled  bool `json:"manual_disabled"`
}

OrgSecurity represents the known fields returned in the security field of Organizations. These fields are not explained in the documentation, so it's up to you to figure out what they mean (or PR if you know).

type Organization

type Organization struct {
	ID        int         `json:"id"`
	Name      string      `json:"name"`       // The organizations name
	CreatedAt time.Time   `json:"created_at"` // The time that this company was created
	Path      string      `json:"path"`       // The url path to access company on app, eg sqwiggle.com/:path
	Billing   OrgBilling  `json:"billing"`
	Security  OrgSecurity `json:"security"`

	// Undocumented
	InviteURL                   string `json:"invite_url"`
	UserCount                   int    `json:"user_count"`
	MaxConversationParticipants int    `json:"max_conversation_participants"`
}

Organization represents a single organization that every user must belong to.

type PostMessageOptions

type PostMessageOptions struct {
	Format string // Set this parameter to 'html' to allow a subset of HTML tags in the message
	Parse  bool   // Whether links in the message should be converted to rich attachments
}

PostMessageOptions is a struct that can be optionally passed to the Client.PostMessage method. It defines the optional parameters available for the /messages POST endpoint.

type Stream

type Stream struct {
	ID         int       `json:"id"`
	UserID     int       `json:"user_id"`    // Id of the user that created this stream
	Name       string    `json:"name"`       // The full stream name
	Path       string    `json:"path"`       // The path to access stream in the web app, eg app.sqwiggle.com/:path
	Icon       string    `json:"icon"`       // An icon representing the stream
	IconColor  string    `json:"icon_color"` // A color representing the stream in hex format (eg: #121212)
	Subscribed bool      `json:"subscribed"` // Whether the user receives notifications for this stream
	CreatedAt  time.Time `json:"created_at"` // The time that this stream was created

	// Undocumented:
	Status      StreamStatus `json:"status"`
	Type        StreamType   `json:"type"`
	Description string       `json:"description"`
}

Stream represents a stream object in the Sqwiggle API, which is similar to the concept of a Room.

type StreamStatus

type StreamStatus string

StreamStatus represents the status of a stream

const (
	StreamStatusActive   StreamStatus = "active"
	StreamStatusInactive              = "inactive"
)

The StreamStatus constants below represent the possible stream states - this is undocumented in the API docs, so take it with a grain of salt.

type StreamType

type StreamType string

StreamType represents the type of a stream

const (
	StreamTypeStandard StreamType = "standard"
	StreamTypeSupport             = "support"
)

The StreamType constants below represent the possible stream types - this is undocumented in the API docs, so take it with a grain of salt.

type User

type User struct {
	ID     int    `json:"id"`
	Name   string `json:"name"`   // The users full name
	Avatar string `json:"avatar"` // URL to a static avatar for the user

	Role          UserRole   `json:"role"`            // user, owner, manager or banned
	MediaDeviceID string     `json:"media_device_id"` // A string representing current device that media is being received on
	Status        UserStatus `json:"status"`          // busy, available
	Message       string     `json:"message"`         // A status message that other users see, such as “out for lunch”

	Email string `json:"email"` // The users email address

	Snapshot         string    `json:"snapshot"`          // URL to the last snapshot for this user (auto or manual)
	SnapshotInterval int       `json:"snapshot_interval"` // Frequency at which automatic snapshots are taken when the app is open
	Confirmed        bool      `json:"confirmed"`         // The users email confirmation status
	TimeZone         string    `json:"time_zone"`         // Timezone (rails format)
	TimeZoneOffset   float64   `json:"time_zone_offset"`  // Hours offset from UTC, note that this may be a non-integer like 5.5
	CreatedAt        time.Time `json:"created_at"`        // The time this user was created
	LastActiveAt     time.Time `json:"last_active_at"`    // The last time we recorded activity for a user
	LastConnectedAt  time.Time `json:"last_connected_at"` // The time this users current online session started

	// undocumented:
	Type UserType `json:"type,omitempty"`
	// IdleAt
	// Contact
	Support bool `json:"support,omitempty"` // Indicates whether user is support or not
}

User represents a single person on your organization's team.

type UserRole

type UserRole string

UserRole describes the role of a user, i.e. normal user, owner, manager or banned

func (UserRole) String

func (ur UserRole) String() string

type UserStatus

type UserStatus string

UserStatus describes the current status of the user

type UserType

type UserType string

UserType describes the type of user, i.e. normal user or support

Jump to

Keyboard shortcuts

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