Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save paigeshin/ef9dabb162a9db61765d43cd2db28f73 to your computer and use it in GitHub Desktop.
Save paigeshin/ef9dabb162a9db61765d43cd2db28f73 to your computer and use it in GitHub Desktop.
const functions = require("firebase-functions");
const admin = require("firebase-admin");
admin.initializeApp();
exports.sendPushMessages = functions.pubsub
.schedule("every 1 hours")
.onRun(async (context) => {
// Retrieve all users from Firestore collection
const usersRef = admin.firestore().collection("users");
const usersSnapshot = await usersRef.get();
const users = usersSnapshot.docs.map((doc) => doc.data());
// Loop through each user
for (const user of users) {
// Get current date and time in user's timezone
const date = new Date().toLocaleString("en-US", {
timeZone: user.timezone,
});
const hour = parseInt(date.split(",")[1].split(":")[0]);
const minute = parseInt(date.split(",")[1].split(":")[1]);
const day = date.split(",")[0];
// Determine message text based on user's preferred language and current day of the week
let messageText;
if (user.language === "ko") {
switch (day) {
case "Monday":
messageText = "월요일에만 나타나는 메시지입니다!";
break;
case "Tuesday":
messageText = "화요일에만 나타나는 메시지입니다!";
break;
case "Wednesday":
messageText = "수요일에만 나타나는 메시지입니다!";
break;
case "Thursday":
messageText = "목요일에만 나타나는 메시지입니다!";
break;
case "Friday":
messageText = "금요일에만 나타나는 메시지입니다!";
break;
case "Saturday":
messageText = "토요일에만 나타나는 메시지입니다!";
break;
case "Sunday":
messageText = "일요일에만 나타나는 메시지입니다!";
break;
default:
messageText = "이는 매 시간마다 발송되는 일반적인 알림입니다.";
break;
}
} else {
switch (day) {
case "Monday":
messageText = "This is a message that only appears on Mondays!";
break;
case "Tuesday":
messageText = "This is a message that only appears on Tuesdays!";
break;
case "Wednesday":
messageText = "This is a message that only appears on Wednesdays!";
break;
case "Thursday":
messageText = "This is a message that only appears on Thursdays!";
break;
case "Friday":
messageText = "This is a message that only appears on Fridays!";
break;
case "Saturday":
messageText = "This is a message that only appears on Saturdays!";
break;
case "Sunday":
messageText = "This is a message that only appears on Sundays!";
break;
default:
messageText = "This is a general reminder that is sent every hour.";
break;
}
}
// Check if it's time to send a notification (11 PM local time)
if (hour === 23) {
const message = {
notification: {
title: "Hourly Reminder",
body: messageText,
},
};
// Send message to user's FCM token
const response = await admin
.messaging()
.sendToDevice(user.fcmToken, message);
console.log(`Message sent to ${user.timezone}:`, response);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment