def send_notification(to, title, body, data): """Send notifications using the appropiate provider.""" user_token = UserToken.query.filter_by(user_id=to).first() if user_token is None: raise UserTokenDoesNotExist(f"UserToken {to} does not exist") try: logger.info("Attempting to send notification") response = PushClient().publish( PushMessage(to=user_token.push_token, title=title, body=body, data=data)) except ( # pylint: disable= W0706 PushServerError, RequestsConnectionError, HTTPError, ) as e: logger.error(e) raise try: response.validate_response() except DeviceNotRegisteredError as e: # TODO: set invalid logger.error(e) raise except PushResponseError as e: # pylint: disable=W0706 logger.error(e) raise
def send_push_notification(expo_token: str, title: str, body: str, data: Dict[Any, Any] = None) -> bool: """Send notification to specified expo token :expo_token: token to send notificaton to :title: notification title :body: notification body :data: extra notification data (total payload must be under 4096 bytes) :raises: ConnectionError, DeviceNotRegisterdError, HTTPError, InvalidExpoToken, PushServerError, PushResponseError """ assert expo_token, "Expo token cannot be None" if PushClient().is_exponent_push_token(expo_token): try: message = PushMessage(to=expo_token, title=title, body=body, data=data) response = PushClient().publish(message) response.validate_response() return True except PushServerError as e: logging.error(f"Push Server Error\n{e}") logging.error(f"Response\n{e.response}") logging.error(f"Args\n{e.args}") except (ConnectionError, HTTPError) as e: logging.error(f"Connection/HTTPError\n{e}") except DeviceNotRegisteredError as e: logging.warning(f'Inactive token\n{e}') except PushResponseError as e: logging.error(f'Notification error\n{e}') return False else: raise InvalidExpoToken()
def send_push_message(db, username, message, title, data=None): data['created'] = str(data['created']) data['updated'] = str(data['updated']) data['_id'] = str(data['_id']) users = db['user'] user = users.find_one({"username": username}) if 'device_token' in user: response = PushClient().publish( PushMessage( to=user['device_token'], body=message, data=data, sound='default', title=title, ttl=500, priority='high', )) try: # We got a response back, but we don't know whether it's an error yet # This call raises errors so we can handle them with normal exception # flows. response.validate_response() except DeviceNotRegisteredError: # Mark the push token as inactive print("device is not registered") except PushResponseError as exc: print("there is some push notification error") else: print("Cannot send the push notification to {}".format(username)) return "Hello"
def send_push_message(token, message, extra=None): try: response = PushClient().publish( PushMessage(to=token, body=message, data=extra)) except PushServerError as exc: # Encountered some likely formatting/validation error. print("push server error") raise except (ConnectionError, HTTPError) as exc: # Encountered some Connection or HTTP error - retry a few times in # case it is transient. print("connection error") raise try: # We got a response back, but we don't know whether it's an error yet. # This call raises errors so we can handle them with normal exception # flows. response.validate_response() except DeviceNotRegisteredError: # Mark the push token as inactive # from notifications.models import PushToken # PushToken.objects.filter(token=token).update(active=False) print("device not registered") raise except PushResponseError as exc: # Encountered some other per-notification error. print("push response error") raise
def send_push_notification(token, message, extra=None): try: response = PushClient().publish( PushMessage(to=token, body=message, data=extra)) except (ConnectionError, HTTPError, PushServerError) as exc: # Encountered some likely formatting/validation error or an http connection error logger.error('could not send notification to client', exc_info={ 'token': token, 'message': message, 'extra': extra, 'errors': exc.errors, 'response_data': exc.response_data, }) raise try: # We got a response back, but we don't know whether it's an error yet. # This call raises errors so we can handle them with normal exception # flows. response.validate_response() except PushResponseError as exc: # Encountered some other per-notification error. logger.error('Encountered some other per-notification error', exc_info={ 'token': token, 'message': message, 'extra': extra, 'push_response': exc.push_response._asdict(), }) raise
def _make_push(cls, user_id, token, title, subtitle, extra): try: response = PushClient().publish( PushMessage(to=token, title=title, body=subtitle, data=extra)) except PushServerError as exc: # Encountered some likely formatting/validation error. cls.logger().error(f"Failed to push notification. Token: {token[:10]}.., Msg: {subtitle}, Extra: {extra}, Error: {exc.errors}, Response Data: {exc.response_data}") except (ConnectionError, HTTPError) as exc: # Encountered some Connection or HTTP error - retry a few times in # case it is transient. cls.logger().error(f"Failed to push notification. Token: {token[:10]}.., Msg: {subtitle}, Extra: {extra}, Error: {exc}") try: # We got a response back, but we don't know whether it's an error yet. # This call raises errors so we can handle them with normal exception # flows. response.validate_response() except DeviceNotRegisteredError: # Mark the push token as inactive UsersDAO.delete_tkn(user_id) except PushResponseError as exc: # Encountered some other per-notification error. cls.logger().error(f"Failed to push notification. Token: {token[:10]}.., Msg: {subtitle}, Extra: {extra}, Error: {exc.errors}, Response Data: {exc.push_response._asdict}")
def send_push_message(self, token, message, extra=None, priority='high'): try: response = PushClient().publish(PushMessage(to=token, body=message, data=extra, priority=priority)) except Exception as exc: # Encountered some likely formatting/validation error. if getattr(settings, 'DJANGO_SENTRY_URL', None): sentry_logger.exception('PushServerError: %s' % exc, exc_info=exc, extra={ 'token': token, 'push_message': message, 'extra': extra, 'errors': getattr(exc, 'errors', None), 'response_data': getattr(exc, 'response_data', None), }) raise try: # We got a response back, but we don't know whether it's an error yet. # This call raises errors so we can handle them with normal exception flows. response.validate_response() except Exception as exc: # Encountered some other per-notification error. push_response = getattr(exc, 'push_response', None) if getattr(settings, 'DJANGO_SENTRY_URL', None): sentry_logger.exception('PushResponseError or DeviceNotRegisteredError: %s' % exc, exc_info=exc, extra={ 'token': token, 'push_message': message, 'extra': extra, 'push_response': push_response._asdict() if push_response else None, }) raise
def send_push_message(message, title, extra=None): try: expotoken = [ Object.expotoken for Object in ExpoPushToken.objects.all() ] PushMessage_packet = [] for token_packet in expotoken: PushMessage_packet.append( PushMessage(to=token_packet, title=title, display_in_foreground=True, body=message, data=extra)) response_wow = PushClient().publish_multiple(PushMessage_packet) # for response_element in response_wow: # response_element.validate_response() except PushServerError as exc: print("PushServerError") except (ConnectionError, HTTPError) as exc: print("ConnectionError") try: # We got a response back, but we don't know whether it's an error yet. # This call raises errors so we can handle them with normal exception # flows. for response_element in response_wow: response_element.validate_response() except DeviceNotRegisteredError as exc: print("DeviceNotRegisterdError") except PushTicketError as exc: print("PushTicketError")
def perform_create(self, serializer): opponentUsername = self.request.data.get('username', None) opponentId = self.request.data.get('opponent', None) if opponentUsername: opponentId = Player.objects.get(username=opponentUsername) if opponentId: opponent = Player.objects.get(pk=opponentId) else: opponent = self.get_random_player() ids = (self.request.user.id, opponent.id) creator = Player.objects.get(pk=self.request.user.id) players = Player.objects.filter(pk__in=ids) serializer.save(players=players) send_push_message(PushMessage( to=opponent.push_notification_token, title='Покана за игра', body='Поканиха Ви за игра', priority='high', channel_id='game_invite', data={ 'invited_by': SimplePlayerSerializer().to_representation(creator), 'channel': serializer.data['channel'] } ))
def send_push_message(message, token, extra=None): try: response = PushClient().publish( PushMessage(to=token, body=message, data=extra)) return response except Exception as e: print(e)
def updateApp(btid): print(tokens['token']) message = btid extra = None response = PushClient().publish( PushMessage(to=tokens['token'], body=message, data=extra)) return 'notif sent'
def push(token, title, msg): if log_instead_of_pushing: print('would send a notification to {} with title "{}" and body "{}"'. format(token, title, msg)) return try: response = PushClient().publish( PushMessage(to=token, title=title, body=msg)) except PushServerError as e: print('got "{}" while sending "{}" to {}'.format(e.errors, msg, token)) except (ConnectionError, HTTPError) as e: print('got a connection error while sending "{}" to {}'.format( msg, token)) except ValueError as e: print('Invalid push token, notifications will not work. Whatevz.') return try: response.validate_response() print('sent {} to {}'.format(msg, token)) except DeviceNotRegisteredError: print('{} is inactive'.format(token)) except PushResponseError as e: print('error while sending "{}" to {}: {}'.format( msg, token, e.push_response._asdict()))
def build_publish_messages(self): for token in self.tokens: new_publish = PushMessage(to=token, body=self.message.get('body'), title=self.message.get('title'), display_in_foreground=self.message.get( 'display_in_foreground')) self.publishmessagelist.append(new_publish)
def send_push_message(token, message, extra=None): try: response = PushClient().publish( PushMessage(to=token, body=message)) return response except PushServerError as exc: raise exc
def perform_create(self, serializer): requirement = serializer.save() student = requirement.student body = f'You have a new requirement in {requirement.subject}' if student.push_notification_token: push_message = PushMessage(to=student.push_notification_token, body=body, sound='default', channel_id='push-notifications') PushClient().publish(push_message)
def send_push_message(self, token, title, message, extra=None): #print("Here push tocke",token) try: response = PushClient().publish( PushMessage(to=token, title=title, body=message, sound="default", badge=0, channel_id="order-notification", data=extra)) except PushServerError as exc: # Encountered some likely formatting/validation error. rollbar.report_exc_info( extra_data={ 'token': token, 'message': message, 'extra': extra, 'errors': exc.errors, 'response_data': exc.response_data, }) pass except (ConnectionError, HTTPError) as exc: # Encountered some Connection or HTTP error - retry a few times in # case it is transient. rollbar.report_exc_info(extra_data={ 'token': token, 'message': message, 'extra': extra }) #raise self.retry(exc=exc) pass try: # We got a response back, but we don't know whether it's an error yet. # This call raises errors so we can handle them with normal exception # flows. response.validate_response() except DeviceNotRegisteredError: # Mark the push token as inactive #from notifications.models import PushToken #PushToken.objects.filter(token=token).update(active=False) pass except PushResponseError as exc: # Encountered some other per-notification error. rollbar.report_exc_info( extra_data={ 'token': token, 'message': message, 'extra': extra, 'push_response': exc.push_response._asdict(), }) #raise self.retry(exc=exc) pass
def send_push_message(token, message, extra=None): try: bodyContent = {'message': "hello"} response = PushClient().publish( PushMessage(to=token, body='hello', data=extra)) print(response.is_success()) except PushServerError as exc: print(exc.errors) print("---") print(exc.response_data) except (ConnectionError, HTTPError) as exc: print(exc.errors) print("---")
def send_push_message(token, message, notification_type, data={}): data['type'] = notification_type try: PushClient().publish( PushMessage( to=token, body=message, data=data ) ) except: pass
def notify_mobile(recipients: List[str], title: str, message: str): message += t('notifications.details') for user_email in recipients: user_devices = cast(List[str], user_dal.get_attributes( user_email, ['devices_to_notify']).get('devices_to_notify', [])) for device_token in user_devices: PushClient().publish( PushMessage( body=message, sound='default', title=title, to=device_token, ) )
def to_push_message(self): push_messages = [] recipients = self.recipients.all() for recipient in recipients: tokens = list(recipient.push_tokens.all().values_list('token', flat=True)) if tokens: for token in tokens: push_messages.append( PushMessage(title=self.title, body=self.body, data=self.data, to=token)) return push_messages
def send_push_message(token, message, extra=None): response = PushClient().publish(PushMessage(to=token, body=message, data=extra)) try: # We got a response back, but we don't know whether it's an error yet. # This call raises errors so we can handle them with normal exception # flows. response.validate_response() except DeviceNotRegisteredError: # self.user_svc.edit_user() # Mark the push token as inactive # PushToken.objects.filter(token=token).update(active=False) print("device not registered") except Exception as exc: # Encountered some other per-notification error. raise exc
def send_push_message(token, message): try: extra = {"title": message} response = PushClient().publish( PushMessage(to=token, body="notification", data=extra)) print(response.is_success()) except PushServerError as exc: print(exc.errors) print(exc.response_data) except (ConnectionError, HTTPError) as exc: print(exc.errors)
def notify_mobile(recipients, title, message): message += t('notifications.details') for user_email in recipients: user_devices = integrates_dao.get_table_attributes_dynamo( 'FI_users', { 'email': user_email }, ['devices_to_notify']).get('devices_to_notify', []) for device_token in user_devices: PushClient().publish( PushMessage( body=message, sound='default', title=title, to=device_token, ))
def send_push_message(token, message, user, extra=None): app.apscheduler.remove_job(user) try: response = PushClient().publish( PushMessage(to=token, body=message, data=extra)) except PushServerError as exc: # Encountered some likely formatting/validation error. rollbar.report_exc_info( extra_data={ 'token': token, 'message': message, 'extra': extra, 'errors': exc.errors, 'response_data': exc.response_data, }) raise except (ConnectionError, HTTPError) as exc: # Encountered some Connection or HTTP error - retry a few times in # case it is transient. rollbar.report_exc_info(extra_data={ 'token': token, 'message': message, 'extra': extra }) raise self.retry(exc=exc) try: # We got a response back, but we don't know whether it's an error yet. # This call raises errors so we can handle them with normal exception # flows. response.validate_response() except DeviceNotRegisteredError: # Mark the push token as inactive from notifications.models import PushToken PushToken.objects.filter(token=token).update(active=False) except PushResponseError as exc: # Encountered some other per-notification error. rollbar.report_exc_info( extra_data={ 'token': token, 'message': message, 'extra': extra, 'push_response': exc.push_response._asdict(), }) raise self.retry(exc=exc)
def send_push_message(self, data): from exponent_server_sdk import DeviceNotRegisteredError from exponent_server_sdk import PushClient from exponent_server_sdk import PushMessage from exponent_server_sdk import PushResponseError from exponent_server_sdk import PushServerError from requests.exceptions import ConnectionError from requests.exceptions import HTTPError try: PushClient().publish( PushMessage(to=self.notification.expo_token, body=self.message, title=self.title, sound='default', data=data)) return status.HTTP_200_OK except: return status.HTTP_400_BAD_REQUEST
def primary_issue_task(issue): Account = apps.get_model('accounts', 'Account') HistoricPosition = apps.get_model('accounts', 'HistoricPosition') RadarIssue = apps.get_model('business', 'RadarIssue') RadarHit = apps.get_model('business', 'RadarHit') point = Point(issue['position']['coordinates'], srid=4326) issue_acutal = RadarIssue.objects.get(pk=issue.id) affected_users = set() queryset = HistoricPosition.objects.filter( position__distance_lte=(point, D(m=issue['radius'])), timestamp__gt=(datetime.utcfromtimestamp(int(issue['timestamp'])) - timedelta(hours=24))) # boil down the queryset to unique users for instance in queryset: affected_users.add(instance.account.first()) # Iterate over found users for user in affected_users: # create a RadarHit object for each user new_hit = RadarHit.objects.create(account=user) issue_acutal.hits.add(new_hit) issue_acutal.save() # If the issue includes sending push notifications if issue['do_notify']: # Make sure that the user has a expo notification token stored if user.notification_token: try: response = PushClient().publish( PushMessage( to=user.notification_token, title=issue['title'], body=issue['short'], )) new_hit.notified = response.ok print(response) except: pass return affected_users
def send_push_notification(expo_token: str, title: str, body: str, data: Dict[Any, Any]=None): """Send notification to specified expo token :expo_token: token to send notificaton to :title: notification title :body: notification body :data: extra notification data (total payload must be under 4096 bytes) :raises: ConnectionError, DeviceNotRegisterdError, HTTPError, InvalidExpoToken, PushServerError, PushResponseError """ assert expo_token, "Expo token cannot be None" if PushClient().is_exponent_push_token(expo_token): message = PushMessage(to=expo_token, title=title, body=body, data=data) response = PushClient().publish(message) response.validate_response() else: raise InvalidExpoToken()
def send_push_notifications(notification: Notification) -> None: push_messages = [] request = SimpleNamespace() request.user = notification.creator for receiver in notification.receivers.all(): for device in receiver.devices.all(): push_messages.append( PushMessage( to=device.expo_push_token, body=notification.content, data=dict( NotificationSerializer( notification, context={"request": request} ).data ), ) ) PushClient().publish_multiple(push_messages)
def save(self, *args, **kwargs): super(Message, self).save(*args, **kwargs) # Send notification for chatter in self.chat.chatters.filter(~Q(id=self.user.id)): if (self.channel and not chatter in self.channel.muted_users.all()) or self.chat.type == 'friend': try: from exponent_server_sdk import PushClient, PushMessage response = PushClient().publish( PushMessage(to=chatter.expo_push_token, body=f'{self.user.username}: {self.__str__()}', data={'_displayInForeground': True, 'chadId': self.chat.id} ) ) except: pass self.read_users.add(self.user)
def send_push_message(token, message, extra=None): try: response = PushClient().publish( PushMessage(to=token, body=message, data=extra)) except PushServerError as exc: rollbar.report_exc_info( extra_data={ 'token': token, 'message': message, 'extra': extra, 'errors': exc.errors, 'response_data': exc.response_data, }) raise except (ConnectionError, HTTPError) as exc: rollbar.report_exc_info(extra_data={ 'token': token, 'message': message, 'extra': extra }) raise self.retry(exc=exc) try: response.validate_response() except DeviceNotRegisteredError: # Mark the push token as inactive from notifications.models import PushToken PushToken.objects.filter(token=token).update(active=False) except PushResponseError as exc: rollbar.report_exc_info( extra_data={ 'token': token, 'message': message, 'extra': extra, 'push_response': exc.push_response._asdict(), }) raise self.retry(exc=exc) return response