質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.50%
C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

Q&A

解決済

1回答

4996閲覧

C#でSlackのチャンネルとダイレクトメッセージに投稿したいです。

cancat

総合スコア313

C#

C#はマルチパラダイムプログラミング言語の1つで、命令形・宣言型・関数型・ジェネリック型・コンポーネント指向・オブジェクティブ指向のプログラミング開発すべてに対応しています。

0グッド

1クリップ

投稿2017/06/09 06:02

こんにちは。
Windows10でWPFのアプリケーションを開発しています。
Visual Studio 2017 Communityを使っています。

###前提・実現したいこと
Slackに投稿したいです。
チャンネルとダイレクトメッセージとを投稿したいです。

###試したこと
TOKENを取得。

###発生している問題・エラーメッセージ
チャンネルはチャンネル名でなく、idを入れるらしいのですが、ダイレクトメッセージの場合にはなにをいれたらよいかわかりません。@USERNAMEとあるので入れてみたところ、エラーになっています。

実行すると、 var response = client.UploadValues(_uri, "POST", data);
の行で、下記のエラーが発生します。

System.Net.WebException が発生しました
HResult=0x80131509
Message=リモート サーバーがエラーを返しました: (404) 見つかりません
Source=<例外のソースを評価できません>
スタック トレース:
場所 System.Net.WebClient.UploadValues(Uri address, String method, NameValueCollection data)
場所 SlackAPI.SlackClient.PostMessage(Payload payload) (C:\Projects\SlackAPI\SlackAPI\MainWindow.xaml.cs):行 66
場所 SlackAPI.SlackClient.PostMessage(String text, String username, String channel) (C:\Projects\SlackAPI\SlackAPI\MainWindow.xaml.cs):行 54
場所 SlackAPI.MainWindow.Button_Click(Object sender, RoutedEventArgs e) (C:\Projects\SlackAPI\SlackAPI\MainWindow.xaml.cs):行 28
場所 System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
場所 System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
場所 System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
場所 System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)
場所 System.Windows.Controls.Primitives.ButtonBase.OnClick()
場所 System.Windows.Controls.Button.OnClick()
場所 System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
場所 System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)
場所 System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
場所 System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
場所 System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
場所 System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
場所 System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)
場所 System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)
場所 System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
場所 System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
場所 System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
場所 System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
場所 System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
場所 System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)
場所 System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
場所 System.Windows.Input.InputManager.ProcessStagingArea()
場所 System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
場所 System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
場所 System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
場所 System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
場所 System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
場所 MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
場所 MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
場所 System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
場所 System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
場所 System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
場所 MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
場所 MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
場所 System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
場所 System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
場所 System.Windows.Application.RunDispatcher(Object ignore)
場所 System.Windows.Application.RunInternal(Window window)
場所 System.Windows.Application.Run(Window window)
場所 System.Windows.Application.Run()
場所 SlackAPI.App.Main()

###該当のソースコード

C#

