Detailed examples of WeChat robot development tutorials
WeChat public platform development tutorial (4) Introduction to examples: robots (with source code)
In the previous article, I wrote the basic framework. Many people may feel confused. Here is a simple example to illustrate it. Description, I hope it can help you solve the mystery.
1. Function introduction
Realize the online customer service robot function through the WeChat public platform. The main functions include: simple conversation, weather query and other services.
Here we only provide relatively simple functions, focusing on using this example to illustrate the specific development process of the public platform. It's just a simple DEMO and can be expanded on this basis if necessary.
Of course, we will also introduce more complex application examples in the future.
2. Specific implementation
1. Provide access to the interface
I won’t go into details here. Refer to the previous chapter, WeChat public account development tutorial (Part 2) ) Basic framework construction
www.cnblogs.com/yank/p/3392394.html
2. Signature authentication and distribution request
I won’t go into details here, refer to the previous chapter, WeChat Public account development tutorial (2) Basic framework construction
www.cnblogs.com/yank/p/3392394.html
3. Process the request and respond
1) Follow
When WeChat users follow public accounts, they can be given appropriate prompts. It can be a welcome message or a help tip.
Go directly to the code:
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) Greetings
Simple exchange of greetings, such as hello, help, etc., is the same as when we use WeChat to chat, but the response is by Our program responds. Specific functions can be added according to your own needs.
WeChat is originally a platform for communication. This case can be used for online service robots, similar to Taobao’s customer service robots, but ours is the WeChat version. Haha
Actually, it’s very simple, get the request message and match the response based on the keywords. Of course, there may be a lot of work to be done here, such as how to support intelligent matching, how to support fuzzy matching, etc.
The code is as follows:
/// <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) Query weather
This function needs to request real-time query, request the official weather release website, and then parse its return value according to our needs format, organize the weather information, and finally send it to WeChat customers.
Using text message processing.
User request, just enter: tq city name/pinyin/initial letter to get the message.
Reply message: (Take Beijing as an example)
北京 2013年11月6日 星期三 今天:(17℃~4℃)晴北风4-5级转3-4级4-5级转3-4级 24小时穿衣指数:天气冷,建议着棉服、羽绒服、皮夹克加羊毛衫等冬季服装。年老体弱者宜着厚棉衣、冬大衣或厚羽绒服。 明天:(14℃~3℃)晴转多云微风小于3级 48小时穿衣指数:天气冷,建议着棉服、羽绒服、皮夹克加羊毛衫等冬季服装。年老体弱者宜着厚棉衣、冬大衣或厚羽绒服。
Let’s take a look at the source code:
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; } } }
[Related recommendations]
1. WeChat public account platform source code download
2. Alizi order system source code
The above is the detailed content of Detailed examples of WeChat robot development tutorials. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



The humanoid robot Ameca has been upgraded to the second generation! Recently, at the World Mobile Communications Conference MWC2024, the world's most advanced robot Ameca appeared again. Around the venue, Ameca attracted a large number of spectators. With the blessing of GPT-4, Ameca can respond to various problems in real time. "Let's have a dance." When asked if she had emotions, Ameca responded with a series of facial expressions that looked very lifelike. Just a few days ago, EngineeredArts, the British robotics company behind Ameca, just demonstrated the team’s latest development results. In the video, the robot Ameca has visual capabilities and can see and describe the entire room and specific objects. The most amazing thing is that she can also

In the field of industrial automation technology, there are two recent hot spots that are difficult to ignore: artificial intelligence (AI) and Nvidia. Don’t change the meaning of the original content, fine-tune the content, rewrite the content, don’t continue: “Not only that, the two are closely related, because Nvidia is expanding beyond just its original graphics processing units (GPUs). The technology extends to the field of digital twins and is closely connected to emerging AI technologies. "Recently, NVIDIA has reached cooperation with many industrial companies, including leading industrial automation companies such as Aveva, Rockwell Automation, Siemens and Schneider Electric, as well as Teradyne Robotics and its MiR and Universal Robots companies. Recently,Nvidiahascoll

