2

The goal is to send an image using the conversations API (group chat) from the backend.

I see how you can use mediaUrl if it's just 1-1 messaging:

MessageResource.Create(
        body: "Hello there!",
        from: new Twilio.Types.PhoneNumber("+15555555555"),
        mediaUrl: mediaUrl,
        to: new Twilio.Types.PhoneNumber("+12316851234")
);

The above doesn't work for me as I'm looking to use a group chat will multiple members. Here is my current implementation for sending a text to multiple participants

// create a group chat
ConversationResource conversation = ConversationResource.Create(client: _twilioClient);

var bootyService = ParticipantResource.Create(
    identity: "myService",
    messagingBindingProjectedAddress: "+15555555555",
    pathConversationSid: conversation.Sid, 
    client: _twilioClient
);

// participant 1
var sender = ParticipantResource.Create(
    messagingBindingAddress: "+12316851234",
    pathConversationSid: conversation.Sid, 
    client: _twilioClient
);

// participant 2
var Receiver = ParticipantResource.Create(
    messagingBindingAddress: "+12316851234",
    pathConversationSid: conversation.Sid, 
    client: _twilioClient
);

var groupMessage = ConversationMessageResource.Create(
    body: "Hi this is a group chat",
    author: "myService",
    pathConversationSid: conversation.Sid, 
    client: _twilioClient
);

The conversations API doesn't have any concept of mediaURL. Is it possible to use Conversations MessageResource to send an image?

pflous
  • 573
  • 6
  • 17
  • You haven't told us what the problem is... – Dai Aug 14 '22 at 23:03
  • `var bootyService` - _hmmmmmm_ – Dai Aug 14 '22 at 23:03
  • @Dai MessageResource.Create() for conversations API has no concept of mediaUrl I'm not seeing an easy way to actually text an image – pflous Aug 14 '22 at 23:34
  • I'm seeing some discussion here regarding media - but this requires the service to upload the image per conversation. I have a single static image URL that I want to send out to new groups https://www.twilio.com/docs/conversations/api/media-resource – pflous Aug 14 '22 at 23:39
  • AFAIk that's not allowed: Twilio only lets you reference images/videos/files hosted by themselves – Dai Aug 14 '22 at 23:42
  • @Dai yah in my case i have an image hosed elsewhere (S3) - lets say we use the sample twilio image "https://demo.twilio.com/owl.png" how can I use conversations API to send this? – pflous Aug 14 '22 at 23:45
  • After you've created a `Media` resource for the single image, use that `mediaSid` value in the new `ConversationMessage` resource object ( https://www.twilio.com/docs/conversations/api/conversation-message-resource#create-a-conversationmessage-resource ) - Twilio seems to restrict media to 1-per-message, fwiw. – Dai Aug 14 '22 at 23:48
  • @Dai ah yes so the creation of the Media resource is the confusing part. How is that done? Does it require a fresh upload per conversation - that's the impression i've been getting here https://www.twilio.com/docs/conversations/api/media-resource – pflous Aug 14 '22 at 23:53
  • `Media` resources are not a member of a `Conversation` - so (I think...) you only need to uplload each distinct image/file/etc _once_, and you can re-use the Twilio-hosted URL in as many different `Conversations` as you like. – Dai Aug 15 '22 at 00:40
  • The only instructions of creating a `Media` resource I've been able to find is here: https://www.twilio.com/docs/conversations/api/media-resource#createupload-a-new-media-resource The POST method requires a chat service SID as part of the URL. They mention that "You can find the Chat Service SID as a property of the Conversation to which you want to add a new media message" – pflous Aug 15 '22 at 00:47

3 Answers3

2

To send media to a conversation is a two part process, unlike sending an MMS message.

First you need to upload the media to the Media resource endpoint. This is by making a POST request to the URL https://mcs.us1.twilio.com/v1/Services/{Chat Service SID}/Media.

You can get the Chat Service SID by fetching a Conversation resource and inspecting the Chat Service SID returned. All conversations in the same conversation service will have the same Chat Service SID.

