chatwork

package module
v0.0.0-...-8716ecf Latest Latest
Warning

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

Go to latest
Published: Jun 17, 2025 License: MIT Imports: 11 Imported by: 0

README

chatwork-go

Go Reference Go Report Card

A Go client library for the ChatWork API.

Installation

go get github.com/nashirox/chatwork-go

Quick Start

import "github.com/nashirox/chatwork-go"

// Create a new client with your API token
client := chatwork.New("YOUR_API_TOKEN")

// Get your rooms
rooms, _, err := client.Rooms.List(context.Background())
if err != nil {
    log.Fatal(err)
}

// Send a message
resp, _, err := client.Messages.SendMessage(context.Background(), roomID, "Hello, ChatWork!")

Usage Examples

Authentication

The library uses API token authentication. You can obtain your API token from your ChatWork account settings.

client := chatwork.New("YOUR_API_TOKEN")
Rooms
ctx := context.Background()

// List all rooms
rooms, _, err := client.Rooms.List(ctx)

// Get a specific room
room, _, err := client.Rooms.Get(ctx, roomID)

// Create a new room
params := &chatwork.RoomCreateParams{
    Name:             "Project Room",
    Description:      "Discussion about the project",
    MembersAdminIDs:  []int{123456},
    MembersMemberIDs: []int{789012, 345678},
}
room, _, err := client.Rooms.Create(ctx, params)

// Update room information
updateParams := &chatwork.RoomUpdateParams{
    Name:        "Updated Project Room",
    Description: "Updated description",
}
room, _, err = client.Rooms.Update(ctx, roomID, updateParams)

// Leave a room
_, err = client.Rooms.Leave(ctx, roomID)

// Delete a room (creator only)
_, err = client.Rooms.DeleteRoom(ctx, roomID)
Messages
// Send a simple message
resp, _, err := client.Messages.SendMessage(ctx, roomID, "Hello, World!")

// Send a message with mentions
accountIDs := []int{123456, 789012}
resp, _, err = client.Messages.SendTo(ctx, roomID, accountIDs, "Hello team!")

// Reply to a message
resp, _, err = client.Messages.Reply(ctx, roomID, messageID, "Thanks for the message!")

// Quote a message
resp, _, err = client.Messages.Quote(ctx, roomID, messageID, "I agree with this")

// Send an info message
resp, _, err = client.Messages.SendInfo(ctx, roomID, "Important Notice", "Meeting at 3 PM")

// Get messages in a room
messages, _, err := client.Messages.List(ctx, roomID, nil)

// Get a specific message
message, _, err := client.Messages.Get(ctx, roomID, messageID)

// Update a message
updateParams := &chatwork.MessageUpdateParams{
    Body: "Updated message content",
}
message, _, err = client.Messages.Update(ctx, roomID, messageID, updateParams)

// Delete a message
_, _, err = client.Messages.Delete(ctx, roomID, messageID)
Tasks
// Create a task
params := &chatwork.TaskCreateParams{
    Body:  "Complete the report",
    ToIDs: []int{123456},
}
taskResp, _, err := client.Tasks.Create(ctx, roomID, params)

// Create a task with deadline
deadline := time.Now().Add(24 * time.Hour).Unix()
taskResp, _, err = client.Tasks.CreateWithDeadline(ctx, roomID, "Submit by tomorrow", []int{123456}, deadline)

// Get task information
task, _, err := client.Tasks.Get(ctx, roomID, taskID)

// Complete a task
task, _, err = client.Tasks.Complete(ctx, roomID, taskID)

// Reopen a task
task, _, err = client.Tasks.Reopen(ctx, roomID, taskID)

// Get my tasks
myTasks, _, err := client.MyTasks.List(ctx, nil)

// Get only open tasks
openTasks, _, err := client.MyTasks.GetOpen(ctx)

// Get completed tasks
completedTasks, _, err := client.MyTasks.GetCompleted(ctx)
User Information
// Get my information
me, _, err := client.Me.Get(ctx)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Name: %s\n", me.Name)
fmt.Printf("ChatWork ID: %s\n", me.ChatworkID)

// Get my status
status, _, err := client.Me.GetStatus(ctx)
fmt.Printf("Unread messages: %d\n", status.UnreadNum)
fmt.Printf("Unread rooms: %d\n", status.UnreadRoomNum)
fmt.Printf("Unread mentions: %d\n", status.MentionNum)
fmt.Printf("Unread tasks: %d\n", status.MytaskNum)
Contacts
// Get all contacts
contacts, _, err := client.Contacts.List(ctx)

// Get incoming requests
requests, _, err := client.IncomingRequests.List(ctx)

// Approve a contact request
approval, _, err := client.IncomingRequests.Approve(ctx, requestID)

// Reject a contact request
_, err = client.IncomingRequests.Reject(ctx, requestID)
Files
// Get files in a room
files, _, err := client.Rooms.GetFiles(ctx, roomID, 0)

// Get files uploaded by a specific user
files, _, err = client.Rooms.GetFiles(ctx, roomID, accountID)

// Get file information with download URL
file, _, err := client.Rooms.GetFile(ctx, roomID, fileID, true)
Error Handling

