C# (.NET) N 个通知推送平台的使用

因为项目中使用了 HtmlAgilityPack,以下代码中所有的 Get 请求都使用了 HtmlAgilityPack 自带的 HtmlWeb

如果不使用 HtmlAgilityPack,等效替换成 System.Net.Http 发送 Get 请求即可

Telegram

Telegram Bot

Nuget

代码

using System;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;
using Telegram.Bot;
using Telegram.Bot.Types.Enums;
using Microsoft.Extensions.Logging;

namespace Notifier {
    public class TgBot {
        private readonly ILogger<TgBot> _logger;

        #region debug strings
        private readonly string debugSendMessage = "Send notification to Telegram";
        #endregion

        public TgBot(ILogger<TgBot> logger) {
            _logger = logger;
        }

        public async Task SendMessage(NotifyConfig config, List<string> msgs) {
            var sb = new StringBuilder();
            var BotClient = new TelegramBotClient(token: config.TelegramToken);

            try {
                foreach (var msg in msgs) {
                    _logger.LogDebug($"{debugSendMessage} : {record.Name}");
                    await BotClient.SendTextMessageAsync(
                        chatId: config.TelegramChatID,
                        text: msg, 
                        parseMode: ParseMode.Html
                    );
                }
                _logger.LogDebug($"Done: {debugSendMessage}");
            } catch (Exception) {
                _logger.LogError($"Error: {debugSendMessage}");
                throw;
            } finally {
                Dispose();
            }
        }

        public void Dispose() {
            GC.SuppressFinalize(this);
        }
    }
}

iOS

Bark

Nuget

  • HtmlAgilityPack

代码

using System;
using System.Text;
using System.Web;
using System.Threading.Tasks;
using System.Collections.Generic;
using HtmlAgilityPack;
using Microsoft.Extensions.Logging;

namespace Notifier {
    class Barker {
        private readonly ILogger<Barker> _logger;

        #region debug strings
        private readonly string debugSendMessage = "Send notification to Bark";
        #endregion

        public Barker(ILogger<Barker> logger) {
            _logger = logger;
        }

        public async Task SendMessage(NotifyConfig config, List<string> msgs) {
            try {
                var sb = new StringBuilder();
                // config.BarkAddress = "https://api.day.app"
                string url = new StringBuilder().AppendFormat("{0}/{1}/", config.BarkAddress, config.BarkToken).ToString();
                var webGet = new HtmlWeb();

                foreach (var msg in msgs) {
                    var resp = await webGet.LoadFromWebAsync(
                        new StringBuilder()
                            .Append(url)
                            .Append("Title/")
                            .Append(HttpUtility.UrlEncode(msg))
                            .ToString()
                    );
                    _logger.LogDebug(resp.Text);
                }

                _logger.LogDebug($"Done: {debugSendMessage}");
            } catch (Exception) {
                _logger.LogDebug($"Error: {debugSendMessage}");
                throw;
            } finally {
                Dispose();
            }
        }

        public void Dispose() {
            GC.SuppressFinalize(this);
        }
    }
}

微信

PushPlus

Nuget

  • HtmlAgilityPack

代码

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Threading.Tasks;
using HtmlAgilityPack;
using Microsoft.Extensions.Logging;

namespace Notifier {
    class PushPlus {
        private readonly ILogger<PushPlus> _logger;

        #region debug strings
        private readonly string debugSendMessage = "Send notification to PushPlus";
        private readonly string debugCreateMessage = "Create notification message";
        #endregion

        public PushPlus(ILogger<PushPlus> logger) {
            _logger = logger;
        }

        private string CreateMessage(List<string> msgs) {
            try {
                _logger.LogDebug(debugCreateMessage);

                var sb = new StringBuilder();
                msgs.ForEach(msg => sb.Append(msg));

                _logger.LogDebug($"Done: {debugCreateMessage}");
                return HttpUtility.UrlEncode(sb.ToString());
            } catch (Exception) {
                _logger.LogError($"Error: {debugCreateMessage}");
                throw;
            }
        }

        public async Task SendMessage(NotifyConfig config, List<string> msgs) {
            try {
                _logger.LogDebug(debugSendMessage);

                var title = HttpUtility.UrlEncode("Test Title");
                var url = new StringBuilder().AppendFormat("http://www.pushplus.plus/send?token={0}&template=html&title={1}&content=", config.PushPlusToken, title);
                var message = CreateMessage(msgs);

                var resp = await new HtmlWeb().LoadFromWebAsync(
                    new StringBuilder()
                        .Append(url)
                        .Append(message)
                        .ToString()
                );
                _logger.LogDebug(resp.Text);

                _logger.LogDebug($"Done: {debugSendMessage}");
            } catch (Exception) {
                _logger.LogError($"Error: {debugSendMessage}");
                throw;
            } finally {
                Dispose();
            }
        }

        public void Dispose() {
            GC.SuppressFinalize(this);
        }
    }
}

QQ

go-cqhttp

Nuget

  • HtmlAgilityPack

代码

using System;
using System.Collections.Generic;
using System.Web;
using System.Text;
using System.Threading.Tasks;
using HtmlAgilityPack;
using Microsoft.Extensions.Logging;