Editor of Machine Power Report: Wu Xin The domestic version of the humanoid robot + large model team completed the operation task of complex flexible materials such as folding clothes for the first time. With the unveiling of Figure01, which integrates OpenAI's multi-modal large model, the related progress of domestic peers has been attracting attention. Just yesterday, UBTECH, China's "number one humanoid robot stock", released the first demo of the humanoid robot WalkerS that is deeply integrated with Baidu Wenxin's large model, showing some interesting new features. Now, WalkerS, blessed by Baidu Wenxin’s large model capabilities, looks like this. Like Figure01, WalkerS does not move around, but stands behind a desk to complete a series of tasks. It can follow human commands and fold clothes

This week, FigureAI, a robotics company invested by OpenAI, Microsoft, Bezos, and Nvidia, announced that it has received nearly $700 million in financing and plans to develop a humanoid robot that can walk independently within the next year. And Tesla’s Optimus Prime has repeatedly received good news. No one doubts that this year will be the year when humanoid robots explode. SanctuaryAI, a Canadian-based robotics company, recently released a new humanoid robot, Phoenix. Officials claim that it can complete many tasks autonomously at the same speed as humans. Pheonix, the world's first robot that can autonomously complete tasks at human speeds, can gently grab, move and elegantly place each object to its left and right sides. It can autonomously identify objects

In the blink of an eye, robots have learned to do magic? It was seen that it first picked up the water spoon on the table and proved to the audience that there was nothing in it... Then it put the egg-like object in its hand, then put the water spoon back on the table and started to "cast a spell"... …Just when it picked up the water spoon again, a miracle happened. The egg that was originally put in disappeared, and the thing that jumped out turned into a basketball... Let’s look at the continuous actions again: △ This animation shows a set of actions at 2x speed, and it flows smoothly. Only by watching the video repeatedly at 0.5x speed can it be understood. Finally, I discovered the clues: if my hand speed were faster, I might be able to hide it from the enemy. Some netizens lamented that the robot’s magic skills were even higher than their own: Mag was the one who performed this magic for us.

The following 10 humanoid robots are shaping our future: 1. ASIMO: Developed by Honda, ASIMO is one of the most well-known humanoid robots. Standing 4 feet tall and weighing 119 pounds, ASIMO is equipped with advanced sensors and artificial intelligence capabilities that allow it to navigate complex environments and interact with humans. ASIMO's versatility makes it suitable for a variety of tasks, from assisting people with disabilities to delivering presentations at events. 2. Pepper: Created by Softbank Robotics, Pepper aims to be a social companion for humans. With its expressive face and ability to recognize emotions, Pepper can participate in conversations, help in retail settings, and even provide educational support. Pepper's

Sweeping and mopping robots are one of the most popular smart home appliances among consumers in recent years. The convenience of operation it brings, or even the need for no operation, allows lazy people to free their hands, allowing consumers to "liberate" from daily housework and spend more time on the things they like. Improved quality of life in disguised form. Riding on this craze, almost all home appliance brands on the market are making their own sweeping and mopping robots, making the entire sweeping and mopping robot market very lively. However, the rapid expansion of the market will inevitably bring about a hidden danger: many manufacturers will use the tactics of sea of machines to quickly occupy more market share, resulting in many new products without any upgrade points. It is also said that they are "matryoshka" models. Not an exaggeration. However, not all sweeping and mopping robots are

"The Legend of Zelda: Tears of the Kingdom" became the fastest-selling Nintendo game in history. Not only did Zonav Technology bring various "Zelda Creator" community content, but it also became the United States' A new engineering course at the University of Maryland (UMD). Rewrite: The Legend of Zelda: Tears of the Kingdom is one of Nintendo's fastest-selling games on record. Not only does Zonav Technology bring rich community content, it has also become part of the new engineering course at the University of Maryland. This fall, Associate Professor Ryan D. Sochol of the University of Maryland opened a course called "
