企业微信、钉钉设置机器人通过winform提醒WxWorkBOT

配置文件

        private static string url = ConfigurationManager.AppSettings["WxWorkBOTUrl"].ToString().Trim();

启动发送

     /// <summary>
        /// 初始加载 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainFrm_Load(object sender, EventArgs e)
        {
            InitMethod();
            projectName = BasicDAL.GetProject();
            this.Text = $"【{projectName}】发票自动识别程序--{DbHelperSQL.connectionString}";

            WxWorkBOT.SendMess("Hi,我是**电子发票服务机器人 ,提醒:**电子发票服务已启动!");
        }

异常退出

 /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.ThreadException += Application_ThreadException;
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            Application.ApplicationExit += Application_ApplicationExit;
            Application.Run(new MainFrm());
        }

        private static void Application_ApplicationExit(object sender, EventArgs e)
        {
            WxWorkBOT.SendMess("Hi,我是**电子发票服务机器人 ,提醒:**电子发票服务已断开!!!");

        }

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                WxWorkBOT.SendMess("Hi,我是**电子发票服务机器人 ,提醒:**合电子发票服务已断开!!!");

            }
            catch { }
        }
        private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            Process[] ps = Process.GetProcessesByName("AutoInvoiceFXLH");
            if (ps.Length < 1)
            {
                WxWorkBOT.SendMess("Hi,我是**电子发票服务机器人 ,提醒:**电子发票服务已断开!!!");

            }

        }
    }
using Newtonsoft.Json;
using System.Configuration;
using System.IO;
using System.Net;
using System.Text;


namespace Common
{
    public class WxWorkBOT
    {
        private static string url = ConfigurationManager.AppSettings["WxWorkBOTUrl"].ToString().Trim();
              
        public static void SendMess(string mse,string connUrl = null)
        {
            try
            {
                var jsonObject = new { msgtype = "text", text = new { content = mse } };
                PostUrl((connUrl == null? url: connUrl), JsonConvert.SerializeObject(jsonObject));
            }
            catch (System.Exception)
            {

            }
        }

        /// <summary>
        /// 普通的post
        /// </summary>
        /// <param name="url"></param>
        /// <param name="postData"></param>
        /// <returns></returns>
        public static string PostUrl(string url, string postData)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/json";
            byte[] data = Encoding.UTF8.GetBytes(postData);
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }

    }
}

钉钉

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace DingRobotDemo
{
    public class CustomSendRobotMessage
    {
        public static readonly string Secret = "你自己的SEC字符串";
        public static string RobotUrl = "你自己的webhook接口地址";
        public void SendMessage()
        {
            try
            {
                long timestamp = DateTimeOffset.Now.ToUnixTimeMilliseconds();
                
                string secret = Secret;
                string stringToSign = $"{timestamp}\n{secret}";
                string sign = HmacSHA256Helper.HmacSHA256(secret, timestamp);
                
                // 构建请求URL,包含签名和时间戳
                string requestUrl = $"{RobotUrl}&sign={sign}&timestamp={timestamp}";

                // 创建HttpClient和发送请求
                using (var client = new HttpClient())
                {
                    var requestContent = new
                    {
                        msgtype = "text",
                        text = new { content = "这是一条来自.NET测试发来的消息,如有打扰,请群友们见谅~" }
                    };

                    var json = JsonSerializer.Serialize(requestContent);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    HttpResponseMessage response = client.PostAsync(requestUrl, content).Result;
                    string result = response.Content.ReadAsStringAsync().Result;
                    Console.WriteLine(result);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
            }
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace DingRobotDemo
{
    public class HmacSHA256Helper
    {
        public static string HmacSHA256(string secret,long timestamp)
        {
            string encodedSign = string.Empty;
            string stringToSign = timestamp + "\n" + secret;
            using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(secret)))
            {
                byte[] signData = hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign));
                string sign = Convert.ToBase64String(signData);
                encodedSign = HttpUtility.UrlEncode(sign);
            }
            return encodedSign;
        }
    }
}

CustomSendRobotMessage robotMessage = new CustomSendRobotMessage();
robotMessage.SendMessage();
  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

是刘彦宏吖

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值