Example #1
0
        /// <summary>
        /// 处理文字请求
        /// </summary>
        public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
        {
            var requestHandler = requestMessage.StartHandler();
            //Logger.Info("msgs:"+JsonConvert.SerializeObject(Messages));

            //1、文字消息回复
            var textResponseMessage = base.CreateResponseMessage <ResponseMessageText>();

            foreach (var keyWord in Messages.KeyWords)
            {
                if (keyWord.Key == "默认")
                {
                    requestHandler.Default(() =>
                    {
                        textResponseMessage.Content = keyWord.Value;
                        return(textResponseMessage);
                    });
                }
                else
                {
                    //如果有逗号表示数组
                    if (keyWord.Key.Contains(','))
                    {
                        requestHandler.Keywords(keyWord.Key.Split(','), () =>
                        {
                            textResponseMessage.Content = keyWord.Value;
                            return(textResponseMessage);
                        });
                    }
                    //表示关键字
                    else
                    {
                        requestHandler.Keyword(keyWord.Key, () =>
                        {
                            textResponseMessage.Content = keyWord.Value;
                            return(textResponseMessage);
                        });
                    }
                }
            }

            //2、图文消息回复
            var newsResponseMessage = base.CreateResponseMessage <ResponseMessageNews>();

            foreach (var keyWordPic in Messages.KeyWordsPic)
            {
                if (keyWordPic.Key == "默认")//注意: 如果配置了文字默认回复,则图文不会被回复
                {
                    requestHandler.Default(() =>
                    {
                        newsResponseMessage.ArticleCount = 1;
                        newsResponseMessage.Articles.Add(keyWordPic.Value);
                        return(newsResponseMessage);
                    });
                }
                else
                {
                    //如果有逗号表示数组
                    if (keyWordPic.Key.Contains(','))
                    {
                        requestHandler.Keywords(keyWordPic.Key.Split(','), () =>
                        {
                            newsResponseMessage.ArticleCount = 1;
                            newsResponseMessage.Articles.Add(keyWordPic.Value);
                            return(newsResponseMessage);
                        });
                    }
                    //表示关键字
                    else
                    {
                        requestHandler.Keyword(keyWordPic.Key, () =>
                        {
                            newsResponseMessage.ArticleCount = 1;
                            newsResponseMessage.Articles.Add(keyWordPic.Value);
                            return(newsResponseMessage);
                        });
                    }
                }
            }

            //3、没有配置则默认 不回复任何消息
            //return new SuccessResponseMessage();

            return(requestHandler.GetResponseMessage() as IResponseMessageBase);
        }
