zulip

package module
v0.1.0-alpha Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2025 License: Unlicense Imports: 19 Imported by: 0

README

go-zulip

Golang Client Library for Zulip (9.4)

go-zulip is a Golang client library designed to interact with Zulip's REST API. It allows you to send messages, receive real-time events, and perform various other operations with ease.

Go Report Card Build Status Go Reference

Installation

go get github.com/wakumaku/go-zulip@latest
Usage

Initialize the client with your Zulip server URL, email, and API key.

credentials := zulip.Credentials("https://chat.zulip.org", "email@zulip.org", "0123456789")
c, err := zulip.NewClient(credentials)
if err != nil {
	log.Fatal(err)
}

Or from a .zuliprc file

credentials := zulip.CredentialsFromZuliprc("path/to/.zuliprc")
c, err := zulip.NewClient(credentials)
if err != nil {
	log.Fatal(err)
}

Sending a message:

// Create a new message service
msgSvc := messages.NewService(c)

// Send a message to a channel/topic
resp, err := msgSvc.SendMessageToChannelTopic(ctx, 
	recipient.ToChannel("general"), "greetings", 
	"Hello Zulip!",
)

...

// Send a private message to a user
resp, err := msgSvc.SendMessageToUsers(ctx, 
	recipient.ToUser("john.doe"), 
	"Hello John!",
)

...

// Send a private message to multiple users
usernames := []string{"john.doe", "jane.doe"}
resp, err := msgSvc.SendMessageToUsers(ctx, 
	recipient.ToUsers(usernames), 
	"Hello John and Jane!",
)

Receiving realtime events:

// Create a new realtime service
realtimeSvc := realtime.NewService(c)

// Register a queue passing the events we want to receive
queue, err := realtimeSvc.RegisterEvetQueue(ctx,
	realtime.EventTypes(
		events.AlertWordsType,
		events.AttachmentType,
		events.MessageType,
		events.PresenceType,
		events.RealmEmojiType,
		events.RealmUserType,
		events.SubmessageType,
		events.TypingType,
		events.UpdateMessageType,
	),
	realtime.AllPublicStreams(true),
)
if err != nil {
	log.Fatalf("error registering event queue: %s", err)
}

if queue.IsError() {
	log.Fatalf("%s: %s", queue.Msg(), queue.Code())
}

log.Printf("QueueId: %s", queue.QueueId)

lastEventID := queue.LastEventId

// Infinite loop polling for new events
for {
	// Long polling HTTP Request
	eventsFromQueue, err := realtimeSvc.GetEventsEventQueue(ctx, queue.QueueId, realtime.LastEventID(lastEventID))
	if err != nil {
		log.Fatalf("error getting events from queue: %s", err)
	}

	for _, e := range eventsFromQueue.Events {
		log.Printf("#%d %s", e.EventID(), e.EventType())
		lastEventID = e.EventID()
	}
}
Other Examples

Check /examples folder.

  • Talking Robots: two bots talking demonstrating sending messages, reactions and events

Talking Robots Running

