Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / IoT / Raspberry-Pi

Slack Chatting with your rPi

5.00/5 (25 votes)
27 Jan 2019CPOL8 min read 22.2K   132  
Talk to your rPi over a Slack channel, getting status, controlling devices, and running shell (bash) commands and viewing the console output posted back to your Slack channel

Contents

Preface

This article is my submission to the Slack API Challenge.

Introduction

So your rPi is sitting there on your local network and you (hopefully!) haven't opened the telnet ports on your router, and you are not at home but you need to talk to your rPi. What's a poor boy to do? Well, if you've added this Slack Bot app to your Slack account, you can talk to your rPi from anywhere! Send bash commands, check on its health, control your devices, all from Slack! 

Examples

Simple Ping

Image 1

Get the Temperature of Your rPi Processor

Image 2

Get Memory Utilization (Bash Command)

Image 3

Get Free Disk Space (Bash Command)

Image 4

Send a Command to a Device, like the LCD1602

Image 5Image 6

Check on a Process (Bash Command)

Image 7

Query Postgres

Image 8

Image 9

Image 10

What You Should Already Know

You should already know:

  1. how to create a .NET Core application
  2. publish it with the linux-arm architecture
  3. WinSCP (or PCSP) it over to the rPi
  4. Fire up a terminal window in Putty to run it.

If you're not familiar with those steps, there are a lot of resources you can find simply by Googling "rpi dotnet core" or by reviewing my previous article, particularly the sections on PuTTY and WinSCP, Installing .NET Core, Run the Test on the rPi. If you're not familiar with the LCD1602, review my article here.

What if I Don't Have an rPi?

If you don't have an rPi, you can still run the application from Visual Studio though of course the Linux, rPi, and LCD1602 specific stuff won't work. That leaves you with sending "ping" but you can easily add additional behaviors. In fact, I did a lot of the Slack API testing from a Windows box with Visual Studio.

Creating a Bot App in Slack

The first step is to create a bot app for your Slack account. If you don't have a Slack account, follow the "How to Get Started" section in the Creating Your First Slack article by Ryan Peden. IMPORTANT! At the point where you create your app, you will also need to create a bot. For example, my bot is called "rpichat" and is listed on the https://api.slack.com/apps page:

Image 11

Click on the bot and you'll see this:

Image 12

Click on "Add Features and functionality" and you'll see this:

Image 13

Click on Bots:

Image 14

and then "Add a Bot User". Set the display name and default user name, then click on Add Bot User:

Image 15

Click on OAuth & Permissions on the left:

Image 16

If you haven't already installed the app in your workspace, you'll see this button:

Image 17

Install the app, authorize it, and now you can see the Bot User OAuth Access token. 

Image 18

The Code

To begin with, three packages need to be added to the project:

Image 19

Image 20

Image 21

Main

This is really simple:

JavaScript
private static SlackSocketClient client;

static void Main(string[] args)
{
  Console.WriteLine("Initializing...");
  InitializeSlack();
  Console.WriteLine("Slack Ready.");
  Console.WriteLine("Press ENTER to exit.");
  Console.ReadLine();
}

SlackAPI

For this article, I'm using the SlackAPI, an open source C#, .NET Standard library which works great on the rPi. Please note that I have not investigated its robustness with regards to losing the websocket connection and restoring it.

Because we're using the Real Time Messaging (RTM) API and a bot app, we'll need to Bot User OAuth Access Token as found on the https://api.slack.com/apps page (navigate then to your app.) This is an important link to remember as it is the gateway to all your apps. In the OAuth Access section, you should see something like this, of course without the tokens blacked out:

Image 22

Copy the Bot Token (and the OAuth Token if you want) into the appSettings.json file:

JavaScript
{
  "Slack": {
    "AccessToken": "[you access token]",
    "BotToken": "your bot token]"
  }
}

The "AccessToken" isn't used in this article but you might want it there for other things that you do.

Initializing the API and Receiving Messages