Example #2
0
        /// <summary>
        /// 处理文字请求
        /// </summary>
        /// <returns></returns>
        public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
        {
            //说明:实际项目中这里的逻辑可以交给Service处理具体信息,参考OnLocationRequest方法或/Service/LocationSercice.cs

            #region 书中例子
            //if (requestMessage.Content == "你好")
            //{
            //    var responseMessage = base.CreateResponseMessage<ResponseMessageNews>();
            //    var title = "Title";
            //    var description = "Description";
            //    var picUrl = "PicUrl";
            //    var url = "Url";
            //    responseMessage.Articles.Add(new Article()
            //    {
            //        Title = title,
            //        Description = description,
            //        PicUrl = picUrl,
            //        Url = url
            //    });
            //    return responseMessage;
            //}
            //else if (requestMessage.Content == "Senparc")
            //{
            //    //相似处理逻辑
            //}
            //else
            //{
            //    //...
            //}

            #endregion

            #region 历史方法

            //方法一(v0.1),此方法调用太过繁琐,已过时(但仍是所有方法的核心基础),建议使用方法二到四
            //var responseMessage =
            //    ResponseMessageBase.CreateFromRequestMessage(RequestMessage, ResponseMsgType.Text) as
            //    ResponseMessageText;

            //方法二(v0.4)
            //var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(RequestMessage);

            //方法三(v0.4),扩展方法,需要using Senparc.Weixin.MP.Helpers;
            //var responseMessage = RequestMessage.CreateResponseMessage<ResponseMessageText>();

            //方法四(v0.6+),仅适合在HandlerMessage内部使用,本质上是对方法三的封装
            //注意:下面泛型ResponseMessageText即返回给客户端的类型,可以根据自己的需要填写ResponseMessageNews等不同类型。

            #endregion

            var defaultResponseMessage = base.CreateResponseMessage <ResponseMessageText>();

            var requestHandler =
                requestMessage.StartHandler()
                //关键字不区分大小写,按照顺序匹配成功后将不再运行下面的逻辑
                .Keyword("约束", () =>
            {
                defaultResponseMessage.Content =
                    @"您正在进行微信内置浏览器约束判断测试。您可以:
<a href=""http://sdk.weixin.senparc.com/FilterTest/"">点击这里</a>进行客户端约束测试(地址:http://sdk.weixin.senparc.com/FilterTest/),如果在微信外打开将直接返回文字。
或:
<a href=""http://sdk.weixin.senparc.com/FilterTest/Redirect"">点击这里</a>进行客户端约束测试(地址:http://sdk.weixin.senparc.com/FilterTest/Redirect),如果在微信外打开将重定向一次URL。";
                return(defaultResponseMessage);
            }).
                //匹配任一关键字
                Keywords(new[] { "托管", "代理" }, () =>
            {
                //开始用代理托管,把请求转到其他服务器上去,然后拿回结果
                //甚至也可以将所有请求在DefaultResponseMessage()中托管到外部。

                DateTime dt1 = DateTime.Now;     //计时开始

                var agentXml = RequestDocument.ToString();

                #region 暂时转发到SDK线上Demo

                agentUrl = "http://sdk.weixin.senparc.com/weixin";
                //agentToken = WebConfigurationManager.AppSettings["WeixinToken"];//Token

                //修改内容,防止死循环
                var agentDoc = XDocument.Parse(agentXml);
                agentDoc.Root.Element("Content").SetValue("代理转发文字:" + requestMessage.Content);
                agentDoc.Root.Element("CreateTime").SetValue(DateTimeHelper.GetWeixinDateTime(DateTime.Now)); //修改时间,防止去重
                agentDoc.Root.Element("MsgId").SetValue("123");                                               //防止去重
                agentXml = agentDoc.ToString();

                #endregion

                var responseXml = MessageAgent.RequestXml(this, agentUrl, agentToken, agentXml);
                //获取返回的XML
                //上面的方法也可以使用扩展方法:this.RequestResponseMessage(this,agentUrl, agentToken, RequestDocument.ToString());

                /* 如果有WeiweihiKey,可以直接使用下面的这个MessageAgent.RequestWeiweihiXml()方法。
                 * WeiweihiKey专门用于对接www.weiweihi.com平台,获取方式见:https://www.weiweihi.com/ApiDocuments/Item/25#51
                 */
                //var responseXml = MessageAgent.RequestWeiweihiXml(weiweihiKey, RequestDocument.ToString());//获取Weiweihi返回的XML

                DateTime dt2 = DateTime.Now;     //计时结束

                //转成实体。

                /* 如果要写成一行,可以直接用:
                 * responseMessage = MessageAgent.RequestResponseMessage(agentUrl, agentToken, RequestDocument.ToString());
                 * 或
                 *
                 */
                var msg = string.Format("\r\n\r\n代理过程总耗时:{0}毫秒", (dt2 - dt1).Milliseconds);
                var agentResponseMessage = responseXml.CreateResponseMessage();
                if (agentResponseMessage is ResponseMessageText)
                {
                    (agentResponseMessage as ResponseMessageText).Content += msg;
                }
                else if (agentResponseMessage is ResponseMessageNews)
                {
                    (agentResponseMessage as ResponseMessageNews).Articles[0].Description += msg;
                }
                return(agentResponseMessage);   //可能出现多种类型,直接在这里返回
            })
                .Keywords(new[] { "测试", "退出" }, () =>
            {
                /*
                 * 这是一个特殊的过程,此请求通常来自于微微嗨(http://www.weiweihi.com)的“盛派网络小助手”应用请求(https://www.weiweihi.com/User/App/Detail/1),
                 * 用于演示微微嗨应用商店的处理过程,由于微微嗨的应用内部可以单独设置对话过期时间,所以这里通常不需要考虑对话状态,只要做最简单的响应。
                 */
                if (defaultResponseMessage.Content == "测试")
                {
                    //进入APP测试
                    defaultResponseMessage.Content = "您已经进入【盛派网络小助手】的测试程序,请发送任意信息进行测试。发送文字【退出】退出测试对话。10分钟内无任何交互将自动退出应用对话状态。";
                }
                else
                {
                    //退出APP测试
                    defaultResponseMessage.Content = "您已经退出【盛派网络小助手】的测试程序。";
                }
                return(defaultResponseMessage);
            })
                .Keyword("AsyncTest", () =>
            {
                //异步并发测试(提供给单元测试使用)
#if NET45
                DateTime begin = DateTime.Now;
                int t1, t2, t3;
                System.Threading.ThreadPool.GetAvailableThreads(out t1, out t3);
                System.Threading.ThreadPool.GetMaxThreads(out t2, out t3);
                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(4));
                DateTime end = DateTime.Now;
                var thread   = System.Threading.Thread.CurrentThread;
                defaultResponseMessage.Content = string.Format("TId:{0}\tApp:{1}\tBegin:{2:mm:ss,ffff}\tEnd:{3:mm:ss,ffff}\tTPool:{4}",
                                                               thread.ManagedThreadId,
                                                               HttpContext.Current != null ? HttpContext.Current.ApplicationInstance.GetHashCode() : -1,
                                                               begin,
                                                               end,
                                                               t2 - t1
                                                               );
#endif

                return(defaultResponseMessage);
            })
                .Keyword("OPEN", () =>
            {
                var openResponseMessage = requestMessage.CreateResponseMessage <ResponseMessageNews>();
                openResponseMessage.Articles.Add(new Article()
                {
                    Title       = "开放平台微信授权测试",
                    Description = @"点击进入Open授权页面。

授权之后,您的微信所收到的消息将转发到第三方(盛派网络小助手)的服务器上,并获得对应的回复。

测试完成后,您可以登陆公众号后台取消授权。",
                    Url         = "http://sdk.weixin.senparc.com/OpenOAuth/JumpToMpOAuth"
                });
                return(openResponseMessage);
            })
                .Keyword("错误", () =>
            {
                var errorResponseMessage = requestMessage.CreateResponseMessage <ResponseMessageText>();
                //因为没有设置errorResponseMessage.Content,所以这小消息将无法正确返回。
                return(errorResponseMessage);
            })
                .Keyword("容错", () =>
            {
                Thread.Sleep(4900);    //故意延时1.5秒,让微信多次发送消息过来,观察返回结果
                var faultTolerantResponseMessage     = requestMessage.CreateResponseMessage <ResponseMessageText>();
                faultTolerantResponseMessage.Content = string.Format("测试容错,MsgId:{0},Ticks:{1}", requestMessage.MsgId,
                                                                     DateTime.Now.Ticks);
                return(faultTolerantResponseMessage);
            })
                .Keyword("TM", () =>
            {
                var openId    = requestMessage.FromUserName;
                var checkCode = Guid.NewGuid().ToString("n").Substring(0, 3);    //为了防止openId泄露造成骚扰,这里启用验证码
                TemplateMessageCollection[checkCode] = openId;
                defaultResponseMessage.Content       = string.Format(@"新的验证码为:{0},请在网页上输入。网址:http://sdk.weixin.senparc.com/AsyncMethods", checkCode);
                return(defaultResponseMessage);
            })
                .Keyword("OPENID", () =>
            {
                var openId   = requestMessage.FromUserName;  //获取OpenId
                var userInfo = AdvancedAPIs.UserApi.Info(appId, openId, Language.zh_CN);

                defaultResponseMessage.Content = string.Format(
                    "您的OpenID为:{0}\r\n昵称:{1}\r\n性别:{2}\r\n地区(国家/省/市):{3}/{4}/{5}\r\n关注时间:{6}\r\n关注状态:{7}",
                    requestMessage.FromUserName, userInfo.nickname, (Sex)userInfo.sex, userInfo.country, userInfo.province, userInfo.city, DateTimeHelper.GetDateTimeFromXml(userInfo.subscribe_time), userInfo.subscribe);
                return(defaultResponseMessage);
            })
                .Keyword("EX", () =>
            {
                var ex = new WeixinException("openid:" + requestMessage.FromUserName + ":这是一条测试异常信息");    //回调过程在global的ConfigWeixinTraceLog()方法中
                defaultResponseMessage.Content = "请等待异步模板消息发送到此界面上(自动延时数秒)。\r\n当前时间:" + DateTime.Now.ToString();
                return(defaultResponseMessage);
            })
                .Keyword("MUTE", () => //不回复任何消息
            {
                //方案一:
                return(new SuccessResponseMessage());

                //方案二:
                var muteResponseMessage = base.CreateResponseMessage <ResponseMessageNoResponse>();
                return(muteResponseMessage);

                //方案三:
                base.TextResponseMessage = "success";
                return(null);
            })
                .Keyword("JSSDK", () =>
            {
                defaultResponseMessage.Content = "点击打开:http://sdk.weixin.senparc.com/WeixinJsSdk";
                return(defaultResponseMessage);
            })
                //Default不一定要在最后一个
                .Default(() =>
            {
                var result = new StringBuilder();
                result.AppendFormat("您刚才发送了文字信息:{0}\r\n\r\n", requestMessage.Content);

                if (CurrentMessageContext.RequestMessages.Count > 1)
                {
                    result.AppendFormat("您刚才还发送了如下消息({0}/{1}):\r\n", CurrentMessageContext.RequestMessages.Count,
                                        CurrentMessageContext.StorageData);
                    for (int i = CurrentMessageContext.RequestMessages.Count - 2; i >= 0; i--)
                    {
                        var historyMessage = CurrentMessageContext.RequestMessages[i];
                        result.AppendFormat("{0} 【{1}】{2}\r\n",
                                            historyMessage.CreateTime.ToString("HH:mm:ss"),
                                            historyMessage.MsgType.ToString(),
                                            (historyMessage is RequestMessageText)
                                    ? (historyMessage as RequestMessageText).Content
                                    : "[非文字类型]"
                                            );
                    }
                    result.AppendLine("\r\n");
                }

                result.AppendFormat("如果您在{0}分钟内连续发送消息,记录将被自动保留(当前设置:最多记录{1}条)。过期后记录将会自动清除。\r\n",
                                    WeixinContext.ExpireMinutes, WeixinContext.MaxRecordCount);
                result.AppendLine("\r\n");
                result.AppendLine(
                    "您还可以发送【位置】【图片】【语音】【视频】等类型的信息(注意是这几种类型,不是这几个文字),查看不同格式的回复。\r\nSDK官方地址:http://sdk.weixin.senparc.com");

                defaultResponseMessage.Content = result.ToString();
                return(defaultResponseMessage);
            })
                //“一次订阅消息”接口测试
                .Keyword("订阅", () =>
            {
                defaultResponseMessage.Content = "点击打开:https://sdk.weixin.senparc.com/SubscribeMsg";
                return(defaultResponseMessage);
            })
                //正则表达式
                .Regex(@"^\d+#\d+$", () =>
            {
                defaultResponseMessage.Content = string.Format("您输入了:{0},符合正则表达式:^\\d+#\\d+$", requestMessage.Content);
                return(defaultResponseMessage);
            });

            return(requestHandler.GetResponseMessage() as IResponseMessageBase);
        }
