
Crear un ChatBot inteligente con WhatsApp en C# (Gratis)
En este tutorial aprenderemos a crear un ChatBot inteligente con WhatsApp en C# totalmente gratis y con la plataforma oficial de WhatsApp (WhatsApp cloud API). La ventaja que tenemos al trabajar con la plataforma oficial es que la informacion que recibiremos y enviaremos será completamente fiable. solo debemos seguir estos pasos:
Creamos una app en Facebook

O podemos aceder a este link Todas las apps – Meta for Developers (facebook.com)





Configuramos el Api de WhatsApp






Código para enviar mensajes con Api Oficial de WhatsApp en C#



Código para recibir mensajes de WhatsApp con C#


//Controllers\RecibirController.cs using ChatBotWa.Models; using Microsoft.AspNetCore.Mvc; using System.IO; using System.Net; using System.Net.Http.Headers; using System.Xml.Linq; namespace ChatBotWa.Controllers { public class RecibirController { //RECIBIMOS LOS DATOS DE VALIDACION VIA GET [HttpGet] //DENTRO DE LA RUTA webhook [Route("webhook")] //RECIBIMOS LOS PARAMETROS QUE NOS ENVIA WHATSAPP PARA VALIDAR NUESTRA URL public string Webhook( [FromQuery(Name = "hub.mode")] string mode, [FromQuery(Name = "hub.challenge")] string challenge, [FromQuery(Name = "hub.verify_token")] string verify_token ) { //SI EL TOKEN ES hola (O EL QUE COLOQUEMOS EN FACEBOOK) if (verify_token.Equals("hola")) { return challenge; } else { return ""; } } //RECIBIMOS LOS DATOS DE VIA POST [HttpPost] //DENTRO DE LA RUTA webhook [Route("webhook")] //RECIBIMOS LOS DATOS Y LOS GUARDAMOS EN EL MODELO WebHookResponseModel public dynamic datos([FromBody] WebHookResponseModel entry) { //ESTRAEMOS EL MENSAJE RECIBIDO string mensaje_recibido = entry.entry[0].changes[0].value.messages[0].text.body; //ESTRAEMOS EL ID UNICO DEL MENSAJE string id_wa = entry.entry[0].changes[0].value.messages[0].id; //ESTRAEMOS EL NUMERO DE TELEFONO DEL CUAL RECIBIMOS EL MENSAJE string telefono_wa = entry.entry[0].changes[0].value.messages[0].from; //CREAMOS EL TEXTO DEL ARCHIVO string texto = "mensaje_recibido="+mensaje_recibido + Environment.NewLine; texto = texto+ "id_wa=" + id_wa + Environment.NewLine; texto = texto + "telefono_wa=" + telefono_wa + Environment.NewLine; File.WriteAllText("texto.txt", texto); //SI NO HAY ERROR RETORNAMOS UN OK var response = new HttpResponseMessage(HttpStatusCode.OK); response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain"); return response; } } }



//Models\Datos.cs namespace ChatBotWa.Models { public class Datos { } public class WebHookResponseModel { public Entry[] entry { get; set; } } public class Entry { public Change[] changes { get; set; } } public class Change { public Value value { get; set; } } public class Value { public int ad_id { get; set; } public long form_id { get; set; } public long leadgen_id { get; set; } public int created_time { get; set; } public long page_id { get; set; } public int adgroup_id { get; set; } public Messages[] messages { get; set; } } public class Messages { public string id { get; set; } public string from { get; set; } public Text text { get; set; } } public class Text { public string body { get; set; } } }

Activamos un servidor ngrok






Código para enviar mensajes de WhatsApp con C#


//Crear un ChatBot inteligente con WhatsApp en C# //Controllers\EnviarController.cs namespace ChatBotWa.Controllers { public class EnviarController { //RECIBIMOS LOS DATOS DE VALIDACION VIA GET [HttpGet] //DENTRO DE LA RUTA envia [Route("envia")] //RECIBIMOS LOS PARAMETROS QUE NOS ENVIA WHATSAPP PARA VALIDAR NUESTRA URL public async Task enviaAsync() { string token = "EAAWRxZBz2YGQBAGlneZCWwJgwkP2ZBYEk5PoHDL9gsZCgxY3C0IpMTgHHW9cAi5PSApuzRSgUu5flKlTGgZCl1uxL6sjCqixRmkhldhOvVOYYIVOZBOyQ6WV3bm3jZCmWlfsdGb9gU8ZCddrHmFNfJ2FyhjJ43G9VgOtNuVTcZAoZAYoyZA1uYZBZB0ICPwDgDcpGscug9L2USOZAKgAZDZD"; //Identificador de número de teléfono string idTelefono = "111290641852610"; //Nuestro telefono string telefono = "527121122441"; HttpClient client = new HttpClient(); HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "https://graph.facebook.com/v15.0/" + idTelefono + "/messages"); request.Headers.Add("Authorization", "Bearer " + token); request.Content = new StringContent("{\"messaging_product\": \"whatsapp\",\"recipient_type\": \"individual\",\"to\": \"" + telefono + "\",\"type\": \"text\",\"text\": {\"body\": \"prueba\"}}"); request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); HttpResponseMessage response = await client.SendAsync(request); //response.EnsureSuccessStatusCode(); string responseBody = await response.Content.ReadAsStringAsync(); } } }