The library provides detailed error information through the ErrorResponse type:

resp, _, err := client.Messages.SendMessage(ctx, roomID, "Hello")
if err != nil {
    if chatworkErr, ok := err.(*chatwork.ErrorResponse); ok {
        // ChatWork API error
        fmt.Printf("API Error: %v\n", chatworkErr.Errors)
        fmt.Printf("Status Code: %d\n", chatworkErr.Response.StatusCode)
    } else {
        // Other error (network, etc.)
        fmt.Printf("Error: %v\n", err)
    }
}
Custom HTTP Client

You can provide a custom HTTP client for advanced use cases:

httpClient := &http.Client{
    Timeout: 30 * time.Second,
    // Add custom transport, middleware, etc.
}

client := chatwork.New("YOUR_API_TOKEN", 
    chatwork.OptionHTTPClient(httpClient),
)

API Coverage

  • Rooms: List, Create, Get, Update, Delete, Leave
  • Room Members: Get, Update
  • Messages: List, Create, Get, Update, Delete
  • Message Features: Mentions, Replies, Quotes, Info messages
  • Tasks: Create, Get, Update status
  • My Tasks: List, Filter by status
  • Me: Get profile, Get status
  • Contacts: List
  • Incoming Requests: List, Approve, Reject
  • Files: List, Get with download URL
  • Read Status: Get unread count, Mark as read

Rate Limiting

ChatWork API has rate limits. The library exposes rate limit information in the Response struct:

messages, resp, err := client.Messages.List(ctx, roomID, nil)
if resp != nil {
    fmt.Printf("Rate Limit: %d\n", resp.RateLimit.Limit)
    fmt.Printf("Remaining: %d\n", resp.RateLimit.Remaining)
    fmt.Printf("Reset: %d\n", resp.RateLimit.Reset)
}

Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Testing

Run tests with:

go test ./...

For integration tests with the actual API, set your API token:

export CHATWORK_API_TOKEN="your_token"
go test -tags=integration ./...

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

Support

Documentation

Overview

Package chatwork provides a client library for the ChatWork API.

The ChatWork API is a RESTful API for ChatWork, a group chat service. This library provides a simple and idiomatic way to interact with the API from Go applications.

Usage

Import the package:

import "github.com/nashirox/chatwork-go"

Create a new client with your API token:

client := chatwork.New("YOUR_API_TOKEN")

Use the client to interact with various endpoints:

// Get rooms
rooms, _, err := client.Rooms.List(context.Background())

// Send a message
resp, _, err := client.Messages.SendMessage(context.Background(), roomID, "Hello!")

For more detailed examples, see the README and example files.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CheckResponse

func CheckResponse(r *http.Response) error

CheckResponse checks the API response for errors.

ChatWork API returns non-2xx status codes to indicate errors. This function extracts error information from the response body and returns an appropriate error type.

Types

type APIError

type APIError struct {
	// The HTTP response that caused this error
	Response *http.Response

	// Error messages returned by the API
	Errors []string `json:"errors"`
}

APIError represents an error response from the ChatWork API.

ChatWork API returns error details in the response body when requests fail. This type captures those details and implements the error interface.

func (*APIError) Error

func (r *APIError) Error() string

Error returns a human-readable description of the API error. It includes the HTTP method, URL, status code, and error messages.

type Client

type Client struct {

	// Base URL for API requests. Defaults to the public ChatWork API.
	BaseURL *url.URL

	// User agent used when communicating with the ChatWork API.
	UserAgent string

	// Services for each endpoint
	Rooms            *RoomsService
	Messages         *MessagesService
	Me               *MeService
	MyTasks          *MyTasksService
	Contacts         *ContactsService
	Tasks            *TasksService
	IncomingRequests *IncomingRequestsService
	// contains filtered or unexported fields
}

Client manages communication with the ChatWork API.

The Client is the main entry point for interacting with the ChatWork API. It provides access to various API endpoints through service properties. The zero value is not usable; use New to create a configured client.

func New

func New(token string, options ...ClientOption) *Client

New creates a new ChatWork API client with the provided API token.

The API token can be obtained from your ChatWork account settings. You can provide additional options to customize the client behavior.

Example:

client := chatwork.New("YOUR_API_TOKEN")

// With custom HTTP client
httpClient := &http.Client{Timeout: 30 * time.Second}
client := chatwork.New("YOUR_API_TOKEN", chatwork.OptionHTTPClient(httpClient))

func (*Client) Do

func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*Response, error)

Do sends an API request and returns the API response.

The API response is JSON decoded and stored in the value pointed to by v, or returned as an error if an API error has occurred. If v implements the io.Writer interface, the raw response body will be written to v, without attempting to first decode it.

The provided context is used to cancel the request if needed.

func (*Client) NewFormRequest

func (c *Client) NewFormRequest(method, urlStr string, body interface{}) (*http.Request, error)

NewFormRequest creates a new API request with form-encoded body.

This method is similar to NewRequest but encodes the body as form data instead of JSON. It's used for endpoints that expect form-encoded data.

The body parameter should be a struct with url tags for encoding.

