/
Bot.cs
468 lines (397 loc) · 13.4 KB
/
Bot.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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition.Hosting;
using System.ComponentModel.Composition.Primitives;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading.Tasks;
using System.Web.Hosting;
using Jabbot.Models;
using Jabbot.Sprockets.Core;
using SignalR.Client.Hubs;
using SignalR.Client.Transports;
using JabbR.Client;
using JabbR.Client.Models;
namespace Jabbot
{
public class Bot
{
private readonly string _password;
private readonly string _url;
private readonly List<ISprocket> _sprockets = new List<ISprocket>();
private readonly List<IUnhandledMessageSprocket> _unhandledMessageSprockets = new List<IUnhandledMessageSprocket>();
private readonly HashSet<string> _rooms = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
private const string ExtensionsFolder = "Sprockets";
private ComposablePartCatalog _catalog = null;
private CompositionContainer _container = null;
JabbRClient client;
private bool _isActive = false;
private bool _containerInitialized = false;
public Bot(string url, string name, string password)
{
Name = name;
_password = password;
_url = url;
TaskScheduler.UnobservedTaskException += new EventHandler<UnobservedTaskExceptionEventArgs>(TaskScheduler_UnobservedTaskException);
InitializeClient();
InitializeContainer();
}
private void InitializeClient()
{
client = new JabbRClient(_url);
client.MessageReceived += (message, room) =>
{
ProcessMessage(message, room);
};
client.UserJoined += (user, message) =>
{
};
}
void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
e.SetObserved();
}
public string Name { get; private set; }
public ICredentials Credentials
{
get
{
return client.Credentials;
}
set
{
client.Credentials = value;
}
}
public event Action Disconnected
{
add
{
client.Disconnected += value;
}
remove
{
client.Disconnected -= value;
}
}
public event Action<ChatMessage> MessageReceived;
/// <summary>
/// Connects to the chat session
/// </summary>
public void PowerUp()
{
if (!_isActive)
{
client.Connect(Name, _password).ContinueWith(task =>
{
if (!task.IsFaulted)
{
LogOnInfo info = task.Result;
// IntializeSprockets();
}
else
{
Elmah.ErrorSignal.FromCurrentContext().Raise(task.Exception);
}
});
_isActive = true;
}
else
{
throw new InvalidOperationException("Bot is already powered up. Call ShutDown first");
}
//if (!_connection.IsActive)
//{
// InitializeContainer();
// _chat.On<dynamic, string>("addMessage", ProcessMessage);
// _chat.On("leave", OnLeave);
// _chat.On("addUser", OnJoin);
// _chat.On<IEnumerable<string>>("logOn", OnLogOn);
// // Start the connection and wait
// _connection.Start(new AutoTransport()).Wait();
// // Join the chat
// var success = _chat.Invoke<bool>("Join").Result;
// if (!success)
// {
// // Setup the name of the bot
// Send(String.Format("/nick {0} {1}", Name, _password));
// IntializeSprockets();
// }
//}
}
/// <summary>
/// Creates a new room
/// </summary>
/// <param name="room">room to create</param>
public void CreateRoom(string room)
{
client.JoinRoom(room);
// Add the room to the list
_rooms.Add(room);
}
/// <summary>
/// Joins a chat room. Changes this to the active room for future messages.
/// </summary>
public void Join(string room)
{
client.JoinRoom(room);
// Add the room to the list
_rooms.Add(room);
}
///// <summary>
///// Sets the Bot's gravatar email
///// </summary>
///// <param name="gravatarEmail"></param>
//public void Gravatar(string gravatarEmail)
//{
// client.
// Send("/gravatar " + gravatarEmail);
//}
/// <summary>
/// Say something to the active room.
/// </summary>
/// <param name="what">what to say</param>
/// <param name="room">the room to say it to</param>
public void Say(string what, string room)
{
if (what == null)
{
throw new ArgumentNullException("what");
}
if (what.StartsWith("/"))
{
throw new InvalidOperationException("Commands are not allowed");
}
if (string.IsNullOrWhiteSpace(room))
{
throw new ArgumentNullException("room");
}
client.Send(what, room);
}
/// <summary>
/// Reply to someone
/// </summary>
/// <param name="who">the person you want the bot to reply to</param>
/// <param name="what">what you want the bot to say</param>
/// <param name="room">the room to say it to</param>
public void Reply(string who, string what, string room)
{
if (who == null)
{
throw new ArgumentNullException("who");
}
if (what == null)
{
throw new ArgumentNullException("what");
}
Say(String.Format("@{0} {1}", who, what), room);
}
public void PrivateReply(string who, string what)
{
if (who == null)
{
throw new ArgumentNullException("who");
}
if (what == null)
{
throw new ArgumentNullException("what");
}
client.SendPrivateMessage(who, what);
}
/// <summary>
/// List of rooms the bot is in.
/// </summary>
public IEnumerable<string> Rooms
{
get
{
return _rooms;
}
}
/// <summary>
/// Disconnect the bot from the chat session. Leaves all rooms the bot entered
/// </summary>
public void ShutDown()
{
// Leave all the rooms ever joined
foreach (var room in _rooms)
{
client.LeaveRoom(room);
}
client.Disconnect();
_isActive = false;
}
public void ProcessMessage(Message message, string room)
{
// Run this on another thread since the signalr client doesn't like it
// when we spend a long time processing messages synchronously
Task.Factory.StartNew(() =>
{
string content = message.Content;
string name = message.User.Name;
// Ignore replies from self
if (name.Equals(Name, StringComparison.OrdinalIgnoreCase))
{
return;
}
// We're going to process commands for the bot here
var chatMessage = new ChatMessage(WebUtility.HtmlDecode(content), name, room);
if (MessageReceived != null)
{
MessageReceived(chatMessage);
}
bool handled = false;
// Loop over the registered sprockets
foreach (var handler in _sprockets)
{
// Stop at the first one that handled the message
if (handler.Handle(chatMessage, this))
{
handled = true;
break;
}
}
if (!handled)
{
// Loop over the unhandled message sprockets
foreach (var handler in _unhandledMessageSprockets)
{
// Stop at the first one that handled the message
if (handler.Handle(chatMessage, this))
{
break;
}
}
}
})
.ContinueWith(task =>
{
// Just write to debug output if it failed
if (task.IsFaulted)
{
Debug.WriteLine("JABBOT: Failed to process messages. {0}", task.Exception.GetBaseException());
}
});
}
private void OnLeave(dynamic user)
{
}
private void OnJoin(dynamic user)
{
}
private void OnLogOn(IEnumerable<string> rooms)
{
foreach (var room in rooms)
{
_rooms.Add(room);
}
}
private void InitializeContainer()
{
if (!_containerInitialized)
{
var container = CreateCompositionContainer();
// Add all the sprockets to the sprocket list
foreach (var sprocket in container.GetExportedValues<ISprocket>())
{
AddSprocket(sprocket);
}
// Add all the sprockets to the sprocket list
foreach (var sprocket in container.GetExportedValues<IUnhandledMessageSprocket>())
{
AddUnhandledMessageSprocket(sprocket);
}
_containerInitialized = true;
}
else
{
throw new InvalidOperationException("Container already initialized");
}
}
private void IntializeSprockets()
{
var container = CreateCompositionContainer();
// Run all sprocket initializers
foreach (var sprocketInitializer in container.GetExportedValues<ISprocketInitializer>())
{
try
{
sprocketInitializer.Initialize(this);
}
catch (Exception ex)
{
Trace.WriteLine(String.Format("Unable to Initialize {0}:{1}", sprocketInitializer.GetType().Name, ex.GetBaseException().Message));
}
}
}
private CompositionContainer CreateCompositionContainer()
{
if (_container == null)
{
string extensionsPath = GetExtensionsPath();
// If the extensions folder exists then use them
if (Directory.Exists(extensionsPath))
{
_catalog = new AggregateCatalog(
new AssemblyCatalog(typeof(Bot).Assembly),
new DirectoryCatalog(extensionsPath, "*.dll"));
}
else
{
_catalog = new AssemblyCatalog(typeof(Bot).Assembly);
}
_container = new CompositionContainer(_catalog);
}
return _container;
}
/// <summary>
/// Add a sprocket to the bot instance
/// </summary>
public void AddSprocket(ISprocket sprocket)
{
_sprockets.Add(sprocket);
}
/// <summary>
/// Remove a sprocket from the bot instance
/// </summary>
public void RemoveSprocket(ISprocket sprocket)
{
_sprockets.Remove(sprocket);
}
/// <summary>
/// Add a sprocket to the bot instance
/// </summary>
public void AddUnhandledMessageSprocket(IUnhandledMessageSprocket sprocket)
{
_unhandledMessageSprockets.Add(sprocket);
}
/// <summary>
/// Remove a sprocket from the bot instance
/// </summary>
public void RemoveUnhandledMessageSprocket(IUnhandledMessageSprocket sprocket)
{
_unhandledMessageSprockets.Remove(sprocket);
}
/// <summary>
/// Remove all sprockets
/// </summary>
public void ClearSprockets()
{
_sprockets.Clear();
}
private static string GetExtensionsPath()
{
string rootPath = null;
if (HostingEnvironment.IsHosted)
{
rootPath = HostingEnvironment.ApplicationPhysicalPath;
}
else
{
rootPath = Directory.GetCurrentDirectory();
}
return Path.Combine(rootPath, ExtensionsFolder);
}
}
}