30a6470a1c67d66f-4207550bd0f024fa-c4cacb89afc04094
. You’ll use this in the HTTP headers to authenticate to the Viber API.public class ViberIncoming { public string Event { get; set; } public long Timestamp { get; set; } public ViberSender Sender { get; set; } public ViberMessage Message { get; set; } } public class ViberSender { public string Id { get; set; } public string Name { get; set; } } public class ViberMessage { public string Text { get; set; } public string Type { get; set; } }
ViberIncoming
object.[FunctionName("Chatbot")] public static async Task<HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log) { var incoming = req.Content.ReadAsAsync<ViberIncoming>().Result; var viber = new ViberProcessor(Bucket.Value); viber.Process(incoming); // return "OK" each time // this is most important for the initial Viber webhook setup return req.CreateResponse(HttpStatusCode.OK); }
ViberProcessor
class with a Process
method that receives this object.public void Process(ViberIncoming incoming) { if (incoming?.Message?.Type == "text") { LogIncoming(incoming); ProcessMessage(incoming); } }
LogIncoming
creates a record (in Couchbase) so that I know everything about each request that comes in.ProcessMessage
will analyze the text of the message and figure out what to do in response. You can check out the complete code on Github, but here’s a brief snippet to give you the idea:// if the message contains "hi", "hello", etc say "howdy" else if (HelloStrings.Any(incoming.Message.Text.ToLower().Contains)) SendTextMessage("Howdy!", incoming.Sender.Id); // if message contains "?" then link to the forums else if (incoming.Message.Text.Contains("?")) SendTextMessage("If you have a Couchbase question, please ask on the forums! http://forums.couchbase.com", incoming.Sender.Id); else SendTextMessage("I'm sorry, I don't understand you. Type 'help' for help!", incoming.Sender.Id);
private string GetMetrics() { var n1ql = @"select value count(*) as totalIncoming from ViberChatBot b where meta(b).id like 'incoming::%';"; var query = QueryRequest.Create(n1ql); var response = _bucket.Query<int>(query); if (response.Success) return $"I have received {response.Rows.First()} incoming messages so far!"; return "Sorry, I'm having trouble getting metrics right now."; }
private void SendTextMessage(string message, string senderId) { var client = new RestClient("https://chatapi.viber.com/pa/send_message"); var request = new RestRequest(RestSharp.Method.POST); request.AddJsonBody(new { receiver = senderId, // receiver (Unique Viber user id, required) type = "text", // type (Message type, required) Available message types: text, picture, etc text = message }); request.AddHeader("X-Viber-Auth-Token", ViberKey); var response = client.Execute(request); // log to Couchbase _bucket.Insert("resp::" + Guid.NewGuid(), response.Content); }