- Notifications
You must be signed in to change notification settings - Fork 843
/
Copy pathProgram.cs
233 lines (197 loc) · 10.4 KB
/
Program.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
usingSystem;
usingSystem.CommandLine;
usingSystem.CommandLine.Invocation;
usingSystem.CommandLine.Parsing;
usingSystem.Linq;
usingSystem.Threading.Tasks;
usingMicrosoft.Bot.Builder;
usingMicrosoft.Bot.Builder.Teams;
usingMicrosoft.Bot.Connector;
usingMicrosoft.Bot.Connector.Authentication;
usingMicrosoft.Bot.Schema;
usingMicrosoft.Bot.Schema.Teams;
usingPolly;
usingPolly.CircuitBreaker;
namespaceMicrosoft.Teams.Samples.ProactiveMessageCmd
{
classProgram
{
staticreadonlyRandomrandom=newRandom();
// Create the send policy for Microsoft Teams
// For more information about these policies
// see: http://www.thepollyproject.org/
staticIAsyncPolicyCreatePolicy(){
// Policy for handling the short-term transient throttling.
// Retry on throttling, up to 3 times with a 2,4,8 second delay between with a 0-1s jitter.
vartransientRetryPolicy=Policy
.Handle<ErrorResponseException>(ex =>ex.Message.Contains("429"))
.WaitAndRetryAsync(
retryCount:3,
(attempt)=>TimeSpan.FromSeconds(Math.Pow(2,attempt))+TimeSpan.FromMilliseconds(random.Next(0,1000)));
// Policy to avoid sending even more messages when the long-term throttling occurs.
// After 5 messages fail to send, the circuit breaker trips & all subsequent calls will throw
// a BrokenCircuitException for 10 minutes.
// Note, in this application this cannot trip since it only sends one message at a time!
// This is left in for completeness / demonstration purposes.
varcircuitBreakerPolicy=Policy
.Handle<ErrorResponseException>(ex =>ex.Message.Contains("429"))
.CircuitBreakerAsync(exceptionsAllowedBeforeBreaking:5,TimeSpan.FromMinutes(10));
// Policy to wait and retry when long-term throttling occurs.
// This will retry a single message up to 5 times with a 10 minute delay between each attempt.
// Note, in this application this cannot trip since the circuit breaker above cannot trip.
// This is left in for completeness / demonstration purposes.
varouterRetryPolicy=Policy
.Handle<BrokenCircuitException>()
.WaitAndRetryAsync(
retryCount:5,
(_)=>TimeSpan.FromMinutes(10));
// Combine all three policies so that it will first attempt to retry short-term throttling (inner-most)
// After 15 (5 messages, 3 failures each) consecutive failed attempts to send a message it will trip the circuit breaker
// which will fail all messages for the next ten minutes. It will attempt to send messages up to 5 times for a total
// wait of 50 minutes before failing a message.
return
outerRetryPolicy.WrapAsync(
circuitBreakerPolicy.WrapAsync(
transientRetryPolicy));
}
staticreadonlyIAsyncPolicyRetryPolicy=CreatePolicy();
staticTaskSendWithRetries(Func<Task>callback)
{
returnRetryPolicy.ExecuteAsync(callback);
}
staticTask<int>Main(string[]args)
{
staticstringNonNullOrWhitespace(ArgumentResultsymbol)
{
returnsymbol.Tokens
.Where(token =>string.IsNullOrWhiteSpace(token.Value))
.Select(token =>$"{symbol.Argument.Name} cannot be null or empty")
.FirstOrDefault();
}
varappIdOption=newOption<string>("--app-id")
{
Argument=newArgument<string>{Arity=ArgumentArity.ExactlyOne},
Required=true
};
appIdOption.Argument.AddValidator(NonNullOrWhitespace);
varappPasswordOption=newOption<string>("--app-password")
{
Argument=newArgument<string>{Arity=ArgumentArity.ExactlyOne},
Required=true
};
appPasswordOption.Argument.AddValidator(NonNullOrWhitespace);
varmessageOption=newOption<string>(newstring[]{"--message","-m"})
{
Argument=newArgument<string>{Arity=ArgumentArity.ExactlyOne},
Required=true
};
messageOption.Argument.AddValidator(NonNullOrWhitespace);
varserviceUrlOption=newOption<string>(newstring[]{"--service-url","-s"})
{
Argument=newArgument<string>{Arity=ArgumentArity.ExactlyOne},
Required=true
};
serviceUrlOption.Argument.AddValidator(NonNullOrWhitespace);
varconversationIdOption=newOption<string>(newstring[]{"--conversation-id","-c"})
{
Argument=newArgument<string>{Arity=ArgumentArity.ExactlyOne},
Required=true
};
conversationIdOption.Argument.AddValidator(NonNullOrWhitespace);
varchannelIdOption=newOption<string>(newstring[]{"--channel-id","-c"})
{
Argument=newArgument<string>{Arity=ArgumentArity.ExactlyOne},
Required=true
};
channelIdOption.Argument.AddValidator(NonNullOrWhitespace);
varnotifyOption=newOption<bool>("--notify")
{
Argument=newArgument<bool>{Arity=ArgumentArity.ExactlyOne}
};
varsendUserMessageCommand=newCommand("sendUserMessage","Send a message to the conversation coordinates")
{
appIdOption,
appPasswordOption,
serviceUrlOption,
conversationIdOption,
messageOption,
notifyOption
};
sendUserMessageCommand.Handler=CommandHandler.Create<string,string,string,string,string>(SendToUserAsync);
varcreateChannelThreadCommand=newCommand("createThread","Create a new thread in a channel")
{
appIdOption,
appPasswordOption,
serviceUrlOption,
channelIdOption,
messageOption
};
createChannelThreadCommand.Handler=CommandHandler.Create<string,string,string,string,string>(CreateChannelThreadAsync);
varsendChannelThreadMessageCommand=newCommand("sendChannelThread","Send a message to a channel thread")
{
appIdOption,
appPasswordOption,
serviceUrlOption,
conversationIdOption,
messageOption,
notifyOption
};
sendChannelThreadMessageCommand.Handler=CommandHandler.Create<string,string,string,string,string>(SendToThreadAsync);
// Create a root command with some options
varrootCommand=newRootCommand
{
sendUserMessageCommand,
createChannelThreadCommand,
sendChannelThreadMessageCommand
};
// Parse the incoming args and invoke the handler
returnrootCommand.InvokeAsync(args);
}
/// Send a one-on-one message to a user.
/// This method also makes the message appear in the activity feed!
publicstaticasyncTaskSendToUserAsync(stringappId,stringappPassword,stringserviceUrl,stringconversationId,stringmessage)
{
varactivity=MessageFactory.Text(message);
activity.Summary=message;// Ensure that the summary text is populated so the toast notifications aren't generic text.
activity.TeamsNotifyUser();// Send the message into the activity feed.
MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);// Required or the activity will be sent w/o auth headers.
varcredentials=newMicrosoftAppCredentials(appId,appPassword);
varconnectorClient=newConnectorClient(newUri(serviceUrl),credentials);
awaitSendWithRetries(async()=>
awaitconnectorClient.Conversations.SendToConversationAsync(conversationId,activity));
}
/// Create a new thread in a channel.
publicstaticasyncTaskCreateChannelThreadAsync(stringappId,stringappPassword,stringserviceUrl,stringchannelId,stringmessage)
{
// Create the connector client using the service url & the bot credentials.
varcredentials=newMicrosoftAppCredentials(appId,appPassword);
varconnectorClient=newConnectorClient(newUri(serviceUrl),credentials);
// Ensure the service url is marked as "trusted" so the SDK will send auth headers
MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);
// Craft an activity from the message
varactivity=MessageFactory.Text(message);
varconversationParameters=newConversationParameters
{
IsGroup=true,
ChannelData=newTeamsChannelData
{
Channel=newChannelInfo(channelId),
},
Activity=activity
};
awaitSendWithRetries(async()=>
awaitconnectorClient.Conversations.CreateConversationAsync(conversationParameters));
}
/// Send a message to a thread in a channel.
publicstaticasyncTaskSendToThreadAsync(stringappId,stringappPassword,stringserviceUrl,stringconversationId,stringmessage)
{
varactivity=MessageFactory.Text(message);
activity.Summary=message;// Ensure that the summary text is populated so the toast notifications aren't generic text.
MicrosoftAppCredentials.TrustServiceUrl(serviceUrl);// Required or the activity will be sent w/o auth headers.
varcredentials=newMicrosoftAppCredentials(appId,appPassword);
varconnectorClient=newConnectorClient(newUri(serviceUrl),credentials);
awaitSendWithRetries(async()=>
awaitconnectorClient.Conversations.SendToConversationAsync(conversationId,activity));
}
}
}