GithubHelp home page GithubHelp logo

onesignal-node's People

Contributors

a-tokyo avatar dependabot[bot] avatar fecaps avatar fxgx avatar j05u3 avatar jwilm avatar larinel avatar linzhiq avatar mehmetcavus avatar rafaelsiqueira avatar thomassnielsen avatar zeyneloz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

onesignal-node's Issues

onclick ,addListenerForNotificationOpened

OneSignal.push(["addListenerForNotificationOpened", function(data) {
console.log("Received NotificationOpened:");
console.log(data);
}]);

how i can improved this event in nodejs ????

How are http errors handled?

Looking at the code, it looks like on error in basic request you call the callback with the http response but you don't reject the promise with it. This means I need to pass a callback in order to get access to this object. I'm wondering if httpResponse will ever be defined in case of error?

Also, based on the code it looks like I need to inspect the status code to determine the request was successful. Is this true? I don't see anywhere in the request module that it throws on non-200.

Thanks for your work on this.

Schedule Notifications may not be scheduled so far in the future

If I try to schedule a notification in late December or in 2020, I get the error "Schedule Notifications may not be scheduled so far in the future". Why?

This is my code:

export function scheduleNotification(
  { userId, heading, body, time, metadata, onError, onSuccess }:
    {
      userId: string,
      heading: string,
      body: string,
      time: Date,
      metadata?: any,
      onError: (err: string) => void,
      onSuccess?: (id: string) => void,
    },
) {
  const notification = new OneSignal.Notification({
    contents: {
      en: body,
    },
  });

  notification.postBody.data = metadata;
  notification.postBody.headings = { en: heading };
  notification.postBody.send_after = time;
  notification.postBody.filters = [{
    field: "tag",
    key: "user_id",
    relation: "=",
    value: userId,
  }];

  return oneSignalClient.sendNotification(notification, (error: any, _: any, data: any) => {
    if (error) {
      return onError(error);
    } else {
      if (data.id) {
        return onSuccess ? onSuccess(data.id) : null;
      } else {
        if (data.errors.length !== 0) {
          return onError(data.errors[0]); // <- Error occurs here! Not in the error section above
        }
        return null;
      }
    }
  });
}

Sending notifications to Android and IOS apps question

We are using this package and it worked very well sending notifications to Android devices. After that, we tried to send notifications to both platforms, Android and IOS using the array method defined in the documentation like this:

// create a Client for a multiple apps
var myClient = new OneSignal.Client({
    userAuthKey: 'XXXXXX',
    apps: ['id1Android', 'idIOS'] // your app ids
});

It this correct? cause when we try to send notifications to both platforms an error ocurrs but when we try to send it individually it works with the following notation:

// create a new Client for a single app
var myClient = new OneSignal.Client({
    userAuthKey: 'XXXXXX',
    // note that "app" must have "appAuthKey" and "appId" keys
    app: { appAuthKey: 'XXXXX', appId: 'XXXXX' }
});

Allow numeric values for tags

Currently, the type definition for tags only allow strings. This is probably because of an earlier error in the API documentation. I inquired about this, since we've always sent (integer) numbers, and it has worked. OneSignal responded that integers are indeed supported, and has since updated the documentation.

All included players are not subscribed

In the example setIncludedSegments uses "All Users", but it must be "All" in order to work. You will get a "All included players are not subscribed" error.

Thanks for the great work!

Connection timeout

Hi , i don't think that this is related to your library but i have an issue sending push notifications from my Nodejs server in Localhost
when iv sent the first test notification it worked and then it gives me

Something went wrong... { Error: connect ETIMEDOUT 104.16.207.165:443
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1161:14)
  errno: 'ETIMEDOUT',
  code: 'ETIMEDOUT',
  syscall: 'connect',
  address: '104.16.207.165',
  port: 443 }

Not on a regular basis

thank you

