Pushing slack channels wip

This commit is contained in:
Nathanial Hendler 2021-09-25 13:26:08 -07:00
parent ddb8ecf415
commit 609072c57b
4 changed files with 147 additions and 39 deletions

View File

@ -14,7 +14,7 @@ ArduinoSlack::ArduinoSlack(Client &client, const char *bearerToken)
this->_bearerToken = bearerToken;
}
int ArduinoSlack::makeGetRequest(const char *command, const char *body, const char *contentType)
int ArduinoSlack::makeGetRequest(const char *command)
{
client->flush();
client->setTimeout(SLACK_TIMEOUT);
@ -36,22 +36,23 @@ int ArduinoSlack::makeGetRequest(const char *command, const char *body, const ch
client->print(F("Host: "));
client->println(SLACK_HOST);
client->println(F("Accept: application/json"));
client->print(F("Content-Type: "));
client->println(contentType);
//client->println(F("Accept: application/json"));
//client->print(F("Content-Type: "));
//client->println(contentType);
client->print(F("Authorization: Bearer "));
client->println(_bearerToken);
client->println(F("Cache-Control: no-cache"));
client->print(F("Content-Length: "));
client->println(strlen(body));
//client->print(F("Content-Length: "));
//client->println(strlen(body));
client->println();
//client->println();
//send Data here?
client->print(body);
//client->print(body);
if (client->println() == 0)
{
@ -162,51 +163,123 @@ bool ArduinoSlack::setPresence(const char *presence)
return okStatus;
}
SlackConvoHist ArduinoSlack::conversationHistory(const char *channel, const char *limit)
SlackUsersConversations ArduinoSlack::usersConversations()
{
SLACK_DEBUG_SERIAL_LN(F("--------------"));
SLACK_DEBUG_SERIAL_LN(F("conversationHistory()"));
char body[300];
sprintf(body, setConvoHistoryBody, channel, limit);
SLACK_DEBUG_SERIAL_LN(body);
//char body[300];
//sprintf(body, setConvoHistoryBody, channel, limit);
//SLACK_DEBUG_SERIAL_LN(body);
// Get from https://arduinojson.org/v6/assistant/
const size_t bufferSize = profileBufferSize;
SlackConvoHist conversation;;
SlackUsersConversations conversations;
// This flag will get cleared if all goes well
conversation.error = true;
if (makePostRequest(SLACK_CONVERSATIONS_HISTORY_ENDPOINT, body) == 200)
conversations.error = true;
//SLACK_SERIAL_LN("GET String:");
//SLACK_SERIAL_LN(SLACK_CONVERSATIONS_HISTORY_ENDPOINT);
//SLACK_SERIAL_LN(usersConversationsGET);
//int response = makeGetRequest(SLACK_USERS_CONVERSATIONS_ENDPOINT);
int response = makeGetRequest("/api/users.conversations?exclude_arc=True&limit=17");
//if (makeGetRequest(SLACK_USERS_CONVERSATIONS_ENDPOINT) == 200)
if (response == 200)
{
// So it seems for whatever reason every other line is bad. I don't
// know why this is, but this will remove them so they don't break
// the Json...
String chunk;
String payload;
int limit=1;
do {
if (client->connected()) {
yield();
chunk = client->readStringUntil('\n');
//SLACK_DEBUG_SERIAL("CHUNK #");
//SLACK_DEBUG_SERIAL(limit);
//SLACK_DEBUG_SERIAL(": ");
//SLACK_DEBUG_SERIAL_LN(chunk);
if (limit % 2 == 0) {
// skip even lines.
} else {
payload += chunk;
}
}
} while (chunk.length() > 0 && ++limit < 100);
//String payload = client->readString();
//SLACK_DEBUG_SERIAL_LN("Payload!");
//SLACK_DEBUG_SERIAL_LN(payload);
// Allocate DynamicJsonDocument
DynamicJsonDocument doc(bufferSize);
// Parse JSON object
DeserializationError error = deserializeJson(doc, *client);
StaticJsonDocument<200> filter;
filter["channels"][0]["name"] = true;
filter["channels"][0]["id"] = true;
filter["response_metadata"]["next_cursor"] = true;
//StaticJsonDocument<400> doc;
//DeserializationError error = deserializeJson(doc, *client, DeserializationOption::Filter(filter));
DeserializationError error = deserializeJson(doc, payload, DeserializationOption::Filter(filter));
if (!error)
{
SLACK_DEBUG_SERIAL_LN(F("parsed Json Object: "));
#ifdef SLACK_ENABLE_DEBUG
serializeJson(doc, Serial);
#endif
JsonObject messageObj = doc["messages"];
conversation.messageObj = messageObj;
//message.text = (char *)messageObj["text"].as<char *>();
//message.username = (char *)messageObj["username"].as<char *>();
//message.bot_id = (char *)messageObj["bot_id"].as<char *>();
//message.type = (char *)messageObj["type"].as<char *>();
JsonObject channelsObj = doc["channels"];
conversations.channelsObj = channelsObj;
SLACK_DEBUG_SERIAL_LN(F(""));
SLACK_DEBUG_SERIAL_LN(F("+++++++++++++++++++++++++++++++++"));
SLACK_DEBUG_SERIAL_LN(doc["channels"].size());
SLACK_DEBUG_SERIAL_LN(F(""));
serializeJsonPretty(doc["channels"][0], Serial);
SLACK_DEBUG_SERIAL_LN(F(""));
serializeJsonPretty(doc["channels"][1], Serial);
SLACK_DEBUG_SERIAL_LN(F(""));
serializeJsonPretty(doc["channels"][doc["channels"].size()-1], Serial);
SLACK_DEBUG_SERIAL_LN(F(""));
SLACK_DEBUG_SERIAL_LN(F("+++++++++++++++++++++++++++++++++"));
SLACK_DEBUG_SERIAL_LN(F(""));
conversation.error = false;
//char (*a[2])[14]
//String *channel_names[doc["channels"].size()];
//String *channel_ids[doc["channels"].size()];
//String channel_names[22];
//String channel_ids[22];
for (int ii=0; ii<doc["channels"].size(); ii++) {
//channel_names[ii] = (char *)doc["channels"][ii]["name"].as<char *>();
//channel_ids[ii] = (char *)doc["channels"][ii]["id"].as<char *>();
//channel_names[ii] = doc["channels"][ii]["name"];
//channel_ids[ii] = doc["channels"][ii]["id"];
//conversations.channelNames[ii] = doc["channels"][ii]["name"];
conversations.channelNames[ii] = (char *)doc["channels"][ii]["name"].as<char *>();
}
//conversations.channelNames = (char *)doc[0]["name"].as<char *>();
//conversations.channelIds = (char *)doc[0]["id"].as<char *>();
//channels.text = (char *)doc["text"].as<char *>();
//channels.username = (char *)doc["username"].as<char *>();
//channels.bot_id = (char *)doc["bot_id"].as<char *>();
//channels.type = (char *)doc["type"].as<char *>();
//channels.channelNames = channel_names;
//channels.channelIds = channel_ids;
conversations.error = false;
}
else
{
SLACK_DEBUG_SERIAL(F("deserializeJson() failed with code "));
SLACK_DEBUG_SERIAL_LN(error.c_str());
}
} else {
SLACK_DEBUG_SERIAL_LN(F("Didn't get 200"));
SLACK_DEBUG_SERIAL_LN(response);
}
closeClient();
return conversation;
return conversations;
}
@ -317,8 +390,8 @@ void ArduinoSlack::skipHeaders(bool tossUnexpectedForJSON)
{
char c = 0;
client->readBytes(&c, 1);
SLACK_DEBUG_SERIAL(F("Tossing an unexpected character: "));
SLACK_DEBUG_SERIAL_LN(c);
//SLACK_DEBUG_SERIAL(F("Tossing an unexpected character: "));
//SLACK_DEBUG_SERIAL_LN(c);
}
}
}

View File

@ -46,6 +46,7 @@ MIT License
#define SLACK_USERS_SET_PRESENCE_ENDPOINT "/api/users.setPresence?presence=%s"
#define SLACK_POST_MESSAGE_ENDPOINT "/api/chat.postMessage"
#define SLACK_CONVERSATIONS_HISTORY_ENDPOINT "/api/conversations.history"
#define SLACK_USERS_CONVERSATIONS_ENDPOINT "/api/users.conversations"
struct SlackProfile
{
@ -66,9 +67,13 @@ struct SlackMessage
bool error;
};
struct SlackConvoHist
struct SlackUsersConversations
{
JsonObject messageObj;
JsonObject channelsObj;
//String channelNames[22];
//String channelIds[22];
char *channelNames[17];
char *channelIds[17];
bool error;
};
@ -78,10 +83,11 @@ class ArduinoSlack
public:
ArduinoSlack(Client &client, const char *bearerToken);
int makeGetRequest(const char *command);
int makePostRequest(const char *command, const char *body, const char *contentType = "application/json");
SlackProfile setCustomStatus(const char *text, const char *emoji, int expiration = 0);
SlackMessage postMessage(const char *channel, const char *text);
SlackConvoHist conversationHistory(const char *channel, const char *limit);
SlackUsersConversations usersConversations();
bool setPresence(const char *presence);
int portNumber = 443;
int profileBufferSize = 10000;
@ -93,6 +99,8 @@ private:
void skipHeaders(bool tossUnexpectedForJSON = true);
void closeClient();
const char *usersConversationsGET =
R"(%s?exclude_arc=True&limit=1)";
const char *setConvoHistoryBody =
R"({"channel": "%s", "limit": "%s"})";
const char *setMessageBody =

6
examples/slack/README.md Normal file
View File

@ -0,0 +1,6 @@
```
~/.arduino15/packages/esp32/hardware/esp32/1.0.6/tools/sdk/sdkconfig
```
Set `CONFIG_SPIRAM_USE_MALLOC=y` to use SPI Ram for heap memory.

View File

@ -1,12 +1,8 @@
/*
Use this program with the Apple2idIOT card and the basic programs RRAM, WRAM and CMDROT to read/write and rot13
a single string contained within the dual port ram on the card.
CA = 49664
AA = CA + 1
*/
// Load Wi-Fi library
#include <WiFi.h>
//#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <ArduinoJson.h>
#include <HTTPClient.h>
@ -33,8 +29,10 @@ char wifi_password[] = WIFI_PASSWORD; // your network password
/*******************/
/* Misc */
/*******************/
SlackUsersConversations conversation;
const long readLoopInterval = 100; // millis
//const long readLoopInterval = 100; // millis
const long readLoopInterval = 44000; // millis
unsigned long lastReadLoopTime = 0;
byte lastAppleCommand = 0;
@ -65,6 +63,28 @@ void setup() {
Serial.println(WiFi.localIP()); //Show ESP32 IP on serial
client.setCACert(slack_server_cert);
//Serial.println(conversation);
int slack_attempts=1;
do {
yield();
conversation = slack.usersConversations();
} while (conversation.error && ++slack_attempts < 5);
yield();
Serial.println("+-+-+-+- CHANNELS -+-+-+-+-+-+-+-+:");
//for (int i=0; i< sizeof(conversation.channelNames)-5; i++) {
//for (int i=0; i<5; i++) {
//Serial.print(conversation.channelNames[i]);
//Serial.print(" -> ");
//Serial.println(conversation.channelIds[i]);
//}
yield();
Serial.println(conversation.channelNames[0]);
Serial.println(conversation.channelNames[1]);
Serial.println(conversation.channelNames[2]);
Serial.println(conversation.channelNames[-1]);
Serial.println("Setup done");
}
@ -80,11 +100,12 @@ void setup() {
//String channel_name = "equant-test";
String channel_name = "C02EAQECY5A";
String message = "";
SlackConvoHist conversation;
void loop() {
if ((millis() - lastReadLoopTime) > readLoopInterval) {
byte command_byte = a2i.read_data(APPLE_COMMAND_ADDRESS);
if (command_byte == RAM_BUSY) {
Serial.println("Command Read: RAM BUSY");
@ -99,8 +120,8 @@ void loop() {
a2i.write_data(ESP_COMMAND_ADDRESS, ACK); // notify Apple IIe we are processing command byte
char cc[250];
channel_name.toCharArray(cc, 250);
conversation = slack.conversationHistory(cc, "2");
serializeJsonPretty(conversation.messageObj, Serial);
conversation = slack.usersConversations();
//serializeJsonPretty(conversation.messageObj, Serial);
a2i.write_data(APPLE_COMMAND_ADDRESS, ACK);
a2i.write_data(ESP_COMMAND_ADDRESS, EOT); // notify Apple IIe we are done processing command byte
break;