如何利用Webhook向Teams中发送卡片消息

1,技术要求:

向Teams的频道中推送自定义卡片

2,准备工作

2.1	visual studio 2022 community
2.2	internet 连接
2.3	teams账号

3 创建Teams频道

我们假定该频道已经创建完毕。
3.1	登录Teams
3.2	创建新的频道

4 创建Webhook

4.1	选择频道
4.2	右键点击选择管理频道
4.3	选择连接器
4.4	点击编辑
4.5	点击configured,第一次建立,可以点击Build your own connector来创建一个新的连接器,如果有的话,会显示已经创建的连接器.
4.6	写入连接器的名字,选择图像,
4.7	点击create,即可创建
4.8	这里需要将连接器的URL记下来,这是关键部分之一
4.9	点击Done,即可创建完毕

5 程序

这里会出现一个问题,就是常见的AdaptiveCard不能再频道中显示,应按照如下格式:

点击查看代码
{
  "type": "message",
  "attachments": [
    {
      "contentType": "application/vnd.microsoft.card.adaptive",
      "contentUrl": "",
      "content": {
        "version": "1.2",
        "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
        "type": "AdaptiveCard",  //此处是硬性要求,Body里面的内容可根据需要自行按照微软提供的设计工具进行设计
        "body": [        //body里面可放入自己想要的内容,下方三个textblock仅仅是为了示例
          {
            "type": "TextBlock",
            "text": "XXXXXXXX",
            "wrap": true,
            "size": "Large"
          },
          {
            "type": "TextBlock",
            "text": "2023-10-01 12:00:00",
            "wrap": true,
            "size": "Default"
          },
          {
            "type": "TextBlock",
            "text": "XXXXXXXX",
            "wrap": true,
            "size": "Medium"
          }
        ]
      }
    }
  ]
}

adaptiveCards库类下的不能使用,这是非常容易犯错的地方;

完成代码如下:

点击查看代码
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Security.Cryptography.X509Certificates;

namespace TeamDemo
{
    internal class Program
    {
        static  void Main(string[] args)
        {
            #region  发送自定义适配卡片消息到Teams
            //在此处的卡片设计可参考微软官方的卡片设计器
            AdaptiveCardDemo adaptiveCard = new AdaptiveCardDemo();
            AdaptiveTextBlock tittle= new AdaptiveTextBlock
            {
                Text = "XXXXXXXX",
                Wrap = true,
                Size = AdaptiveTextBlockSize.Large.ToString()
            };
            AdaptiveTextBlock timeBlock= new AdaptiveTextBlock
            {
                Text = "XXXXXXXXXX",
                Wrap = true,
            };

            AdaptiveTextBlock messageBlock= new AdaptiveTextBlock
            {
                Text = "XXXXXXXXXXXXXXXXXXXXX",
                Wrap = true,
                Size = AdaptiveTextBlockSize.Medium.ToString()
            };

            adaptiveCard.Body.Add(tittle);
            adaptiveCard.Body.Add(timeBlock);
            adaptiveCard.Body.Add(messageBlock);
            #endregion

            Root root = new Root();
            root.Attachments.Add(new Attachment
            {
                Content = adaptiveCard,
                ContentType = "application/vnd.microsoft.card.adaptive",
                ContentUrl = string.Empty
            });
            string jsonString= JsonConvert.SerializeObject(root, Formatting.Indented);
            try
            {
                string webHook = "xxxxxxx";
                TeamsWebHook hook = new TeamsWebHook
                {
                    Url = webHook,
                    Message = jsonString
                };
                hook.SendPost();
                
            }
            catch (Exception ex)
            {
                Console.WriteLine("发送失败:" + ex.Message);
            }
             
            Console.ReadKey();
        }

        public class Root
        {

           [JsonProperty("type")]
            public string Type { get; set; } = "message";
            [JsonProperty("attachments")]
            public List<Attachment> Attachments { get; set; } = new List<Attachment>();
        }

        public class Attachment
        {
            [JsonProperty("contentType")]
            public string ContentType { get; set; } = "application/vnd.microsoft.card.adaptive";
            [JsonProperty("contentUrl")]
            public string ContentUrl { get; set; } = string.Empty;
            [JsonProperty("content")]
            public AdaptiveCardDemo Content { get; set; } = new AdaptiveCardDemo();
        }

        public class AdaptiveCardDemo
        {
            [JsonProperty("version")]
            public string Version { get; set; } = "1.2";
            [JsonProperty("$schema")]
            public string Schema { get; set; } = "http://adaptivecards.io/schemas/adaptive-card.json";
            [JsonProperty("type")]
            public string Type { get; set; } = "AdaptiveCard";
            [JsonProperty("body")]
            public List<AdaptiveTextBlock> Body { get; set; } = new List<AdaptiveTextBlock>();
        }
        public class AdaptiveTextBlock
        {
            [JsonProperty("type")]
            public string Type { get; set; }= "TextBlock";
            [JsonProperty("text")]
            public string Text { get; set; }
            [JsonProperty("wrap")]
            public bool Wrap { get; set; } = true;
            [JsonProperty("size")]
            public string Size { get; set; } = AdaptiveTextBlockSize.Default.ToString();
        }
            
        public enum AdaptiveTextBlockSize
        {
            Small,
            Default,
            Medium,
            Large,
            ExtraLarge
        }
    }

    public class TeamsWebHook
    {
        private string message = string.Empty;

        public string Message
        {
            get
            {
               if (string.IsNullOrEmpty(message))
                {
                    return string.Empty;
                }
                return message;
            }
            set
            {
                message = value;
            }
        }

        public string Url { get; set; }

        public bool SendPost()
        {
            try
            {
                HttpWebRequest obj = (HttpWebRequest)WebRequest.Create(Url);
                obj.Method = "POST";
                obj.ContentType = "application/json;charset=UTF-8";
                byte[] bytes = Encoding.UTF8.GetBytes(Message);
                int num = bytes.Length;
                obj.ContentLength = num;
                Stream requestStream = obj.GetRequestStream();
                requestStream.Write(bytes, 0, num);
                requestStream.Close();
                new StreamReader(((HttpWebResponse)obj.GetResponse()).GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
            }
            catch
            {
                return false;
            }

            return true;
        }
    }
}
posted @ 2025-06-19 13:44  采姑娘的小蘑菇Miya  阅读(489)  评论(1)    收藏  举报