nidus-sync/comms/text/twilio.go

58 lines
1.7 KiB
Go
Raw Normal View History

package text
import (
"context"
"fmt"
2026-05-19 16:03:42 +00:00
"net/http"
"time"
"github.com/rs/zerolog/log"
"github.com/twilio/twilio-go"
2026-05-19 16:03:42 +00:00
twilioClient "github.com/twilio/twilio-go/client"
twilioApi "github.com/twilio/twilio-go/rest/api/v2010"
"source.gleipnir.technology/Gleipnir/nidus-sync/config"
)
2026-05-19 16:03:42 +00:00
// forceContextRoundTripper sets the given context on every request and passes it to the wrapped RoundTripper
type forceContextRoundTripper struct {
roundTripper http.RoundTripper
ctx context.Context
}
func (f *forceContextRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) {
req = req.Clone(f.ctx)
return f.roundTripper.RoundTrip(req)
}
func sendTextTwilio(ctx context.Context, source string, destination string, message string) (string, error) {
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
client := twilio.NewRestClient()
2026-05-19 16:03:42 +00:00
http_client := &http.Client{
Timeout: 30 * time.Second,
}
http_client.Transport = &forceContextRoundTripper{
ctx: ctx,
roundTripper: http_client.Transport,
}
client.RequestHandler.Client.(*twilioClient.Client).HTTPClient = http_client
params := &twilioApi.CreateMessageParams{}
params.SetMessagingServiceSid(config.TwilioMessagingServiceSID)
params.SetBody(message)
params.SetTo(destination)
resp, err := client.Api.CreateMessage(params)
if err != nil {
return "", fmt.Errorf("Failed to create message to %s: %w", destination, err)
}
if resp.Sid == nil {
log.Warn().Str("src", source).Str("dst", destination).Msg("Text message sid is nil")
return "", nil
}
log.Info().Str("src", source).Str("dst", destination).Str("message", message).Str("sid", *resp.Sid).Msg("Created text message")
return *resp.Sid, nil
}