Using the API is straight forward. One method handles the startup and message routing, the comments and code, which I've modified a bit, come from the SlackAPI wiki page examples:

JavaScript
static void InitializeSlack()
{   string botToken = Configuration["Slack:BotToken"];
  ManualResetEventSlim clientReady = new ManualResetEventSlim(false);
  client = new SlackSocketClient(botToken);

  client.Connect((connected) => {
    // This is called once the client has emitted the RTM start command
    clientReady.Set();
  }, () => {
    // This is called once the RTM client has connected to the end point
  });

  client.OnMessageReceived += (message) =>
  {
    // Handle each message as you receive them
    Console.WriteLine(message.user + "(" + message.username + "): " + message.text);

    if (message.text.StartsWith("rpi:"))
    {
      // Skip any spaces after "rpi:" and get what's left of the first space, ignoring data.
      string cmd = message.text.RightOf("rpi:").Trim().LeftOf(" ");

      // Get everything to the right after the command and any number of spaces 
     // separating the start of the data.
      string data = message.text.RightOf("rpi:").Trim().RightOf(" ").Trim();

      Console.WriteLine("cmd: " + cmd);
      Console.WriteLine("data: " + data);

      string ret = "Error occurred.";

      if (router.TryGetValue(cmd, out Func<string, string> fnc))
      {
        ret = fnc(data);
      }
      else
      {
        // Try as bash command.
        string cmdline = message.text.RightOf("rpi:").Trim();
        ret = "```" + cmdline.Bash() + "```";
      }

      client.PostMessage((mr) => { }, message.channel, ret);
    }
  };

  clientReady.Wait();
}

There are three things to note about the message handler in the above code:

  1. Any message that does not being with "rpi:" will be ignored. This is because when the application posts a message, the message event is fired so the application gets back the very message that was just posted. To distinguish between commands that you, the user, are sending, your commands must be prefixed with "rpi:".
  2. For console output of bash commands is returned in markdown block quotes which uses a monospace font and preserves leading spaces, so you get back a nicely formatted result.
  3. We always reply on the channel from which the message was received. You might be chatting with the bot in its app direct message channel, or if the bot has been invited to a "human" channel, we can chat with it there as well.

Setting Up the Configuration Parser

The configuration parser requires using Microsoft.Extensions.Configuration; and is implemented as a static getter (borrowed from here) and the two NuGet packages mentioned earlier:

JavaScript
public static IConfiguration Configuration { get; } = new ConfigurationBuilder()
  .SetBasePath(Directory.GetCurrentDirectory())
  .AddJsonFile("appSettings.json", optional: false, reloadOnChange: true)
  .Build();

The file on the *nix side is case-sensitive, so make sure to preserve the case of the filename and how you reference it in the above code.

The Command Router

The router is simply a command key - function dictionary -- if a command has an associated function, that function is called, otherwise it's assumed to be a bash command and the process is invoked.

JavaScript
private static Dictionary<string, Func<string, string>> router = 
                               new Dictionary<string, Func<string, string>>
{
  {"temp", GetTemp },
  {"display", Display },
  {"ping", (_) => "pong" },
};

Extend this for custom C# implementations.

The Bash Process Invoker

This code was borrowed from here:

JavaScript
public static string Bash(this string cmd)
{
  var escapedArgs = cmd.Replace("\"", "\\\"");

  var process = new Process()
  {
    StartInfo = new ProcessStartInfo
    {
      FileName = "/bin/bash",
      Arguments = $"-c \"{escapedArgs}\"",
      RedirectStandardOutput = true,
      UseShellExecute = false,
      CreateNoWindow = true,
    }
  };

  process.Start();
  string result = process.StandardOutput.ReadToEnd();
  process.WaitForExit();
  return result;
}

It implements an extension method, hence its usage looks like "df -h".Bash(). The -c in the arguments is actually telling bash the command (as an argument to bash) to run.

The Commands I've Implemented

Besides the "ping" command, I implemented a couple other things based on what I've got hooked up at the moment.