Supported API Endpoints
  • Messages

    • Send a message
    • Upload a file
    • Edit a message
    • Delete a message
    • Get messages
    • Add an emoji reaction
    • Remove an emoji reaction
    • Render a message
    • Fetch a single message
    • Check if messages match a narrow
    • Get a message's edit history
    • Update personal message flags
    • Update personal message flags for narrow
    • Get a message's read receipts
  • Scheduled messages

    • Get scheduled messages
    • Create a scheduled message
    • Edit a scheduled message
    • Delete a scheduled message
  • Drafts

    • Get drafts
    • Create drafts
    • Edit a draft
    • Delete a draft
    • Get all saved snippets
    • Create a saved snippet
    • Delete a saved snippet
  • Channels

    • Get subscribed channels
    • Subscribe to a channel
    • Unsubscribe from a channel
    • Get subscription status
    • Get channel subscribers
    • Update subscription settings
    • Get all channels
    • Get a channel by ID
    • Get channel ID
    • Create a channel - see Subscribe to a channel
    • Update a channel
    • Archive a channel
    • Get channel's email address
    • Get topics in a channel
    • Topic muting
    • Update personal preferences for a topic
    • Delete a topic
    • Add a default channel
    • Remove a default channel
  • Users

    • Get a user
    • Get a user by email
    • Get own user
    • Get all users
    • Create a user
    • Update a user
    • Update a user by email
    • Deactivate a user
    • Deactivate own user
    • Reactivate a user
    • Get a user's status
    • Update your status
    • Set "typing" status
    • Get a user's presence
    • Get presence of all users
    • Update your presence
    • Get attachments
    • Delete an attachment
    • Update settings
    • Get user groups
    • Create a user group
    • Update a user group
    • Deactivate a user group
    • Update user group members
    • Update subgroups of a user group
    • Get user group membership status
    • Get user group members
    • Get subgroups of a user group
    • Mute a user
    • Unmute a user
    • Get all alert words
    • Add alert words
    • Remove alert words
  • Invitations

    • Get all invitations
    • Send invitations
    • Create a reusable invitation link
    • Resend an email invitation
    • Revoke an email invitation
    • Revoke a reusable invitation link
  • Server & organizations

    • Get server settings
    • Get linkifiers
    • Add a linkifier
    • Update a linkifier
    • Remove a linkifier
    • Reorder linkifiers
    • Add a code playground
    • Remove a code playground
    • Get all custom emoji
    • Upload custom emoji
    • Deactivate custom emoji
    • Get all custom profile fields
    • Reorder custom profile fields
    • Create a custom profile field
    • Update realm-level defaults of user settings
    • Get all data exports
    • Create a data export
    • Get data export consent state
  • Real-time events

    • Register an event queue
    • Get events from an event queue
    • Delete an event queue
    • Event Types
      • AlertWords
      • Attachment: add, removem update
      • CustomProfileFields
      • DefaultStreamGroups
      • DefaultStreams
      • DeleteMessage
      • Drafts: add, remove, update
      • HasZoomToken
      • Heartbeat
      • InvitesChanged
      • Message
      • MutedTopics
      • MutedUsers
      • OnboardingSteps
      • Presence
      • Reaction: add, remove
      • Realm: deactivated , update , updatedict
      • RealmBot: add, delete, remove, update
      • RealmDomains: add, change, remove
      • RealmEmoji: update
      • RealmExport
      • RealmExportConsent
      • RealmFilters
      • RealmLinkifiers
      • RealmPlaygrounds
      • RealmUser: add, remove, update
      • RealmUserSettingsDefaults: update
      • Restart
      • SavedSnippets: add, remove
      • ScheduledMessages: add, remove, update
      • Stream: create, delete, update
      • Submessage
      • Subscription: add, peeradd, peerremove, remove, update
      • Typing: start, stop
      • UpdateDisplaySettings
      • UpdateGlobalNotifications
      • UpdateMessage
      • UpdateMessageFlags: add, remove
      • UserGroup: add, addmembers, addsubgroups, remove, removemembers, removesubgroups, update
      • UserSettings: update
      • UserStatus
      • UserTopic
      • WebReloadClient
  • Specialty endpoints

    • Fetch an API key (production)
    • Fetch an API key (development only)
    • Send a test notification to mobile device(s)
    • Add an APNs device token
    • Remove an APNs device token
    • Add an FCM registration token
    • Remove an FCM registration token
    • Create BigBlueButton video call
Developing

Check /dev folder and read the SETUP.md file.

Documentation

For detailed documentation on all available methods and features, please refer to the GoDoc.

Contributing

Contributions are welcome! Please open an issue or submit a pull request on GitHub.

Documentation

Index

Constants

View Source
const (
	// X-RateLimit-Remaining: The number of additional requests of this type
	// that the client can send before exceeding its limit.
	XRateLimitRemaining string = "X-RateLimit-Remaining"
	// X-RateLimit-Limit: The limit that would be applicable to a client that
	// had not made any recent requests of this type. This is useful for
	// designing a client's burst behavior so as to avoid ever reaching a
	// rate limit.
	XRateLimitLimit string = "X-RateLimit-Limit"
	// X-RateLimit-Reset: The time at which the client will no longer have any
	// rate limits applied to it (and thus could do a burst of
	// X-RateLimit-Limit requests).
	XRateLimitReset string = "X-RateLimit-Reset"

	// ResultSuccess is the string returned in the result field when there is
	// a success operation
	ResultSuccess string = "success"
	// ResultError is the string returned in the result field when there is
	// an error
	ResultError string = "error"
)
View Source
const (
	RESTClientDefaultTimeout  = 5 * time.Second
	RESTClientLongPollTimeout = 10 * time.Minute
)
View Source
const (
	DefaultUserAgentName = "go-zulip"
	Version              = "v0.1.0-alpha"
)

Variables

This section is empty.

Functions

This section is empty.

Types

type APIResponse

type APIResponse interface {
	SetHTTPCode(httpCode int)
	SetHTTPHeaders(headers http.Header)
	json.Unmarshaler
	json.Marshaler
}

APIResponse is the interface that wraps the basic methods of an API response.

type APIResponseBase

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

APIResponseBase is the base struct for all API responses.

func (APIResponseBase) AllFields

func (a APIResponseBase) AllFields() map[string]any

AllFields returns all the fields in the response.