Example #3
0
        public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
        {
            var handler = requestMessage.StartHandler(false)
                          .Keyword("cmd", () =>
            {
                var responseMessageText = requestMessage.CreateResponseMessage <ResponseMessageText>();

                CurrentMessageContext.StorageData = new StorageModel()
                {
                    IsInCmd = true
                };

                responseMessageText.Content += "\r\n已经进入CMD状态";

                return(responseMessageText);
            })
                          .Keywords(new[] { "exit", "quit", "close" }, () =>
            {
                var responseMessageText = requestMessage.CreateResponseMessage <ResponseMessageText>();

                var storageModel = CurrentMessageContext.StorageData as StorageModel;
                if (storageModel != null)
                {
                    storageModel.IsInCmd = false;
                }
                return(responseMessageText);
            }).Regex(@"^http", () =>
            {
                var responseMessageNews = requestMessage.CreateResponseMessage <ResponseMessageNews>();


                var news = new Article()
                {
                    Title       = "您输入了网址:" + requestMessage.Content,
                    Description = "这里是描述,第一行\r\n这里是描述,第二行",
                    PicUrl      = "http://sdk.weixin.senparc.com/images/book-cover-front-small-3d-transparent.png",
                    Url         = requestMessage.Content
                };

                responseMessageNews.Articles.Add(news);

                return(responseMessageNews);
            })
                          .Regex(@"天气 \S+", () =>
            {
                var city   = Regex.Match(requestMessage.Content, @"(?<=天气 )(\S+)").Value;
                var url    = "http://www.sojson.com/open/api/weather/json.shtml?city={0}".FormatWith(city.UrlDecode());
                var result = Senparc.Weixin.HttpUtility.Get.GetJson <WeatherResult>(url, null, null);
                var responseMessageText     = requestMessage.CreateResponseMessage <ResponseMessageText>();
                responseMessageText.Content = @"天气查询
=============
城市:{0}
添加时间:{1}
日期:{2}
Count:{3}".FormatWith(result.city, result.AddTime, result.date, result.count);
                return(responseMessageText);
            })
                          .Default(() =>
            {
                var responseMessageText     = requestMessage.CreateResponseMessage <ResponseMessageText>();
                responseMessageText.Content = "这是一条默认的文本请求回复信息";
                return(responseMessageText);
            });

            var responseMessage = handler.ResponseMessage;

            if (responseMessage is ResponseMessageText)
            {
                (responseMessage as ResponseMessageText).Content += "\r\n您输入了文字:" + requestMessage.Content;

                var storageModel = CurrentMessageContext.StorageData as StorageModel;
                if (storageModel != null)
                {
                    (responseMessage as ResponseMessageText).Content += "当前CMD Count:" +
                                                                        storageModel.CmdCount;
                }
            }

            return(handler.ResponseMessage as IResponseMessageBase);
        }