Error : TypeError: Cannot read property 'push' of undefined at app.post (

when i send notification on single device or player_id send me erro in response
TypeError: Cannot read property 'push' of undefined at app.post
My code is
app.post('/api/onesignal', (req, res) => {
var firstNotification = new OneSignal.Notification({
contents: {
en: "Test notification",
tr: "Test mesajı"
},
include_player_ids: ["c0dd0877-3885-4610-9751-d01c5e6bed3e"]
});

// Add a new target after creating initial notification body
firstNotification.postBody["include_player_ids"].push["c0dd0877-3885-4610-9751-d01c5e6bed3e"]

myClient.sendNotification(firstNotification, function (err, httpResponse, data) {
if (err) {
console.log('Something went wrong...');
} else {
console.log(data);
}
});
});

How can I add subTitle

I read through the code and it looks like subtitle is in todo, how can I add subtitle to the library.

Sending Push Notification to IOS Sends Twice

Whenever I try to send a notification it is sent twice although on the console it is only logged as once.

Here is my code:

 const OneSignal = require('onesignal-node');    
 const client = new OneSignal.Client('****', '****');  // private keys

async function sendNotification(notification) {
  
  try {
    const response = await client.createNotification(notification);
    console.log(response.body.id);
  } catch (e) {
    if (e instanceof OneSignal.HTTPError) {
      // When status code of HTTP response is not 2xx, HTTPError is thrown.
      console.log(e.statusCode);
      console.log(e.body);
    }
  }
  
  // or you can use promise style:
  client.createNotification(notification)
      .then(response => {
          console.log('sent notification')
        console.log(response);
    })
      .catch(e => {
          console.log('problem w notification sending')
          console.log(e)
    });
}

sendNotification({
    contents: {
        'en': 'test 3!',
    },
    include_player_ids: ['****'] // my phone's ID
});

Here is the response from the console:
Screen Shot 2022-01-01 at 12 32 51 PM

And I am getting the notification twice on my test device (IOS 14,2). I have looked on the duplicated notifications one signal page and it has been no help: https://documentation.onesignal.com/docs/duplicated-notifications.

web push

How to use this package and send push to web,
And also when user clicks on notification from desktop/web it redirect to specific page.

Proxy

Hello
How can I set http proxy to requests?

One invalid player id cancels whole operation

Hello, i am trying to send an notification with an array of include_player_id and if a single one of the array is invalid, it cancels my whole notification. I.E: my data gets to be

data: {"id":"","recipients":0,"errors":{"invalid_player_ids":["XXXXXXX-XXXXX-XXX-XXXX-XXXXXX"]}}

and it doesn't sends to the other valid player ids.

Here's my code to the creation of the notification

const notification = new OneSignal.Notification({
    contents: {
      en: message,
    },
    data: data,
    'include_player_ids': playersId && playersId.length > 0 ? playersId.filter((v, i, a) => a.indexOf(v) === i) : playersId,
  });

send_after

Hi,

I am trying to send post notification, But send_after is not working for me.
I am trying this way-
firstNotification.postBody["send_after"] =
"Mon Jan 11 2019 15:39:00 GMT-0700 (PDT)";
myClient.sendNotification(firstNotification, function(
err,
httpResponse,
data
) {
if (err) {
console.log("Something went wrong...");
} else {
console.log('success : '+data);
}
});
Can someOne help on this ??

All included players are not subscribed 200

Hi,

thank you for creating this plug-in! Please pardon me if the question is stupid because I am fairly new to coding apps. I've been getting the following error and I was wondering anyone would be so kind to help me out:

I20180629-12:38:32.129(-4)? { id: '',
I20180629-12:38:32.130(-4)? recipients: 0,
I20180629-12:38:32.130(-4)? errors: [ 'All included players are not subscribed' ] } 200

I also checked my users on the onesignal control panel, and I have zero users. Should I subscribe the user differently other than using the code below? In the previous similar issue that's already resolved, I saw that firstNotification.setIncludedSegments(['All']) should be in the code, and I have already done so.

The code I used are from modified from the onesignal-node github wiki (title: Sending a notification using segments) after putting in my keys and appid:

var OneSignal = require('onesignal-node');

// first we need to create a client
var myClient = new OneSignal.Client({
    userAuthKey: 'XXXXXX',
    app: { appAuthKey: 'XXXXX', appId: 'XXXXX' }
});

// we need to create a notification to send
var firstNotification = new OneSignal.Notification({
    contents: {
        en: "Test notification",
        tr: "Test mesajı"
    }
});

// set target users
firstNotification.setIncludedSegments(['All']);
firstNotification.setExcludedSegments(['Inactive Users']);

// set notification parameters
firstNotification.setParameter('data', {"abc": "123", "foo": "bar"});
firstNotification.setParameter('send_after', 'Thu Sep 24 2015 14:00:00 GMT-0700 (PDT)');

// send this notification to All Users except Inactive ones
myClient.sendNotification(firstNotification, function (err, httpResponse,data) {
   if (err) {
       console.log('Something went wrong...');
   } else {
       console.log(data, httpResponse.statusCode);
   }
});

The coding language I'm using is Meteor JS 1.6.1. Let me know if you have any questions about my question!

Thank you again!

ETIMEDOUT issue

I am getting below error
{"errno":"ETIMEDOUT","code":"ETIMEDOUT","syscall":"connect","address":"104.18.225.52","port":443}

Is something wrong

the title of the received notification is always "my notification title"

with the nodejs module or from the platform website, the notification received is always "my notification title"

client.createNotification({ headings: { "en": "bbbbbbbbbbbbb", "fr": "eeeeeeeeeee" }, contents: { "en": "hhhhhhhhhhhh", "fr": "ttttttttttttttt" }, title: { "fr": 'textttttttt', "en": 'textbbbbbbbbbb' }, subtitle: { "fr": 'text13', "en": 'tex2222t' }, url: 'http://google.com', userIds: ["5e5f78b7cb1bff005fc238d8"] }) .then(response => { console.log(response); }) .catch(e => { console.log(e); });

Changelog/upgrade from 2.x.x to 3.x.x

Are there any instructions/documentation for upgrading from v2.x.x to v3.x.x of the library? Per the README "This documentation belongs to v3.x.x which has no backward compatibility" but it's not clear what actually changed/breaks between v2 and v3?

silent push notification

I am wondering if we can send the silent push notifications through your API.
Help will be highly appreciated.

Typescript error with example code

Hello,

I installed the latest version, I copy / paste the example code and there is a Typescript error.

The example code :

// ...
// using async/await
try {
  const response = await client.createNotification(notification);
  console.log(response.body.id); // <-- HERE
} catch (e) {
  if (e instanceof OneSignal.HTTPError) {
    // When status code of HTTP response is not 2xx, HTTPError is thrown.
    console.log(e.statusCode);
    console.log(e.body);
  }

The Typescript error:

Property 'id' does not exist on type '{}'

Why there is this error? Because of this in index.d.ts:

export interface ClientResponse {
    statusCode: number;
    body: {};
    headers: {
        [key: string]: any;
    };
}

Hitting a lot of HTTP 524 errors and other upstream errors.

We're receiving quite a lot of errors suggesting OneSignal is down, but I'm not sure if it's actually the case or if we're rather being rate limited. Here's an example of the different errors we're receiving:

Error: upstream connect error or disconnect/reset before headers. reset reason: overflow at Request._callback (/app/backend/node_modules/onesignal-node/src/utils.ts:56:23) at Request.self.callback (/app/backend/node_modules/request/request.js:185:22) at Request.emit (node:events:390:28) at Request.emit (node:domain:475:12) at Request.<anonymous> (/app/backend/node_modules/request/request.js:1154:10) at Request.emit (node:events:390:28) at Request.emit (node:domain:475:12) at IncomingMessage.<anonymous> (/app/backend/node_modules/request/request.js:1076:12) at Object.onceWrapper (node:events:509:28) at IncomingMessage.emit (node:events:402:35) at IncomingMessage.emit (node:domain:475:12) at endReadableNT (node:internal/streams/readable:1343:12) at processTicksAndRejections (node:internal/process/task_queues:83:21) 
Error: upstream connect error or disconnect/reset before headers. reset reason: connection failure at Request._callback (/app/backend/node_modules/onesignal-node/src/utils.ts:56:23) at Request.self.callback (/app/backend/node_modules/request/request.js:185:22) at Request.emit (node:events:390:28) at Request.emit (node:domain:475:12) at Request.<anonymous> (/app/backend/node_modules/request/request.js:1154:10) at Request.emit (node:events:390:28) at Request.emit (node:domain:475:12) at IncomingMessage.<anonymous> (/app/backend/node_modules/request/request.js:1076:12) at Object.onceWrapper (node:events:509:28) at IncomingMessage.emit (node:events:402:35) at IncomingMessage.emit (node:domain:475:12) at endReadableNT (node:internal/streams/readable:1343:12) at processTicksAndRejections (node:internal/process/task_queues:83:21) 
Error: <html> <head><title>524 Origin Time-out</title></head> <body bgcolor="white"> <center><h1>524 Origin Time-out</h1></center> <hr><center>cloudflare-nginx</center> </body> </html> at Request._callback (/app/backend/node_modules/onesignal-node/src/utils.ts:56:23) at Request.self.callback (/app/backend/node_modules/request/request.js:185:22) at Request.emit (node:events:390:28) at Request.emit (node:domain:475:12) at Request.<anonymous> (/app/backend/node_modules/request/request.js:1154:10) at Request.emit (node:events:390:28) at Request.emit (node:domain:475:12) at IncomingMessage.<anonymous> (/app/backend/node_modules/request/request.js:1076:12) at Object.onceWrapper (node:events:509:28) at IncomingMessage.emit (node:events:402:35) at IncomingMessage.emit (node:domain:475:12) at endReadableNT (node:internal/streams/readable:1343:12) at processTicksAndRejections (node:internal/process/task_queues:83:21) 
Error: at Request._callback (/app/backend/node_modules/onesignal-node/src/utils.ts:56:23) at Request.self.callback (/app/backend/node_modules/request/request.js:185:22) at Request.emit (node:events:390:28) at Request.emit (node:domain:475:12) at Request.<anonymous> (/app/backend/node_modules/request/request.js:1154:10) at Request.emit (node:events:390:28) at Request.emit (node:domain:475:12) at IncomingMessage.<anonymous> (/app/backend/node_modules/request/request.js:1076:12) at Object.onceWrapper (node:events:509:28) at IncomingMessage.emit (node:events:402:35) at IncomingMessage.emit (node:domain:475:12) at endReadableNT (node:internal/streams/readable:1343:12) at processTicksAndRejections (node:internal/process/task_queues:83:21) 

Have you ever had these kinds of errors before? Trying to figure out how I could prevent them from happening.

import syntax not working

Hi,

Thanks for the great library!

I just upgraded from 2.x to 3.0.0 and unfortunately it seems that the import syntax is not working anymore.

I am working in Typescript, using ts-node to run my script but I suspect this is a global issue.

Please let me know if you need any further information or help testing/debugging on a branch.

Btw it is not a blocker for me since I'll just use the require syntax until this issue is solved.

chrome_web_badge not working

Hi you,
I use chrome_web_badge in option onesignal nodejs with chrome_web_badge then received response : ""chrome_web_badge" is not present in documentation" how can i fix it ?, because i read in document onesignal have this function. And i want change title near badge icon , how i can do it ? .
I look forward to receiving an early reply from you . Thank you so much

Incorrect Error message type

According to HTTPError, the message/body should be a string

export class HTTPError extends Error {
public statusCode: number;
public body: string;
constructor(status: number, body: string) {
super(body);
this.body = body;
this.statusCode = status;
}
}

However, the body comes from request's reponse which is not definitely a string.

// Check if status code is 2xx.
if (httpResponse.statusCode - 299 > 0) {
return reject(new HTTPError(httpResponse.statusCode, httpResponse.body));
}

It can be a string or a buffer or a stream or an object.
image

Actually in your case, it is almost always an object (at least for basicAuthRequest) because it sends json: true in the config

const options: request.Options = {
uri,
method,
headers: {
'Content-Type': 'application/json; charset=utf-8',
Authorization: `Basic ${authKey}`,
},
json: true,
};

This has lead to many Error: [object Object] in our logs making it very hard to understand why the request failed.

You should update the typings to reflect the type of body in HTTPError and ensure the error message is always a string

viewDevice doesn't let me pass an email auth hash

The docs for viewDevice say I need to pass an email_auth_hash if I'm getting an device that's for email, but the viewDevice() method provided by this module doesn't let me pass parameters. Indeed, if I try to call the method without an email auth hash I receive {"errors":["invalid identifier_auth_hash"]}

Cancel Notifications don't work

Hi,

I'm trying cancel a scheduled notification using method "cancelNotification" of class "OneSignal.Client", but I'm receiving the error: 400 Bad Request.

I already updated my dependency for latest version 2.1.0, but don't resolved.

Someone can help me?

Message Notifications must have English language content"

Currently we cannot send notification using different languages

This is the code that throw the error

  const vietnameseNotification = {
    headings: {
      vi: "Message written in vietnamese"
    },
    contents: {
      vi: text
    },
    large_icon: "image.jpg",
    include_player_ids: vietnameseUsers.map(user => user.onesignal_id)
  };

  await client.createNotification(vietnameseNotification);

error:

{
    "message": {
        "type": "one-signal",
        "body": {
            "errors": [
                "Message Notifications must have English language content"
            ]
        },
        "statusCode": 400
    },
    "level": "error"
}

Packages versions:

node: 10
onesignal-node: 3.0.0

As a workaround if I substitute vi with en should work?

Thanks

One invalid player ID cancels whole operation; error doesn't specify which player IDs are invalid

Hello - I'm attempting to send a push notification to a large amount of users (30+). I'm getting an error Incorrect player_id format in include_player_ids (not a valid UUID). The error returns a list of all of the player IDs I passed in, as opposed to those which are invalid - so there's no way to handle this error or remove the invalid IDs. All of these player IDs appear valid or were valid at some time.

The error is also not in a useful format - it is difficult to ultimately parse the array from within the strings and format it is given.

HTTPError: {"errors":["Incorrect player_id format in include_player_ids (not a valid UUID): [\"b767d517-40cd-4ff3-98bb-5d4e1f7109c5\", \"d269832b-cac6-4d2d-bdfb-e01279f5079a\", \"b8d8ae84-5495-433a-8ac7-abb030e90ba9\", ... \"c29a973a-cc3b-478b-8e82-ad71c19ef6d3\"]"]}

Sending a push notification to a single player ID included in the list - take c29a973a-cc3b-478b-8e82-ad71c19ef6d3 at the end - works fine, showing that everything has been set up correctly. This valid ID is still included in the error list when trying to send to the larger number of users, though.

Tracing environment support

Our company is using the onesignal-node library to send notification messages.
The main path is implemented as an event-driven architecture. Therefore, a tracing environment is essential for us.
Is there a way to trace the APIs of this librarDy using AWS X-Ray or OpenTelemetry SDK? We would like to be able to trace information about calls and responses.

IOS 13 notifications not working

{
description: 'OTRN error',
code: 1011,
message:  'The operation couldn't be completed. (OTSessionErrorDomain error 1011.)'
}

iOS Critical Notifications

If I use the onesignal "Send message" GUI form on the website I can get a critical alert on my test phone just fine. This tells me my app is fine. However, through the API with this plugin I can't get critical notifications to work. See code below. The notification with the code below will come through if I turn DND off. However, with DND I get nothing even though I should.

const notification = new OneSignal.Notification();
notification.app_id = ONESIGNAL_APP_ID;
notification.include_player_ids = [pushId];
notification.include_player_ids = [pushId];
notification.priority = 10;
notification.ios_interruption_level = "critical";
notification.mutable_content = true;
notification.data = {
type: "test"
}
notification.android_channel_id = getAudioTag(sound).android;

notification.ios_sound = getAudioTag(sound).ios;
notification.contents = {
    en: "Test Push Notification @ " + pageGetTime((Date.now() / 1000), users.getUserData(userId).timeFormat)
};
notification.headings = {
    "en": "Test"
}

Error on unhandle Promise rejection

Promise are rejected even if callback are pass to onesignal notification.
It result to reject a promise which is not handle.

if (err) {
callback && callback(err, httpResponse, data);
return reject(err);
}

[DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

The problem is developer have to add a callback and catch the error.

// send this notification to All Users except Inactive ones      
myClient.sendNotification(firstNotification, function (err, httpResponse,data) {      
   if (err) {
       console.log('Something went wrong…');
   } else {
       console.log(data, httpResponse.statusCode);
   }
}).catch(() => {
       console.log('Something went wrong…');
});

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.