LoginSignup
9
7

More than 3 years have passed since last update.

C#でslackにPOST

Last updated at Posted at 2019-07-22

プロローグ

ちょっとつまづいたので残しておきたくって。
誰かの参考になればと思って。
コピってぺして動かなかったら、調べてどうにかしって。(語彙不足)
俺も調べてどうにかなったって。(越中さんのモノマネしてるケンコバさん?)

準備

slack側

アイコン

「ワークスペースのカスタマイズ」⇒「カスタム絵文字を追加する」
で、":mybot:"という名称を付け事前に追加した。

POST先

1.App管理で、Incoming Webhookを検索。
2.「設定を追加」を押す。
3.とりあえずのPOST先チャンネルを指定し、「インテグレーションの追加」を押す。
  後で変更できるのでどこでもいい。
4.インテグレーションの設定欄にある、Webhook URLをコピー
5.C#で作成するPostClassのpostUrlに割り当てる。

C#側

プロジェクト

お好きなC#プロジェクトを。

Nugetパッケージの追加

Newtonsoft.Json を追加した。

パラメータクラス

NewsData.cs
public class Attachment
{
    public string color { get; set; }
    public string title { get; set; }
    public string title_link { get; set; }
    public string text { get; set; }
}
SendParameters.cs
public class SendParameters
{
    public string username => "俺bot";
    public string icon_emoji => ":mybot:";
    public string text { get; set; }

    // POST先のチャンネルを指定する場合使用。
    // POST先がデフォルトのチェンネルの場合は空白で良い。
    public string channel { get; set; }

    // チュートリアルを見ると、[]で囲まれていた。
    // リストとして扱うと、jsonシリアライズする際スムーズ。
    public List<Attachment> attachments { get; set; }
}

HttpClient

※2019年7月23日。コメントでご指摘いただいたサイト参考。
HttpClientは、staticで宣言して使いまわすのが望ましいらしい。
よって、使いまわせるように、スタティックしておく。

GlobalClass.cs
using System.Net.Http;

public class GlobalClass
{
    public static HttpClient httpClient = new HttpClient();
}

本題

POSTクラス作成

PostClass.cs
using System.Net.Http;
using Newtonsoft.Json;

public class PostClass
{
    // Webhook URLをコピってペ
    private const string postUrl = "";

    // POST本体。
    public async Task<bool> PostMethod(string titleText, string bodyText, string urlText, string colorText)
    {
        // 送信パラメータ作成
        var attachment = new Attachment()
        {
            color = colorText,
            title = titleText,
            title_link = urlText,
            text = bodyText
        };
        var sendParams = new SendParameters()
        {
            attachments = new List<Attachment> { attachment },
            text = "ワイはbotやさかい、日本語がOK牧場じゃないところは堪忍してやー。",
            channel = "#random"
        };

        // パラメータクラスをJSONにシリアライズ。
        var paramJson = JsonConvert.SerializeObject(sendParams);

        // POSTデータを作成
        var sendData = new Dictionary<string, string>
        {
            { "payload", paramJson }
        };
        var content = new FormUrlEncodedContent(sendData);

        // POST!!
        var res = await GlobalClass.httpClient.PostAsync(postUrl, content);

        return (res.StatusCode == System.Net.HttpStatusCode.OK);
    }
}

呼び出すところ

var postClass = new PostClass();
var isOk = await postClass.PostMethod("グーグル", "中の人何人くらいで動かしてるんやろ", "https://www.google.co.jp", "#ff0000");

結果

こんな感じに表示されます。
qiita1.jpg

エピローグ

もうちょっと色々やりたい場合、この辺見ると、
attachmentsのほかの要素などが書いてあるので、参考になるのかなと思いましたって。
https://api.slack.com/incoming-webhooks

9
7
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
7