Getting the rPi Temperature

The processor has a built-in temperature sensor and the temperature is exposed a a file (I found this originally in some Python code and added the Fahrenheit math):

JavaScript
private static string GetTemp(string _)
{
  string ret;
  string temp = System.IO.File.ReadAllText("/sys/class/thermal/thermal_zone0/temp");
  Console.WriteLine(temp);
  double t = Convert.ToDouble(temp);
  string dc = String.Format("{0:N2}", t / 1000);
  string df = String.Format("{0:N2}", t / 1000 * 9 / 5 + 32);
  ret = dc + "C" + " " + df + "F";

  return ret;
} 

Writing to the LCD1602

From my previous article, I can now display messages to the LCD1602 from Slack!

JavaScript
// Data must be in the format of one of these two options:
// "This is line 1"
// "This is line 1"[d]"This is line 2"
// where [d] is an optional delimiter of any string.
private static string Display(string data)
{
  int numQuotes = data.Count(c => c == '\"');

  if (data.First() != '\"' || data.Last() != '\"' && (numQuotes != 2 && numQuotes != 4))
  {
    return "bad format";
  }

  Lcd1602 lcd = new Lcd1602();
  lcd.OpenDevice("/dev/i2c-1", LCD1602_ADDRESS);
  lcd.Init();
  lcd.Clear();

  if (numQuotes == 2)
  {
    lcd.Write(0, 0, data.Between("\"", "\""));
  }
  else
  {
    // two lines
    lcd.Write(0, 0, data.Between("\"", "\""));
    lcd.Write(0, 1, data.RightOf("\"").RightOf("\"").Between("\"", "\""));
  }

  lcd.CloseDevice();

  return "ok";
}

Querying Postgres

Actually, any Postgres SQL command can be executed through your Slack bot, here I show queries.

Executing the SQL, including queries, is straight forward using ADO.NET. For queries, an option for formatting (defaults to JSON) can be provided. The Match extension method is documented in my article here. My Match extension method would probably be replaced with the C# 8's switch statement and its lovely terseness.

The Northwind database was imported into Postgres using this GitHub repo.

Regarding fetch first 2 rows only, this is part of SQL 2008 but doesn't work in MS SQL Server!

Also, to get this to work, add the appropriate connection string to your appsettings.json file:

JavaScript
"ConnectionStrings": {
  "rpidb": "Host=[your IP];Database=Northwind;Username=pi;Password=[your password]"
}

The ExecuteSQL method:

JavaScript
enum OutputFormat
{
  JSON,
  CSV,
  Tabular,
}

private static string ExecuteSql(string data, List<string> options)
{
  string sql = data;
  var outputFormat = OutputFormat.JSON;
  string ret = "";
  string validOptionsErrorMessage = "Valid options are --json, --csv, --tabular";

  try
  {
    options.Match(
      (o => o.Count == 0,           _ => { }),
      (o => o.Count > 1,            _ => throw new Exception(validOptionsErrorMessage)),
      (o => o[0] == "--json",       _ => outputFormat = OutputFormat.JSON),
      (o => o[0] == "--csv",        _ => outputFormat = OutputFormat.CSV),
      (o => o[0] == "--tabular",    _ => outputFormat = OutputFormat.Tabular),
      (_ => true,                   _ => throw new Exception(validOptionsErrorMessage))
    );

    string connStr = Configuration.GetValue<string>("ConnectionStrings:rpidb");
    var conn = new NpgsqlConnection(connStr);
    conn.Open();
    var cmd = new NpgsqlCommand(sql, conn);

    NpgsqlDataAdapter da = new NpgsqlDataAdapter(cmd);
    DataTable dt = new DataTable();
    da.Fill(dt);

    ret = outputFormat.MatchReturn(
      (f => f == OutputFormat.JSON, _ => Jsonify(dt)),
      (f => f == OutputFormat.CSV, _ => Csvify(dt)),
      (f => f == OutputFormat.Tabular, _ => Tabify(dt))
    );

    ret = "```\r\n" + ret + "```";
  }
  catch (Exception ex)
  {
    ret = ex.Message;
  }

  return ret;
}