func (*Client) NewFormRequestWithContext

func (c *Client) NewFormRequestWithContext(ctx context.Context, method, urlStr string, body interface{}) (*http.Request, error)

NewFormRequestWithContext creates a new API request with context and form-encoded body.

func (*Client) NewRequest

func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error)

NewRequest creates a new API request with JSON body.

The urlStr is relative to the BaseURL of the client. The body, if specified, is JSON encoded and included as the request body. The appropriate headers are automatically set.

This method is primarily used internally by service methods, but can be used directly for making custom API requests.

func (*Client) NewRequestWithContext

func (c *Client) NewRequestWithContext(ctx context.Context, method, urlStr string, body interface{}) (*http.Request, error)

NewRequestWithContext creates a new API request with context and JSON body.

type ClientOption

type ClientOption func(*Client)

ClientOption is a functional option for configuring the Client.

func OptionDebug

func OptionDebug(debug bool) ClientOption

OptionDebug enables debug mode for the client. When enabled, the client will log detailed information about API requests and responses. This is useful for troubleshooting and development.

func OptionHTTPClient

func OptionHTTPClient(httpClient *http.Client) ClientOption

OptionHTTPClient sets a custom HTTP client to be used for API requests. This is useful for setting custom timeouts, transport settings, or middleware.

Example:

httpClient := &http.Client{
	Timeout: 30 * time.Second,
}
client := chatwork.New("token", chatwork.OptionHTTPClient(httpClient))

type Contact

type Contact struct {
	AccountID        int    `json:"account_id"`
	RoomID           int    `json:"room_id"`
	Name             string `json:"name"`
	ChatworkID       string `json:"chatwork_id"`
	OrganizationID   int    `json:"organization_id"`
	OrganizationName string `json:"organization_name"`
	Department       string `json:"department"`
	AvatarImageURL   string `json:"avatar_image_url"`
}

Contact represents a user in your ChatWork contacts list.

Contacts are users you have connected with on ChatWork. This type contains their basic information and organization details.

type ContactsService

type ContactsService service

ContactsService handles communication with the contacts related methods of the ChatWork API.

ChatWork API docs: https://developer.chatwork.com/reference/contacts

func (*ContactsService) List

func (s *ContactsService) List(ctx context.Context) ([]*Contact, *Response, error)

List returns all contacts of the authenticated user.

ChatWork API docs: https://developer.chatwork.com/reference/get-contacts

type File

type File struct {
	FileID      int    `json:"file_id"`
	Account     User   `json:"account"`
	MessageID   string `json:"message_id"`
	Filename    string `json:"filename"`
	Filesize    int    `json:"filesize"`
	UploadTime  int64  `json:"upload_time"`
	DownloadURL string `json:"download_url,omitempty"`
}

File represents a file uploaded to a ChatWork room.

Files can be images, documents, or any other type of attachment. Download URLs are only included when specifically requested.

type IncomingRequest

type IncomingRequest struct {
	RequestID        int    `json:"request_id"`
	AccountID        int    `json:"account_id"`
	Message          string `json:"message"`
	Name             string `json:"name"`
	ChatworkID       string `json:"chatwork_id"`
	OrganizationID   int    `json:"organization_id"`
	OrganizationName string `json:"organization_name"`
	Department       string `json:"department"`
	AvatarImageURL   string `json:"avatar_image_url"`
}

IncomingRequest represents a pending contact request.

These are requests from other users to connect with you on ChatWork. You can approve or reject these requests.

type IncomingRequestActionResponse

type IncomingRequestActionResponse struct {
	AccountID        int    `json:"account_id"`
	RoomID           int    `json:"room_id"`
	Name             string `json:"name"`
	ChatworkID       string `json:"chatwork_id"`
	OrganizationID   int    `json:"organization_id"`
	OrganizationName string `json:"organization_name"`
	Department       string `json:"department"`
	AvatarImageURL   string `json:"avatar_image_url"`
}

IncomingRequestActionResponse represents the response when approving a contact request.

type IncomingRequestsService

type IncomingRequestsService service

IncomingRequestsService handles communication with the incoming requests related methods of the ChatWork API.

ChatWork API docs: https://developer.chatwork.com/reference/incoming-requests

func (*IncomingRequestsService) Approve

Approve approves a contact request.

ChatWork API docs: https://developer.chatwork.com/reference/put-incoming_requests-request_id

func (*IncomingRequestsService) List

List returns all pending contact requests.

ChatWork API docs: https://developer.chatwork.com/reference/get-incoming_requests

func (*IncomingRequestsService) Reject

func (s *IncomingRequestsService) Reject(ctx context.Context, requestID int) (*Response, error)

Reject rejects a contact request.

ChatWork API docs: https://developer.chatwork.com/reference/delete-incoming_requests-request_id

type Me

