Trying to create a web chat application where we fetch all the channels a user is a part of from Backend. Backend returns an array of objects containing twilio access tokens and channel names. After getting API response, Javascript iterates through the array and creates chat clients for each channel using following code:
let apiResponse = [
{token: 'abcdefgh', channel_name: 'a'},
{token: 'abcdef', channel_name: 'b'},
{token: 'abcd', channel_name: 'c'}
];
let createdClients = [];
apiResponse.forEach((item) => {
Chat.create(chatRoomToken)
.then(client => {
// You get the client here which can be pushed into createdClients array
})
}
Currently this is done in sequence as JS is single threaded and then as and when promises are resolved, createdClients array is being populated . How can I possibly parallelise Chat.create(chatRoomToken) for multiple channels in order to save more time. Has anybody solved this using web workers or service workers? Thanks.
Twilio developer evangelist here.
You only need one Chat client to interact with a Chat service, not one per channel. With the chat client you can then load the user's channels with client.getUserChannelDescriptors() and load individual channels with client.getChannelBySid().
Related
I'm using activityFeedNotification graph api to send push notification to the users of our teams tab app from backend using nodejs. The notification is sending successfully in both teams desktop and mobile client but we're not getting the data assigned to subEntityId in mobile client(In desktop client and browser we're getting it).
We are encoding the data(object) and assigning it to the subEntityId in teams context in our nodejs application. Then in teams client, we get that data from teams context using microsoft teams sdk and redirect user to the respective page in our application based on whatever data we get in subEntityId
In desktop, deeplinking is working perfectly but in android client, we're not getting any data in subEntityId. It is just opening the homepage of our tab app but I need to redirect user to specific page based whatever data is assigned to subEntityId.
Below I've provided how we're encoding the data and assigning it to subEntityId.
Server Side:
const context = encodeURIComponent(
JSON.stringify({
"subEntityId": {
"type": "PROGRAM_PROFILE",
"program_id": "12345",
uid: uuidv4(),
}
})
);
const body = {
topic: {
source: 'text',
value: notificationTopic,
webUrl: `https://teams.microsoft.com/l/entity/${TEAMS_APP_ID}/index?context=${context}`,
},
activityType: 'commonNotification',
previewText: {
content: notificationSubtitle,
},
templateParameters: [
{
name: 'title',
value: notificationTitle,
},
],
};
const url = `https://graph.microsoft.com/v1.0/users/${userId}/teamwork/sendActivityNotification`;
await axios.post(url, body));
Client Side:
const context = await app.getContext();
console.log(context?.page?.subPageId); // getting undefined
Any kind of help is appreciated!
From the documentation:
{page.subPageId}: The developer-defined unique ID for the subpage this content points defined when generating a deep link for a specific item within the page. (Known as {subEntityId} prior to TeamsJS v.2.0.0).
You are using subEntityId on the backend but accessing subPageId on the client side.
Problem: I want API to serve all the calls that were received by any given twilio number. It works just fine initially when the call logs are in 50s but as the number increases the call logs API is becoming very slow as there are too many call logs to fetch and process on our end.
Expected Result: I want to paginate the call logs to fetch only 20 call logs at a time.
I tried using List all calls api
// Download the helper library from https://www.twilio.com/docs/node/install
// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);
client.calls.list({limit: 3})
.then(calls => calls.forEach(c => console.log(c.sid)));
The expected result contain the following:
"calls": [1.., 2.., 3..],
"end": 1,
"first_page_uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls.json?Status=completed&To=%2B123456789&From=%2B987654321&StartTime=2008-01-02&ParentCallSid=CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&EndTime=2009-01-02&PageSize=2&Page=0",
"next_page_uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls.json?Status=completed&To=%2B123456789&From=%2B987654321&StartTime=2008-01-02&ParentCallSid=CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&EndTime=2009-01-02&PageSize=2&Page=1&PageToken=PACAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0",
"page": 0,
"page_size": 2,
"previous_page_uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls.json?Status=completed&To=%2B123456789&From=%2B987654321&StartTime=2008-01-02&ParentCallSid=CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&EndTime=2009-01-02&PageSize=2&Page=0",
"start": 0,
"uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls.json?Status=completed&To=%2B123456789&From=%2B987654321&StartTime=2008-01-02&ParentCallSid=CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&EndTime=2009-01-02&PageSize=2&Page=0"
But in my case its only returning, even though there are more call logs present
"calls": []
Now since I am not able to get next_page_uri, I am not able to paginate.
How can I get next_page_uri?
If you are using the latest version of the Twilio Node module then you can get all your calls in a couple of ways:
The library automatically handles paging for you. Collections, such as
calls, have list and each methods that page under the hood. With
both list and each, you can specify the number of records you want
to receive (limit) and the maximum size you want each page fetch to
be (pageSize). The library will then handle the task for you.
list eagerly fetches all records and returns them as a list, whereas
each streams records and lazily retrieves pages of records as you
iterate over the collection. You can also page manually using the
page method.
For more information about these methods, view the [auto-generated
library https://www.twilio.com/docs/libraries/reference/twilio-node/).
If you want to use paging anyway, it'd probably recommend the page option:
client.calls.page({ pageSize: 10 }, function pageReceived(page) {
page.instances.forEach(function(call) {
console.log(call);
});
if (page.nextPage) {
page.nextPage().then(pageReceived);
}
})
I am developing a 1:1 chat application. I use a PHP server to create the private channel before starting the application. The channels are created correctly.
The user tokens are genereated, chat client also created correctly. I see that the user is also created in the service.
When joining the private channel, it throws the error.
code:50400 message:"User not member of channel" status:403
Javascript code:
Twilio.Chat.Client.create(token,clientOptions).then(client => {
chatClient = client;
showMessage('Connecting.....');
chatClient.getChannelBySid(channelid)
.then(function(chosenChannel) {
showMessage('Joining Chat.....');
myChannel=chosenChannel;
joinChannel();
})
.catch(function(err) {
console.log(err);
})
});
It shows the message 'Connecting....' and then stops with the error.
PHP Code:
$client = new Client("sid", "token");
$channel = $client->chat->services("serviceid")->channels
->create(array('friendlyName' => $friendlyName, 'uniqueName' => $uniqueName, 'type' => 'private'));
Twilio developer evangelist here.
When you create a private channel there's no way to define at that stage who is allowed to enter the channel. From the documentation:
Private Channels are not visible to Users that have not been invited or added to them. Private Channel Members can only be added by other Members with sufficient permissions, or via the REST API as controlled by your business logic.
So, in order for a user to join a private channel you need to either:
Add them to the channel using the REST API
Invite the user to the channel from a channel admin of the private channel
Let me know if that makes sense at all
I am working on a program where I will text a message to my Twilio number and have it send the message out to a group of people. I want the numbers to read from either a SQL database (so that people can sign up on a website via PHP) or through a Google Sheets spreadsheet. I really don't know where to start and was wondering if I could get some input from the pros.
Thank you!
Anthony
Twilio developer evangelist here.
If what you're looking for is using Google Spreadsheets, we actually have a pretty comprehensive tutorial on how to use Google Spreadsheets with PHP here.
But the gist is the following:
Enable your spreadsheet for programmatic access
Start reading the data from it and loop through your records.
Looping through your records can be as easy as this:
// Get our spreadsheet
$spreadsheet = (new Google\Spreadsheet\SpreadsheetService)
->getSpreadsheetFeed()
->getByTitle('Phone Numbers');
// Get the first worksheet (tab)
$worksheets = $spreadsheet->getWorksheetFeed()->getEntries();
$worksheet = $worksheets[0];
$listFeed = $worksheet->getListFeed();
/** #var ListEntry */
foreach ($listFeed->getEntries() as $entry) {
$phone = $entry->getValues();
}
On the loop above, you could also use the Twilio REST api to start sending SMS messages with Twilio as follows:
$sms = $client->account->messages->create(
// the number we are sending to - Any phone number
$phone,
array(
// Step 6: Change the 'From' number below to be a valid Twilio number
// that you've purchased
'from' => "YOUR_NUMBER",
// the sms body
'body' => "Hey $name, Monkey Party at 6PM. Bring Bananas!"
)
);
So it's just a matter of using the two together. you can read more about sending messages with PHP here.
Hope this helps you out
In Twilio when the ImageMedia URL is given it is accessing the twilio api as follows
https://api.twilio.com/2010-04-01/Accounts/{account sid}/Messages/{message sid}/Media/{media sid}
If you have manually logged into the twilio API that url redirects to the image located at
http://media.twiliocdn.com.s3-website-us-east-1.amazonaws.com/{account sid}/{image id}
How can I get the direct image ID from the twilio API to include in my web app?
I am working with node.js and every time I try to poll the media resources all I receive is the link to the api.twilio.com and not the mdeia.twiliocdn.com
The library doesn't handle this feature that I can find
However, if anyone else comes across the same problem here is the solution
install request.
Then just get NumMedia and MediaUrl parameters...
if(req.body.NumMedia > 0){
var request = require('request')
request.get(req.body.MediaUrl0).auth(config.twilio.sid, config.twilio.auth, false).pipe(fs.createWriteStream("/var/www/app/public/mms/" + sid + '1.jpg' ));
}
Remember that up to 10 images can be sent so you would just need the logic too gather those extra images.