Example #4
0
        public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
        {
            var defaultResponseMessage = base.CreateResponseMessage <ResponseMessageText>();

            using (IocManager.Instance.CreateScope())
            {
                var projectManager       = IocManager.Instance.Resolve <MESProjectManager>();
                var fileManager          = IocManager.Instance.Resolve <IFileManager>();
                var userManager          = IocManager.Instance.Resolve <UserManager>();
                var startupConfiguration = IocManager.Instance.Resolve <IAbpStartupConfiguration>();
                var abpSession           = IocManager.Instance.Resolve <IAbpSession>();

                var user    = GetCurrentUser(requestMessage);
                var baseUrl = startupConfiguration.Modules.WebCore().BaseUrl;//基url,如http://demo.imould.me
                if (user == null)
                {
                    defaultResponseMessage.Content = "当前用户未在系统中绑定";
                    return(defaultResponseMessage);
                }
                //模拟账套数据查询
                using (abpSession.Use(user.TenantId, user.Id))
                {
                    var requestHandler =
                        requestMessage.StartHandler()
                        .Keyword("交接", () =>
                    {
                        //操作工设备交接
                        var equipmentManager = IocManager.Instance.Resolve <EquipmentManager>();
                        var equipments       = equipmentManager.GetByOperatorId(user.Id).Result;
                        if (equipments.Count == 0)
                        {
                            defaultResponseMessage.Content = "您没有正在操作的设备,不需要交接";
                            return(defaultResponseMessage);
                        }
                        else
                        {
                            var responseMessage = CreateResponseMessage <ResponseMessageNews>();
                            responseMessage.Articles.Add(new Article()
                            {
                                Title = "点击链接进行设备交接",
                                Url   = $"{baseUrl}/MES/EquipmentTranisitionCode"
                            });

                            return(responseMessage);
                        }
                    })
                        .Default(() =>
                    {
                        #region 寻找模具信息返回
                        //寻找匹配的模具
                        var project = projectManager.GetAll()
                                      .Where(o => o.ProjectSN.Contains(requestMessage.Content))
                                      .OrderByDescending(o => o.Id)
                                      .FirstOrDefault();

                        if (project == null)
                        {
                            defaultResponseMessage.Content = "未找到模具信息";
                            return(defaultResponseMessage);
                        }
                        var responseMessage = CreateResponseMessage <ResponseMessageNews>();


                        var fileUrl = "";
                        if (project.ProjectPic.HasValue)
                        {
                            fileUrl = baseUrl + fileManager.GetFileUrl(project.ProjectPic.Value, 100, 100);
                        }

                        responseMessage.Articles.Add(new Article()
                        {
                            Title       = project.ProjectSN,
                            Description = project.ProjectName,
                            PicUrl      = fileUrl,
                            Url         = $"{baseUrl}/mes/ProcessTaskWechat#/charger/project/user?projectId={project.Id}"
                        });

                        return(responseMessage);

                        #endregion
                    });

                    return(requestHandler.GetResponseMessage() as IResponseMessageBase);
                }
            }
        }
        /// <summary>
        /// 处理文字请求
        /// </summary>
        /// <param name="requestMessage">请求消息</param>
        /// <returns></returns>
        public override async Task <IResponseMessageBase> OnTextRequestAsync(RequestMessageText requestMessage)
        {
            //说明:实际项目中这里的逻辑可以交给Service处理具体信息,参考OnLocationRequest方法或/Service/LocationSercice.cs

            #region 书中例子
            //if (requestMessage.Content == "你好")
            //{
            //    var responseMessage = base.CreateResponseMessage<ResponseMessageNews>();
            //    var title = "Title";
            //    var description = "Description";
            //    var picUrl = "PicUrl";
            //    var url = "Url";
            //    responseMessage.Articles.Add(new Article()
            //    {
            //        Title = title,
            //        Description = description,
            //        PicUrl = picUrl,
            //        Url = url
            //    });
            //    return responseMessage;
            //}
            //else if (requestMessage.Content == "Senparc")
            //{
            //    //相似处理逻辑
            //}
            //else
            //{
            //    //...
            //}

            #endregion

            #region 历史方法

            //方法一(v0.1),此方法调用太过繁琐,已过时(但仍是所有方法的核心基础),建议使用方法二到四
            //var responseMessage =
            //    ResponseMessageBase.CreateFromRequestMessage(RequestMessage, ResponseMsgType.Text) as
            //    ResponseMessageText;

            //方法二(v0.4)
            //var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(RequestMessage);

            //方法三(v0.4),扩展方法,需要using Senparc.Weixin.MP.Helpers;
            //var responseMessage = RequestMessage.CreateResponseMessage<ResponseMessageText>();

            //方法四(v0.6+),仅适合在HandlerMessage内部使用,本质上是对方法三的封装
            //注意:下面泛型ResponseMessageText即返回给客户端的类型,可以根据自己的需要填写ResponseMessageNews等不同类型。

            #endregion

            var defaultResponseMessage = base.CreateResponseMessage <ResponseMessageText>();

            var requestHandler = await requestMessage.StartHandler()
                                 //关键字不区分大小写,按照顺序匹配成功后将不再运行下面的逻辑
                                 .Keyword("约束", () =>
            {
                defaultResponseMessage.Content =
                    @"您正在进行微信内置浏览器约束判断测试。您可以:
<a href=""https://sdk.weixin.senparc.com/FilterTest/"">点击这里</a>进行客户端约束测试(地址:https://sdk.weixin.senparc.com/FilterTest/),如果在微信外打开将直接返回文字。
或:
<a href=""https://sdk.weixin.senparc.com/FilterTest/Redirect"">点击这里</a>进行客户端约束测试(地址:https://sdk.weixin.senparc.com/FilterTest/Redirect),如果在微信外打开将重定向一次URL。";
                return(defaultResponseMessage);
            }).
                                 //匹配任一关键字
                                 Keywords(new[] { "托管", "代理" }, () =>
            {
                //开始用代理托管,把请求转到其他服务器上去,然后拿回结果
                //甚至也可以将所有请求在DefaultResponseMessage()中托管到外部。

                var dt1 = SystemTime.Now;     //计时开始

                var agentXml = RequestDocument.ToString();

                #region 暂时转发到SDK线上Demo

                agentUrl = "https://sdk.weixin.senparc.com/weixin";
                //agentToken = WebConfigurationManager.AppSettings["WeixinToken"];//Token

                //修改内容,防止死循环
                var agentDoc = XDocument.Parse(agentXml);
                agentDoc.Root.Element("Content").SetValue("代理转发文字:" + requestMessage.Content);
                agentDoc.Root.Element("CreateTime").SetValue(DateTimeHelper.GetUnixDateTime(SystemTime.Now)); //修改时间,防止去重
                agentDoc.Root.Element("MsgId").SetValue("123");                                               //防止去重
                agentXml = agentDoc.ToString();

                #endregion

                var responseXml = MessageAgent.RequestXml(this,
#if NET462
                                                          null,
#else
                                                          Senparc.CO2NET.SenparcDI.GetServiceProvider(),
#endif
                                                          agentUrl, agentToken, agentXml);
                //获取返回的XML
                //上面的方法也可以使用扩展方法:this.RequestResponseMessage(this,agentUrl, agentToken, RequestDocument.ToString());

                /* 如果有WeiweihiKey,可以直接使用下面的这个MessageAgent.RequestWeiweihiXml()方法。
                 * WeiweihiKey专门用于对接www.weiweihi.com平台,获取方式见:https://www.weiweihi.com/ApiDocuments/Item/25#51
                 */
                //var responseXml = MessageAgent.RequestWeiweihiXml(weiweihiKey, RequestDocument.ToString());//获取Weiweihi返回的XML

                var dt2 = SystemTime.Now;     //计时结束

                //转成实体。

                /* 如果要写成一行,可以直接用:
                 * responseMessage = MessageAgent.RequestResponseMessage(agentUrl, agentToken, RequestDocument.ToString());
                 * 或
                 *
                 */
                var msg = string.Format("\r\n\r\n代理过程总耗时:{0}毫秒", (dt2 - dt1).Milliseconds);
                var agentResponseMessage = responseXml.CreateResponseMessage(this.MessageEntityEnlightener);
                if (agentResponseMessage is ResponseMessageText)
                {
                    (agentResponseMessage as ResponseMessageText).Content += msg;
                }
                else if (agentResponseMessage is ResponseMessageNews)
                {
                    (agentResponseMessage as ResponseMessageNews).Articles[0].Description += msg;
                }
                return(agentResponseMessage);   //可能出现多种类型,直接在这里返回
            })
                                 .Keywords(new[] { "测试", "退出" }, () =>
            {
                /*
                 * 这是一个特殊的过程,此请求通常来自于微微嗨(http://www.weiweihi.com)的“盛派网络小助手”应用请求(https://www.weiweihi.com/User/App/Detail/1),
                 * 用于演示微微嗨应用商店的处理过程,由于微微嗨的应用内部可以单独设置对话过期时间,所以这里通常不需要考虑对话状态,只要做最简单的响应。
                 */
                if (defaultResponseMessage.Content == "测试")
                {
                    //进入APP测试
                    defaultResponseMessage.Content = "您已经进入【盛派网络小助手】的测试程序,请发送任意信息进行测试。发送文字【退出】退出测试对话。10分钟内无任何交互将自动退出应用对话状态。";
                }
                else
                {
                    //退出APP测试
                    defaultResponseMessage.Content = "您已经退出【盛派网络小助手】的测试程序。";
                }
                return(defaultResponseMessage);
            })
                                 .Keyword("AsyncTest", () =>
            {
                //异步并发测试(提供给单元测试使用)
#if NET462
                var begin = SystemTime.Now;
                int t1, t2, t3;
                System.Threading.ThreadPool.GetAvailableThreads(out t1, out t3);
                System.Threading.ThreadPool.GetMaxThreads(out t2, out t3);
                System.Threading.Thread.Sleep(TimeSpan.FromSeconds(4));
                var end    = SystemTime.Now;
                var thread = System.Threading.Thread.CurrentThread;
                defaultResponseMessage.Content = string.Format("TId:{0}\tApp:{1}\tBegin:{2:mm:ss,ffff}\tEnd:{3:mm:ss,ffff}\tTPool:{4}",
                                                               thread.ManagedThreadId,
                                                               HttpContext.Current != null ? HttpContext.Current.ApplicationInstance.GetHashCode() : -1,
                                                               begin,
                                                               end,
                                                               t2 - t1
                                                               );
#endif

                return(defaultResponseMessage);
            })
                                 .Keyword("OPEN", () =>
            {
                var openResponseMessage = requestMessage.CreateResponseMessage <ResponseMessageNews>();
                openResponseMessage.Articles.Add(new Article()
                {
                    Title       = "开放平台微信授权测试!",
                    Description = @"点击进入Open授权页面。

授权之后,您的微信所收到的消息将转发到第三方(盛派网络小助手)的服务器上,并获得对应的回复。

测试完成后,您可以登陆公众号后台取消授权。",
                    Url         = "https://sdk.weixin.senparc.com/OpenOAuth/JumpToMpOAuth"
                });
                return(openResponseMessage);
            })
                                 .Keyword("错误", () =>
            {
                var errorResponseMessage = requestMessage.CreateResponseMessage <ResponseMessageText>();
                //因为没有设置errorResponseMessage.Content,所以这小消息将无法正确返回。
                return(errorResponseMessage);
            })
                                 .Keyword("容错", () =>
            {
                Thread.Sleep(4900);    //故意延时1.5秒,让微信多次发送消息过来,观察返回结果
                var faultTolerantResponseMessage     = requestMessage.CreateResponseMessage <ResponseMessageText>();
                faultTolerantResponseMessage.Content = string.Format("测试容错,MsgId:{0},Ticks:{1}", requestMessage.MsgId,
                                                                     SystemTime.Now.Ticks);
                return(faultTolerantResponseMessage);
            })
                                 .Keyword("TM", () =>
            {
                var openId    = requestMessage.FromUserName;
                var checkCode = Guid.NewGuid().ToString("n").Substring(0, 3);    //为了防止openId泄露造成骚扰,这里启用验证码

                Task.Factory.StartNew(async() =>
                {
                    var currentCache = CacheStrategyFactory.GetObjectCacheStrategyInstance();
                    await currentCache.SetAsync($"TestCheckCode:{checkCode}", openId, TimeSpan.FromHours(1));    //使用缓存,如果多台服务器可以使用分布式缓存共享
                }).Wait();

                defaultResponseMessage.Content = string.Format(@"新的验证码为:{0},请在网页上输入。网址:https://sdk.weixin.senparc.com/AsyncMethods", checkCode);
                return(defaultResponseMessage);
            })
                                 .Keyword("OPENID", () =>
            {
                var openId   = requestMessage.FromUserName;  //获取OpenId
                var userInfo = MP.AdvancedAPIs.UserApi.Info(appId, openId, Language.zh_CN);

                defaultResponseMessage.Content = string.Format(
                    "您的OpenID为:{0}\r\n昵称:{1}\r\n性别:{2}\r\n地区(国家/省/市):{3}/{4}/{5}\r\n关注时间:{6}\r\n关注状态:{7}\r\n\r\n说明:从2021年12月27日起,公众号无法直接获取用户昵称、性别、地区等信息,如需获取相关信息,需要使用<a href=\"https://sdk.weixin.senparc.com/oauth2?returnUrl=%2FOAuth2%2FTestReturnUrl\">OAuth 2.0 接口</a>。",
                    requestMessage.FromUserName, userInfo.nickname, (WeixinSex)userInfo.sex, userInfo.country, userInfo.province, userInfo.city, DateTimeHelper.GetDateTimeFromXml(userInfo.subscribe_time), userInfo.subscribe);
                return(defaultResponseMessage);
            })
                                 .Keyword("EX", () =>
            {
                var ex = new WeixinException("openid:" + requestMessage.FromUserName + ":这是一条测试异常信息");    //回调过程在global的ConfigWeixinTraceLog()方法中
                defaultResponseMessage.Content = "请等待异步模板消息发送到此界面上(自动延时数秒)。\r\n当前时间:" + SystemTime.Now.ToString();
                return(defaultResponseMessage);
            })
                                 .Keyword("MUTE", () => //不回复任何消息
            {
                //方案一:
                return(new SuccessResponseMessage());

                //方案二:
                var muteResponseMessage = base.CreateResponseMessage <ResponseMessageNoResponse>();
                return(muteResponseMessage);

                //方案三:
                base.TextResponseMessage = "success";
                return(null);

                //方案四:
                return(null);   //在 Action 中结合使用 return new FixWeixinBugWeixinResult(messageHandler);
            })
                                 .Keyword("JSSDK", () =>
            {
                defaultResponseMessage.Content = "点击打开:https://sdk.weixin.senparc.com/WeixinJsSdk";
                return(defaultResponseMessage);
            })


                                 //选择菜单,关键字:101(微信服务器端最终格式:id="s:101",content="满意")
                                 .SelectMenuKeyword("101", () =>
            {
                defaultResponseMessage.Content = $"感谢您的评价({requestMessage.Content})!我们会一如既往为提高企业和开发者生产力而努力!";
                return(defaultResponseMessage);
            })
                                 //选择菜单,关键字:102(微信服务器端最终格式:id="s:102",content="一般")
                                 .SelectMenuKeyword("102", () =>
            {
                defaultResponseMessage.Content = $"感谢您的评价({requestMessage.Content})!希望我们的服务能让您越来越满意!";
                return(defaultResponseMessage);
            })
                                 //选择菜单,关键字:103(微信服务器端最终格式:id="s:103",content="不满意")
                                 .SelectMenuKeyword("103", () =>
            {
                defaultResponseMessage.Content = $"感谢您的评价({requestMessage.Content})!我们需要您的意见或建议,欢迎向我们反馈! <a href=\"https://weixin.senparc.com/QA\">点击这里</a>";
                return(defaultResponseMessage);
            })
                                 .SelectMenuKeywords(new[] { "110", "111" }, () =>
            {
                defaultResponseMessage.Content = $"这里只是演示,可以同时支持多个选择菜单";
                return(defaultResponseMessage);
            })


                                 //“一次订阅消息”接口测试
                                 .Keyword("订阅", () =>
            {
                defaultResponseMessage.Content = "点击打开:https://sdk.weixin.senparc.com/SubscribeMsg";
                return(defaultResponseMessage);
            })
                                 //正则表达式
                                 .Regex(@"^\d+#\d+$", () =>
            {
                defaultResponseMessage.Content = string.Format("您输入了:{0},符合正则表达式:^\\d+#\\d+$", requestMessage.Content);
                return(defaultResponseMessage);
            })
                                 //ServiceProvider
                                 .Keyword("SP", () =>
            {
                if (base.ServiceProvider == null)
                {
                    defaultResponseMessage.Content = "ServiceProvider 为 null";
                }
                else
                {
#if !NET462
                    var httpContextAccessor        = base.ServiceProvider.GetService <IHttpContextAccessor>();
                    defaultResponseMessage.Content = $"ServiceProvider 载入成功,从 IHttpContextAccessor 读取当前服务器协议:{httpContextAccessor.HttpContext.Request.Scheme}";
#endif
                }


                return(defaultResponseMessage);
            })
                                 //企业微信审批
                                 .Keyword("审批", () =>
            {
                MP.AdvancedAPIs.CustomApi.SendText(appId, OpenId, "请将下方地址在企业微信内打开(如果您还没有加入企业微信测试账号,可在QQ群内联系管理员申请):");
                defaultResponseMessage.Content = "https://sdk.weixin.senparc.com/Work/Approval";
                return(defaultResponseMessage);
            })

                                 //当 Default 使用异步方法时,需要写在最后一个,且 requestMessage.StartHandler() 前需要使用 await 等待异步方法执行;
                                 //当 Default 使用同步方法,不一定要在最后一个,并且不需要使用 await
                                 .Default(async() =>
            {
                var result = new StringBuilder();
                result.AppendFormat("您刚才发送了文字信息:{0}\r\n\r\n", requestMessage.Content);

                var currentMessageContext = await base.GetCurrentMessageContext();
                if (currentMessageContext.RequestMessages.Count > 1)
                {
                    result.AppendFormat("您此前还发送了如下消息({0}/{1}):\r\n", currentMessageContext.RequestMessages.Count,
                                        currentMessageContext.StorageData);
                    for (int i = currentMessageContext.RequestMessages.Count - 2; i >= 0; i--)
                    {
                        var historyMessage = currentMessageContext.RequestMessages[i];
                        result.AppendFormat("{0} 【{1}】{2}\r\n",
                                            historyMessage.CreateTime.ToString("HH:mm:ss"),
                                            historyMessage.MsgType.ToString(),
                                            (historyMessage is RequestMessageText)
                                    ? (historyMessage as RequestMessageText).Content
                                    : $"[非文字类型{((historyMessage is IRequestMessageEventKey eventKey) ? $"-{eventKey.EventKey}" : "")}]"
                                            );
                    }
                    result.AppendLine("\r\n");
                }

                result.AppendFormat("如果您在{0}分钟内连续发送消息,记录将被自动保留(当前设置:最多记录{1}条)。过期后记录将会自动清除。\r\n",
                                    GlobalMessageContext.ExpireMinutes, GlobalMessageContext.MaxRecordCount);
                result.AppendLine("\r\n");
                result.AppendLine(
                    "您还可以发送【位置】【图片】【语音】【视频】等类型的信息(注意是这几种类型,不是这几个文字),查看不同格式的回复。\r\nSDK官方地址:https://sdk.weixin.senparc.com");

                defaultResponseMessage.Content = result.ToString();

                return(defaultResponseMessage);
            });

            return(requestHandler.GetResponseMessage() as IResponseMessageBase);
        }
        /// <summary>
        /// 处理文字消息
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
        {
            //关键字回复
            var keyWordHandler = requestMessage.StartHandler(false)
                                 .Keyword("cmd", () =>
            {
                var responseMessage = this.CreateResponseMessage <ResponseMessageText>();
                var storageModel    = new StorageModel()
                {
                    IsInCmd = true
                };

                base.GetCurrentMessageContext().Result.StorageData = storageModel;

                responseMessage.Content = "您进入了CDM模式";

                return(responseMessage);
            }).Keywords(new string[] { "exit", "quit", "close" }, () =>
            {
                var responseMessage = this.CreateResponseMessage <ResponseMessageText>();
                var storageModel    = base.GetCurrentMessageContext().Result.StorageData as StorageModel;


                if (storageModel != null)
                {
                    storageModel.IsInCmd = false;
                }

                responseMessage.Content = "您退出了CMD模式";

                return(responseMessage);
            }).Regex(@"^http", () =>
            {
                var responseMessage = this.CreateResponseMessage <ResponseMessageNews>();

                var article = new Article
                {
                    Description = "你看看这里\r\n有换行\r\n再换行",
                    PicUrl      = "https://sdk.weixin.senparc.com/images/book-cover-front-small-3d-transparent.png",
                    Title       = "您输入了:" + requestMessage.Content,
                    Url         = "https://sdk.weixin.senparc.com/"
                };

                responseMessage.Articles.Add(article);

                return(responseMessage);
            }).Keyword("123", () =>
            {
                var responseMessage = this.CreateResponseMessage <ResponseMessageText>();

                responseMessage.Content = "关键字回复:" + requestMessage.Content;

                return(responseMessage);
            }).Default(() =>
            {
                var responseMessage = this.CreateResponseMessage <ResponseMessageText>();

                responseMessage.Content = "您输入了文字:" + requestMessage.Content;

                return(responseMessage);
            });


            return(keyWordHandler.ResponseMessage);
        }