type Me struct {
	AccountID        int    `json:"account_id"`
	RoomID           int    `json:"room_id"`
	Name             string `json:"name"`
	ChatworkID       string `json:"chatwork_id"`
	OrganizationID   int    `json:"organization_id"`
	OrganizationName string `json:"organization_name"`
	Department       string `json:"department"`
	Title            string `json:"title"`
	URL              string `json:"url"`
	Introduction     string `json:"introduction"`
	Mail             string `json:"mail"`
	TelOrganization  string `json:"tel_organization"`
	TelExtension     string `json:"tel_extension"`
	TelMobile        string `json:"tel_mobile"`
	Skype            string `json:"skype"`
	Facebook         string `json:"facebook"`
	Twitter          string `json:"twitter"`
	AvatarImageURL   string `json:"avatar_image_url"`
	LoginMail        string `json:"login_mail"`
}

Me represents the authenticated user's detailed information.

This type contains all available information about the current user, including private details like email addresses that are not visible for other users.

type MeService

type MeService service

MeService handles communication with the "me" related methods of the ChatWork API.

ChatWork API docs: https://developer.chatwork.com/reference/me

func (*MeService) Get

func (s *MeService) Get(ctx context.Context) (*Me, *Response, error)

Get returns detailed information about the authenticated user.

This includes private information like email addresses that are not visible when viewing other users' profiles.

ChatWork API docs: https://developer.chatwork.com/reference/get-me

Example
// クライアントの作成
client := chatwork.New("YOUR_API_TOKEN")
ctx := context.Background()

// 自分の情報を取得
me, _, err := client.Me.Get(ctx)
if err != nil {
	log.Fatal(err)
}

fmt.Printf("Name: %s\n", me.Name)
fmt.Printf("ChatWork ID: %s\n", me.ChatworkID)

func (*MeService) GetStatus

func (s *MeService) GetStatus(ctx context.Context) (*MyStatus, *Response, error)

GetStatus returns the authenticated user's unread counts.

This includes counts for: - Unread messages - Unread rooms - Mentions - Tasks

ChatWork API docs: https://developer.chatwork.com/reference/get-my-status

type Member

type Member struct {
	AccountID        int    `json:"account_id"`
	Role             string `json:"role"`
	Name             string `json:"name"`
	ChatworkID       string `json:"chatwork_id"`
	OrganizationID   int    `json:"organization_id"`
	OrganizationName string `json:"organization_name"`
	Department       string `json:"department"`
	AvatarImageURL   string `json:"avatar_image_url"`
}

Member represents a member of a ChatWork room.

This includes their role in the room (admin, member, or readonly) and their basic account information.

type Message

type Message struct {
	MessageID  string `json:"message_id"`
	Account    User   `json:"account"`
	Body       string `json:"body"`
	SendTime   int64  `json:"send_time"`
	UpdateTime int64  `json:"update_time"`
}

Message represents a message in a ChatWork room.

Messages are the primary communication unit in ChatWork. They can contain text, mentions, quotes, and attachments.

type MessageCreateParams

type MessageCreateParams struct {
	Body       string `url:"body"`
	SelfUnread bool   `url:"self_unread,omitempty"`
}

MessageCreateParams represents the parameters for creating a new message.

type MessageCreatedResponse

type MessageCreatedResponse struct {
	// The ID of the created message
	MessageID string `json:"message_id"`
}

MessageCreatedResponse represents the response when a message is created.

type MessageListParams

type MessageListParams struct {
	// Force retrieval of messages
	// 0: Get up to 100 most recent messages (default)
	// 1: Get messages older than the most recent 100
	Force int
}

MessageListParams represents the parameters for listing messages.

type MessageUpdateParams

type MessageUpdateParams struct {
	Body string `url:"body"`
}

MessageUpdateParams represents the parameters for updating a message.

type MessagesService

type MessagesService service

MessagesService handles communication with the message related methods of the ChatWork API.

ChatWork API docs: https://developer.chatwork.com/reference/messages

func (*MessagesService) Create

Create posts a new message to the specified room.

The message body supports ChatWork message notation for mentions, quotes, etc.

ChatWork API docs: https://developer.chatwork.com/reference/post-rooms-room_id-messages

Example
// クライアントの作成
client := chatwork.New("YOUR_API_TOKEN")
ctx := context.Background()

// メッセージの送信
params := &chatwork.MessageCreateParams{
	Body: "Hello, ChatWork!",
}
resp, _, err := client.Messages.Create(ctx, 123456, params)
if err != nil {
	log.Fatal(err)
}

fmt.Printf("Message sent with ID: %s\n", resp.MessageID)

func (*MessagesService) Delete

func (s *MessagesService) Delete(ctx context.Context, roomID int, messageID string) (*Message, *Response, error)

Delete deletes the specified message.

Only the message creator can delete their own messages. Messages can only be deleted for a limited time after creation.

ChatWork API docs: https://developer.chatwork.com/reference/delete-rooms-room_id-messages-message_id

func (*MessagesService) Get

func (s *MessagesService) Get(ctx context.Context, roomID int, messageID string) (*Message, *Response, error)

Get returns information about a specific message.

ChatWork API docs: https://developer.chatwork.com/reference/get-rooms-room_id-messages-message_id

func (*MessagesService) GetUnreadCount

func (s *MessagesService) GetUnreadCount(ctx context.Context, roomID int) (int, *Response, error)