Once you have the Chat Service SID, you can upload the file. Here is an example in curl:

curl -u "<account_sid>:<account_secret>" --data-binary @<filename.png> -H "Content-Type: <content-type of upload>" https://mcs.us1.twilio.com/v1/Services/<chat_service_sid>/Media

Now that you have uploaded the media, you can use it in a conversation message. To do so, you need to pass an array of media objects that you want to send as part of the message. A media object has a content_type with the MIME type of the media, a filename, a size and the sid of the media resource you just created.

var groupMessage = ConversationMessageResource.Create(
    body: "Hi this is a group chat",
    author: "myService",
    pathConversationSid: conversation.Sid, 
    client: _twilioClient,
    media: {
      new {
        content_type = "image/png",
        size = 123456,
        filename: "filename.png",
        sid = "MEDIA_SID"
      }
    }]
);

(Please excuse my C# if that's not the right way to initialize a list of objects, hopefully it gets the idea across.)

philnash
  • 70,667
  • 10
  • 60
  • 88
  • Manage to get it to send this way! Very surprising how involved this is. I have a welcome image I send out to every new group chat spawned. With this process I'm going to have to send a POST and upload the image every time a new conversation is spawned which feels very wasteful. If I try and re-use the SID I get https://www.twilio.com/docs/api/errors/50508 So it seems I really need to upload every single time :( – pflous Aug 15 '22 at 15:22
  • 1
    Glad to hear this worked. I agree that it is a bit of a hassle that you want to send the same image each time to upload it again each time, but that seems to be how the API works. – philnash Aug 15 '22 at 23:36
0

For sake of completeness I'll post here what I have ended up doing - it's not pretty but doesn't seem like there a less ugly way to do it

TL;DR is you have to upload the image to Twilio as a Media object every time. In the response you get the SID and pass that through to the message you send with image

ConversationResource conversation = ConversationResource.Create(client: _twilioClient);
string postUrl = "https://mcs.us1.twilio.com/v1/Services/" + conversation.ChatServiceSid + "/Media";

string filePath = "./wwwroot/img/myImage.png";
FileStream fs = System.IO.File.OpenRead(filePath);
var formContent = new MultipartFormDataContent
{
    {new StreamContent(fs), "file", "myImage.png"}
};


var myHttpClient = new HttpClient();
myHttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
    "Basic", Convert.ToBase64String(
          System.Text.ASCIIEncoding.ASCII.GetBytes(_config.Twilio.AccountSid + ":" + _config.Twilio.AuthToken)));
var response = await myHttpClient.PostAsync(postUrl, formContent);
var stringContent = await response.Content.ReadFromJsonAsync<TwilioPost>();
var textImage = ParticipantResource.Create(
    identity: "myService",
    messagingBindingProjectedAddress: _config.Twilio.FromNumber,
    pathConversationSid: conversation.Sid,
    client: _twilioClient
);

if (stringContent != null && stringContent.Sid != null)
{
    var groupMessage = ConversationMessageResource.Create(
        body: body,
        mediaSid: stringContent.Sid,
        author: "myService",
        pathConversationSid: conversation.Sid,
        client: _twilioClient
    );
}
pflous
  • 573
  • 6
  • 17
0
const client = require('twilio')(process.env.twilioAccountSid, process.env.twilioAuthToken);
client.messages.create({
   to: xxxxxxxxx,
   from: xxxxxxxxxx,
   mediaUrl:"" 
}).then(message=>{})
MALIK KHAN
  • 41
  • 1
  • 3
    Thank you for contributing to the Stack Overflow community. This may be a correct answer, but it’d be really useful to provide additional explanation of your code so developers can understand your reasoning. This is especially useful for new developers who aren’t as familiar with the syntax or struggling to understand the concepts. **Would you kindly [edit] your answer to include additional details for the benefit of the community?** – Jeremy Caney Aug 03 '23 at 00:26