Use Javascript to list all Twilio Messages - javascript

I am using the Twilio Node.js documentation here:
https://www.twilio.com/docs/api/rest/message#list-get-filters
I am simply trying to list all of the messages in the message log for an account. Following the example here:
var accountSid = 'your_sid';
var authToken = "your_auth_token";
var client = require('twilio')(accountSid, authToken);
client.messages.list(function(err, data) {
data.messages.forEach(function(message) {
console.log(message.body);
});
});
Instead I get an error back:
/home/ubuntu/workspace/twilio/app.js:9
data.messages.forEach(function(message) {
^
TypeError: Cannot read property 'forEach' of undefined
at /home/ubuntu/workspace/twilio/app.js:9:18
at /home/ubuntu/workspace/twilio/node_modules/q/q.js:1547:13
at Promise_done_fulfilled (/home/ubuntu/workspace/twilio/node_modules/q/q.js:835:31)
at Fulfilled_dispatch [as dispatch] (/home/ubuntu/workspace/twilio/node_modules/q/q.js:1229:9)
at Pending_become_eachMessage_task (/home/ubuntu/workspace/twilio/node_modules/q/q.js:1369:30)
at RawTask.call (/home/ubuntu/workspace/twilio/node_modules/asap/asap.js:40:19)
at flush (/home/ubuntu/workspace/twilio/node_modules/asap/raw.js:50:29)
at _combinedTickCallback (internal/process/next_tick.js:73:7)
at process._tickCallback (internal/process/next_tick.js:104:9)
Note sure why it is not finding anything. I would simply like to print all messages in the message logs or from a specific phone number.

Twilio's documentation is no longer accurate for NodeJS, the correct way to pull up list of all messages is through the following:
client.messages.list(function(err, data) {
//notice we have removed 'messages'
data.forEach(function(message){
console.log(message.body);
});
});

Twilio developer evangelist here.
We recently released version 3 of our Node library. I believe you are still looking at the documentation for version 2. You can change this in the Twilio documentation by checking the top right of the code samples and selecting 3.x instead of 2.x.
The up to date documentation for version 3 suggests you use code like this:
client.messages.each((message) => console.log(message.body));
Let me know if that helps at all.

Related

Twilio javascript SDK .sendDigits example needed -

I have tried a dozen ways to make a button on a webpage that's got a connected Twilio client voice call perform .sendDigits. This is the most recent try.
const dtmf_1 = document.getElementById('DTMF1');
dtmf_1.onclick = function(){call.sendDigits('1')};
This returns
Uncaught ReferenceError: call is not defined at dtmf_1.onclick (quickstart.js:46:79)
Frankly, I have no idea if fixing the reference is even going to work.
Does anyone have an example of working code that will play a DTMF tone on a live call with the Twilio JavaScript SDK?
Thanks to a timely comment by Tristan Blackwell (see above), I was able to fix this issue which was indeed a scoping problem.
The fix was to put the line
dtmf_1.onclick = function(){call.sendDigits('1')};
right under the line where the call is connected.
const call = await device.connect({ params });
Like so
const call = await device.connect({ params });
dtmf_1.onclick = function(){call.sendDigits('1')};

JavaScript runtime error: [Messenger] Required property 'target' was not provided occurred

I am using the Developers API with an App I created in LinkedIn.
When I call this method to sign in.....
IN.UI.Authorize().params({ "scope": ["r_liteprofile", "r_emailaddress"] }).place()
a Window begins to open and I get this error message:
Unhandled exception at line 7, column 56783 in
http://platform.linkedin.com/in.js 0x800a139e - JavaScript runtime
error: [Messenger] Required property 'target' was not provided
occurred
I have completed LinkedIn's App Setup, but can't figure what could be causing this. My JavaScript code is below:
[script type="text/javascript" src="//platform.linkedin.com/in.js"]
api_key: 'xxxxx......xxxxx'
authorize: true
[/script]
function LinkedInSignIn() {
IN.UI.Authorize().params({ "scope": ["r_liteprofile", "r_emailaddress"] }).place();
IN.Event.on(IN, 'auth', getProfileData);
}
function getProfileData() { // Use the API call wrapper to request the member's basic profile data
IN.API.Profile("me").fields("id,firstName,lastName,email-address,picture-urls::(original),public-profile-url,location:(name)").result(function (me) {
var profile = me.values[0];
var id = profile.id;
alert(profile.firstName);
});
}
As it turned out, the reason this is not working is becuase LinkedIn discontinued it at the end of 2018. Contacting LinkIn's support wasn't much help either. They only said they do no support thier code library and referred my back here to StackOverflow.
For anyone having the same problem, the solutions is to use Oauth2, which is documented at:
https://learn.microsoft.com/en-us/linkedin/shared/authentication/authorization-code-flow?context=linkedin/context
Happy Coding!
Graham

Error: Network error: Error writing result to store for query (Apollo Client)

I am using Apollo Client to make an application to query my server using Graphql. I have a python server on which I execute my graphql queries which fetches data from the database and then returns it back to the client.
I have created a custom NetworkInterface for the client that helps me to make make customized server request (by default ApolloClient makes a POST call to the URL we specify). The network interface only has to have a query() method wherein we return the promise for the result of form Promise<ExecutionResult>.
I am able to make the server call and fetch the requested data but still getting the following error.
Error: Network error: Error writing result to store for query
{
query something{
row{
data
}
}
}
Cannot read property 'row' of undefined
at new ApolloError (ApolloError.js:32)
at ObservableQuery.currentResult (ObservableQuery.js:76)
at GraphQL.dataForChild (react-apollo.browser.umd.js:410)
at GraphQL.render (react-apollo.browser.umd.js:448)
at ReactCompositeComponent.js:796
at measureLifeCyclePerf (ReactCompositeComponent.js:75)
at ReactCompositeComponentWrapper._renderValidatedComponentWithoutOwnerOrContext (ReactCompositeComponent.js:795)
at ReactCompositeComponentWrapper._renderValidatedComponent (ReactCompositeComponent.js:822)
at ReactCompositeComponentWrapper._updateRenderedComponent (ReactCompositeComponent.js:746)
at ReactCompositeComponentWrapper._performComponentUpdate (ReactCompositeComponent.js:724)
at ReactCompositeComponentWrapper.updateComponent (ReactCompositeComponent.js:645)
at ReactCompositeComponentWrapper.performUpdateIfNecessary (ReactCompositeComponent.js:561)
at Object.performUpdateIfNecessary (ReactReconciler.js:157)
at runBatchedUpdates (ReactUpdates.js:150)
at ReactReconcileTransaction.perform (Transaction.js:140)
at ReactUpdatesFlushTransaction.perform (Transaction.js:140)
at ReactUpdatesFlushTransaction.perform (ReactUpdates.js:89)
at Object.flushBatchedUpdates (ReactUpdates.js:172)
at ReactDefaultBatchingStrategyTransaction.closeAll (Transaction.js:206)
at ReactDefaultBatchingStrategyTransaction.perform (Transaction.js:153)
at Object.batchedUpdates (ReactDefaultBatchingStrategy.js:62)
at Object.enqueueUpdate (ReactUpdates.js:200)
I want to know the possible cause of the error and solution if possible.
I had a similar error.
I worked it out by adding id to query.
for example, my current query was
query {
service:me {
productServices {
id
title
}
}
}
my new query was
query {
service:me {
id // <-------
productServices {
id
title
}
}
}
we need to include id,
otherwise it will cause the mentioned error.
{
query something {
id
row {
id
data
}
}
}
I've finally found out what is causing this issue after battling with it in various parts of our app for months. What helped to shed some light on it was switching from apollo-cache-inmemory to apollo-cache-hermes.
I experimented with Hermes hoping to mitigate this ussue, but unfortunately it fails to update the cache the same as apollo-cache-inmemory. What is curious though is that hermes shows a very nice user friendly message, unlike apollo-cache-inmemory. This lead me to a revelation that cache really hits this problem when it's trying to store an object type that is already in the cache with an ID, but the new object type is lacking it. So apollo-cache-inmemory should work fine if you are meticulously consistent when querying your fields. If you omit id field everywhere for a certain object type it will happily work. If you use id field everywhere it will work correctly. Once you mix queries with and without id that's when cache blows up with this horrible error message.
This is not a bug-it's working as intended, it's even documented here: https://www.apollographql.com/docs/react/caching/cache-configuration/#default-identifiers
2020 update: Apollo has since removed this "feature" from the cache, so this error should not be thrown anymore in apollo-client 3 and newer.
I had a similar looking issue.
Perhaps your app was attempting to write (the network response data) to the store with the wrong store address?
Solution for my problem
I was updating the store after adding a player to a team:
// Apollo option object for `mutation AddPlayer`
update: (store, response) => {
const addr = { query: gql(QUERY_TEAM), variables: { _id } };
const data = store.readQuery(addr);
stored.teams.players.push(response.data.player));
store.writeQuery({...addr, data});
}
I started to get a similar error above (I'm on Apollo 2.0.2)
After digging into the store, I realised my QUERY_TEAM request made with one variable meta defaulting to null. The store "address" seems to use the *stringified addr to identify the record. So I changed my above code to mimic include the null:
// Apollo option object for `mutation AddPlayer`
update: (store, response) => {
const addr = { query: gql(QUERY_TEAM), variables: { _id, meta: null } };
const data = store.readQuery(addr);
data.teams.players.push(response.data.player));
store.writeQuery({...addr, data});
}
And this fixed my issue.
* Defaulting to undefined instead of null will probably avoid this nasty bug (unverified)
Further info
My issue may be only tangentially related, so if that doesn't help I have two peices of advice:
First, add these 3 lines to node_modules/apollo-cache-inmemory/lib/writeToStore.js to alert you when the "record" is empty.
And then investigate _a to understand what is going wrong.
exports.writeResultToStore = writeResultToStore;
function writeSelectionSetToStore(_a) {
var result = _a.result, dataId = _a.dataId, selectionSet = _a.selectionSet, context = _a.context;
var variables = context.variables, store = context.store, fragmentMap = context.fragmentMap;
+if (typeof result === 'undefined') {
+ debugger;
+}
Second, ensure all queries, mutations and manual store updates are saving with the variables you expect
For me adding "__typename" into query helped.
Solution for this is 1. it happening when missing id, second one is it is happening when you have same query and hitting them alternately.
Example if you have query like dog and cat.
query dog(){id, name}
query cat(){id, name }
here both query are same just their header are different, during that time, this type of issue is coming. currently i have fetching same query with different status and getting this error and am lost in search of solution.

Discord make channel using bot

I'm making a discord bot, and I'm trying to make use of the createChannel function shown here in the documentation. For some reason, I am getting the following error:
TypeError: bot.createChannel is not a function.
My code is within a function which I pass a message to, and I have been able to create roles and add users to roles within the same function. It's just the createChannel function that's not working. Below is the relevant portions of the code.
const bot = new Discord.Client();
function makeChannel(message){
var server = message.guild;
var name = message.author.username;
server.createRole(data);
var newrole = server.roles.find("name", name);
message.author.addrole(newrole);
/* The above 3 lines all work perfectly */
bot.createChannel(server,name);
}
I have also tried bot.addChannel, and bot.ChannelCreate, since ChannelCreate.js is the name of the file which contains the code for this command. Also, I have attempted specifying channel type and assigning a callback function as well, but the main issue is the TypeError saying that this isn't a function at all. Any idea what I'm doing wrong?
Additionally, I plan to use ServerChannel.update() at some point in the future, so any advice on getting that to work once the previous problem is resolved would be greatly appreciated.
Alright, after a few days of trying things and going through the docs, I have discovered the solution. I am using a more recent version of Discord than the docs I was reading were written for. In the newer version, channels are created with a method in the server, not a client method. so, the code should be:
const bot = new Discord.Client();
function makeChannel(message){
var server = message.guild;
var name = message.author.username;
server.createChannel(name, "text");
}
The "text" value is the type of channel you are making. Can be text or voice.
I'll post a link to the most recent documentation for anyone else who encounters this problem here.
The answer should update documentation link to the GuildChannelManager which is now responsible for creating new channel.
(Example from docs)
// Create a new text channel
guild.channels.create('new-general', { reason: 'Needed a cool new channel' })
.then(console.log)
.catch(console.error);
https://discord.js.org/#/docs/main/stable/class/GuildChannelManager
#Jim Knee's I think your answer is v11, I'm new in discord.js, using Visual Studio Code's auto-code thingy. You can do all the same things except your thing must be this. If you are poor people, getting errors on doing #Jim Knee's answer, this is the place for "YOU!"
Get rid of server.createChannel(name, "text/voice");
And get it to THIS server.channels.create(name, "text/voice");
Hope I can help at least ;)
I'm just a new guy here too
I think you have not logged in with your bot.
From the docs:
const Discord = require('discord.js');
var client = new Discord.Client();
client.login('mybot#example.com', 'password', output); // you seem to be missing this
function output(error, token) {
if (error) {
console.log(`There was an error logging in: ${error}`);
return;
} else
console.log(`Logged in. Token: ${token}`);
}
Alternatively, you can also login with a token instead. See the docs for the example.

GitHub API (Octokat.js): Cannot get Projects

I'm trying to access projects of a repository through GitHub API using Octokat.js.
The API guide says I need to use preview header, which I am using:
https://developer.github.com/v3/projects/
I'm getting error for property fetchAll of undefined (= projects).
I'm not sure what I'm doing wrong here - does anybody have an experience with this?
var Octokat = require('octokat')
var octo = new Octokat({
// put your own token here
token: 'XXX',
acceptHeader: 'application/vnd.github.inertia-preview+json'
})
octo.repos('YYY', 'ZZZ').projects.fetchAll((e, val) => {
this.projectsList = val
})
OK, turns out the API preview isn't implemented in the library yet.
https://github.com/philschatz/octokat.js/issues/144

Categories