Пример #1
0
        public static WxAccessToken CreateToken(string appId, string appSecret)
        {
            "使用自有微信令牌获取功能".WriteWarningLine();
            if (token.ContainsKey(appId))
            {
                var tres = token[appId];
                if (tres.expires_time > DateTimeOffset.Now)
                {
                    return(tres);
                }
            }

            var wc  = new WebClientLy();
            var url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appId}&secret={appSecret}";

            $"访问{url}".WriteWarningLine();
            var accessTokenJson = wc.DownloadString(url);

            $"结果{accessTokenJson}".WriteWarningLine();
            var res = Newtonsoft.Json.JsonConvert.DeserializeObject <WxAccessToken>(accessTokenJson);

            lock (token)
            {
                if (token.ContainsKey(appId))
                {
                    token.Remove(appId);
                }
                token.Add(appId, res);
            }
            return(res);
        }
Пример #2
0
        /// <summary>
        /// 客服主动发送消息
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="text"></param>
        /// <param name="cache"></param>
        /// <returns></returns>
        public ExecuteResult <bool> SendTextMsg(string openid, string text)
        {
            ExecuteResult <bool> result = new ExecuteResult <bool>();
            //Console.WriteLine($"参数>{AppSettings.AppId} {AppSettings.AppSecret}");
            var wxtoken = WxAccessToken.GetToken(WechatMpSettings.Default.AppId, WechatMpSettings.Default.AppSecret);

            if (wxtoken.errcode != 0)
            {
                return(result.SetFail(wxtoken.errmsg));
            }
            var    url   = SendUrl.Replace("$access_token$", wxtoken.access_token);
            var    wc    = new WebClientLy();
            var    msg   = $@"{{
    ""touser"":""{openid}"",
    ""msgtype"":""text"",
    ""text"":
    {{
                ""content"":""{text}""
    }}
}}";
            string upmsg = msg;

            ////加密信息
            //if (Encrypt_type == "aes")
            //{
            //    var rTimeStamp = DateTime.Now.GetTimestamp10();
            //    var rNonce = RandomString.BuildRndString(16);
            //    string restr = null;
            //    var rb = WxCrypt.EncryptMsg(msg, rTimeStamp + "", rNonce, ref restr);
            //    if (rb == 0)
            //    {
            //        upmsg = restr;
            //    }
            //    else
            //    {
            //        $"{rb} EncryptMsg".WriteErrorLine();
            //    }
            //}
            //LogService.AnyLog("WeChatWebHook", "客服密数据", $"{upmsg}");

            var            res  = wc.UploadString(url, upmsg);
            SentSponseInfo sent = Newtonsoft.Json.JsonConvert.DeserializeObject <SentSponseInfo>(res);

            if (sent.errcode == 0)
            {
                return(result.SetData(true).SetOk());
            }
            else
            {
                if (sent.errcode == 48001)
                {
                    AccessSendMsg = false;
                }
                return(result.SetData(false).SetFail(sent.errmsg));
            }
        }
Пример #3
0
        /// <summary>
        /// 获取网站授权令牌
        /// </summary>
        /// <param name="webcode"></param>
        /// <param name="appid"></param>
        /// <param name="appsecrete"></param>
        /// <returns></returns>
        public static WxAccessToken GetWxWebToken(string webcode, string appid, string appsecret)
        {
            var         apiurl = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={appsecret}&code={webcode}&grant_type=authorization_code";
            WebClientLy wc     = new WebClientLy();
            var         rejson = wc.DownloadString(apiurl);

            LogService.AnyLog("WxWebToken", rejson);
            var res = Newtonsoft.Json.JsonConvert.DeserializeObject <WxAccessToken>(rejson);

            if (res != null)
            {
                lock (webtoken)
                {
                    if (webtoken.ContainsKey(res.openid))
                    {
                        webtoken.Remove(res.openid);
                    }
                    webtoken.Add(res.openid, res);
                }
            }
            return(res);
        }