GetUnreadCount returns the number of unread messages in a room.

This is a convenience method that uses the Rooms service's GetMessagesUnreadCount.

func (*MessagesService) List

func (s *MessagesService) List(ctx context.Context, roomID int, params *MessageListParams) ([]*Message, *Response, error)

List returns messages in the specified room.

By default, returns up to 100 most recent messages. Use params.Force = 1 to retrieve older messages.

ChatWork API docs: https://developer.chatwork.com/reference/get-rooms-room_id-messages

func (*MessagesService) MarkAsRead

func (s *MessagesService) MarkAsRead(ctx context.Context, roomID int, messageID string) (*Response, error)

MarkAsRead marks all messages up to the specified message as read.

This is a convenience method that uses the Rooms service's MarkMessagesAsRead.

func (*MessagesService) Quote

func (s *MessagesService) Quote(ctx context.Context, roomID int, messageID, body string) (*MessageCreatedResponse, *Response, error)

Quote sends a message quoting another message.

This fetches the original message and includes it in a quote block before the new message body.

func (*MessagesService) Reply

func (s *MessagesService) Reply(ctx context.Context, roomID int, messageID, body string) (*MessageCreatedResponse, *Response, error)

Reply sends a reply to a specific message.

This creates a threaded conversation by linking the new message to the original.

func (*MessagesService) SendInfo

func (s *MessagesService) SendInfo(ctx context.Context, roomID int, title, body string) (*MessageCreatedResponse, *Response, error)

SendInfo sends an information message with a title.

Information messages are displayed with special formatting to highlight important information.

func (*MessagesService) SendMessage

func (s *MessagesService) SendMessage(ctx context.Context, roomID int, body string) (*MessageCreatedResponse, *Response, error)

SendMessage is a convenience method for sending a simple text message.

This is equivalent to calling Create with a MessageCreateParams containing only the body.

func (*MessagesService) SendTo

func (s *MessagesService) SendTo(ctx context.Context, roomID int, accountIDs []int, body string) (*MessageCreatedResponse, *Response, error)

SendTo sends a message with mentions to specified users.

The message will include [To:accountID] tags for each specified user, which will trigger notifications for those users.

func (*MessagesService) Update

func (s *MessagesService) Update(ctx context.Context, roomID int, messageID string, params *MessageUpdateParams) (*Message, *Response, error)

Update updates the specified message.

Only the message creator can update their own messages. Messages can only be updated for a limited time after creation.

ChatWork API docs: https://developer.chatwork.com/reference/put-rooms-room_id-messages-message_id

type MyStatus

type MyStatus struct {
	UnreadRoomNum  int `json:"unread_room_num"`
	MentionRoomNum int `json:"mention_room_num"`
	MytaskRoomNum  int `json:"mytask_room_num"`
	UnreadNum      int `json:"unread_num"`
	MentionNum     int `json:"mention_num"`
	MytaskNum      int `json:"mytask_num"`
}

MyStatus represents the authenticated user's unread counts and status.

This provides a quick overview of pending items that need attention, including unread messages, mentions, and assigned tasks.

type MyTask

type MyTask struct {
	TaskID            int         `json:"task_id"`
	Room              TaskRoom    `json:"room"`
	AssignedByAccount TaskAccount `json:"assigned_by_account"`
	MessageID         string      `json:"message_id"`
	Body              string      `json:"body"`
	LimitTime         int64       `json:"limit_time"`
	Status            string      `json:"status"`
	LimitType         string      `json:"limit_type"`
}

MyTask represents a task assigned to the authenticated user.

This type includes additional room information compared to the regular Task type, making it easier to see tasks across multiple rooms.

type MyTaskListParams

type MyTaskListParams struct {
	// Filter by the account ID of who assigned the task
	AssignedByAccountID int

	// Filter by task status: "open" or "done"
	Status string
}

MyTaskListParams represents optional parameters for listing my tasks.

type MyTasksService

type MyTasksService service

MyTasksService handles communication with the "my tasks" related methods of the ChatWork API.

ChatWork API docs: https://developer.chatwork.com/reference/my-tasks

func (*MyTasksService) CompleteTask

func (s *MyTasksService) CompleteTask(ctx context.Context, roomID, taskID int) (*Task, *Response, error)

CompleteTask marks a task as completed.

This is a convenience method that uses the Tasks service to complete a task.

func (*MyTasksService) GetByRoom

func (s *MyTasksService) GetByRoom(ctx context.Context, roomID int) ([]*MyTask, *Response, error)

GetByRoom returns tasks assigned to the authenticated user in a specific room.

This fetches all tasks and filters them by room ID locally.

func (*MyTasksService) GetCompleted

func (s *MyTasksService) GetCompleted(ctx context.Context) ([]*MyTask, *Response, error)

GetCompleted returns all completed tasks assigned to the authenticated user.

This is a convenience method that calls List with status "done".

func (*MyTasksService) GetOpen

func (s *MyTasksService) GetOpen(ctx context.Context) ([]*MyTask, *Response, error)

GetOpen returns all open (uncompleted) tasks assigned to the authenticated user.

This is a convenience method that calls List with status "open".

