-
Notifications
You must be signed in to change notification settings - Fork 243
Complete example for sending a message
Erik Kalkoken edited this page Nov 17, 2018
·
3 revisions
This is a simple, but complete example for sending a message to a Slack channel with the SlackAPI library.
The library has two different client classes for making calls to the Slack API. Each are using a different approach for implementing asynchronous calls to the API.
-
SlackClientAsync
: The newer Async pattern -
SlackClient
: The older delegate /callback approach
Below you find one example for each approach.
This example shows how to send a message to Slack using the newer Async approach.
// minimal example for sending a simple message to a channel with the SlackAPI library
// this example uses the Async method
using System;
using System.Threading.Tasks;
using SlackAPI;
namespace TestingSlackAPI
{
class Async
{
public async Task Run()
{
// instantiate a new Slack Client by provding a token
var token = "xoxp-YOUR-TOKEN";
var client = new SlackTaskClient(token);
// send simple message to channel and wait for the call to complete
var channel = "test";
var text = "hello world";
var response = await client.PostMessageAsync(channel, text);
// process response from API call
if (response.ok)
{
Console.WriteLine("Message sent successfully");
}
else
{
Console.WriteLine("Message sending failed. error: " + response.error);
}
}
static void Main(string[] args)
{
// instantiate main class and start execution by calling its Run() method
// then wait for the task to complete
var p = new Async();
p.Run().Wait();
Console.ReadKey();
}
}
}
This example shows how to send a message to Slack using the older callback / delegate approach.
using System;
using System.Threading;
using SlackAPI;
namespace TestingSlackAPI
{
class Program
{
// needed to wait for callback method
AutoResetEvent stopWaitHandle = new AutoResetEvent(false);
// callback for PostMessage - will be called when message sending is complete
private void callback(PostMessageResponse obj)
{
if (obj.ok)
{
Console.WriteLine("Message sent successfully");
}
else
{
Console.WriteLine("Message sending failed. error: " + obj.error);
}
// notify that callback is complete
stopWaitHandle.Set();
}
public void Run()
{
// instantiate a new Slack Client by proving a token
var token = "YOUR-TOKEN";
var client = new SlackClient(token);
// send simple message to channel
var channel = "my_channel";
var text = "hello world";
client.PostMessage(callback, channel, text);
// wait for callback to complete
stopWaitHandle.WaitOne();
}
static void Main(string[] args)
{
// instantiate main class and start execution by calling its Run() method
var p = new Program();
p.Run();
Console.ReadKey();
}
}
}