1using Newtonsoft.Json; 2using System; 3using System.Collections.Specialized; 4using System.Net; 5using System.Text; 6using System.Windows; 7 8namespace SlackAPI 9{ 10 public partial class MainWindow : Window 11 { 12 public MainWindow() 13 { 14 InitializeComponent(); 15 } 16 17 private void Button_Click(object sender, RoutedEventArgs e) 18 { 19 string urlWithAccessToken = "https://cancat.slack.com/services/hooks/incoming-webhook?token=xoxp-000000000000-000000000000-000000000000-0000000000000000000000000000"; 20 SlackClient client = new SlackClient(urlWithAccessToken); 21 22 client.PostMessage(username: "cannat", text: "THIS IS A TEST MESSAGE! SQUEEDLYBAMBLYFEEDLYMEEDLYMOWWWWWWWW!",channel: "@cancat"); 23 } 24 } 25 26 public class SlackClient 27 { 28 private readonly Uri _uri; 29 private readonly Encoding _encoding = new UTF8Encoding(); 30 31 public SlackClient(string urlWithAccessToken) 32 { 33 _uri = new Uri(urlWithAccessToken); 34 } 35 36 //Post a message using simple strings 37 public void PostMessage(string text, string username = null, string channel = null) 38 { 39 Payload payload = new Payload() 40 { 41 Channel = channel, 42 Username = username, 43 Text = text 44 }; 45 46 PostMessage(payload); 47 } 48 49 //Post a message using a Payload object 50 public void PostMessage(Payload payload) 51 { 52 string payloadJson = JsonConvert.SerializeObject(payload); 53 using (WebClient client = new WebClient()) 54 { 55 NameValueCollection data = new NameValueCollection(); 56 data["payload"] = payloadJson; 57 58 var response = client.UploadValues(_uri, "POST", data); 59 //The response text is usually "ok" 60 string responseText = _encoding.GetString(response); 61 } 62 } 63 } 64 65 //This class serializes into the Json payload required by Slack Incoming WebHooks 66 67 public class Payload 68 { 69 [JsonProperty("channel")] 70 public string Channel { get; set; } 71 72 [JsonProperty("username")] 73 public string Username { get; set; } 74 75 [JsonProperty("text")] 76 public string Text { get; set; } 77 } 78}

###補足情報(言語/FW/ツール等のバージョンなど)
Microsoft Visual Studio Community 2017
Version 15.0.26228.9 D15RTWSVC
Microsoft .NET Framework
Version 4.6.01586

です。
よろしくお願いします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

guest

回答1

0

ベストアンサー

通常のチャンネル投稿はうまく行っているのですか?
私はこんな感じで、チャンネル投稿はできています。
ダイレクトメッセージはやったことないけど、
http://qiita.com/rubytomato@github/items/6558bfdb37d982891c09
を読む限り、チャンネルを変えるだけみたいですね。

public static class SlackBot { public static string Slack_API_Url = "https://hooks.slack.com/services/*************"; public static void Post(string text) { using (System.Net.WebClient wc = new System.Net.WebClient()) { wc.Headers.Add(HttpRequestHeader.ContentType, "application/json;charset=UTF-8"); wc.Encoding = Encoding.UTF8; Message m = new Message() { text = text }; wc.UploadString(Slack_API_Url, JsonConvert.SerializeObject(m)); } } public class Message { public string channel { get; set; } = "#test"; public string username { get; set; } = "webhookbot"; public string text { get; set; } public string icon_emoji { get; set; } = ":ghost:"; } }

投稿2017/06/09 07:18

kiichi54321

総合スコア1984

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

cancat

2017/06/09 08:56

ご回答ありがとうございます。 Slackは仕事で使うもので、すでにあるところに入ったので、テストでチャンネルに投稿することができずにいます。 新人なので、下手なことをすると怒られそう。 なので最初に自分あてにダイレクトメッセージを送ってみようと考えました。 わたしも同じサイトを見ていたのですが、エラーになっていて困っています。
kiichi54321

2017/06/09 10:00

テスト用のチャンネルを作ればいいじゃないとしか、思いません。誰だってミスるし、あたりまえのことです。 URLは、どういうふうに作ったのか忘れましたが、?token=*** とかいうアドレスではありません。こういうのは手順をちゃんと踏むのがいいと思います。
cancat

2017/06/13 09:21

ご教示いただいたURLのhttps://hooks.slack.com/services/*************"の*************はTokenですか?
kiichi54321

2017/06/13 09:27 編集

おそらくそうですね。これ使ってやって、と言われたのやっただけなので詳細はわかっていないのですが、Slackで発行されるアドレスをそのまま使っているだけだと思います。
cancat

2017/06/13 09:42

?token=とかはなしで、いきなりですか? それもためしてみたのですが。。。
cancat

2017/07/01 03:14

hooksでは投稿できました。ありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.50%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問