-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTimerTrigger.cs
89 lines (76 loc) · 2.74 KB
/
TimerTrigger.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
using System.Globalization;
using System.Linq;
using System;
using System.Collections.Generic;
using Twilio;
using Twilio.Rest.Api.V2010.Account;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Extensions.Logging;
namespace DeevCorp.Function
{
public static class TimerTrigger
{
[FunctionName("TimerTrigger")]
public static void Run(
[TimerTrigger("0 0 0 * * *")]
TimerInfo myTimer,
[CosmosDB(
Constants.COSMOS_DB_DATABASE_NAME,
Constants.COSMOS_DB_CONTAINER_NAME,
ConnectionStringSetting = "CosmosDBConnection")
]
IEnumerable<dynamic> users,
ILogger log)
{
// timer executes every day at 12:00am
// loop through db and check if any date matches current day
var usersWithBirthdateToday = new List<dynamic>();
foreach (var user in users)
{
var userBirthdate = (DateTime)user.birthdate;
if (userBirthdate.Month == DateTime.Today.Month &&
userBirthdate.Day == DateTime.Today.Day)
{
usersWithBirthdateToday.Add(user);
}
}
if (usersWithBirthdateToday.Count == 0) return;
InitializeTwilio();
usersWithBirthdateToday.ForEach(user =>
{
// Send SMS to recipient
if (user.messages != null && user.messages.Count > 0)
{
var message = $"{user.messages[user.messages.Count - 1]}";
try
{
SendSMS(message, (string)user.phoneNumber, true);
log.LogInformation($"Sent message to {user.name.firstName}");
}
catch (Exception e)
{
log.LogError(e.Message);
}
}
});
}
public static void SendSMS(string text, string recipient, bool isSending = true)
{
if (isSending)
{
MessageResource.Create(
body: text,
from: new Twilio.Types.PhoneNumber(Environment.GetEnvironmentVariable("TwilioNumber")),
to: new Twilio.Types.PhoneNumber(recipient)
);
}
}
public static void InitializeTwilio()
{
var twilioAccountSid = Environment.GetEnvironmentVariable("TwilioAccountSid");
var twilioAuthToken = Environment.GetEnvironmentVariable("TwilioAuthToken");
TwilioClient.Init(twilioAccountSid, twilioAuthToken);
}
}
}