### Install mixi2 Go SDK Source: https://developer.mixi.social/docs/guides/sdk Command to install the official mixi2 application SDK for Go using the go get tool. ```bash go get github.com/mixigroup/mixi2-application-sdk-go ``` -------------------------------- ### InitiatePostMediaUpload Source: https://developer.mixi.social/docs/reference/api-document Starts the media upload process and returns a URL for uploading data. ```APIDOC ## RPC InitiatePostMediaUpload ### Description Initiates media upload for posts or messages and issues an upload URL. ### Method RPC (gRPC) ### Endpoint InitiatePostMediaUpload ### Request Body - **content_type** (string) - Required - Content-Type of the data. - **data_size** (uint64) - Required - Size of the data in bytes. - **media_type** (Type) - Required - Type of media. ### Response #### Success Response (200) - **media_id** (string) - ID for tracking and attachment. - **upload_url** (string) - URL to upload the media data. ### Response Example { "media_id": "media_001", "upload_url": "https://upload.example.com/v1/media/001" } ``` -------------------------------- ### Initiate Media Upload for Posts/DMs using mixi2 API Source: https://developer.mixi.social/docs/guides/api-usage Explains the first step in uploading media (images/videos) for posts or DMs: initiating the upload to get a `media_id` and `upload_url`. ```Go description := "画像の説明(任意)" resp, err := client.InitiatePostMediaUpload(ctx, &application_apiv1.InitiatePostMediaUploadRequest{ MediaType: application_apiv1.InitiatePostMediaUploadRequest_TYPE_IMAGE, ContentType: "image/jpeg", DataSize: uint64(len(imageData)), Description: &description, }) mediaId := resp.MediaId uploadUrl := resp.UploadUrl ``` -------------------------------- ### Run Sample Application Source: https://developer.mixi.social/docs/guides/sdk Commands to clone, configure, and run the sample Go application in either gRPC stream or Webhook mode. ```bash # リポジトリをクローン git clone https://github.com/mixigroup/mixi2-application-sample-go.git cd mixi2-application-sample-go # 環境変数を設定 cp .env.example .env # .env を編集して環境変数を設定 source .env go mod tidy # gRPC ストリームモード(ローカル開発向け) go run cmd/stream/main.go # HTTP Webhook モード(デプロイ向け) go run cmd/webhook/main.go ``` -------------------------------- ### Implement OAuth2 Authentication Source: https://developer.mixi.social/docs/guides/sdk Demonstrates how to initialize the Authenticator and obtain an authorized context for gRPC requests using environment variables. ```go package main import ( "context" "log" "os" "github.com/mixigroup/mixi2-application-sdk-go/auth" ) func main() { authenticator, err := auth.NewAuthenticator( os.Getenv("CLIENT_ID"), os.Getenv("CLIENT_SECRET"), os.Getenv("TOKEN_URL"), ) if err != nil { log.Fatal(err) } // gRPC リクエスト用のコンテキストを取得 ctx, err := authenticator.AuthorizedContext(context.Background()) if err != nil { log.Fatal(err) } // ctx を使って gRPC リクエストを送信 _ = ctx } ``` -------------------------------- ### Get User Information using Go Source: https://developer.mixi.social/docs/guides/api-usage Retrieves user information using the `GetUsers` RPC. This function takes a list of user IDs and returns details such as display name and icon URL. It is limited to fetching information for users that the application has access to. ```Go resp, err := client.GetUsers(ctx, &application_apiv1.GetUsersRequest{ UserIdList: []string{event.Post.CreatorId}, }) for _, user := range resp.Users { fmt.Printf("ユーザー名: %s\n", user.DisplayName) } ``` -------------------------------- ### Generate Code without SDK Source: https://developer.mixi.social/docs/guides/sdk Commands to generate Protocol Buffers code directly from the API definition repository using buf. ```bash # API Proto リポジトリをクローン git clone https://github.com/mixigroup/mixi2-api.git # buf を使用してコード生成 cd mixi2-api buf generate ``` -------------------------------- ### Get Post Information using Go Source: https://developer.mixi.social/docs/guides/api-usage Retrieves post information using the `GetPosts` RPC. This function allows fetching details of specific posts, including their text, media, and stamps, by providing a list of post IDs. It is limited to retrieving posts that the application has access to. ```Go resp, err := client.GetPosts(ctx, &application_apiv1.GetPostsRequest{ PostIdList: []string{event.Post.GetInReplyToPostId()}, }) for _, post := range resp.Posts { fmt.Printf("ポスト本文: %s\n", post.Text) } ``` -------------------------------- ### Create a Basic Post using mixi2 API Source: https://developer.mixi.social/docs/guides/api-usage Demonstrates how to create a simple text post using the `CreatePost` RPC. This is the most basic form of posting content. ```Go resp, err := client.CreatePost(ctx, &application_apiv1.CreatePostRequest{ Text: "こんにちは!", }) ``` -------------------------------- ### Reply to a Post using mixi2 API Source: https://developer.mixi.social/docs/guides/api-usage Shows how to reply to an existing post by specifying the `in_reply_to_post_id`. This allows for conversational threads within the platform. ```Go inReplyToPostId := event.Post.PostId resp, err := client.CreatePost(ctx, &application_apiv1.CreatePostRequest{ Text: "返信ありがとうございます!", InReplyToPostId: &inReplyToPostId, }) ``` -------------------------------- ### GET /healthz Source: https://developer.mixi.social/docs/guides/webhook A health check endpoint used to verify the availability of the webhook server. ```APIDOC ## GET /healthz ### Description Provides a simple health check mechanism for the webhook server. ### Method GET ### Endpoint /healthz ### Response #### Success Response (200) - **status** (string) - Returns "OK" or similar status indicating the server is healthy. ``` -------------------------------- ### Define Event Handler Interface Source: https://developer.mixi.social/docs/guides/sdk Defines the EventHandler interface required for processing events in both Webhook and gRPC stream modes. ```go import modelv1 "github.com/mixigroup/mixi2-application-sdk-go/gen/go/social/mixi/application/model/v1" type EventHandler interface { Handle(ctx context.Context, event *modelv1.Event) error } ``` -------------------------------- ### Quote a Post using mixi2 API Source: https://developer.mixi.social/docs/guides/api-usage Illustrates how to quote another post by using the `quoted_post_id` parameter. Note that `in_reply_to_post_id` and `quoted_post_id` cannot be used simultaneously. ```Go quotedPostId := originalPostId resp, err := client.CreatePost(ctx, &application_apiv1.CreatePostRequest{ Text: "これは面白い投稿ですね!", QuotedPostId: "edPostId, }) ``` -------------------------------- ### Upload Media Data to Provided URL Source: https://developer.mixi.social/docs/guides/api-usage Details the second step of media upload: sending the actual media data to the `upload_url` obtained from `InitiatePostMediaUpload` using an HTTP POST request. ```Go req, err := http.NewRequest(http.MethodPost, uploadUrl, bytes.NewReader(imageData)) req.Header.Set("Content-Type", "image/jpeg") httpClient.Do(req) ``` -------------------------------- ### Control Post Publishing Type using mixi2 API Source: https://developer.mixi.social/docs/guides/api-usage Demonstrates how to control the visibility of a post using the `PublishingType` field. This allows posts to be visible only on the profile or to followers. ```Go publishingType := constv1.PostPublishingType_POST_PUBLISHING_TYPE_NOT_PUBLISHING resp, err := client.CreatePost(ctx, &application_apiv1.CreatePostRequest{ Text: "このポストはプロフィールにのみ表示されます", PublishingType: &publishingType, }) ``` -------------------------------- ### Create a Masked Post (Spoiler/Sensitive) using mixi2 API Source: https://developer.mixi.social/docs/guides/api-usage Explains how to create posts with masks for sensitive content or spoilers using the `PostMask` field. This is useful for content warnings. ```Go caption := "映画のネタバレ注意" resp, err := client.CreatePost(ctx, &application_apiv1.CreatePostRequest{ Text: "ネタバレを含む内容です...", PostMask: &modelv1.PostMask{ MaskType: constv1.PostMaskType_POST_MASK_TYPE_SPOILER, Caption: &caption, }, }) ``` -------------------------------- ### Attach Uploaded Media to a Post using mixi2 API Source: https://developer.mixi.social/docs/guides/api-usage The final step in media integration: attaching the processed media to a post by including the `media_id` in the `CreatePost` request. ```Go resp, err := client.CreatePost(ctx, &application_apiv1.CreatePostRequest{ Text: "画像を添付しました!", MediaIdList: []string{mediaId}, }) ``` -------------------------------- ### Send a Direct Message using mixi2 API Source: https://developer.mixi.social/docs/guides/api-usage Shows how to send a direct message (DM) using the `SendChatMessage` RPC. Note that direct messages can only be sent in reply to a user's message. ```Go text := "メッセージを受け取りました!" resp, err := client.SendChatMessage(ctx, &application_apiv1.SendChatMessageRequest{ RoomId: event.Message.RoomId, Text: &text, }) ``` -------------------------------- ### Add Stamp to Post using Go Source: https://developer.mixi.social/docs/guides/api-usage Adds a stamp to a post using the `AddStampToPost` RPC. It first retrieves available stamps using `GetStamps` and then applies the selected stamp to the specified post. Limitations include only official stamps can be used and a post cannot be stamped multiple times by the same application. ```Go // 利用可能なスタンプ一覧を取得 language := constv1.LanguageCode_LANGUAGE_CODE_JP stampsResp, err := client.GetStamps(ctx, &application_apiv1.GetStampsRequest{ OfficialStampLanguage: &language, }) // スタンプを付与 _, err = client.AddStampToPost(ctx, &application_apiv1.AddStampToPostRequest{ PostId: postId, StampId: stampsResp.OfficialStampSets[0].Stamps[0].StampId, }) ``` -------------------------------- ### Check Media Upload Status using mixi2 API Source: https://developer.mixi.social/docs/guides/api-usage Describes the third step in media upload: polling the `GetPostMediaStatus` RPC to check the processing status of the uploaded media until it's `STATUS_COMPLETED` or `STATUS_FAILED`. ```Go for { statusResp, err := client.GetPostMediaStatus(ctx, &application_apiv1.GetPostMediaStatusRequest{ MediaId: mediaId, }) if statusResp.Status == application_apiv1.GetPostMediaStatusResponse_STATUS_COMPLETED { break } if statusResp.Status == application_apiv1.GetPostMediaStatusResponse_STATUS_FAILED { // エラー処理: アップロードをやり直す必要があります return errors.New("media processing failed") } time.Sleep(1 * time.Second) } ``` -------------------------------- ### Go SDK を使用した Webhook イベント受信サーバーの実装 Source: https://developer.mixi.social/docs/guides/webhook Go SDK を使用して Webhook イベントを受信するサーバーを実装する方法を示します。このコードは、指定されたポートでリッスンし、受信したイベントをログに記録します。署名検証は SDK によって自動的に処理されます。 ```go package main import ( "context" "crypto/ed25519" "encoding/base64" "log" "os" "github.com/mixigroup/mixi2-application-sdk-go/event/webhook" modelv1 "github.com/mixigroup/mixi2-application-sdk-go/gen/go/social/mixi/application/model/v1" ) type MyHandler struct{} func (h *MyHandler) Handle(ctx context.Context, ev *modelv1.Event) error { log.Printf("Received event: %v", ev) return nil } func main() { publicKeyBase64 := os.Getenv("SIGNATURE_PUBLIC_KEY") publicKey, err := base64.StdEncoding.DecodeString(publicKeyBase64) if err != nil { log.Fatal(err) } server := webhook.NewServer( ":8080", ed25519.PublicKey(publicKey), &MyHandler{}, ) if err := server.Start(); err != nil { log.Fatal(err) } } ``` -------------------------------- ### gRPCストリームによるイベント受信の実装 (Go) Source: https://developer.mixi.social/docs/guides/grpc-stream mixi2 SDK for Goを使用してgRPCストリームを確立し、イベントを処理する実装例です。認証情報の初期化、gRPCコネクションの作成、およびStreamWatcherによるイベント監視の開始手順を示しています。 ```go package main import ( "context" "crypto/tls" "log" "os" "google.golang.org/grpc" "google.golang.org/grpc/credentials" "github.com/mixigroup/mixi2-application-sdk-go/auth" "github.com/mixigroup/mixi2-application-sdk-go/event/stream" application_streamv1 "github.com/mixigroup/mixi2-application-sdk-go/gen/go/social/mixi/application/service/application_stream/v1" modelv1 "github.com/mixigroup/mixi2-application-sdk-go/gen/go/social/mixi/application/model/v1" ) type MyHandler struct{} func (h *MyHandler) Handle(ctx context.Context, ev *modelv1.Event) error { log.Printf("Received event: %v", ev) return nil } func main() { authenticator, err := auth.NewAuthenticator( os.Getenv("CLIENT_ID"), os.Getenv("CLIENT_SECRET"), os.Getenv("TOKEN_URL"), ) if err != nil { log.Fatal(err) } conn, err := grpc.NewClient( os.Getenv("STREAM_ADDRESS"), grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{})), ) if err != nil { log.Fatal(err) } defer conn.Close() client := application_streamv1.NewApplicationServiceClient(conn) watcher := stream.NewStreamWatcher(client, authenticator) if err := watcher.Watch(context.Background(), &MyHandler{}); err != nil { log.Fatal(err) } } ``` -------------------------------- ### CreatePost Source: https://developer.mixi.social/docs/reference/api-document Creates a new post on the platform, supporting replies, quotes, and media attachments. ```APIDOC ## RPC CreatePost ### Description Creates a post. Note: in_reply_to_post_id and quoted_post_id cannot be specified simultaneously. ### Method RPC (gRPC) ### Endpoint CreatePost ### Request Body - **text** (string) - Required - The body of the post. - **in_reply_to_post_id** (optional string) - Optional - ID of the post to reply to. - **quoted_post_id** (optional string) - Optional - ID of the post to quote. - **media_id_list** (repeated string) - Optional - List of media IDs to attach (max 4). - **publishing_type** (optional PostPublishingType) - Optional - Publishing settings. ### Response #### Success Response (200) - **post** (Post) - The created post object. ### Response Example { "post": { "id": "post789", "text": "Hello World" } } ``` -------------------------------- ### POST /events Source: https://developer.mixi.social/docs/guides/webhook The event reception endpoint used by the mixi2 platform to push events to your application server. ```APIDOC ## POST /events ### Description This endpoint receives event payloads from the mixi2 platform. It must be implemented as an HTTPS endpoint and requires mandatory Ed25519 signature verification. ### Method POST ### Endpoint /events ### Parameters #### Request Headers - **x-mixi2-application-event-signature** (string) - Required - Base64 encoded Ed25519 signature. - **x-mixi2-application-event-timestamp** (integer) - Required - Unix timestamp in seconds. ### Request Example { "event_type": "example_event", "data": { ... } } ### Response #### Success Response (200) - **status** (string) - Indicates successful receipt and processing of the event. #### Error Response (401) - **error** (string) - Returned when signature verification fails or timestamp is invalid. ``` -------------------------------- ### GetUsers Source: https://developer.mixi.social/docs/reference/api-document Retrieves user information for a specified list of user IDs. ```APIDOC ## RPC GetUsers ### Description Retrieves user information for a specified list of user IDs. ### Method RPC (gRPC) ### Endpoint GetUsers ### Request Body - **user_id_list** (repeated string) - Required - List of user IDs to retrieve. ### Response #### Success Response (200) - **users** (repeated User) - List of user information. ### Response Example { "users": [ { "id": "user123", "name": "Example User" } ] } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.