Пример #4
0
        /// <summary>
        /// 客服主动发送消息
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="text"></param>
        /// <param name="cache"></param>
        /// <returns></returns>
        public ExecuteResult <bool> SendTextMsg(string openid, string text)
        {
            ExecuteResult <bool> result = new ExecuteResult <bool>();
            //Console.WriteLine($"参数>{AppSettings.AppId} {AppSettings.AppSecret}");
            var wxtoken = WxAccessToken.GetToken(WechatMpSettings.Default.AppId, WechatMpSettings.Default.AppSecret);

            if (wxtoken.errcode != 0)
            {
                return(result.SetFail(wxtoken.errmsg));
            }
            var url = SendUrl.Replace("$access_token$", wxtoken.access_token);
            var wc  = new WebClientLy();
            var msg = $@"{{
    ""touser"":""{openid}"",
    ""msgtype"":""text"",
    ""text"":
    {{
                ""content"":""{text}""
    }}
}}";
            var res = wc.UploadString(url, msg);

            return(result.SetOk(res));
        }
Пример #5
0
        public WechatResponse Rebot()
        {
            var dtnow   = DateTime.Now;
            var dtday_1 = dtnow.AddDays(-1);

            try
            {
                switch (PostWxMsgType)
                {
                //文本
                case WxMsgType.TEXT:
                {
                    RebotContext    rc     = null;
                    string          rcrkey = null;
                    RebotChatRecord rcr    = null;
                    var             from   = xdict["FromUserName"];
                    if (rcdict.ContainsKey(from))
                    {
                        rc = rcdict[from];
                    }
                    else
                    {
                        rc = new RebotContext(from);
                    }

                    var botres = MLAiBot.Default.Processing(PostContent);
                    if (botres.IsOk)
                    {
                        _ = GetTextResponse(botres.Msg);
                        return(this);
                    }

                    //数字
                    if (dblBodyRegex.IsMatch(PostContent))
                    {
                        var val = 0d;
                        double.TryParse(PostContent, out val);
                        string res = null;
                        switch (val)
                        {
                        //不处理
                        case 1:
                            //return GetEmptyResponse();
                            break;

                        //原文返回
                        case 88:
                        case 886:
                        case 3166:
                            res = PostContent;
                            //return GetTextResponse(PostContent);
                            break;

                        default:
                            res = PostContent;
                            break;
                        }

                        if (string.IsNullOrEmpty(res))
                        {
                            _ = GetEmptyResponse();
                        }
                        else
                        {
                            _ = GetTextResponse(res);
                        }


                        if (rcr != null)
                        {
                            rcr.Records.Add(new ChatRecordInfo()
                                {
                                    Q = PostContent,
                                    A = Content,
                                    T = "数字",
                                    P = 1,
                                    //RT = -1,
                                    DT = DateTime.Now,
                                });
                        }

                        return(this);
                    }

                    //算术表达式
                    if (ArithmeticRegex.IsMatch(PostContent))
                    {
                        var res = rc.Exp_Cal_Async(PostContent).Result;
                        if (res.IsOk)
                        {
                            _ = GetTextResponse(res);
                        }

                        if (rcr != null)
                        {
                            rcr.Records.Add(new ChatRecordInfo()
                                {
                                    Q = PostContent,
                                    A = Content,
                                    T = "算术",
                                    P = 1,
                                    //RT= dtday_1,
                                    DT = DateTime.Now,
                                    IM = 0.01,
                                });
                            //cache.Replace(rcrkey, rcr);
                        }
                        if (res.IsOk)
                        {
                            return(this);
                        }
                    }


                    //闹钟服务
                    var alaim = setAlaim1.Match(PostContent);
                    if (alaim == null)
                    {
                        alaim = setAlaim2.Match(PostContent);
                    }
                    if (alaim != null && rc != null)
                    {
                        rc.ServiceType = ServiceTypeCode.闹钟服务;
                    }
                    if (alaim != null && rc != null && rc.ServiceType == ServiceTypeCode.闹钟服务)
                    {
                        if (!WechatCustomService.Default.AccessSendMsg)
                        {
                            _ = GetTextResponse($"抱歉,当前小玉无权向您主动发送消息,所以无法为您提供闹钟服务。");
                            return(this);
                        }

                        var time = -1;
                        int.TryParse(alaim.Groups["time"]?.Value, out time);
                        if (time > 0)
                        {
                            var      unit   = alaim.Groups["unit"].Value;
                            var      dothin = alaim.Groups["do"].Value;
                            DateTime dt     = DateTime.MinValue;
                            if (unit == "秒")
                            {
                                dt = DateTime.Now.AddSeconds(time);
                            }
                            else if (unit == "分钟")
                            {
                                dt = DateTime.Now.AddMinutes(time);
                            }
                            else if (unit == "小时")
                            {
                                dt = DateTime.Now.AddHours(time);
                            }

                            //添加 任务
                            WechatCustomService.Default.Enqueue(() =>
                                {
                                    //LogService.AnyLog("MLBot", "执行提醒服务");

                                    if (DateTime.Now >= dt)
                                    {
                                        var sentres = WechatCustomService.Default.SendTextMsg(xdict["FromUserName"], $"您让我{time}{unit}提醒您{dothin},现在时间已经到了!");
                                        if (!sentres.IsOk)
                                        {
                                            LogService.AnyLog("WeChatKF", "提醒服务", sentres.Code.ToString(), sentres.Msg);
                                        }
                                        return(true);
                                    }
                                    else
                                    {
                                        return(false);
                                    }
                                });
                            _ = GetTextResponse($"{time}{unit}后提醒您{dothin},闹钟设置已完成");

                            if (rcr != null)
                            {
                                rcr.Records.Add(new ChatRecordInfo()
                                    {
                                        Q  = PostContent,
                                        A  = Content,
                                        T  = "设定闹钟",
                                        P  = 1,
                                        RT = dtday_1,
                                        DT = DateTime.Now,
                                        IM = 0.01,
                                    });
                            }
                            return(this);
                        }
                    }

                    //招呼
                    if (new Regex(regHeaderString + "[你您]好[!.。!,,]" + regEnderString, RegexOptions.Compiled).IsMatch(PostContent))
                    {
                        _ = GetTextResponse("您好,我是小玉,正在为您服务!");
                        if (rcr != null)
                        {
                            rcr.Records.Add(new ChatRecordInfo()
                                {
                                    Q = PostContent,
                                    A = Content,
                                    T = "被招呼",
                                    P = 1,
                                    //RT = dtday_1,
                                    DT = DateTime.Now,
                                    IM = 0.01,
                                });
                        }
                        return(this);
                    }

                    //回应感谢
                    if (new Regex(regHeaderString + "谢谢[您你]?[啦了]?[!.。!,,]" + regEnderString, RegexOptions.Compiled).IsMatch(PostContent))
                    {
                        _ = GetTextResponse("能为您服务,是小玉的荣幸!");
                        if (rcr != null)
                        {
                            rcr.Records.Add(new ChatRecordInfo()
                                {
                                    Q = PostContent,
                                    A = Content,
                                    T = "被感谢",
                                    P = 1,
                                    //RT = -1,
                                    DT = DateTime.Now,
                                    IM = 0.01,
                                });
                        }
                        return(this);
                    }

                    //再见
                    if (new Regex(regHeaderString + "再见[啦了]?[!.。!,,]" + regEnderString, RegexOptions.Compiled).IsMatch(PostContent))
                    {
                        _ = GetTextResponse("能为您服务,是小玉的荣幸,期待您的再次光临!");
                        if (rcr != null)
                        {
                            rcr.Records.Add(new ChatRecordInfo()
                                {
                                    Q = PostContent,
                                    A = Content,
                                    T = "被再见",
                                    P = 1,
                                    //RT = -1,
                                    DT = DateTime.Now,
                                    IM = 0.01,
                                });
                        }
                        return(this);
                    }

                    ////意图或问题分类
                    //var words = LinyeeNLAnalyzer.Default.WordAnalyJieba(PostContent.ToLower()).Data;//暂时全转小写
                    //var yt = 0;

                    ////根据意图不同使用不同类型
                    //var s2s = s2ses[yt];
                    //switch (yt)
                    //{
                    //    case 0:
                    //    default:
                    //        var sres= s2s.Predict(words);
                    //        LogService.AnyLog("WxRebotNoSuper","seq2seq预测", $"{sres.ToJsonString()}");
                    //        if (sres.IsOk)
                    //        {
                    //            _ = GetTextResponse(string.Join("",sres.Data));
                    //            if (rcr != null)
                    //            {
                    //                rcr.Records.Add(new ChatRecordInfo()
                    //                {
                    //                    Q = PostContent,
                    //                    A = Content,
                    //                    T = "对话",
                    //                    P = 0,
                    //                    //RT = -1,
                    //                    DT = DateTime.Now,
                    //                    IM = 0.01,
                    //                });
                    //            }
                    //            return this;
                    //        }
                    //        break;
                    //}


                    //微信对话
                    {
                        var signedData  = jwt.Encode(new { username = fromuser, msg = PostContent }, WxopenAISettings.Default.EncodingAESKey);
                        var postjwtdata = "query=" + signedData;

                        var wc = new WebClientLy();
                        try
                        {
                            LogService.AnyLog("wxopenai", "提交参数", postjwtdata);
                            wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
                            var resjson = wc.UploadString("https://openai.weixin.qq.com/openapi/message/" + WxopenAISettings.Default.TOKEN, postjwtdata);
                            LogService.AnyLog("wxopenai", "响应参数", resjson);
                            var res = Newtonsoft.Json.JsonConvert.DeserializeObject <WxopenAIMessageSponseInfo>(resjson);
                            _ = GetTextResponse(res.answer);
                            return(this);
                        }
                        catch (Exception ex)
                        {
                            //res = new { ex.Message, Details = ex.ToString() }.ToJson();
                        }
                    }


                    //不能处理
                    LogService.AnyLog("WxRebotNoSuper", $@"小玉未能处理信息:{PostXml}");
                    _ = GetTextResponse($@"亲,小玉暂时不能理解您的信息,已收妥保存信息。请切换服务方式或通过其它途径获得解答。");

                    if (rcr != null)
                    {
                        rcr.Records.Add(new ChatRecordInfo()
                            {
                                Q = PostContent,
                                A = Content,
                                T = "未处理",
                                P = 1,
                                //RT = -1,
                                DT = DateTime.Now,
                                IM = 0.01,
                            });
                    }
                    return(this);
                }

                //事件
                case WxMsgType.EVENT:
                {
                    switch (PostWxEvent)
                    {
                    //关注
                    case WxEventType.SUBSCRIBE:
                        return(GetTextResponse($@"欢迎回家!!我是小玉,可以为您提供很多服务哦!"));

                    //取消关注
                    case WxEventType.UNSUBSCRIBE:
                        return(GetTextResponse($@"亲,小玉都很舍不得您!!记得常回来看看哦!"));

                    //菜单处理
                    case WxEventType.CLICK:
                        return(GetResponseFromMenu(PostEventKey));

                    //不处理
                    case WxEventType.TEMPLATESENDJOBFINISH:
                        return(GetEmptyResponse());

                    //url跳转
                    case WxEventType.VIEW:
                        return(GetEmptyResponse());

                    //不能处理
                    case WxEventType.SCAN:
                    case WxEventType.LOCATION:
                    case WxEventType.NONE:
                    default:
                        LogService.AnyLog("WxRebotNoSuper", $@"小玉未能处理信息:{PostXml}");
                        return(GetTextResponse($@"亲,抱歉!小玉暂时不能理解您的{PostWxEvent.ToString()}事件信息,已收妥保存信息。请通过其它途径获得解答。"));
                    }
                }

                //不能处理
                case WxMsgType.IMAGE:
                case WxMsgType.LINK:
                case WxMsgType.LOCATION:
                case WxMsgType.SHORTVIDEO:
                case WxMsgType.VIDEO:
                case WxMsgType.VOICE:
                case WxMsgType.NONE:
                default:
                    LogService.AnyLog("WxRebotNoSuper", $@"小玉未能处理信息:{PostXml}");
                    return(GetTextResponse($@"亲,抱歉!小玉暂时不能理解您的{PostWxMsgType.ToString()}信息,已收妥保存信息。请通过其它途径获得解答。"));
                }
            }
            catch (Exception ex)
            {
                LogService.Exception(ex);
                return(GetTextResponse($@"亲,小玉的软体出问题了{ex.Message},请通过其它途径获得解答。"));
            }
        }