func (*MyTasksService) List

func (s *MyTasksService) List(ctx context.Context, params *MyTaskListParams) ([]*MyTask, *Response, error)

List returns all tasks assigned to the authenticated user.

Tasks can be filtered by status and who assigned them.

ChatWork API docs: https://developer.chatwork.com/reference/get-my-tasks

func (*MyTasksService) ReopenTask

func (s *MyTasksService) ReopenTask(ctx context.Context, roomID, taskID int) (*Task, *Response, error)

ReopenTask marks a task as open (not completed).

This is a convenience method that uses the Tasks service to reopen a task.

type RateLimit

type RateLimit struct {
	// The maximum number of requests that can be made in the rate limit window.
	Limit int

	// The number of requests remaining in the current rate limit window.
	Remaining int

	// The time at which the current rate limit window resets, in Unix timestamp.
	Reset int64
}

RateLimit represents the rate limit information for the ChatWork API. ChatWork imposes rate limits on API requests to ensure fair usage.

type Response

type Response struct {
	*http.Response

	// Rate limit information parsed from headers
	RateLimit RateLimit
}

Response is a ChatWork API response. This wraps the standard http.Response and provides convenient access to rate limit information and other ChatWork-specific response data.

type Room

type Room struct {
	RoomID         int    `json:"room_id"`
	Name           string `json:"name"`
	Type           string `json:"type"`
	Role           string `json:"role"`
	Sticky         bool   `json:"sticky"`
	UnreadNum      int    `json:"unread_num"`
	MentionNum     int    `json:"mention_num"`
	MytaskNum      int    `json:"mytask_num"`
	MessageNum     int    `json:"message_num"`
	FileNum        int    `json:"file_num"`
	TaskNum        int    `json:"task_num"`
	IconPath       string `json:"icon_path"`
	LastUpdateTime int64  `json:"last_update_time"`
	Description    string `json:"description,omitempty"`
}

Room represents a ChatWork room (chat room).

Rooms are the primary organizational unit in ChatWork. They can be either group chats, direct messages, or task-specific rooms.

type RoomCreateParams

type RoomCreateParams struct {
	Name               string `url:"name"`
	Description        string `url:"description,omitempty"`
	IconPreset         string `url:"icon_preset,omitempty"`
	MembersAdminIDs    []int  `url:"members_admin_ids,comma,omitempty"`
	MembersMemberIDs   []int  `url:"members_member_ids,comma,omitempty"`
	MembersReadonlyIDs []int  `url:"members_readonly_ids,comma,omitempty"`
}

RoomCreateParams represents the parameters for creating a new room.

Name is required. Other fields are optional. Members can be specified with different permission levels.

type RoomMembersUpdateParams

type RoomMembersUpdateParams struct {
	MembersAdminIDs    []int `url:"members_admin_ids,comma,omitempty"`
	MembersMemberIDs   []int `url:"members_member_ids,comma,omitempty"`
	MembersReadonlyIDs []int `url:"members_readonly_ids,comma,omitempty"`
}

RoomMembersUpdateParams represents the parameters for updating room members.

This replaces all members in the room with the specified member lists. Be careful to include all desired members, not just new ones.

type RoomUpdateParams

type RoomUpdateParams struct {
	Name        string `url:"name,omitempty"`
	Description string `url:"description,omitempty"`
	IconPreset  string `url:"icon_preset,omitempty"`
}

RoomUpdateParams represents the parameters for updating a room.

All fields are optional. Only fields with non-zero values will be updated.

type RoomsService

type RoomsService service

RoomsService handles communication with the room related methods of the ChatWork API.

ChatWork API docs: https://developer.chatwork.com/reference/rooms

func (*RoomsService) Create

func (s *RoomsService) Create(ctx context.Context, params *RoomCreateParams) (*Room, *Response, error)

Create creates a new group chat room.

The authenticated user will automatically become an admin of the created room.

ChatWork API docs: https://developer.chatwork.com/reference/post-rooms

func (*RoomsService) Delete

func (s *RoomsService) Delete(ctx context.Context, roomID int, actionType string) (*Response, error)

Delete performs room deletion or user removal based on the specified action type.

The actionType parameter accepts "leave" or "delete": - "leave": Leave the room (any member can do this) - "delete": Delete the room (only room creator can do this)

ChatWork API docs: https://developer.chatwork.com/reference/delete-rooms-room_id

func (*RoomsService) DeleteRoom

func (s *RoomsService) DeleteRoom(ctx context.Context, roomID int) (*Response, error)

DeleteRoom deletes the specified room.

Only the room creator can delete a room. This is a convenience method that calls Delete with actionType "delete".

func (*RoomsService) Get

func (s *RoomsService) Get(ctx context.Context, roomID int) (*Room, *Response, error)

Get returns information about the specified room.

ChatWork API docs: https://developer.chatwork.com/reference/get-rooms-room_id

func (*RoomsService) GetFile

func (s *RoomsService) GetFile(ctx context.Context, roomID, fileID int, createDownloadURL bool) (*File, *Response, error)

GetFile returns information about a specific file.