Example #7
0
        public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
        {
            //说明:实际项目中这里的逻辑可以交给Service处理具体信息,参考OnLocationRequest方法或/Service/LocationSercice.cs
            var defaultResponseMessage = base.CreateResponseMessage <ResponseMessageText>();

            var requestHandler = requestMessage.StartHandler();

            requestHandler.Keywords(new string[] { "使用指南", "使用", "使用手册", "如何使用" }, () =>
            {
                var responseMessage          = ResponseMessageBase.CreateFromRequestMessage <ResponseMessageNews>(requestMessage);
                responseMessage.ArticleCount = 1;
                responseMessage.Articles.Add(GetPicSubscribe());
                return(responseMessage);
            });
            //requestHandler.Keywords(new string[] { "转载须知"}, () =>
            //{
            //    var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageNews>(requestMessage);
            //    responseMessage.ArticleCount = 1;
            //    responseMessage.Articles.Add(GetPicZhuanZaiXuZhi());
            //    return responseMessage;
            //});
            foreach (var item in this.MessageInfo.KeyWords)
            {
                //if (item.Key == "客户电话")
                //{
                //    requestHandler.Default(() =>
                //    {
                //        var responseMessage = this.CreateResponseMessage<ResponseMessageText>();
                //        responseMessage.Content = this.MessageInfo.KeyWords["客户电话"];
                //        //var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageNews>(requestMessage);
                //        //responseMessage.ArticleCount = 1;
                //        //responseMessage.Articles.Add(GetPicSubscribe());
                //        return responseMessage;
                //    });
                //}
                if (item.Key == "默认")
                {
                    requestHandler.Default(() =>
                    {
                        //var responseMessage = this.CreateResponseMessage<ResponseMessageText>();
                        //responseMessage.Content = this.MessageInfo.KeyWords["默认"];
                        var responseMessage          = ResponseMessageBase.CreateFromRequestMessage <ResponseMessageNews>(requestMessage);
                        responseMessage.ArticleCount = 1;
                        responseMessage.Articles.Add(GetPicSubscribe());
                        return(responseMessage);
                    });
                }
                else
                {
                    //如果有逗号表示数组
                    if (item.Key.Contains(','))
                    {
                        requestHandler.Keywords(item.Key.Split(','), () =>
                        {
                            var responseMessage     = this.CreateResponseMessage <ResponseMessageText>();
                            responseMessage.Content = item.Value;
                            return(responseMessage);
                        });
                    }
                    //表示关键字
                    else
                    {
                        requestHandler.Keyword(item.Key, () =>
                        {
                            var responseMessage     = this.CreateResponseMessage <ResponseMessageText>();
                            responseMessage.Content = item.Value;
                            return(responseMessage);
                        });
                    }
                }
            }
            foreach (var item in this.MessageInfo.KeyWordsPic)
            {
                if (item.Key == "默认")
                {
                    requestHandler.Default(() =>
                    {
                        //var responseMessage = this.CreateResponseMessage<ResponseMessageText>();
                        //responseMessage.Content = this.MessageInfo.KeyWords["默认"];
                        var responseMessage          = ResponseMessageBase.CreateFromRequestMessage <ResponseMessageNews>(requestMessage);
                        responseMessage.ArticleCount = 1;
                        responseMessage.Articles.Add(GetPicSubscribe());
                        return(responseMessage);
                    });
                }
                else
                {
                    requestHandler.Keyword(item.Key, () =>
                    {
                        var responseMessage          = ResponseMessageBase.CreateFromRequestMessage <ResponseMessageNews>(requestMessage);
                        responseMessage.ArticleCount = 1;
                        responseMessage.Articles.Add(item.Value);
                        return(responseMessage);
                    });
                }
            }
            return(requestHandler.GetResponseMessage() as IResponseMessageBase);
        }
