I want to use ESP8266 to lights up LEDs when I get notification from slack.
Everything seems to work fine when there is utime.sleep() in the main loop, but once it's removed nothing happens.
It looks like loop execute only once, if there is some slack message on start ESP8266 is detecting that.
I have also added some del because I was getting "memory allocation failed"
It takes few seconds to retrieve data from slack and it returns JSON. Depending on the slack workspace it can be quit big.
What can causing this?
Code: Select all
import network
import urllib.urequest
import json
import gc
import utime
slack_api = "https://slack.com/api/"
slack_token = "xoxp-000000000000-000000000000-000000000000-00000000000000000000000000000000"
#get all channels, groups and direct messages
def conversations_list():
url = slack_api + "conversations.list?token=" + slack_token + "&types=public_channel,private_channel,mpim,im"
f = urllib.urequest.urlopen(url)
j = json.loads(f.read())
f.close()
del url
del f
return j
#get direct messages history from slack, needed for "unread_count_display"
def im_history(id):
url = slack_api + "im.history?token=" + slack_token + "&channel=" + id + "&count=1&unreads=1"
f = urllib.urequest.urlopen(url)
j = json.loads(f.read())
f.close()
del url
del f
return j
#get direct channels info from slack, needed for "unread_count_display"
def channels_info(id):
url = slack_api + "channels.info?token=" + slack_token + "&channel=" + id
f = urllib.urequest.urlopen(url)
j = json.loads(f.read())
f.close()
del url
del f
return j
#get direct groups info from slack, needed for "unread_count_display"
def groups_info(id):
url = slack_api + "groups.info?token=" + slack_token + "&channel=" + id
f = urllib.urequest.urlopen(url)
j = json.loads(f.read())
f.close()
del url
del f
return j
#connect to WiFi
sta_if = network.WLAN(network.STA_IF)
ap_if = network.WLAN(network.AP_IF)
sta_if.active(True)
ap_if.active(False)
sta_if.connect('SSID', '*****')
oldState = False
while True:
convList = conversations_list()["channels"]
state = False
#loop that iterates conversations (channels/groups/direct messages) and checks for unread messages
for conv in convList:
#"is_channel" and "is_group" aren't present in direct message record, so we need to test this first.
if conv["is_im"] == True:
info = im_history(conv["id"])
if info["unread_count_display"] > 0:
state = True
del info
break
del info
continue
if conv["is_channel"] == True and conv["is_member"] == True:
info = channels_info(conv["id"])["channel"]
if info["is_member"] == True and info["unread_count_display"] > 0:
state = True
del info
break
del info
if conv["is_group"] == True:
info = groups_info(conv["id"])["group"]
if info["unread_count_display"] > 0:
state = True
del info
break
del info
del convList
#check if state changed
if state != oldState:
print("state changed")
oldState = state
gc.collect()