做网站组服务器,查icp备案是什么网站,软件商城电脑版,荥阳市网站建设C# 企业微信机器人推送消息 先添加一个机器人!
然后查看机器人就可以得到一个 webhook 特别特别要注意#xff1a;一定要保护好机器人的webhook地址#xff0c;避免泄漏#xff01;
然后开始写代码 #xff0c;只需要httpPost 调用一下这个地址就可以发送消息了。 首先我…C# 企业微信机器人推送消息 先添加一个机器人!
然后查看机器人就可以得到一个 webhook 特别特别要注意一定要保护好机器人的webhook地址避免泄漏
然后开始写代码 只需要httpPost 调用一下这个地址就可以发送消息了。 首先我们创建服务项目可以更好的定时发送
设置服务的属性 服务添加完成后可以写一个批处理文件去安装服务 使用微软的installutil 去安装服务 在程序debug目录 创建一个文本文件 扩展名改为bat就可以然后把下面内容复制进去。最后以管理员方式运行 %~dp0 获取当前目录 WindowsService1.exe 项目的名称 根据实际情况定 %SystemRoot%\Microsoft.NET\Framework\v4.0.30319\installutil.exe %~dp0WindowsService1.exe pause 运行成功后可以看到有我们刚刚创建好的服务
以上是windows服务程序的安装。 接下来我们写推送消息的实现
先写一个post请求的方法 private static string HttpPost(string url, string body){try{Encoding encoding Encoding.UTF8;HttpWebRequest request (HttpWebRequest)WebRequest.Create(url);request.Method POST;request.Accept text/html, application/xhtmlxml, */*;request.ContentType application/json;byte[] buffer encoding.GetBytes(body);request.ContentLength buffer.Length;request.GetRequestStream().Write(buffer, 0, buffer.Length);HttpWebResponse response (HttpWebResponse)request.GetResponse();using (StreamReader reader new StreamReader(response.GetResponseStream(), Encoding.UTF8)){return reader.ReadToEnd();}}catch (Exception){}return ;}然后是我们请求的内容 使用json格式更方便 于是我创建了一个请求的类 最后转换成json就可以 class RequestModel{public string msgtype { get; set; } text;public text text { get; set; } new text();}class text{/// summary/// 发松的内容/// /summarypublic string content { get; set; } 广州今日天气29度大部分多云降雨概率60%;public string mentioned_list { get; set; } all;}最后我们写一个方法去调用使用 JsonConvert可以把实体类转换成Json格式 需要下载Newtonsoft.Json.dll 可以鼠标右键在nuget管理包中搜索下载 /// summary/// 机器人发送消息/// /summary/// param namemessage/parampublic static void WeChatRobot(string message){try{RequestModel request new RequestModel();request.text.content message;string json JsonConvert.SerializeObject(request);string webhookUrl 这里填写机器人的webhook 可以在机器人信息那里查看;string response string.Empty;while (string.IsNullOrEmpty(response)){//3s请求一次 直到请求成功response HttpPost(webhookUrl, json);Thread.Sleep(3000);}File.AppendAllText(D:\\Response.txt, response);}catch (Exception){throw;}}最后我们在服务启动里面调用这个机器人发送的方法就可以 判断每周五发送消息 protected override void OnStart(string[] args){Task.Factory.StartNew(() {while (true){DayOfWeek DayOfWeek DateTime.Now.DayOfWeek;if (DayOfWeek DayOfWeek.Friday){Services.WeChatRobot($今天是{DayOfWeek});break;}Thread.Sleep(1000);}});}protected override void OnStop(){}
程序有改动只需要重新生成程序。 在安装一遍服务就可以。