Returning JSON

Dead simple using Newtsoft.JSON:

JavaScript
static string Jsonify(DataTable dt)
{
  string ret = JsonConvert.SerializeObject(dt, Formatting.Indented);

  return ret.ToString();
}

Example:

Image 23

Returning a CSV

It is also quite simple:

JavaScript
static string Csvify(DataTable dt)
{
  StringBuilder sb = new StringBuilder();

  sb.AppendLine(String.Join(", ", dt.Columns.Cast<DataColumn>().Select(dc => dc.ColumnName)));

  foreach (DataRow row in dt.Rows)
  {
    sb.AppendLine(String.Join(", ", dt.Columns.Cast<DataColumn>().Select(dc => row[dc].ToString())));
  }

  return sb.ToString();
}

Example:

Image 24

Returning Tabular Formatted Data

Here, the width of each column name and row's data is accounted for requires some of Math.Max for the column names and each row data. Tabify is probably not the greatest name!

JavaScript
static string Tabify(DataTable dt)
{
  StringBuilder sb = new StringBuilder();
  int[] colWidth = new int[dt.Columns.Count];

  // Get max widths for each column.
  dt.Columns.Cast<DataColumn>().ForEachWithIndex((dc, idx) =>
  colWidth[idx] = Math.Max(colWidth[idx], dc.ColumnName.Length));

  // Get the max width of each row's column.
  dt.AsEnumerable().ForEach(r =>
  {
    dt.Columns.Cast<DataColumn>().ForEachWithIndex((dc, idx) =>
      colWidth[idx] = Math.Max(colWidth[idx], r[dc].ToString().Length));
  });

  // Bump all widths by 3 for better visual separation
  colWidth.ForEachWithIndex((n, idx) => colWidth[idx] = n + 3);

  // Padded column names:
  sb.AppendLine(string.Concat(dt.Columns.Cast<DataColumn>().Select((dc, idx) =>
    dc.ColumnName.PadRight(colWidth[idx]))));

  // Padded row data:
  dt.AsEnumerable().ForEach(r =>
    sb.AppendLine(string.Concat(dt.Columns.Cast<DataColumn>().Select((dc, idx) =>
      r[dc].ToString().PadRight(colWidth[idx])))));

  return sb.ToString();
}

Example:

Image 25

Limitations

There's a 4,000 character limit on what can be posted to a Slack channel, so don't go nuts querying hundreds of records and dozens of columns!

Leaving the Program Running

If you want to make the application a service so it always starts up, in the event of a power loss, for example, refer to my previous article on setting up a service. Alternatively, if you simply want to have the program keep running even after you close the terminal window:

nohup  > /dev/null &

The & makes the process run in the background (this is true for any process that you start), and nohup is "no hang up" when the terminal closes. The redirect > /dev/null redirects console output to nothing rather than the nohup.out file. Read about nohup here.

In this case, I changed main, removing the "press ENTER to exit" and replaced it with a do nothing loop:

JavaScript
while (!stop) Thread.Sleep(1);
Thread.Sleep(1000); // wait for final message to be sent.
// Console.WriteLine("Press ENTER to exit.");
//Console.ReadLine();

and I added a "stop" command to terminate the program from Slack:

JavaScript
{"stop", _ => {stop=true; return "Stopping..."; } }

Image 26

Conclusion

While the code is very simple, this opens up a whole new world of bidirectional communication between Slack and the rPi (or any SBC for that matter). I can imagine using this to do things like starting and stopping services, getting the status of various devices attached to the rPi, issuing commands, and so forth. I can imagine mounting an rPi or an Arduino on a LEGO robot and using Slack messaging to drive the robot and even post image files! If I had the time and the hardware, I'd definitely play around with that some more. 

Revision History

  • 1/27/2019 - Added Postgres command processing

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)