namespace Notifier {
    class QQPusher {
        private readonly ILogger<QQPusher> _logger;

        #region debug strings
        private readonly string debugSendMessage = "Send notifications to QQ";
        #endregion

        public QQPusher(ILogger<QQPusher> logger) {
            _logger = logger;
        }

        public async Task SendMessage(NotifyConfig config, List<string> msgs) {
            try {
                _logger.LogDebug(debugSendMessage);

                // qqUrlFormat = "http://{0}:{1}/send_private_msg?user_id={2}&message="
                string url = new StringBuilder().AppendFormat(qqUrlFormat, config.QQAddress, config.QQPort, config.ToQQID).ToString();

                var webGet = new HtmlWeb();

                foreach (var msg in msgs) {
                    _logger.LogDebug($"{debugSendMessage} : {record.Name}");
                    var resp = await webGet.LoadFromWebAsync(
                        new StringBuilder()
                            .Append(url)
                            .Append(HttpUtility.UrlEncode(msg))
                            .ToString()
                    );
                    _logger.LogDebug(resp.Text);
                }

                _logger.LogDebug($"Done: {debugSendMessage}");
            } catch (Exception) {
                _logger.LogError($"Error: {debugSendMessage}");
                throw;
            } finally {
                Dispose();
            }
        }

        public void Dispose() {
            GC.SuppressFinalize(this);
        }
    }
}

钉钉

钉钉企业内部机器人

Nuget

代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace Notifier {

    public class Content {
        #pragma warning disable IDE1006
        public string content { get; set; }
        #pragma warning restore IDE1006
    }
    public class DingTalkPostContent {
        #pragma warning disable IDE1006 // 命名样式
        public string msgtype { get; set; }
        public Content text { get; set; }
        #pragma warning restore IDE1006

        public DingTalkPostContent() {
            msgtype = "text";
            text = new Content();
        }
    }
    
    class DingTalk {
        private readonly ILogger<DingTalk> _logger;

        #region debug strings
        private readonly string debugSendMessage = "Send notifications to DingTalk";
        #endregion

        public DingTalk(ILogger<DingTalk> logger) {
            _logger = logger;
        }

        public async Task SendMessage(NotifyConfig config, List<string> msgs) {
            try {
                _logger.LogDebug(debugSendMessage);

                // dingTalkUrlFormat = "https://oapi.dingtalk.com/robot/send?access_token={0}"
                var url = new StringBuilder().AppendFormat(dingTalkUrlFormat, config.DingTalkBotToken).ToString();
                var content = new DingTalkPostContent();

                var client = new HttpClient();

                foreach (var msg in msgs) {
                    content.text.content = msg;
                    var data = new StringContent(JsonConvert.SerializeObject(content), Encoding.UTF8, "application/json");
                    var resp = await client.PostAsync(url, data);
                    _logger.LogDebug(await resp.Content.ReadAsStringAsync());
                }

                _logger.LogDebug($"Done: {debugSendMessage}");
            } catch (Exception) {
                _logger.LogError($"Error: {debugSendMessage}");
                throw;
            } finally {
                Dispose();
            }
        }

        public void Dispose() {
            GC.SuppressFinalize(this);
        }
    }
}

邮件

第三方

Nuget

代码

using System;
using System.Text;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.Extensions.Logging;
using MailKit.Net.Smtp;
using MimeKit;

namespace Notifier {
    class Email {
        private readonly ILogger<Email> _logger;

        #region debug strings
        private readonly string debugSendMessage = "Send notification to Email";
        private readonly string debugCreateMessage = "Create notification message";
        #endregion

        public Email(ILogger<Email> logger) {
            _logger = logger;
        }

        private MimeMessage CreateMessage(List<string> msgs, string fromAddress, string toAddress) {
            try {
                _logger.LogDebug(debugCreateMessage);

                var message = new MimeMessage();

                message.From.Add(new MailboxAddress("Sender Name", fromAddress));
                message.To.Add(new MailboxAddress("Receiver Name", toAddress));

                message.Subject = "Test Mail";

                var sb = new StringBuilder();
                msgs.ForEach(msg => sb.Append(msg));

                message.Body = new TextPart("html") {
                    Text = sb.ToString()
                };
        
                _logger.LogDebug($"Done: {debugCreateMessage}");
                return message;
            } catch (Exception) {
                _logger.LogError($"Error: {debugCreateMessage}");
                throw;
            }
        }

        public async Task SendMessage(NotifyConfig config, List<string> msgs) {
            try {
                _logger.LogDebug(debugSendMessage);

                var message = CreateMessage(msgs, config.FromEmailAddress, config.ToEmailAddress);

                using var client = new SmtpClient();
                client.Connect(config.SMTPServer, config.SMTPPort, true);
                client.Authenticate(config.AuthAccount, config.AuthPassword);
                await client.SendAsync(message);
                client.Disconnect(true);

                _logger.LogDebug($"Done: {debugSendMessage}");
            } catch (Exception) {
                _logger.LogError($"Error: {debugSendMessage}");
                throw;
            } finally {
                Dispose();
            }   
        }

        public void Dispose() {
            GC.SuppressFinalize(this);
        }
    }
}

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据