If createDownloadURL is true, a download URL will be included in the response. Download URLs are valid for a limited time.

ChatWork API docs: https://developer.chatwork.com/reference/get-rooms-room_id-files-file_id

func (*RoomsService) GetFiles

func (s *RoomsService) GetFiles(ctx context.Context, roomID, accountID int) ([]*File, *Response, error)

GetFiles returns the list of files in a room.

If accountID is specified (non-zero), only files uploaded by that user are returned.

ChatWork API docs: https://developer.chatwork.com/reference/get-rooms-room_id-files

func (*RoomsService) GetMembers

func (s *RoomsService) GetMembers(ctx context.Context, roomID int) ([]*Member, *Response, error)

GetMembers returns the list of all members in the specified room.

ChatWork API docs: https://developer.chatwork.com/reference/get-rooms-room_id-members

func (*RoomsService) GetMessagesReadStatus

func (s *RoomsService) GetMessagesReadStatus(ctx context.Context, roomID int, messageID string) (map[string]int, *Response, error)

GetMessagesReadStatus returns the read/unread status of a message.

The response is a map with "unread_num" and "mention_num" keys.

ChatWork API docs: https://developer.chatwork.com/reference/get-rooms-room_id-messages-read

func (*RoomsService) GetMessagesUnreadCount

func (s *RoomsService) GetMessagesUnreadCount(ctx context.Context, roomID int) (map[string]int, *Response, error)

GetMessagesUnreadCount returns the number of unread messages in a room.

The response includes "unread_num" and "mention_num".

ChatWork API docs: https://developer.chatwork.com/reference/get-rooms-room_id-messages-unread

func (*RoomsService) GetTasks

func (s *RoomsService) GetTasks(ctx context.Context, roomID int, params *TaskListParams) ([]*Task, *Response, error)

GetTasks returns the list of tasks in a room.

Tasks can be filtered by various parameters.

ChatWork API docs: https://developer.chatwork.com/reference/get-rooms-room_id-tasks

func (*RoomsService) Leave

func (s *RoomsService) Leave(ctx context.Context, roomID int) (*Response, error)

Leave leaves the specified room.

This is a convenience method that calls Delete with actionType "leave".

func (*RoomsService) List

func (s *RoomsService) List(ctx context.Context) ([]*Room, *Response, error)

List returns the list of all rooms the authenticated user participates in.

ChatWork API docs: https://developer.chatwork.com/reference/get-rooms

Example
// クライアントの作成
client := chatwork.New("YOUR_API_TOKEN")
ctx := context.Background()

// ルーム一覧の取得
rooms, _, err := client.Rooms.List(ctx)
if err != nil {
	log.Fatal(err)
}

for _, room := range rooms {
	fmt.Printf("Room: %s (ID: %d)\n", room.Name, room.RoomID)
}

func (*RoomsService) MarkMessagesAsRead

func (s *RoomsService) MarkMessagesAsRead(ctx context.Context, roomID int, messageID string) (map[string]string, *Response, error)

MarkMessagesAsRead marks messages as read up to the specified message.

All messages up to and including the specified message will be marked as read.

ChatWork API docs: https://developer.chatwork.com/reference/put-rooms-room_id-messages-read

func (*RoomsService) Update

func (s *RoomsService) Update(ctx context.Context, roomID int, params *RoomUpdateParams) (*Room, *Response, error)

Update updates the room information.

Only room admins can update room information.

ChatWork API docs: https://developer.chatwork.com/reference/put-rooms-room_id

func (*RoomsService) UpdateMembers

func (s *RoomsService) UpdateMembers(ctx context.Context, roomID int, params *RoomMembersUpdateParams) (*Member, *Response, error)

UpdateMembers updates the members of a room.

This replaces all members in the room. Be sure to include all desired members. Only room admins can update members.

ChatWork API docs: https://developer.chatwork.com/reference/put-rooms-room_id-members

type Task

type Task struct {
	TaskID            int    `json:"task_id"`
	Account           User   `json:"account"`
	AssignedByAccount User   `json:"assigned_by_account"`
	MessageID         string `json:"message_id"`
	Body              string `json:"body"`
	LimitTime         int64  `json:"limit_time"`
	Status            string `json:"status"`
	LimitType         string `json:"limit_type"`
}

Task represents a task assigned in a ChatWork room.

Tasks are used to track work items and responsibilities. They can have assignees, due dates, and completion status.

type TaskAccount

type TaskAccount struct {
	AccountID      int    `json:"account_id"`
	Name           string `json:"name"`
	AvatarImageURL string `json:"avatar_image_url"`
}

TaskAccount represents minimal account information for task assignees. This is used in task responses to identify who assigned or is assigned to tasks.

type TaskCreateParams

type TaskCreateParams struct {
	// Task description (required)
	Body string `url:"body"`

	// Account IDs to assign the task to (required)
	ToIDs []int `url:"to_ids,comma"`

	// Task deadline as Unix timestamp (optional)
	Limit int64 `url:"limit,omitempty"`

	// Type of deadline: "none", "date", or "time" (optional)
	LimitType string `url:"limit_type,omitempty"`
}

