amr_aly

Push_notification

Dec 23rd, 2021 (edited)
445
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.89 KB | None | 0 0
  1. def send_notification(registration_ids, message_title , message_desc):
  2.     #* this is the API key
  3.     fcm_api = "Your_API_KEY"
  4.    
  5.     url = "https://fcm.googleapis.com/fcm/send"
  6.  
  7.     headers = {
  8.         "Content-Type": "application/json",
  9.         "Authorization": 'key=' + fcm_api
  10.     }
  11.  
  12.     payload = {
  13.         "registration_ids": registration_ids,
  14.         "priority": "high",
  15.         "notification": {
  16.             "body": message_desc,
  17.             "title": message_title,
  18.             "image": "https://i.ytimg.com/vi/m5WUPHRgdOA/hqdefault.jpg?sqp=-oaymwEXCOADEI4CSFryq4qpAwkIARUAAIhCGAE=&rs=AOn4CLDwz-yjKEdwxvKjwMANGk5BedCOXQ",
  19.             "icon": "https://yt3.ggpht.com/ytc/AKedOLSMvoy4DeAVkMSAuiuaBdIGKC7a5Ib75bKzKO3jHg=s900-c-k-c0x00ffffff-no-rj",
  20.  
  21.         }
  22.     }
  23.  
  24.     result = requests.post(url,  data=json.dumps(payload), headers=headers)
  25.     return result
  26.  
  27.  
  28. ####### in any views.py you can put the next lines to send notification for many users and don't forget to import sen_notification()method
  29.         qs = CustomUser.objects.values('id').exclude(id=request.user.id)    # exclude user to send to himself
  30.         users = [obj[0] for obj in qs]
  31.             fcm_user = [
  32.                 (FCMDevice.objects
  33.                     .values(
  34.                         'registration_id'
  35.                     ).filter(
  36.                         user_id=obj
  37.                     )
  38.                 ) for obj in users
  39.             ]
  40.             ## An error occurs by the next line when sending notification to any user
  41.             ## that has no record in FCMDevice model SO YOU MUST MAKE ALL USERS HAVE A RECORD IN THIS TABLE
  42.             ## TO AVOID ERROR  
  43.             reg_id = [obj[0] for obj in fcm_user]
  44.            
  45.             send_to_supplier = send_notification(
  46.                 reg_id, 'for all user New Order Created',
  47.                 str("Order Created Successfully ...")
  48.             )
  49.  
  50.  
Add Comment
Please, Sign In to add comment