微信公众平台开发教程(四) 实例入门:机器人(附源码)
上一篇文章,写了基本框架,可能很多人会觉得晕头转向,这里提供一个简单的例子来予以说明,希望能帮你解开谜团。
一、功能介绍
通过微信公众平台实现在线客服机器人功能。主要的功能包括:简单对话、查询天气等服务。
这里只是提供比较简单的功能,重在通过此实例来说明公众平台的具体研发过程。只是一个简单DEMO,如果需要的话可以在此基础上进行扩展。
当然后续我们还会推出比较复杂的应用实例。
二、具体实现
1、提供访问接口
这里不再赘述,参照上一章,微信公众账号开发教程(二) 基础框架搭建
http://www.cnblogs.com/yank/p/3392394.html
2、签名认证和分发请求
这里不再赘述,参照上一章,微信公众账号开发教程(二) 基础框架搭建
http://www.cnblogs.com/yank/p/3392394.html
3、处理请求,并响应
1)关注
当微信用户关注公众账号时,可以给其适当的提示。可以是欢迎词,可以是帮助提示。
直接上代码:
class EventHandler : IHandler { /// <summary> /// 请求的xml /// </summary> private string RequestXml { get; set; } /// <summary> /// 构造函数 /// </summary> /// <param name="requestXml"></param> public EventHandler(string requestXml) { this.RequestXml = requestXml; } /// <summary> /// 处理请求 /// </summary> /// <returns></returns> public string HandleRequest() { string response = string.Empty; EventMessage em = EventMessage.LoadFromXml(RequestXml); if (em.Event.Equals("subscribe",StringComparison.OrdinalIgnoreCase)) { //回复欢迎消息 TextMessage tm = new TextMessage(); tm.ToUserName = em.FromUserName; tm.FromUserName = em.ToUserName; tm.CreateTime = Common.GetNowTime(); tm.Content = "欢迎您关注***,我是大哥大,有事就问我,呵呵!\n\n"; response = tm.GenerateContent(); } return response; } }
2)问候
简单的交流问候,比如你好、帮助等等,跟我们使用微信聊天一样,不过回应是由我们的程序响应。具体功能,可以根据自己的需要进行添加。
微信本来就是沟通的平台。这个案例,可以用于在线服务机器人,类似于淘宝的客服机器人,可是我们这个是微信版的。呵呵
其实,很简单,获取请求消息,根据关键字来匹配回应。当然这里可能要做的工作很多,如何支持智能匹配,如何支持模糊匹配等。
代码如下:
/// <summary> /// 文本信息处理类 /// </summary> public class TextHandler : IHandler { /// <summary> /// 请求的XML /// </summary> private string RequestXml { get; set; } /// <summary> /// 构造函数 /// </summary> /// <param name="requestXml">请求的xml</param> public TextHandler(string requestXml) { this.RequestXml = requestXml; } /// <summary> /// 处理请求 /// </summary> /// <returns></returns> public string HandleRequest() { string response = string.Empty; TextMessage tm = TextMessage.LoadFromXml(RequestXml); string content = tm.Content.Trim(); if (string.IsNullOrEmpty(content)) { response = "您什么都没输入,没法帮您啊,%>_<%。"; } else { if (content.StartsWith("tq", StringComparison.OrdinalIgnoreCase)) { string cityName = content.Substring(2).Trim(); response = WeatherHelper.GetWeather(cityName); } else { response = HandleOther(content); } } tm.Content = response; //进行发送者、接收者转换 string temp = tm.ToUserName; tm.ToUserName = tm.FromUserName; tm.FromUserName = temp; response = tm.GenerateContent(); return response; } /// <summary> /// 处理其他消息 /// </summary> /// <param name="tm"></param> /// <returns></returns> private string HandleOther(string requestContent) { string response = string.Empty; if (requestContent.Contains("你好") || requestContent.Contains("您好")) { response = "您也好~"; } else if (requestContent.Contains("傻")) { response = "我不傻!哼~ "; } else if (requestContent.Contains("逼") || requestContent.Contains("操")) { response = "哼,你说脏话! "; } else if (requestContent.Contains("是谁")) { response = "我是大哥大,有什么能帮您的吗?~"; } else if (requestContent.Contains("再见")) { response = "再见!"; } else if (requestContent.Contains("bye")) { response = "Bye!"; } else if (requestContent.Contains("谢谢")) { response = "不客气!嘿嘿"; } else if (requestContent == "h" || requestContent == "H" || requestContent.Contains("帮助")) { response = @"查询天气,输入tq 城市名称\拼音\首字母"; } else { response = "您说的,可惜,我没明白啊,试试其他关键字吧。"; } return response; } }
3)查询天气
这个功能需要请求实时查询的,请求官方的天气发布网站,然后解析其返回值,按照我们需要的格式,组织天气信息,最后发送给微信客户。
采用文本消息方式处理。
用户请求,只需输入:tq 城市名称/拼音/首字母,即可获取消息。
回复的消息:(以北京为例)
北京 2013年11月6日 星期三 今天:(17℃~4℃)晴北风4-5级转3-4级4-5级转3-4级 24小时穿衣指数:天气冷,建议着棉服、羽绒服、皮夹克加羊毛衫等冬季服装。年老体弱者宜着厚棉衣、冬大衣或厚羽绒服。 明天:(14℃~3℃)晴转多云微风小于3级 48小时穿衣指数:天气冷,建议着棉服、羽绒服、皮夹克加羊毛衫等冬季服装。年老体弱者宜着厚棉衣、冬大衣或厚羽绒服。
来看源码吧:
class WeatherHelper { /// <summary> /// 城市集合字段 /// </summary> private static Dictionary<string, City> mCities; /// <summary> /// 城市集合 /// </summary> public static Dictionary<string, City> Cities { get { if (mCities == null) { LoadCities(); } return mCities; } } /// <summary> /// 加载城市 /// </summary> private static void LoadCities() { mCities = new Dictionary<string, City>(); mCities.Clear(); mCities.Add("101010100", new City() { Code = "101010100", Name = "北京", PinYin = "beijing", FristLetter = "bj" }); mCities.Add("101020100", new City() { Code = "101020100", Name = "上海", PinYin = "shanghai", FristLetter = "sh" }); mCities.Add("101200101", new City() { Code = "101200101", Name = "武汉", PinYin = "wuhai", FristLetter = "wh" }); } /// <summary> /// 获取城市的天气 /// </summary> /// <param name="name">城市名称、拼音或首字母</param> /// <returns></returns> public static string GetWeather(string name) { string result = string.Empty; string cityCode = string.Empty; //获取城市编码 IEnumerable<string> codes = from item in Cities where item.Value != null && (item.Value.Name.Equals(name, StringComparison.OrdinalIgnoreCase) || item.Value.PinYin.Equals(name, StringComparison.OrdinalIgnoreCase) || item.Value.FristLetter.Equals(name, StringComparison.OrdinalIgnoreCase)) select item.Value.Code; if (codes != null && codes.Count() > 0) { cityCode = codes.First<string>(); } //http请求,获取天气 if (!string.IsNullOrEmpty(cityCode)) { string url = "http://m.weather.com.cn/data/{0}.html"; url = string.Format(url, cityCode); WebRequest request = HttpWebRequest.Create(url); //超时时间为:2秒 request.Timeout = 2000; request.Credentials = CredentialCache.DefaultCredentials; WebResponse response = request.GetResponse(); StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); string weahterInfo = reader.ReadToEnd(); if (string.IsNullOrEmpty(weahterInfo)) { result = "暂时没有取到天气数据,请稍后再试"; } else { XmlDocument doc = JsonConvert.DeserializeXmlNode(weahterInfo); if (doc != null) { XmlNode node = doc.DocumentElement; if (node != null) { StringBuilder builder = new StringBuilder(); builder.Append(node["city"].InnerText).Append("\n"); builder.Append(node["date_y"].InnerText).Append(" ").Append(node["week"].InnerText).Append("\n"); builder.Append("今天:").Append("(").Append(node["temp1"].InnerText).Append(")").Append(node["weather1"].InnerText).Append(node["wind1"].InnerText).Append(node["fl1"].InnerText).Append("\n"); builder.Append("24小时穿衣指数:").Append(node["index_d"].InnerText).Append("\n"); builder.Append("明天:").Append("(").Append(node["temp2"].InnerText).Append(")").Append(node["weather2"].InnerText).Append(node["wind2"].InnerText).Append(node["fl2"].InnerText).Append("\n"); builder.Append("48小时穿衣指数:").Append(node["index48_d"].InnerText).Append("\n"); result = builder.ToString(); } } #region 天气json数据格式 /* { "weatherinfo": { "city": "北京", "city_en": "beijing", "date_y": "2013年11月4日", "date": "", "week": "星期一", "fchh": "11", "cityid": "101010100", "temp1": "17℃~5℃", "temp2": "16℃~5℃", "temp3": "18℃~4℃", "temp4": "17℃~5℃", "temp5": "14℃~6℃", "temp6": "14℃~2℃", "tempF1": "62.6℉~41℉", "tempF2": "60.8℉~41℉", "tempF3": "64.4℉~39.2℉", "tempF4": "62.6℉~41℉", "tempF5": "57.2℉~42.8℉", "tempF6": "57.2℉~35.6℉", "weather1": "晴转多云", "weather2": "多云", "weather3": "多云转晴", "weather4": "晴转多云", "weather5": "多云转阴", "weather6": "阴转晴", "img1": "0", "img2": "1", "img3": "1", "img4": "99", "img5": "1", "img6": "0", "img7": "0", "img8": "1", "img9": "1", "img10": "2", "img11": "2", "img12": "0", "img_single": "0", "img_title1": "晴", "img_title2": "多云", "img_title3": "多云", "img_title4": "多云", "img_title5": "多云", "img_title6": "晴", "img_title7": "晴", "img_title8": "多云", "img_title9": "多云", "img_title10": "阴", "img_title11": "阴", "img_title12": "晴", "img_title_single": "晴", "wind1": "微风", "wind2": "微风", "wind3": "微风", "wind4": "微风", "wind5": "微风", "wind6": "北风4-5级", "fx1": "微风", "fx2": "微风", "fl1": "小于3级", "fl2": "小于3级", "fl3": "小于3级", "fl4": "小于3级", "fl5": "小于3级", "fl6": "4-5级", "index": "较冷", "index_d": "建议着大衣、呢外套加毛衣、卫衣等服装。体弱者宜着厚外套、厚毛衣。因昼夜温差较大,注意增减衣服。", "index48": "冷", "index48_d": "天气冷,建议着棉服、羽绒服、皮夹克加羊毛衫等冬季服装。年老体弱者宜着厚棉衣、冬大衣或厚羽绒服。", "index_uv": "中等", "index48_uv": "弱", "index_xc": "适宜", "index_tr": "适宜", "index_co": "舒适", "st1": "17", "st2": "5", "st3": "17", "st4": "5", "st5": "18", "st6": "6", "index_cl": "适宜", "index_ls": "适宜", "index_ag": "极不易发" } } */ #endregion } } else { result = "没有获取到该城市的天气,请确定输入了正确的城市名称,如\‘北京\‘或者\‘beijing\‘或者\‘bj\‘"; } //返回 return result; } /// <summary> /// 内部类:城市 /// </summary> internal class City { /// <summary> /// 编码 /// </summary> public string Code { get; set; } /// <summary> /// 名称 /// </summary> public string Name { get; set; } /// <summary> /// 拼音 /// </summary> public string PinYin { get; set; } /// <summary> /// 拼音首字母 /// </summary> public string FristLetter { get; set; } } }
三、源码
这里可是可执行的代码哦。应大家的需求,这里提供全部的源代码。
http://files.cnblogs.com/yank/Yank.WeiXin.Robot.zip