Created
October 2, 2015 17:36
-
-
Save IanMercer/5fe1d5539df7527b0971 to your computer and use it in GitHub Desktop.
A sample Slackbot responder using Margiebot and AboditNLP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Concurrent; | |
using AboditNLP; | |
using log4net; | |
using MargieBot.Models; | |
using MargieBot.Responders; | |
using Services; | |
namespace NLPService | |
{ | |
public class SlackResponder : IResponder | |
{ | |
private static readonly ILog log = LogManager.GetLogger("Slack"); | |
private readonly INLP nlp; | |
private readonly IUserService userService; | |
public SlackResponder(INLP nlp, IUserService userService) | |
{ | |
this.nlp = nlp; | |
this.userService = userService; | |
} | |
public bool CanRespond(ResponseContext context) | |
{ | |
return true; | |
} | |
// Should really be in a database but for demo, use static | |
private static readonly ConcurrentDictionary<string, RememberedHistory> inMemoryHistory = new ConcurrentDictionary<string, RememberedHistory>(); | |
public RememberedHistory GetHistoryForUser(string userId) | |
{ | |
var history = inMemoryHistory.GetOrAdd(userId, new RememberedHistory()); | |
return history; | |
} | |
public BotMessage GetResponse(ResponseContext context) | |
{ | |
string chatId = context.Message.User.ID; | |
// Get or create the user | |
var user = userService.GetUserByWebId(chatId); | |
if (user == null) | |
{ | |
log.Debug($"About to create the user record for '{chatId}'"); | |
user = userService.CreateUser(name: chatId, callerId: "", emailAddress: "", webId: chatId); | |
} | |
else | |
{ | |
log.Debug("Found an existing user in database"); | |
} | |
// Get or create history for the user | |
var memory = GetHistoryForUser(chatId); | |
var collector = new Collector(memory); | |
DateTime lastAccessed = user.DateTimeAccessed ?? new DateTime(2011, 1, 1); | |
if (DateTime.UtcNow.Subtract(lastAccessed).TotalHours > 12) | |
{ | |
collector.Say("Welcome back."); | |
} | |
user.DateTimeAccessed = userService.MarkAccessedNow(user); | |
bool ok = nlp.Execute(context.Message.Text, collector, user); | |
if (!ok) | |
return new BotMessage { Text = $"Did not recognize '{context.Message.Text}" }; | |
else | |
return new BotMessage { Text = string.Join(System.Environment.NewLine, collector.Result) }; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment