Contents
This article is my submission to the Slack API Challenge.
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!
You should already know:
- how to create a .NET Core application
- publish it with the linux-arm architecture
- WinSCP (or PCSP) it over to the rPi
- 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.
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.
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:
Click on the bot and you'll see this:
Click on "Add Features and functionality" and you'll see this:
Click on Bots:
and then "Add a Bot User". Set the display name and default user name, then click on Add Bot User:
Click on OAuth & Permissions on the left:
If you haven't already installed the app in your workspace, you'll see this button:
Install the app, authorize it, and now you can see the Bot User OAuth Access token.
To begin with, three packages need to be added to the project:
This is really simple:
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();
}
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:
Copy the Bot Token (and the OAuth Token if you want) into the appSettings.json file:
{
"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.
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:
static void InitializeSlack()
{ string botToken = Configuration["Slack:BotToken"];
ManualResetEventSlim clientReady = new ManualResetEventSlim(false);
client = new SlackSocketClient(botToken);
client.Connect((connected) => {
clientReady.Set();
}, () => {
});
client.OnMessageReceived += (message) =>
{
Console.WriteLine(message.user + "(" + message.username + "): " + message.text);
if (message.text.StartsWith("rpi:"))
{
string cmd = message.text.RightOf("rpi:").Trim().LeftOf(" ");
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
{
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:
- 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:
". - 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.
- 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.
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:
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 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.
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.
This code was borrowed from here:
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.
Besides the "ping
" command, I implemented a couple other things based on what I've got hooked up at the moment.
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):
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;
}
From my previous article, I can now display messages to the LCD1602
from Slack!
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
{
lcd.Write(0, 0, data.Between("\"", "\""));
lcd.Write(0, 1, data.RightOf("\"").RightOf("\"").Between("\"", "\""));
}
lcd.CloseDevice();
return "ok";
}
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:
"ConnectionStrings": {
"rpidb": "Host=[your IP];Database=Northwind;Username=pi;Password=[your password]"
}
The ExecuteSQL
method:
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;
}
Dead simple using Newtsoft.JSON:
static string Jsonify(DataTable dt)
{
string ret = JsonConvert.SerializeObject(dt, Formatting.Indented);
return ret.ToString();
}
Example:
It is also quite simple:
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:
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!
static string Tabify(DataTable dt)
{
StringBuilder sb = new StringBuilder();
int[] colWidth = new int[dt.Columns.Count];
dt.Columns.Cast<DataColumn>().ForEachWithIndex((dc, idx) =>
colWidth[idx] = Math.Max(colWidth[idx], dc.ColumnName.Length));
dt.AsEnumerable().ForEach(r =>
{
dt.Columns.Cast<DataColumn>().ForEachWithIndex((dc, idx) =>
colWidth[idx] = Math.Max(colWidth[idx], r[dc].ToString().Length));
});
colWidth.ForEachWithIndex((n, idx) => colWidth[idx] = n + 3);
sb.AppendLine(string.Concat(dt.Columns.Cast<DataColumn>().Select((dc, idx) =>
dc.ColumnName.PadRight(colWidth[idx]))));
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:
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!
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:
while (!stop) Thread.Sleep(1);
Thread.Sleep(1000);
and I added a "stop
" command to terminate the program from Slack:
{"stop", _ => {stop=true; return "Stopping..."; } }
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.
- 1/27/2019 - Added Postgres command processing