func (APIResponseBase) Code

func (a APIResponseBase) Code() string

Code returns a machine-readable error string.

func (APIResponseBase) FieldValue

func (a APIResponseBase) FieldValue(field string) (any, error)

FieldValue returns the value of a field in the response.

func (APIResponseBase) HTTPCode

func (a APIResponseBase) HTTPCode() int

HTTPCode returns the HTTP status code of the response.

func (APIResponseBase) HTTPHeaders

func (a APIResponseBase) HTTPHeaders() http.Header

HTTPHeaders returns the HTTP headers of the response.

func (APIResponseBase) IsError

func (a APIResponseBase) IsError() bool

IsError returns true if the result is an error.

func (APIResponseBase) IsSuccess

func (a APIResponseBase) IsSuccess() bool

IsSuccess returns true if the result is a success.

func (APIResponseBase) MarshalJSON

func (a APIResponseBase) MarshalJSON() ([]byte, error)

func (APIResponseBase) Msg

func (a APIResponseBase) Msg() string

Msg returns the human-readable error message string.

func (APIResponseBase) Result

func (a APIResponseBase) Result() string

Result returns either "error" or "success".

func (*APIResponseBase) SetHTTPCode

func (a *APIResponseBase) SetHTTPCode(code int)

SetHTTPCode sets the HTTP status code of the response.

func (*APIResponseBase) SetHTTPHeaders

func (a *APIResponseBase) SetHTTPHeaders(headers http.Header)

SetHTTPHeaders sets the HTTP headers of the response.

func (*APIResponseBase) UnmarshalJSON

func (a *APIResponseBase) UnmarshalJSON(b []byte) error

func (APIResponseBase) XRateLimitLimit

func (a APIResponseBase) XRateLimitLimit() string

func (APIResponseBase) XRateLimitRemaining

func (a APIResponseBase) XRateLimitRemaining() string

func (APIResponseBase) XRateLimitReset

func (a APIResponseBase) XRateLimitReset() string

type Client

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

Client is the main HTTP Client to interact with Zulip's API

func NewClient

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

func (*Client) DoFileRequest

func (c *Client) DoFileRequest(ctx context.Context, method, path string, fileName string, file io.Reader, response APIResponse, opts ...DoRequestOption) error

DoFileRequest is the main function to send requests to Zulip's API with a file. For file and emoji uploads.

func (*Client) DoRequest

func (c *Client) DoRequest(ctx context.Context, method, path string, data map[string]any, response APIResponse, opts ...DoRequestOption) error

DoRequest is the main function to send requests to Zulip's API.

type ClientOption

type ClientOption func(*clientOptions) error

func WithCustomUserAgent

func WithCustomUserAgent(userAgent string) ClientOption

func WithHTTPClient

func WithHTTPClient(client *http.Client) ClientOption

func WithLogger

func WithLogger(logger *slog.Logger) ClientOption

type CredentialsProvider

type CredentialsProvider func() (*credentials, error)

func Credentials

func Credentials(site, email, apiKey string) CredentialsProvider

func CredentialsFromZuliprc

func CredentialsFromZuliprc(filePath string, section string) CredentialsProvider

type DoRequestOption

type DoRequestOption func(*clientSendRequestOptions)

func WithTimeout

func WithTimeout(duration time.Duration) DoRequestOption

type OrganizationRoleLevel

type OrganizationRoleLevel int
const (
	OwnerRole         OrganizationRoleLevel = 100
	AdministratorRole OrganizationRoleLevel = 200
	ModeratorRole     OrganizationRoleLevel = 300
	MemberRole        OrganizationRoleLevel = 400
	GuestRole         OrganizationRoleLevel = 600
)

type RESTClient

type RESTClient interface {
	DoRequest(ctx context.Context, method, path string, data map[string]any, response APIResponse, opts ...DoRequestOption) error
	DoFileRequest(ctx context.Context, method, path string, fileName string, file io.Reader, response APIResponse, opts ...DoRequestOption) error
}

type ReactionType

type ReactionType string
const (
	UnicodeEmojiType    ReactionType = "unicode_emoji"
	RealmEmojiType      ReactionType = "realm_emoji"
	ZulipExtraEmojiType ReactionType = "zulip_extra_emoji"
)

type SectionData

type SectionData struct {
	Email  string
	APIKey string
	Site   string
}

SectionData represents the key-value pairs of a section in a zuliprc file

type Zuliprc

type Zuliprc map[string]SectionData

Zuliprc represents the content of a zuliprc file It is a map of sections, where each section is a map of key-value pairs

func ParseZuliprc

func ParseZuliprc(file string) (Zuliprc, error)

Jump to

Keyboard shortcuts

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