TaskCreateParams represents the parameters for creating a new task.

type TaskCreatedResponse

type TaskCreatedResponse struct {
	// IDs of the created tasks (one for each assignee)
	TaskIDs []int `json:"task_ids"`
}

TaskCreatedResponse represents the response when tasks are created.

type TaskListParams

type TaskListParams struct {
	// Filter by the account ID of the task assignee
	AccountID int

	// Filter by the account ID of the task creator
	AssignedByAccountID int

	// Filter by task status: "open" or "done"
	Status string
}

TaskListParams represents optional parameters for listing tasks.

type TaskRoom

type TaskRoom struct {
	RoomID   int    `json:"room_id"`
	Name     string `json:"name"`
	IconPath string `json:"icon_path"`
}

TaskRoom represents minimal room information associated with a task. This is used in MyTask responses to provide context about where the task exists.

type TasksService

type TasksService service

TasksService handles communication with the task related methods of the ChatWork API.

ChatWork API docs: https://developer.chatwork.com/reference/tasks

func (*TasksService) Complete

func (s *TasksService) Complete(ctx context.Context, roomID, taskID int) (*Task, *Response, error)

Complete marks a task as completed.

This is a convenience method that calls UpdateStatus with status "done".

func (*TasksService) Create

func (s *TasksService) Create(ctx context.Context, roomID int, params *TaskCreateParams) (*TaskCreatedResponse, *Response, error)

Create creates new tasks in the specified room.

A separate task is created for each account ID specified in ToIDs.

ChatWork API docs: https://developer.chatwork.com/reference/post-rooms-room_id-tasks

Example
// クライアントの作成
client := chatwork.New("YOUR_API_TOKEN")
ctx := context.Background()

// タスクの作成
params := &chatwork.TaskCreateParams{
	Body:  "プレゼン資料を作成する",
	ToIDs: []int{123456, 789012},
}

resp, _, err := client.Tasks.Create(ctx, 123456, params)
if err != nil {
	log.Fatal(err)
}

fmt.Printf("Created %d tasks\n", len(resp.TaskIDs))

func (*TasksService) CreateSimple

func (s *TasksService) CreateSimple(ctx context.Context, roomID int, body string, toIDs []int) (*TaskCreatedResponse, *Response, error)

CreateSimple is a convenience method for creating a task without a deadline.

func (*TasksService) CreateWithDeadline

func (s *TasksService) CreateWithDeadline(ctx context.Context, roomID int, body string, toIDs []int, deadline int64) (*TaskCreatedResponse, *Response, error)

CreateWithDeadline is a convenience method for creating a task with a deadline.

The deadline should be a Unix timestamp.

func (*TasksService) Get

func (s *TasksService) Get(ctx context.Context, roomID, taskID int) (*Task, *Response, error)

Get returns information about a specific task.

ChatWork API docs: https://developer.chatwork.com/reference/get-rooms-room_id-tasks-task_id

func (*TasksService) Reopen

func (s *TasksService) Reopen(ctx context.Context, roomID, taskID int) (*Task, *Response, error)

Reopen marks a task as open (not completed).

This is a convenience method that calls UpdateStatus with status "open".

func (*TasksService) UpdateStatus

func (s *TasksService) UpdateStatus(ctx context.Context, roomID, taskID int, status string) (*Task, *Response, error)

UpdateStatus updates the status of a task.

Status can be "open" or "done".

ChatWork API docs: https://developer.chatwork.com/reference/put-rooms-room_id-tasks-task_id-status

type Timestamp

type Timestamp int64

Timestamp represents a Unix timestamp used throughout the ChatWork API.

ChatWork uses Unix timestamps (seconds since epoch) for all time values. This type provides convenient conversion methods to Go's time.Time.

func (Timestamp) String

func (t Timestamp) String() string

String returns the string representation of the timestamp. This is equivalent to calling Time().String().

func (Timestamp) Time

func (t Timestamp) Time() time.Time

Time converts the Unix timestamp to a time.Time value.

type User

type User struct {
	AccountID        int    `json:"account_id"`
	RoomID           int    `json:"room_id,omitempty"`
	Name             string `json:"name"`
	AvatarImageURL   string `json:"avatar_image_url"`
	ChatworkID       string `json:"chatwork_id,omitempty"`
	OrganizationID   int    `json:"organization_id,omitempty"`
	OrganizationName string `json:"organization_name,omitempty"`
	Department       string `json:"department,omitempty"`
	Title            string `json:"title,omitempty"`
	URL              string `json:"url,omitempty"`
	Introduction     string `json:"introduction,omitempty"`
	Mail             string `json:"mail,omitempty"`
	TelOrganization  string `json:"tel_organization,omitempty"`
	TelExtension     string `json:"tel_extension,omitempty"`
	TelMobile        string `json:"tel_mobile,omitempty"`
	Skype            string `json:"skype,omitempty"`
	Facebook         string `json:"facebook,omitempty"`
	Twitter          string `json:"twitter,omitempty"`
}

User represents a ChatWork user account.

This type contains both basic user information (like name and avatar) and detailed profile information when available.

Jump to

Keyboard shortcuts

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