Skip to content

Send and receive SMS messages using your Android phone programmatically via a simple HTTP API

Add discord integration

Acho Arnoldd1367cc5a765
diff --git a/api/pkg/di/container.go b/api/pkg/di/container.go
index 8fa4f078..985325dd 100644
--- a/api/pkg/di/container.go
+++ b/api/pkg/di/container.go
@@ -888,6 +888,7 @@ func (container *Container) DiscordClient() (client *discord.Client) {
container.logger.Debug(fmt.Sprintf("creating %T", client))
return discord.New(
discord.WithHTTPClient(container.HTTPClient("discord")),
+ discord.WithApplicationID(os.Getenv("DISCORD_APPLICATION_ID")),
discord.WithBotToken(os.Getenv("DISCORD_BOT_TOKEN")),
)
}
diff --git a/api/pkg/discord/application.go b/api/pkg/discord/application.go
index 47c80286..c6fae57c 100644
--- a/api/pkg/discord/application.go
+++ b/api/pkg/discord/application.go
@@ -2,14 +2,14 @@ package discord
// CommandCreateRequest is the request for creating a new command
type CommandCreateRequest struct {
- Name string `json:"name"`
- Type int `json:"type"`
- Description string `json:"description"`
- Options []CommandCreateRequestOptions `json:"options"`
+ Name string `json:"name"`
+ Type int `json:"type"`
+ Description string `json:"description"`
+ Options []CommandCreateRequestOption `json:"options"`
}
-// CommandCreateRequestOptions are options for creating a command
-type CommandCreateRequestOptions struct {
+// CommandCreateRequestOption are options for creating a command
+type CommandCreateRequestOption struct {
Name string `json:"name"`
Description string `json:"description"`
Type int `json:"type"`
@@ -18,22 +18,22 @@ type CommandCreateRequestOptions struct {
// CommandCreateResponse is the response after creating a command
type CommandCreateResponse struct {
- ID string `json:"id"`
- ApplicationID string `json:"application_id"`
- Version string `json:"version"`
- DefaultMemberPermissions any `json:"default_member_permissions"`
- Type int `json:"type"`
- Name string `json:"name"`
- NameLocalizations any `json:"name_localizations"`
- Description string `json:"description"`
- DescriptionLocalizations any `json:"description_localizations"`
- GuildID string `json:"guild_id"`
- Options []CommandCreateResponseOptions `json:"options"`
- Nsfw bool `json:"nsfw"`
+ ID string `json:"id"`
+ ApplicationID string `json:"application_id"`
+ Version string `json:"version"`
+ DefaultMemberPermissions any `json:"default_member_permissions"`
+ Type int `json:"type"`
+ Name string `json:"name"`
+ NameLocalizations any `json:"name_localizations"`
+ Description string `json:"description"`
+ DescriptionLocalizations any `json:"description_localizations"`
+ GuildID string `json:"guild_id"`
+ Options []CommandCreateResponseOption `json:"options"`
+ Nsfw bool `json:"nsfw"`
}
-// CommandCreateResponseOptions are options after creating a command
-type CommandCreateResponseOptions struct {
+// CommandCreateResponseOption are options after creating a command
+type CommandCreateResponseOption struct {
Type int `json:"type"`
Name string `json:"name"`
NameLocalizations any `json:"name_localizations"`
diff --git a/api/pkg/discord/application_service.go b/api/pkg/discord/application_service.go
index 504038f6..33368d15 100644
--- a/api/pkg/discord/application_service.go
+++ b/api/pkg/discord/application_service.go
@@ -13,8 +13,8 @@ type ApplicationService service
// CreateCommand creates a new guild command
//
// API Docs: https://discord.com/developers/docs/interactions/application-commands#create-guild-application-command
-func (service *ApplicationService) CreateCommand(ctx context.Context, serverID string, channelID string, params *CommandCreateRequest) (*CommandCreateResponse, *Response, error) {
- url := fmt.Sprintf("/applications/%s/guilds/%s/commands", serverID, channelID)
+func (service *ApplicationService) CreateCommand(ctx context.Context, serverID string, params *CommandCreateRequest) (*CommandCreateResponse, *Response, error) {
+ url := fmt.Sprintf("/applications/%s/guilds/%s/commands", service.client.applicationID, serverID)
request, err := service.client.newRequest(ctx, http.MethodPost, url, params)
if err != nil {
return nil, nil, err
diff --git a/api/pkg/discord/client.go b/api/pkg/discord/client.go
index b53eaf71..8aa13fd7 100644
--- a/api/pkg/discord/client.go
+++ b/api/pkg/discord/client.go
@@ -16,10 +16,11 @@ type service struct {
// Client is the campay API client.
// Do not instantiate this client with Client{}. Use the New method instead.
type Client struct {
- httpClient *http.Client
- common service
- baseURL string
- botToken string
+ httpClient *http.Client
+ common service
+ baseURL string
+ applicationID string
+ botToken string
Channel *ChannelService
Guild *GuildService
@@ -35,9 +36,10 @@ func New(options ...Option) *Client {
}
client := &Client{
- httpClient: config.httpClient,
- botToken: config.botToken,
- baseURL: config.baseURL,
+ httpClient: config.httpClient,
+ botToken: config.botToken,
+ baseURL: config.baseURL,
+ applicationID: config.applicationID,
}
client.common.client = client
diff --git a/api/pkg/discord/client_config.go b/api/pkg/discord/client_config.go
index 9e7deeae..736e03f6 100644
--- a/api/pkg/discord/client_config.go
+++ b/api/pkg/discord/client_config.go
@@ -3,15 +3,17 @@ package discord
import "net/http"
type clientConfig struct {
- httpClient *http.Client
- botToken string
- baseURL string
+ httpClient *http.Client
+ botToken string
+ applicationID string
+ baseURL string
}
func defaultClientConfig() *clientConfig {
return &clientConfig{
- httpClient: http.DefaultClient,
- botToken: "",
- baseURL: "https://discord.com/api",
+ httpClient: http.DefaultClient,
+ botToken: "",
+ applicationID: "",
+ baseURL: "https://discord.com/api",
}
}
diff --git a/api/pkg/discord/client_option.go b/api/pkg/discord/client_option.go
index 731aab68..6f2008d4 100644
--- a/api/pkg/discord/client_option.go
+++ b/api/pkg/discord/client_option.go
@@ -35,6 +35,13 @@ func WithBaseURL(baseURL string) Option {
})
}
+// WithApplicationID sets the discord bot application ID
+func WithApplicationID(applicationID string) Option {
+ return clientOptionFunc(func(config *clientConfig) {
+ config.applicationID = applicationID
+ })
+}
+
// WithBotToken sets the discord bot token
func WithBotToken(botToken string) Option {
return clientOptionFunc(func(config *clientConfig) {
diff --git a/api/pkg/entities/discord.go b/api/pkg/entities/discord.go
index 57627461..6cad93ed 100644
--- a/api/pkg/entities/discord.go
+++ b/api/pkg/entities/discord.go
@@ -11,7 +11,7 @@ type Discord struct {
ID uuid.UUID `json:"id" gorm:"primaryKey;type:uuid;" example:"32343a19-da5e-4b1b-a767-3298a73703cb"`
UserID UserID `json:"user_id" gorm:"index" example:"WB7DRDWrJZRGbYrv2CKGkqbzvqdC"`
Name string `json:"name" example:"Game Server"`
- ServerID string `json:"server_id" gorm:"uniqueIndex" example:"1095780203256627291"`
+ ServerID string `json:"server_id" gorm:"uniqueIndex" example:"1095778291488653372"`
IncomingChannelID string `json:"incoming_channel_id" example:"1095780203256627291"`
CreatedAt time.Time `json:"created_at" example:"2022-06-05T14:26:02.302718+03:00"`
UpdatedAt time.Time `json:"updated_at" example:"2022-06-05T14:26:10.303278+03:00"`
diff --git a/api/pkg/handlers/discord_handler.go b/api/pkg/handlers/discord_handler.go
index 39e37c70..6ecbe663 100644
--- a/api/pkg/handlers/discord_handler.go
+++ b/api/pkg/handlers/discord_handler.go
@@ -8,6 +8,8 @@ import (
"fmt"
"os"
+ "github.com/google/uuid"
+
"github.com/NdoleStudio/httpsms/pkg/repositories"
"github.com/NdoleStudio/httpsms/pkg/requests"
"github.com/NdoleStudio/httpsms/pkg/services"
@@ -47,24 +49,148 @@ func (h *DiscordHandler) RegisterRoutes(app *fiber.App, authMiddleware fiber.Han
router := app.Group("discord")
router.Post("/event", h.computeRoute(middlewares, h.Event)...)
- authRouter := app.Group("v1/discord")
- authRouter.Post("/", h.computeRoute(append(middlewares, authMiddleware), h.Event)...)
+ authRouter := app.Group("v1/discord-integrations")
+ authRouter.Post("/", h.computeRoute(append(middlewares, authMiddleware), h.Store)...)
+ authRouter.Get("/", h.computeRoute(append(middlewares, authMiddleware), h.Index)...)
+ authRouter.Delete("/:discordID", h.computeRoute(append(middlewares, authMiddleware), h.Delete)...)
+ authRouter.Put("/:discordID", h.computeRoute(append(middlewares, authMiddleware), h.Update)...)
+}
+
+// Index returns the discord integrations of a user
+// @Summary Get discord integrations of a user
+// @Description Get the discord integrations of a user
+// @Security ApiKeyAuth
+// @Tags DiscordIntegration
+// @Accept json
+// @Produce json
+// @Param skip query int false "number of discord integrations to skip" minimum(0)
+// @Param query query string false "filter discord integrations containing query"
+// @Param limit query int false "number of discord integrations to return" minimum(1) maximum(20)
+// @Success 200 {object} responses.DiscordsResponse
+// @Failure 400 {object} responses.BadRequest
+// @Failure 401 {object} responses.Unauthorized
+// @Failure 422 {object} responses.UnprocessableEntity
+// @Failure 500 {object} responses.InternalServerError
+// @Router /discord-integrations [get]
+func (h *DiscordHandler) Index(c *fiber.Ctx) error {
+ ctx, span, ctxLogger := h.tracer.StartFromFiberCtxWithLogger(c, h.logger)
+ defer span.End()
+
+ var request requests.DiscordIndex
+ if err := c.QueryParser(&request); err != nil {
+ msg := fmt.Sprintf("cannot marshall URL [%s] into %T", c.OriginalURL(), request)
+ ctxLogger.Warn(stacktrace.Propagate(err, msg))
+ return h.responseBadRequest(c, err)
+ }
+
+ if errors := h.validator.ValidateIndex(ctx, request.Sanitize()); len(errors) != 0 {
+ msg := fmt.Sprintf("validation errors [%s], while fetching discord integrations [%+#v]", spew.Sdump(errors), request)
+ ctxLogger.Warn(stacktrace.NewError(msg))
+ return h.responseUnprocessableEntity(c, errors, "validation errors while fetching discord integrations")
+ }
+
+ discordIntegrations, err := h.service.Index(ctx, h.userIDFomContext(c), request.ToIndexParams())
+ if err != nil {
+ msg := fmt.Sprintf("cannot get discord integrations with params [%+#v]", request)
+ ctxLogger.Error(stacktrace.Propagate(err, msg))
+ return h.responseInternalServerError(c)
+ }
+
+ return h.responseOK(c, fmt.Sprintf("fetched %d discord %s", len(discordIntegrations), h.pluralize("integration", len(discordIntegrations))), discordIntegrations)
}
-// Store a webhook
-// @Summary Store a webhook
-// @Description Store a webhook for the authenticated user
+// Delete a discord integration
+// @Summary Delete discord integration
+// @Description Delete a discord integration for a user
// @Security ApiKeyAuth
// @Tags Webhooks
// @Accept json
// @Produce json
-// @Param payload body requests.WebhookStore true "Payload of the webhook request"
-// @Success 200 {object} responses.WebhookResponse
+// @Param discordID path string true "ID of the discord integration" default(32343a19-da5e-4b1b-a767-3298a73703ca)
+// @Success 204 {object} responses.NoContent
+// @Failure 400 {object} responses.BadRequest
+// @Failure 401 {object} responses.Unauthorized
+// @Failure 422 {object} responses.UnprocessableEntity
+// @Failure 500 {object} responses.InternalServerError
+// @Router /discord-integrations/{discordID} [delete]
+func (h *DiscordHandler) Delete(c *fiber.Ctx) error {
+ ctx, span, ctxLogger := h.tracer.StartFromFiberCtxWithLogger(c, h.logger)
+ defer span.End()
+
+ discordID := c.Params("discordID")
+ if errors := h.validator.ValidateUUID(ctx, discordID, "discordID"); len(errors) != 0 {
+ msg := fmt.Sprintf("validation errors [%s], while deleting discord integration with ID [%s]", spew.Sdump(errors), discordID)
+ ctxLogger.Warn(stacktrace.NewError(msg))
+ return h.responseUnprocessableEntity(c, errors, "validation errors while deleting discord integration")
+ }
+
+ err := h.service.Delete(ctx, h.userIDFomContext(c), uuid.MustParse(discordID))
+ if err != nil {
+ msg := fmt.Sprintf("cannot delete discord integration with ID [%+#v]", discordID)
+ ctxLogger.Error(stacktrace.Propagate(err, msg))
+ return h.responseInternalServerError(c)
+ }
+
+ return h.responseOK(c, "discord integration deleted successfully", nil)
+}
+
+// Update an entities.Discord
+// @Summary Update a discord integration
+// @Description Update a discord integration for the currently authenticated user
+// @Security ApiKeyAuth
+// @Tags DiscordIntegration
+// @Accept json
+// @Produce json
+// @Param discordID path string true "ID of the discord integration" default(32343a19-da5e-4b1b-a767-3298a73703ca)
+// @Param payload body requests.DiscordUpdate true "Payload of discord integration to update"
+// @Success 200 {object} responses.DiscordResponse
+// @Failure 400 {object} responses.BadRequest
+// @Failure 401 {object} responses.Unauthorized
+// @Failure 422 {object} responses.UnprocessableEntity
+// @Failure 500 {object} responses.InternalServerError
+// @Router /discord-integrations/{discordID} [put]
+func (h *DiscordHandler) Update(c *fiber.Ctx) error {
+ ctx, span, ctxLogger := h.tracer.StartFromFiberCtxWithLogger(c, h.logger)
+ defer span.End()
+
+ var request requests.DiscordUpdate
+ if err := c.BodyParser(&request); err != nil {
+ msg := fmt.Sprintf("cannot marshall params [%s] into [%T]", c.Body(), request)
+ ctxLogger.Warn(stacktrace.Propagate(err, msg))
+ return h.responseBadRequest(c, err)
+ }
+
+ request.DiscordID = c.Params("discordID")
+ if errors := h.validator.ValidateUpdate(ctx, request.Sanitize()); len(errors) != 0 {
+ msg := fmt.Sprintf("validation errors [%s], while updating user [%+#v]", spew.Sdump(errors), request)
+ ctxLogger.Warn(stacktrace.NewError(msg))
+ return h.responseUnprocessableEntity(c, errors, "validation errors while updating discord integration")
+ }
+
+ user, err := h.service.Update(ctx, request.ToUpdateParams(h.userFromContext(c)))
+ if err != nil {
+ msg := fmt.Sprintf("cannot update discord integration with params [%+#v]", request)
+ ctxLogger.Error(stacktrace.Propagate(err, msg))
+ return h.responseInternalServerError(c)
+ }
+
+ return h.responseOK(c, "discord integration updated successfully", user)
+}
+
+// Store an entities.Discord
+// @Summary Store discord integration
+// @Description Store a discord integration for the authenticated user
+// @Security ApiKeyAuth
+// @Tags DiscordIntegration
+// @Accept json
+// @Produce json
+// @Param payload body requests.DiscordStore true "Payload of the discord integration request"
+// @Success 201 {object} responses.DiscordResponse
// @Failure 400 {object} responses.BadRequest
// @Failure 401 {object} responses.Unauthorized
// @Failure 422 {object} responses.UnprocessableEntity
// @Failure 500 {object} responses.InternalServerError
-// @Router /webhooks [post]
+// @Router /discord-integrations [post]
func (h *DiscordHandler) Store(c *fiber.Ctx) error {
ctx, span := h.tracer.StartFromFiberCtx(c)
defer span.End()
diff --git a/api/pkg/requests/discord_index_request.go b/api/pkg/requests/discord_index_request.go
new file mode 100644
index 00000000..1189366f
--- /dev/null
+++ b/api/pkg/requests/discord_index_request.go
@@ -0,0 +1,37 @@
+package requests
+
+import (
+ "strings"
+
+ "github.com/NdoleStudio/httpsms/pkg/repositories"
+)
+
+// DiscordIndex is the payload for fetching entities.Discord of a user
+type DiscordIndex struct {
+ request
+ Skip string `json:"skip" query:"skip"`
+ Query string `json:"query" query:"query"`
+ Limit string `json:"limit" query:"limit"`
+}
+
+// Sanitize sets defaults to MessageOutstanding
+func (input *DiscordIndex) Sanitize() DiscordIndex {
+ if strings.TrimSpace(input.Limit) == "" {
+ input.Limit = "1"
+ }
+ input.Query = strings.TrimSpace(input.Query)
+ input.Skip = strings.TrimSpace(input.Skip)
+ if input.Skip == "" {
+ input.Skip = "0"
+ }
+ return *input
+}
+
+// ToIndexParams converts HeartbeatIndex to repositories.IndexParams
+func (input *DiscordIndex) ToIndexParams() repositories.IndexParams {
+ return repositories.IndexParams{
+ Skip: input.getInt(input.Skip),
+ Query: input.Query,
+ Limit: input.getInt(input.Limit),
+ }
+}
diff --git a/api/pkg/requests/discord_update_request.go b/api/pkg/requests/discord_update_request.go
new file mode 100644
index 00000000..30b05d95
--- /dev/null
+++ b/api/pkg/requests/discord_update_request.go
@@ -0,0 +1,30 @@
+package requests
+
+import (
+ "github.com/NdoleStudio/httpsms/pkg/entities"
+ "github.com/NdoleStudio/httpsms/pkg/services"
+ "github.com/google/uuid"
+)
+
+// DiscordUpdate is the payload for updating an entities.Webhook
+type DiscordUpdate struct {
+ DiscordStore
+ DiscordID string `json:"discordID" swaggerignore:"true"` // used internally for validation
+}
+
+// Sanitize sets defaults to WebhookUpdate
+func (input *DiscordUpdate) Sanitize() DiscordUpdate {
+ input.DiscordStore.Sanitize()
+ return *input
+}
+
+// ToUpdateParams converts DiscordUpdate to services.DiscordUpdateParams
+func (input *DiscordUpdate) ToUpdateParams(user entities.AuthUser) *services.DiscordUpdateParams {
+ return &services.DiscordUpdateParams{
+ UserID: user.ID,
+ Name: input.Name,
+ ServerID: input.ServerID,
+ IncomingChannelID: input.IncomingChannelID,
+ DiscordID: uuid.MustParse(input.DiscordID),
+ }
+}
diff --git a/api/pkg/responses/discord_responses.go b/api/pkg/responses/discord_responses.go
new file mode 100644
index 00000000..6febe2a1
--- /dev/null
+++ b/api/pkg/responses/discord_responses.go
@@ -0,0 +1,15 @@
+package responses
+
+import "github.com/NdoleStudio/httpsms/pkg/entities"
+
+// DiscordResponse is the payload containing entities.Discord
+type DiscordResponse struct {
+ response
+ Data entities.Discord `json:"data"`
+}
+
+// DiscordsResponse is the payload containing []entities.Discord
+type DiscordsResponse struct {
+ response
+ Data []entities.Discord `json:"data"`
+}
diff --git a/api/pkg/services/discord_service.go b/api/pkg/services/discord_service.go
index 038cb90b..49cebdc6 100644
--- a/api/pkg/services/discord_service.go
+++ b/api/pkg/services/discord_service.go
@@ -11,7 +11,6 @@ import (
"github.com/NdoleStudio/httpsms/pkg/repositories"
"github.com/NdoleStudio/httpsms/pkg/telemetry"
"github.com/google/uuid"
- "github.com/lib/pq"
"github.com/palantir/stacktrace"
)
@@ -57,23 +56,23 @@ func (service *DiscordService) Index(ctx context.Context, userID entities.UserID
}
// Delete an entities.Discord
-func (service *DiscordService) Delete(ctx context.Context, userID entities.UserID, webhookID uuid.UUID) error {
+func (service *DiscordService) Delete(ctx context.Context, userID entities.UserID, discordID uuid.UUID) error {
ctx, span := service.tracer.Start(ctx)
defer span.End()
ctxLogger := service.tracer.CtxLogger(service.logger, span)
- if _, err := service.repository.Load(ctx, userID, webhookID); err != nil {
- msg := fmt.Sprintf("cannot load discord integration with userID [%s] and phoneID [%s]", userID, webhookID)
+ if _, err := service.repository.Load(ctx, userID, discordID); err != nil {
+ msg := fmt.Sprintf("cannot load discord integration with userID [%s] and discordID [%s]", userID, discordID)
return service.tracer.WrapErrorSpan(span, stacktrace.PropagateWithCode(err, stacktrace.GetCode(err), msg))
}
- if err := service.repository.Delete(ctx, userID, webhookID); err != nil {
- msg := fmt.Sprintf("cannot delete discord integration with id [%s] and user id [%s]", webhookID, userID)
+ if err := service.repository.Delete(ctx, userID, discordID); err != nil {
+ msg := fmt.Sprintf("cannot delete discord integration with id [%s] and discordID [%s]", discordID, userID)
return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
- ctxLogger.Info(fmt.Sprintf("deleted discord integration with id [%s] and user id [%s]", webhookID, userID))
+ ctxLogger.Info(fmt.Sprintf("deleted discord integration with id [%s] and user id [%s]", discordID, userID))
return nil
}
@@ -83,17 +82,19 @@ type DiscordStoreParams struct {
Name string
ServerID string
IncomingChannelID string
- Events pq.StringArray
}
// Store a new entities.Discord
func (service *DiscordService) Store(ctx context.Context, params *DiscordStoreParams) (*entities.Discord, error) {
- ctx, span := service.tracer.Start(ctx)
+ ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
defer span.End()
- ctxLogger := service.tracer.CtxLogger(service.logger, span)
+ if err := service.createSlashCommand(ctx, params.ServerID); err != nil {
+ msg := fmt.Sprintf("cannot create slash command for server [%s]", params.ServerID)
+ return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
+ }
- discord := &entities.Discord{
+ discordIntegration := &entities.Discord{
ID: uuid.New(),
UserID: params.UserID,
Name: params.Name,
@@ -103,47 +104,91 @@ func (service *DiscordService) Store(ctx context.Context, params *DiscordStorePa
UpdatedAt: time.Now().UTC(),
}
- if err := service.repository.Save(ctx, discord); err != nil {
- msg := fmt.Sprintf("cannot save discord integration with id [%s]", discord.ID)
+ if err := service.repository.Save(ctx, discordIntegration); err != nil {
+ msg := fmt.Sprintf("cannot save discord integration with id [%s]", discordIntegration.ID)
return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
}
- ctxLogger.Info(fmt.Sprintf("discord integration saved with id [%s] in the [%T]", discord.ID, service.repository))
- return discord, nil
+ ctxLogger.Info(fmt.Sprintf("discord integration saved with id [%s] in the [%T]", discordIntegration.ID, service.repository))
+ return discordIntegration, nil
+}
+
+func (service *DiscordService) createSlashCommand(ctx context.Context, serverID string) error {
+ ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
+ defer span.End()
+
+ command, _, err := service.client.Application.CreateCommand(ctx, serverID, &discord.CommandCreateRequest{
+ Name: "httpsms",
+ Type: 1,
+ Description: "Send an SMS via httpsms.com",
+ Options: []discord.CommandCreateRequestOption{
+ {
+ Name: "from",
+ Description: "Sender phone number",
+ Type: 3,
+ Required: true,
+ },
+ {
+ Name: "to",
+ Description: "Recipient phone number",
+ Type: 3,
+ Required: true,
+ },
+ {
+ Name: "message",
+ Description: "Text message content",
+ Type: 3,
+ Required: true,
+ },
+ },
+ })
+ if err != nil {
+ msg := fmt.Sprintf("cannot create slash command for server [%s]", serverID)
+ return service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
+ }
+
+ ctxLogger.Info(fmt.Sprintf("upserted a slash command with ID [%s] for discord server [%s] and applicationID [%s]", command.ID, serverID, command.ApplicationID))
+ return nil
+}
+
+// DiscordUpdateParams are parameters for updating an entities.Discord
+type DiscordUpdateParams struct {
+ UserID entities.UserID
+ Name string
+ ServerID string
+ IncomingChannelID string
+ DiscordID uuid.UUID
+}
+
+// Update an entities.Discord
+func (service *DiscordService) Update(ctx context.Context, params *DiscordUpdateParams) (*entities.Discord, error) {
+ ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
+ defer span.End()
+
+ discordIntegration, err := service.repository.Load(ctx, params.UserID, params.DiscordID)
+ if err != nil {
+ msg := fmt.Sprintf("cannot load discord integration with userID [%s] and discordID [%s]", params.UserID, params.DiscordID)
+ return nil, service.tracer.WrapErrorSpan(span, stacktrace.PropagateWithCode(err, stacktrace.GetCode(err), msg))
+ }
+
+ if err = service.createSlashCommand(ctx, params.ServerID); err != nil {
+ msg := fmt.Sprintf("cannot create slash command for server [%s]", params.ServerID)
+ return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
+ }
+
+ discordIntegration.Name = params.Name
+ discordIntegration.ServerID = params.ServerID
+ discordIntegration.IncomingChannelID = params.IncomingChannelID
+
+ if err = service.repository.Save(ctx, discordIntegration); err != nil {
+ msg := fmt.Sprintf("cannot save discord integration with id [%s] after update", discordIntegration.ID)
+ return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
+ }
+
+ ctxLogger.Info(fmt.Sprintf("discord integration updated with id [%s] in the [%T]", discordIntegration.ID, service.repository))
+ return discordIntegration, nil
}
-//// DiscordUpdateParams are parameters for updating an entities.Discord
-//type DiscordUpdateParams struct {
-// UserID entities.UserID
-// SigningKey string
-// URL string
-// Events pq.StringArray
-// DiscordID uuid.UUID
-//}
-//
-//// Update an entities.Discord
-//func (service *DiscordService) Update(ctx context.Context, params *DiscordUpdateParams) (*entities.Discord, error) {
-// ctx, span, ctxLogger := service.tracer.StartWithLogger(ctx, service.logger)
-// defer span.End()
-//
-// webhook, err := service.repository.Load(ctx, params.UserID, params.DiscordID)
-// if err != nil {
-// msg := fmt.Sprintf("cannot load webhook with userID [%s] and phoneID [%s]", params.UserID, params.DiscordID)
-// return nil, service.tracer.WrapErrorSpan(span, stacktrace.PropagateWithCode(err, stacktrace.GetCode(err), msg))
-// }
-//
-// webhook.URL = params.URL
-// webhook.SigningKey = params.SigningKey
-// webhook.Events = params.Events
-//
-// if err = service.repository.Save(ctx, webhook); err != nil {
-// msg := fmt.Sprintf("cannot save webhook with id [%s] after update", webhook.ID)
-// return nil, service.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg))
-// }
-//
-// ctxLogger.Info(fmt.Sprintf("webhook updated with id [%s] in the [%T]", webhook.ID, service.repository))
-// return webhook, nil
-//}
//
//// Send an event to a subscribed webhook
//func (service *DiscordService) Send(ctx context.Context, userID entities.UserID, event cloudevents.Event) error {
diff --git a/api/pkg/validators/discord_handler_validator.go b/api/pkg/validators/discord_handler_validator.go
index bc375e6c..0968bc94 100644
--- a/api/pkg/validators/discord_handler_validator.go
+++ b/api/pkg/validators/discord_handler_validator.go
@@ -35,29 +35,29 @@ func NewDiscordHandlerValidator(
}
}
-//// ValidateIndex validates the requests.HeartbeatIndex request
-//func (validator *DiscordHandlerValidator) ValidateIndex(_ context.Context, request requests.DiscordIndex) url.Values {
-// v := govalidator.New(govalidator.Options{
-// Data: &request,
-// Rules: govalidator.MapData{
-// "limit": []string{
-// "required",
-// "numeric",
-// "min:1",
-// "max:100",
-// },
-// "skip": []string{
-// "required",
-// "numeric",
-// "min:0",
-// },
-// "query": []string{
-// "max:100",
-// },
-// },
-// })
-// return v.ValidateStruct()
-//}
+// ValidateIndex validates the requests.DiscordIndex request
+func (validator *DiscordHandlerValidator) ValidateIndex(_ context.Context, request requests.DiscordIndex) url.Values {
+ v := govalidator.New(govalidator.Options{
+ Data: &request,
+ Rules: govalidator.MapData{
+ "limit": []string{
+ "required",
+ "numeric",
+ "min:1",
+ "max:100",
+ },
+ "skip": []string{
+ "required",
+ "numeric",
+ "min:0",
+ },
+ "query": []string{
+ "max:100",
+ },
+ },
+ })
+ return v.ValidateStruct()
+}
// ValidateStore validates the requests.DiscordStore request
func (validator *DiscordHandlerValidator) ValidateStore(ctx context.Context, request requests.DiscordStore) url.Values {
@@ -93,42 +93,64 @@ func (validator *DiscordHandlerValidator) ValidateStore(ctx context.Context, req
if _, _, err := validator.client.Channel.Get(ctx, request.IncomingChannelID); err != nil {
msg := fmt.Sprintf("cannot fetch discord channel with ID [%s]", request.IncomingChannelID)
ctxLogger.Error(validator.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg)))
- result.Add("incoming_channel_id", fmt.Sprintf("cannot fetch discord channel with ID [%s] make sure the bot has access to the channel"))
+ result.Add("incoming_channel_id", fmt.Sprintf("cannot fetch discord channel with ID [%s] make sure the bot has access to the channel", request.IncomingChannelID))
}
if _, _, err := validator.client.Guild.Get(ctx, request.ServerID); err != nil {
msg := fmt.Sprintf("cannot fetch discord channel with ID [%s]", request.IncomingChannelID)
ctxLogger.Error(validator.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg)))
- result.Add("server_id", fmt.Sprintf("cannot fetch discord channel with ID [%s] make sure the bot has access to the channel"))
+ result.Add("server_id", fmt.Sprintf("cannot fetch discord server with ID [%s] make sure the bot has access to the channel", request.ServerID))
}
return result
}
-//// ValidateUpdate validates the requests.DiscordUpdate request
-//func (validator *DiscordHandlerValidator) ValidateUpdate(_ context.Context, request requests.DiscordUpdate) url.Values {
-// v := govalidator.New(govalidator.Options{
-// Data: &request,
-// Rules: govalidator.MapData{
-// "signing_key": []string{
-// "required",
-// "min:1",
-// "max:255",
-// },
-// "webhookID": []string{
-// "required",
-// "uuid",
-// },
-// "url": []string{
-// "required",
-// "url",
-// "max:255",
-// },
-// "events": []string{
-// "required",
-// webhookEventsRule,
-// },
-// },
-// })
-// return v.ValidateStruct()
-//}
+// ValidateUpdate validates the requests.DiscordUpdate request
+func (validator *DiscordHandlerValidator) ValidateUpdate(ctx context.Context, request requests.DiscordUpdate) url.Values {
+ ctx, span, ctxLogger := validator.tracer.StartWithLogger(ctx, validator.logger)
+ defer span.End()
+
+ v := govalidator.New(govalidator.Options{
+ Data: &request,
+ Rules: govalidator.MapData{
+ "name": []string{
+ "required",
+ "min:1",
+ "max:255",
+ },
+ "server_id": []string{
+ "required",
+ "numeric",
+ "max:255",
+ },
+ "incoming_channel_id": []string{
+ "required",
+ "max:255",
+ "numeric",
+ },
+ "discordID": []string{
+ "required",
+ "uuid",
+ },
+ },
+ })
+
+ result := v.ValidateStruct()
+ if len(result) > 0 {
+ return result
+ }
+
+ if _, _, err := validator.client.Channel.Get(ctx, request.IncomingChannelID); err != nil {
+ msg := fmt.Sprintf("cannot fetch discord channel with ID [%s]", request.IncomingChannelID)
+ ctxLogger.Error(validator.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg)))
+ result.Add("incoming_channel_id", fmt.Sprintf("cannot fetch discord channel with ID [%s] make sure the bot has access to the channel", request.IncomingChannelID))
+ }
+
+ if _, _, err := validator.client.Guild.Get(ctx, request.ServerID); err != nil {
+ msg := fmt.Sprintf("cannot fetch discord channel with ID [%s]", request.IncomingChannelID)
+ ctxLogger.Error(validator.tracer.WrapErrorSpan(span, stacktrace.Propagate(err, msg)))
+ result.Add("server_id", fmt.Sprintf("cannot fetch discord server with ID [%s] make sure the bot has access to the channel", request.ServerID))
+ }
+
+ return result
+}
diff --git a/web/models/api.ts b/web/models/api.ts
index 633d9b96..10e5e15d 100644
--- a/web/models/api.ts
+++ b/web/models/api.ts
@@ -1,3 +1,4 @@
+/* eslint-disable */
/* tslint:disable */
/*
* ---------------------------------------------------------------
@@ -29,6 +30,23 @@ export interface EntitiesBillingUsage {
user_id: string
}
+export interface EntitiesDiscord {
+ /** @example "2022-06-05T14:26:02.302718+03:00" */
+ created_at: string
+ /** @example "32343a19-da5e-4b1b-a767-3298a73703cb" */
+ id: string
+ /** @example "1095780203256627291" */
+ incoming_channel_id: string
+ /** @example "Game Server" */
+ name: string
+ /** @example "1095778291488653372" */
+ server_id: string
+ /** @example "2022-06-05T14:26:10.303278+03:00" */
+ updated_at: string
+ /** @example "WB7DRDWrJZRGbYrv2CKGkqbzvqdC" */
+ user_id: string
+}
+
export interface EntitiesHeartbeat {
/** @example "32343a19-da5e-4b1b-a767-3298a73703cb" */
id: string
@@ -82,6 +100,14 @@ export interface EntitiesMessage {
send_time: number
/** @example "2022-06-05T14:26:09.527976+03:00" */
sent_at: string
+ /**
+ * SIM is the SIM card to use to send the message
+ * * SMS1: use the SIM card in slot 1
+ * * SMS2: use the SIM card in slot 2
+ * * DEFAULT: used the default communication SIM card
+ * @example "DEFAULT"
+ */
+ sim: string
/** @example "pending" */
status: string
/** @example "mobile-terminated" */
@@ -124,6 +150,8 @@ export interface EntitiesPhone {
fcm_token: string
/** @example "32343a19-da5e-4b1b-a767-3298a73703cb" */
id: string
+ /** @example false */
+ is_dual_sim: boolean
/**
* MaxSendAttempts determines how many times to retry sending an SMS message
* @example 1
@@ -189,10 +217,36 @@ export interface EntitiesWebhook {
user_id: string
}
+export interface RequestsDiscordStore {
+ incoming_channel_id: string
+ name: string
+ server_id: string
+}
+
+export interface RequestsDiscordUpdate {
+ incoming_channel_id: string
+ name: string
+ server_id: string
+}
+
export interface RequestsHeartbeatStore {
owner: string
}
+export interface RequestsMessageBulkSend {
+ /** @example "This is a sample text message" */
+ content: string
+ /** @example "+18005550199" */
+ from: string
+ /**
+ * sim card to use to send the message
+ * @example "DEFAULT"
+ */
+ sim: string
+ /** @example ["+18005550100","+18005550100"] */
+ to: string[]
+}
+
export interface RequestsMessageEvent {
/**
* EventName is the type of event
@@ -216,6 +270,11 @@ export interface RequestsMessageReceive {
content: string
/** @example "+18005550199" */
from: string
+ /**
+ * SIM card that received the message
+ * @example "DEFAULT"
+ */
+ sim: string
/**
* Timestamp is the time when the event was emitted, Please send the timestamp in UTC with as much precision as possible
* @example "2022-06-05T14:26:09.527976+03:00"
@@ -230,6 +289,11 @@ export interface RequestsMessageSend {
content: string
/** @example "+18005550199" */
from: string
+ /**
+ * sim card to use to send the message
+ * @example "DEFAULT"
+ */
+ sim: string
/** @example "+18005550100" */
to: string
}
@@ -242,6 +306,11 @@ export interface RequestsMessageThreadUpdate {
export interface RequestsPhoneUpsert {
/** @example "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzd....." */
fcm_token: string
+ /**
+ * IsDualSIM is true if the phone has more than one SIM active
+ * @example false
+ */
+ is_dual_sim: boolean
/**
* MaxSendAttempts is the number of attempts when sending an SMS message to handle the case where the phone is offline.
* @example 2
@@ -300,6 +369,22 @@ export interface ResponsesBillingUsagesResponse {
status: string
}
+export interface ResponsesDiscordResponse {
+ data: EntitiesDiscord
+ /** @example "item created successfully" */
+ message: string
+ /** @example "success" */
+ status: string
+}
+
+export interface ResponsesDiscordsResponse {
+ data: EntitiesDiscord[]
+ /** @example "item created successfully" */
+ message: string
+ /** @example "success" */
+ status: string
+}
+
export interface ResponsesHeartbeatResponse {
data: EntitiesHeartbeat
/** @example "item created successfully" */
diff --git a/web/pages/settings/index.vue b/web/pages/settings/index.vue
index 26da1a4e..43d98f8c 100644
--- a/web/pages/settings/index.vue
+++ b/web/pages/settings/index.vue
@@ -83,7 +83,7 @@
<h5 class="text-h4 mb-3 mt-12">Webhooks</h5>
<p class="text--secondary">
Webhooks allow us to send events to your server for example when
- the android phone receives an SMS message we can foward the
+ the android phone receives an SMS message we can forward the
message to your server.
</p>
<div v-if="loadingWebhooks">
@@ -148,9 +148,58 @@
<h5 class="text-h4 mb-3 mt-12">Discord Integration</h5>
<p class="text--secondary">
Send and receive SMS messages without leaving your discord server
- with the httpsms discord app.
+ with the httpsms discord app using the
+ <code>/httpsms</code> command.
</p>
- <v-btn color="#5865f2" @click="onWebhookCreate">
+ <div v-if="loadingDiscordIntegrations">
+ <v-progress-circular
+ :size="60"
+ :width="2"
+ color="primary"
+ class="mb-4"
+ indeterminate
+ ></v-progress-circular>
+ </div>
+ <v-simple-table v-else-if="discords.length" class="mb-4">
+ <template #default>
+ <thead>
+ <tr class="text-uppercase subtitle-2">
+ <th class="text-left">Name</th>
+ <th class="text-left">Server ID</th>
+ <th class="text-left">Channel ID</th>
+ <th class="text-center">Action</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr v-for="discord in discords" :key="discord.id">
+ <td class="text-left">
+ {{ discord.name }}
+ </td>
+ <td class="text-left">
+ {{ discord.server_id }}
+ </td>
+ <td class="text-left">
+ {{ discord.incoming_channel_id }}
+ </td>
+ <td class="text-center">
+ <v-btn
+ :icon="$vuetify.breakpoint.mdAndDown"
+ small
+ color="info"
+ :disabled="updatingDiscord"
+ @click.prevent="onDiscordEdit(discord.id)"
+ >
+ <v-icon small>{{ mdiSquareEditOutline }}</v-icon>
+ <span v-if="!$vuetify.breakpoint.mdAndDown">
+ Edit
+ </span>
+ </v-btn>
+ </td>
+ </tr>
+ </tbody>
+ </template>
+ </v-simple-table>
+ <v-btn color="#5865f2" @click="onDiscordCreate">
<v-img
contain
height="24"
@@ -219,7 +268,6 @@
<td class="text-center">
<v-btn
:icon="$vuetify.breakpoint.mdAndDown"
- small
color="info"
:disabled="updatingPhone"
@click.prevent="showEditPhone(phone.id)"
@@ -417,6 +465,119 @@
</v-card-actions>
</v-card>
</v-dialog>
+ <v-dialog v-model="showDiscordEdit" max-width="700px">
+ <v-card>
+ <v-card-title>
+ <span v-if="!activeDiscord.id">Add a new&nbsp;</span>
+ <span v-else>Edit&nbsp;</span>
+ discord integration
+ </v-card-title>
+ <v-card-text>
+ <v-row>
+ <v-col class="pt-8">
+ <p class="mt-n4 subtitle-1">
+ Click the button below to add the httpSMS bot to your discord
+ server. You need to do this so we can have permission to send
+ and receive messages on your discord server.
+ </p>
+ <v-btn
+ color="#5865f2"
+ class="mb-6"
+ target="_blank"
+ href="https://discord.com/api/oauth2/authorize?client_id=1095780203256627291&permissions=2147485760&scope=bot%20applications.commands"
+ >
+ <v-icon left>{{ mdiConnection }}</v-icon>
+ Add Discord Bot
+ </v-btn>
+ <v-text-field
+ v-if="activeDiscord.id"
+ outlined
+ dense
+ disabled
+ label="ID"
+ :value="activeDiscord.id"
+ >
+ </v-text-field>
+ <v-text-field
+ v-model="activeDiscord.name"
+ outlined
+ dense
+ label="Name"
+ persistent-placeholder
+ persistent-hint
+ :error="errorMessages.has('name')"
+ :error-messages="errorMessages.get('name')"
+ hint="The name of the discord integration"
+ placeholder="e.g Game Server"
+ >
+ </v-text-field>
+ <v-text-field
+ v-model="activeDiscord.server_id"
+ outlined
+ dense
+ class="mt-6"
+ persistent-placeholder
+ persistent-hint
+ label="Discord Server ID"
+ placeholder="e.g 1095778291488653372"
+ :error="errorMessages.has('server_id')"
+ :error-messages="errorMessages.get('server_id')"
+ hint="You can get this by right clicking on your server and clicking Copy Server ID."
+ >
+ </v-text-field>
+ <v-text-field
+ v-model="activeDiscord.incoming_channel_id"
+ outlined
+ dense
+ class="mt-6"
+ persistent-placeholder
+ persistent-hint
+ label="Discord Incoming Channel ID"
+ placeholder="e.g 1095778291488653372"
+ :error="errorMessages.has('incoming_channel_id')"
+ :error-messages="errorMessages.get('incoming_channel_id')"
+ hint="You can get this by right clicking on your discord channel and clicking Copy Chanel ID."
+ >
+ </v-text-field>
+ </v-col>
+ </v-row>
+ </v-card-text>
+ <v-card-actions class="mt-n4 pb-4 pl-6">
+ <loading-button
+ v-if="!activeDiscord.id"
+ :icon="mdiContentSave"
+ :loading="updatingDiscord"
+ @click="createDiscord"
+ >
+ Save Discord Integration
+ </loading-button>
+ <loading-button
+ v-else
+ color="info"
+ :loading="updatingDiscord"
+ @click="updateDiscord"
+ >
+ <v-icon v-if="$vuetify.breakpoint.lgAndUp" small>
+ {{ mdiContentSave }}
+ </v-icon>
+ Update Discord Integration
+ </loading-button>
+ <v-spacer></v-spacer>
+ <v-btn
+ v-if="activeDiscord.id"
+ :disabled="updatingDiscord"
+ color="error"
+ text
+ @click="deleteDiscord(activeDiscord.id)"
+ >
+ <v-icon v-if="$vuetify.breakpoint.lgAndUp" small>
+ {{ mdiDelete }}
+ </v-icon>
+ Delete
+ </v-btn>
+ </v-card-actions>
+ </v-card>
+ </v-dialog>
</v-container>
</template>
@@ -428,6 +589,7 @@ import {
mdiShieldCheck,
mdiDelete,
mdiContentSave,
+ mdiConnection,
mdiEye,
mdiLinkVariant,
mdiEyeOff,
@@ -451,21 +613,32 @@ export default Vue.extend({
mdiLinkVariant,
mdiContentSave,
mdiSquareEditOutline,
+ mdiConnection,
errorMessages: new ErrorMessages(),
apiKeyShow: false,
showPhoneEdit: false,
+ showDiscordEdit: false,
activeWebhook: {
id: null,
url: '',
signing_key: '',
events: ['message.phone.received'],
},
+ activeDiscord: {
+ id: null,
+ name: '',
+ server_id: '',
+ incoming_channel_id: '',
+ },
updatingWebhook: false,
loadingWebhooks: false,
+ discords: [],
webhooks: [],
showWebhookEdit: false,
activePhone: null,
updatingPhone: false,
+ updatingDiscord: false,
+ loadingDiscordIntegrations: false,
events: ['message.phone.received'],
}
},
@@ -486,6 +659,7 @@ export default Vue.extend({
this.$store.dispatch('clearAxiosError')
this.$store.dispatch('loadUser')
this.loadWebhooks()
+ this.loadDiscordIntegrations()
},
methods: {
@@ -514,6 +688,21 @@ export default Vue.extend({
this.resetErrors()
},
+ onDiscordEdit(discordId) {
+ const discord = this.discords.find((x) => x.id === discordId)
+ if (!discord) {
+ return
+ }
+ this.activeDiscord = {
+ id: discord.id,
+ name: discord.name,
+ server_id: discord.server_id,
+ incoming_channel_id: discord.incoming_channel_id,
+ }
+ this.showDiscordEdit = true
+ this.resetErrors()
+ },
+
onWebhookCreate() {
this.activeWebhook = {
id: null,
@@ -525,6 +714,17 @@ export default Vue.extend({
this.resetErrors()
},
+ onDiscordCreate() {
+ this.activeDiscord = {
+ id: null,
+ name: '',
+ server_id: '',
+ incoming_channel_id: '',
+ }
+ this.showDiscordEdit = true
+ this.resetErrors()
+ },
+
async updatePhone() {
this.updatingPhone = true
await this.$store.dispatch('clearAxiosError')
@@ -541,6 +741,65 @@ export default Vue.extend({
this.errorMessages = new ErrorMessages()
},
+ createDiscord() {
+ this.resetErrors()
+ this.updatingDiscord = true
+ this.$store
+ .dispatch('createDiscord', this.activeDiscord)
+ .then(() => {
+ this.$store.dispatch('addNotification', {
+ message: 'Discord integration created successfully',
+ type: 'success',
+ })
+ this.showDiscordEdit = false
+ this.loadDiscordIntegrations()
+ })
+ .catch((errors) => {
+ this.errorMessages = errors
+ })
+ .finally(() => {
+ this.updatingDiscord = false
+ })
+ },
+
+ updateDiscord() {
+ this.resetErrors()
+ this.updatingDiscord = true
+ this.$store
+ .dispatch('updateDiscordIntegration', this.activeDiscord)
+ .then(() => {
+ this.$store.dispatch('addNotification', {
+ message: 'Discord integration updated successfully',
+ type: 'success',
+ })
+ this.showDiscordEdit = false
+ this.loadDiscordIntegrations()
+ })
+ .catch((errors) => {
+ this.errorMessages = errors
+ })
+ .finally(() => {
+ this.updatingDiscord = false
+ })
+ },
+
+ deleteDiscord(discordId) {
+ this.updatingDiscord = true
+ this.$store
+ .dispatch('deleteDiscordIntegration', discordId)
+ .then(() => {
+ this.$store.dispatch('addNotification', {
+ message: 'Discord integration deleted successfully',
+ type: 'success',
+ })
+ this.showDiscordEdit = false
+ this.loadDiscordIntegrations()
+ })
+ .finally(() => {
+ this.updatingDiscord = false
+ })
+ },
+
createWebhook() {
this.resetErrors()
this.updatingWebhook = true
@@ -612,6 +871,18 @@ export default Vue.extend({
})
},
+ loadDiscordIntegrations() {
+ this.loadingDiscordIntegrations = true
+ this.$store
+ .dispatch('getDiscordIntegrations')
+ .then((discords) => {
+ this.discords = discords
+ })
+ .finally(() => {
+ this.loadingDiscordIntegrations = false
+ })
+ },
+
deletePhone(phoneId) {
this.updatingPhone = true
this.$store.dispatch('deletePhone', phoneId).finally(() => {
diff --git a/web/store/index.ts b/web/store/index.ts
index 7e5b54c3..c7d18486 100644
--- a/web/store/index.ts
+++ b/web/store/index.ts
@@ -8,9 +8,14 @@ import { Phone } from '~/models/phone'
import { User } from '~/models/user'
import { BillingUsage } from '~/models/billing'
import {
+ EntitiesDiscord,
EntitiesWebhook,
+ RequestsDiscordStore,
+ RequestsDiscordUpdate,
RequestsWebhookStore,
RequestsWebhookUpdate,
+ ResponsesDiscordResponse,
+ ResponsesDiscordsResponse,
ResponsesNoContent,
ResponsesOkString,
ResponsesWebhookResponse,
@@ -594,6 +599,106 @@ export const actions = {
})
},
+ createDiscord(
+ context: ActionContext<State, State>,
+ payload: RequestsDiscordStore
+ ): Promise<EntitiesDiscord> {
+ return new Promise<EntitiesDiscord>((resolve, reject) => {
+ axios
+ .post<ResponsesDiscordResponse>(`/v1/discord-integrations`, payload)
+ .then((response: AxiosResponse<ResponsesDiscordResponse>) => {
+ resolve(response.data.data)
+ })
+ .catch(async (error: AxiosError) => {
+ await Promise.all([
+ context.dispatch('addNotification', {
+ message:
+ error.response?.data?.message ??
+ 'Error while adding discord integration',
+ type: 'error',
+ }),
+ ])
+ reject(getErrorMessages(error))
+ })
+ })
+ },
+
+ getDiscordIntegrations(context: ActionContext<State, State>) {
+ return new Promise<Array<EntitiesDiscord>>((resolve, reject) => {
+ axios
+ .get<ResponsesDiscordsResponse>(`/v1/discord-integrations`, {
+ params: {
+ limit: 100,
+ },
+ })
+ .then((response: AxiosResponse<ResponsesDiscordsResponse>) => {
+ resolve(response.data.data)
+ })
+ .catch(async (error: AxiosError) => {
+ await Promise.all([
+ context.dispatch('addNotification', {
+ message:
+ error.response?.data?.message ??
+ 'Error while fetching discord integrations',
+ type: 'error',
+ }),
+ ])
+ reject(getErrorMessages(error))
+ })
+ })
+ },
+
+ updateDiscordIntegration(
+ context: ActionContext<State, State>,
+ payload: RequestsDiscordUpdate & { id: string }
+ ) {
+ return new Promise<EntitiesDiscord>((resolve, reject) => {
+ axios
+ .put<ResponsesDiscordResponse>(
+ `/v1/discord-integrations/${payload.id}`,
+ payload
+ )
+ .then((response: AxiosResponse<ResponsesDiscordResponse>) => {
+ resolve(response.data.data)
+ })
+ .catch(async (error: AxiosError) => {
+ await Promise.all([
+ context.dispatch('addNotification', {
+ message:
+ error.response?.data?.message ??
+ 'Error while updating discord integration',
+ type: 'error',
+ }),
+ ])
+ reject(getErrorMessages(error))
+ })
+ })
+ },
+
+ deleteDiscordIntegration(
+ context: ActionContext<State, State>,
+ payload: string
+ ) {
+ return new Promise<void>((resolve, reject) => {
+ axios
+ .delete<ResponsesNoContent>(`/v1/discord-integrations/${payload}`)
+ .then(() => {
+ resolve()
+ })
+ .catch(async (error: AxiosError) => {
+ await Promise.all([
+ context.dispatch('addNotification', {
+ message:
+ error.response?.data?.message ??
+ 'Error while deleting discord integration',
+ type: 'error',
+ }),
+ ])
+ reject(getErrorMessages(error))
+ })
+ })
+ },
+
createWebhook(
context: ActionContext<State, State>,
payload: RequestsWebhookStore