Example #8
0
        /// <summary>
        /// 处理文字请求
        /// </summary>
        /// <returns></returns>
        public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
        {
            //说明:实际项目中这里的逻辑可以交给Service处理具体信息,参考OnLocationRequest方法或/Service/LocationSercice.cs

            #region 书中例子
            //if (requestMessage.Content == "你好")
            //{
            //    var responseMessage = base.CreateResponseMessage<ResponseMessageNews>();
            //    var title = "Title";
            //    var description = "Description";
            //    var picUrl = "PicUrl";
            //    var url = "Url";
            //    responseMessage.Articles.Add(new Article()
            //    {
            //        Title = title,
            //        Description = description,
            //        PicUrl = picUrl,
            //        Url = url
            //    });
            //    return responseMessage;
            //}
            //else if (requestMessage.Content == "Senparc")
            //{
            //    //相似处理逻辑
            //}
            //else
            //{
            //    //...
            //}

            #endregion

            #region 历史方法

            //方法一(v0.1),此方法调用太过繁琐,已过时(但仍是所有方法的核心基础),建议使用方法二到四
            //var responseMessage =
            //    ResponseMessageBase.CreateFromRequestMessage(RequestMessage, ResponseMsgType.Text) as
            //    ResponseMessageText;

            //方法二(v0.4)
            //var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(RequestMessage);

            //方法三(v0.4),扩展方法,需要using Senparc.Weixin.MP.Helpers;
            //var responseMessage = RequestMessage.CreateResponseMessage<ResponseMessageText>();

            //方法四(v0.6+),仅适合在HandlerMessage内部使用,本质上是对方法三的封装
            //注意:下面泛型ResponseMessageText即返回给客户端的类型,可以根据自己的需要填写ResponseMessageNews等不同类型。

            #endregion

            var defaultResponseMessage = base.CreateResponseMessage <ResponseMessageText>();

            var requestHandler =
                requestMessage.StartHandler()
                //关键字不区分大小写,按照顺序匹配成功后将不再运行下面的逻辑
                .Keyword("笑话", () =>
            {
                    << << << < HEAD
                    defaultResponseMessage.Content = Senparc.Weixin.MP.Sample.CommonService.JuHeAPI.JuHe.GetXiaohua("笑话");
                return(defaultResponseMessage);
            }).LikeKeyword("图", () =>
        /// <summary>
        /// 处理文字请求
        /// </summary>
        /// <param name="requestMessage">请求消息</param>
        /// <returns></returns>
        public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
        {
            //说明:实际项目中这里的逻辑可以交给Service处理具体信息,参考OnLocationRequest方法或/Service/LocationSercice.cs

            #region 书中例子
            //if (requestMessage.Content == "你好")
            //{
            //    var responseMessage = base.CreateResponseMessage<ResponseMessageNews>();
            //    var title = "Title";
            //    var description = "Description";
            //    var picUrl = "PicUrl";
            //    var url = "Url";
            //    responseMessage.Articles.Add(new Article()
            //    {
            //        Title = title,
            //        Description = description,
            //        PicUrl = picUrl,
            //        Url = url
            //    });
            //    return responseMessage;
            //}
            //else if (requestMessage.Content == "Senparc")
            //{
            //    //相似处理逻辑
            //}
            //else
            //{
            //    //...
            //}

            #endregion

            #region 历史方法

            //方法一(v0.1),此方法调用太过繁琐,已过时(但仍是所有方法的核心基础),建议使用方法二到四
            //var responseMessage =
            //    ResponseMessageBase.CreateFromRequestMessage(RequestMessage, ResponseMsgType.Text) as
            //    ResponseMessageText;

            //方法二(v0.4)
            //var responseMessage = ResponseMessageBase.CreateFromRequestMessage<ResponseMessageText>(RequestMessage);

            //方法三(v0.4),扩展方法,需要using Senparc.Weixin.MP.Helpers;
            //var responseMessage = RequestMessage.CreateResponseMessage<ResponseMessageText>();

            //方法四(v0.6+),仅适合在HandlerMessage内部使用,本质上是对方法三的封装
            //注意:下面泛型ResponseMessageText即返回给客户端的类型,可以根据自己的需要填写ResponseMessageNews等不同类型。

            #endregion

            var defaultResponseMessage = base.CreateResponseMessage <ResponseMessageText>();

            var requestHandler =
                requestMessage.StartHandler()
                //关键字不区分大小写,按照顺序匹配成功后将不再运行下面的逻辑
                .Keyword("约束", () =>
            {
                defaultResponseMessage.Content =
                    @"您正在进行微信内置浏览器约束判断测试。您可以:
<a href=""https://sdk.weixin.senparc.com/FilterTest/"">点击这里</a>进行客户端约束测试(地址:https://sdk.weixin.senparc.com/FilterTest/),如果在微信外打开将直接返回文字。
或:
<a href=""https://sdk.weixin.senparc.com/FilterTest/Redirect"">点击这里</a>进行客户端约束测试(地址:https://sdk.weixin.senparc.com/FilterTest/Redirect),如果在微信外打开将重定向一次URL。";
                return(defaultResponseMessage);
            })
                //匹配任一关键字
                .Keywords(new[] { "测试", "退出" }, () =>
            {
                /*
                 * 这是一个特殊的过程,此请求通常来自于微微嗨(http://www.weiweihi.com)的“盛派网络小助手”应用请求(https://www.weiweihi.com/User/App/Detail/1),
                 * 用于演示微微嗨应用商店的处理过程,由于微微嗨的应用内部可以单独设置对话过期时间,所以这里通常不需要考虑对话状态,只要做最简单的响应。
                 */
                if (requestMessage.Content == "测试")
                {
                    //进入APP测试
                    defaultResponseMessage.Content = "您已经进入测试程序,请发送任意信息进行测试。发送文字【退出】退出测试对话。10分钟内无任何交互将自动退出应用对话状态。";
                }
                else
                {
                    //退出APP测试
                    defaultResponseMessage.Content = "您已经退出测试程序。";
                }
                return(defaultResponseMessage);
            })
                .Keyword("容错", () =>
            {
                Thread.Sleep(4900);    //故意延时1.5秒,让微信多次发送消息过来,观察返回结果
                var faultTolerantResponseMessage     = requestMessage.CreateResponseMessage <ResponseMessageText>();
                faultTolerantResponseMessage.Content = string.Format("测试容错,MsgId:{0},Ticks:{1}", requestMessage.MsgId,
                                                                     SystemTime.Now.Ticks);
                return(faultTolerantResponseMessage);
            })
                .Keyword("TM", () =>
            {
                var openId    = requestMessage.FromUserName;
                var checkCode = Guid.NewGuid().ToString("n").Substring(0, 3);    //为了防止openId泄露造成骚扰,这里启用验证码
                TemplateMessageCollection[checkCode] = openId;
                defaultResponseMessage.Content       = string.Format(@"新的验证码为:{0},请在网页上输入。http://www.baidu.com", checkCode);
                return(defaultResponseMessage);
            })
                .Keyword("OPENID", () =>
            {
                var openId   = requestMessage.FromUserName;  //获取OpenId
                var userInfo = Senparc.Weixin.MP.AdvancedAPIs.UserApi.Info(appId, openId);

                defaultResponseMessage.Content = string.Format(
                    "您的OpenID为:{0}\r\n昵称:{1}\r\n性别:{2}\r\n地区(国家/省/市):{3}/{4}/{5}\r\n关注时间:{6}\r\n关注状态:{7}",
                    requestMessage.FromUserName, userInfo.nickname, (WeixinSex)userInfo.sex, userInfo.country, userInfo.province, userInfo.city, DateTimeHelper.GetDateTimeFromXml(userInfo.subscribe_time), userInfo.subscribe);
                return(defaultResponseMessage);
            })
                .Keyword("EX", () =>
            {
                var ex = new WeixinException("openid:" + requestMessage.FromUserName + ":这是一条测试异常信息");    //回调过程在global的ConfigWeixinTraceLog()方法中
                defaultResponseMessage.Content = "请等待异步模板消息发送到此界面上(自动延时数秒)。\r\n当前时间:" + SystemTime.Now.ToString();
                return(defaultResponseMessage);
            })
                .Keyword("MUTE", () => //不回复任何消息
            {
                //方案一:
                return(new SuccessResponseMessage());

                //方案二:
                var muteResponseMessage = base.CreateResponseMessage <ResponseMessageNoResponse>();
                return(muteResponseMessage);

                //方案三:
                base.TextResponseMessage = "success";
                return(null);

                //方案四:
                return(null);   //在 Action 中结合使用 return new FixWeixinBugWeixinResult(messageHandler);
            })
                .Keyword("JSSDK", () =>
            {
                defaultResponseMessage.Content = "点击打开:https://sdk.weixin.senparc.com/WeixinJsSdk";
                return(defaultResponseMessage);
            })


                ////选择菜单,关键字:101(微信服务器端最终格式:id="s:101",content="满意")
                //.SelectMenuKeyword("101", () =>
                //{
                //    defaultResponseMessage.Content = $"感谢您的评价({requestMessage.Content})!我们会一如既往为提高企业和开发者生产力而努力!";
                //    return defaultResponseMessage;
                //})
                ////选择菜单,关键字:102(微信服务器端最终格式:id="s:102",content="一般")
                //.SelectMenuKeyword("102", () =>
                //{
                //    defaultResponseMessage.Content = $"感谢您的评价({requestMessage.Content})!希望我们的服务能让您越来越满意!";
                //    return defaultResponseMessage;
                //})
                ////选择菜单,关键字:103(微信服务器端最终格式:id="s:103",content="不满意")
                //.SelectMenuKeyword("103", () =>
                //{
                //    defaultResponseMessage.Content = $"感谢您的评价({requestMessage.Content})!我们需要您的意见或建议,欢迎向我们反馈! <a href=\"https://github.com/JeffreySu/WeiXinMPSDK/issues/new\">点击这里</a>";
                //    return defaultResponseMessage;
                //})
                //.SelectMenuKeywords(new[] { "110", "111" }, () =>
                //{
                //    defaultResponseMessage.Content = $"这里只是演示,可以同时支持多个选择菜单";
                //    return defaultResponseMessage;
                //})

                //Default不一定要在最后一个
                .Default(() =>
            {
                var result = new StringBuilder();
                result.AppendFormat("您刚才发送了文字信息:{0}\r\n\r\n", requestMessage.Content);

                if (CurrentMessageContext.RequestMessages.Count > 1)
                {
                    result.AppendFormat("您刚才还发送了如下消息({0}/{1}):\r\n", CurrentMessageContext.RequestMessages.Count,
                                        CurrentMessageContext.StorageData);
                    for (int i = CurrentMessageContext.RequestMessages.Count - 2; i >= 0; i--)
                    {
                        var historyMessage = CurrentMessageContext.RequestMessages[i];
                        result.AppendFormat("{0} 【{1}】{2}\r\n",
                                            historyMessage.CreateTime.ToString("HH:mm:ss"),
                                            historyMessage.MsgType.ToString(),
                                            (historyMessage is RequestMessageText)
                                    ? (historyMessage as RequestMessageText).Content
                                    : "[非文字类型]"
                                            );
                    }
                    result.AppendLine("\r\n");
                }

                result.AppendFormat("如果您在{0}分钟内连续发送消息,记录将被自动保留(当前设置:最多记录{1}条)。过期后记录将会自动清除。\r\n",
                                    GlobalMessageContext.ExpireMinutes, GlobalMessageContext.MaxRecordCount);
                result.AppendLine("\r\n");
                result.AppendLine(
                    "您还可以发送【位置】【图片】【语音】【视频】等类型的信息(注意是这几种类型,不是这几个文字),查看不同格式的回复。\r\n");

                defaultResponseMessage.Content = result.ToString();

                return(defaultResponseMessage);
            })
                //“一次订阅消息”接口测试
                //.Keyword("订阅", () =>
                //{
                //    defaultResponseMessage.Content = "点击打开:https://sdk.weixin.senparc.com/SubscribeMsg";
                //    return defaultResponseMessage;
                //})
                //正则表达式
                .Regex(@"^\d+#\d+$", () =>
            {
                defaultResponseMessage.Content = string.Format("您输入了:{0},符合正则表达式:^\\d+#\\d+$", requestMessage.Content);
                return(defaultResponseMessage);
            });

            return(requestHandler.GetResponseMessage() as IResponseMessageBase);
        }
        /// <summary>
        /// 根据用户发送的消息,返回消息
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns></returns>
        public override IResponseMessageBase OnTextRequest(RequestMessageText requestMessage)
        {
            //IResponseMessageBase responseMessage = null;

            ////输入cmd 进入cmd状态 , exit退出cmd状态
            //if (requestMessage.Content == "cmd")
            //{
            //    CurrentMessageContext.StorageData = new StorageModel()
            //    {
            //        IsInCmd = true
            //    };
            //}
            //if (requestMessage.Content == "exit")
            //{
            //    var storageModel = CurrentMessageContext.StorageData as StorageModel;
            //    if (storageModel != null)
            //    {
            //        storageModel.IsInCmd = false;
            //    }
            //}

            //根据关键字、正则表达式,返回不同的消息内容
            RequestMessageTextKeywordHandler handler = requestMessage.StartHandler()
                                                       .Keyword("cmd", () =>
            {
                var responseMessageText = requestMessage.CreateResponseMessage <ResponseMessageText>();

                CurrentMessageContext.StorageData = new StorageModel()
                {
                    IsInCmd = true
                };
                responseMessageText.Content += "\r\n您已进入cmd模式";

                return(responseMessageText);
            })
                                                       .Keyword("电子卡", () =>
            {
                CustomApi.SendCard(Config.AppId, WeixinOpenId, "pifDGvpJKLpOc2vQxZHPslkxItqw", null, 10000);
                return(new ResponseMessageNoResponse());
            })
                                                       .Keywords(new[] { "exit", "close", "quit" }, () =>
            {
                var responseMessageText = requestMessage.CreateResponseMessage <ResponseMessageText>();

                CurrentMessageContext.StorageData = new StorageModel()
                {
                    IsInCmd = false
                };
                responseMessageText.Content += "\r\n您已退出cmd模式";

                return(responseMessageText);
            }).Regex(@"天气 \S+", () =>
            {
                //Get Json Result 获取天气信息。 正则表达式 使用
                var city = Regex.Match(requestMessage.Content, @"(?<=天气 )(\S+)").Value;
                var url  = "https://www.sojson.com/open/api/weather/json.shtml?city={0}".FormatWith(city.UrlEncode());

                //直接返回Json结果
                var weatherResult = Get.GetJson <WeatherResult>(url, null, null);

                var responseMessageText     = requestMessage.CreateResponseMessage <ResponseMessageText>();
                responseMessageText.Content = @"天气查询结果
==========
城市:{0}的天气信息
时期:{1}
结果:{2}
时间:{3}".FormatWith(weatherResult.city, weatherResult.date,
                   weatherResult.message, weatherResult.AddTime);

                return(responseMessageText);
            }).Regex(@"^http", () =>
            {
                var responseMessageNews = requestMessage.CreateResponseMessage <ResponseMessageNews>();
                var articleNew          = new Article()
                {
                    Title       = "您输入了" + requestMessage.Content,
                    PicUrl      = "http://sdk.weixin.senparc.com/images/book-cover-front-small-3d-transparent.png",
                    Url         = "http://www.baidu.com",
                    Description = "这是一篇文章\r\n换行了\r\n哈哈",
                };
                responseMessageNews.Articles.Add(articleNew);

                return(responseMessageNews);
            }).Default(() =>
            {
                var responseMessageText     = requestMessage.CreateResponseMessage <ResponseMessageText>();
                responseMessageText.Content = "这是一条默认的消息回复";
                return(responseMessageText);
            });

            //如果输入的是文字,再回复中添加输入的文字
            var responseMessage = handler.ResponseMessage;

            if (responseMessage is ResponseMessageText)
            {
                var storageModel = CurrentMessageContext.StorageData as StorageModel;
                if (storageModel != null)
                {
                    requestMessage.Content += "\r\nCount:" + storageModel.CmdCount.ToString();
                }

                (responseMessage as ResponseMessageText).Content += "\r\n您输入了:" + requestMessage.Content;
            }

            //返回内容转为基类
            return(responseMessage as IResponseMessageBase);
        }
Example #11
0
        /// <summary>
        /// 处理文字请求
        /// </summary>
        /// <param name="requestMessage">请求消息</param>
        /// <returns></returns>
        public override async Task <IResponseMessageBase> OnTextRequestAsync(RequestMessageText requestMessage)
        {
            var defaultResponseMessage = base.CreateResponseMessage <ResponseMessageText>();
            IResponseMessageBase IR    = null;

            Common.MessageFunction cmfun = new Common.MessageFunction();
            int ruleId = 0;

            var requestHandler = await requestMessage.StartHandler().Default(async() =>
            {
                string keywords = requestMessage.Content;
                if (!string.IsNullOrEmpty(keywords))
                {
                    keywords = keywords.Trim();
                }

                var currentMessageContext = await base.GetCurrentMessageContext();

                //先精确匹配,再模糊匹配
                Core.WeixinRequestRule rule = Core.WeixinRequestRule.Find(Core.WeixinRequestRule._.Keywords == keywords & Core.WeixinRequestRule._.RequestType == (int)Core.WeixinRequestRule.XRequestType.Text);

                if (rule == null)
                {
                    //模糊匹配
                    IList <Core.WeixinRequestRule> listRule = Core.WeixinRequestRule.FindAll(Core.WeixinRequestRule._.RequestType == (int)Core.WeixinRequestRule.XRequestType.Text & Core.WeixinRequestRule._.IsLikeQuery == 1, null, null, 0, 0);
                    if (listRule != null && listRule.Count > 0)
                    {
                        int lenKeyword = keywords.Length;
                        foreach (var item in listRule)
                        {
                            if (lenKeyword >= item.Keywords.Length && keywords.IndexOf(item.Keywords) >= 0)
                            {
                                rule = item;//规则
                                break;
                            }
                        }
                    }
                }
                if (rule == null)
                {
                    Core.WeixinRequestRule notFindKeywordRule = Core.WeixinRequestRule.Find(Core.WeixinRequestRule._.RequestType == (int)Core.WeixinRequestRule.XRequestType.NotFindKeyword);
                    if (notFindKeywordRule == null)
                    {
                        //找不到规则
                        Core.WeixinResponseContent entity = new Core.WeixinResponseContent()
                        {
                            OpenId         = requestMessage.FromUserName,
                            RequestType    = requestMessage.MsgType.ToString(),
                            RequestContent = requestMessage.Content,
                            ResponseType   = "none",
                            ReponseContent = "未取到关键词对应的数据",
                            XmlContent     = requestMessage.ToUserName
                        };
                        entity.Insert();
                        return(cmfun.GetResponseMessageTxtByContent(requestMessage, "未找到匹配的关键词", 0));
                    }
                    else
                    {
                        ruleId = notFindKeywordRule.Id;
                        switch (notFindKeywordRule.ResponseType)
                        {
                        case (int)Core.WeixinRequestRule.XResponseType.Text:
                            //发送纯文字
                            IR = cmfun.GetResponseMessageTxt(requestMessage, ruleId, 0);
                            break;

                        case (int)Core.WeixinRequestRule.XResponseType.Image:
                            //发送多图文
                            IR = cmfun.GetResponseMessageNews(requestMessage, ruleId, 0);
                            break;

                        case (int)Core.WeixinRequestRule.XResponseType.Voice:
                            //发送语音
                            IR = cmfun.GetResponseMessageeMusic(requestMessage, ruleId, 0);
                            break;

                        case (int)Core.WeixinRequestRule.XResponseType.SingleImage:
                            IR = cmfun.GetResponseMessageSingleImagesContent(requestMessage, ruleId, 0);
                            break;

                        default:
                            break;
                        }
                        return(IR);
                    }
                }
                Core.WeixinResponseContent model = new Core.WeixinResponseContent()
                {
                    OpenId         = requestMessage.FromUserName,
                    RequestType    = requestMessage.MsgType.ToString(),
                    RequestContent = requestMessage.Content,
                    ResponseType   = Core.WeixinResponseContent.GetResponseType((int)requestMessage.MsgType),
                    ReponseContent = requestMessage.ToString(),
                    XmlContent     = string.Empty
                };
                model.Insert();


                return(IR);
            });

            return(requestHandler.GetResponseMessage() as IResponseMessageBase);
        }