Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading incoming slack message

A report is posted every 5 hrs on a Slack channel, from which we need to sort/filter some information and put it into a file.

So, is there any way to read the channel continuously or run some command every 5 minutes or so before that time, and capture the report for future processing?

like image 251
user3561766 Avatar asked Oct 17 '22 07:10

user3561766


2 Answers

Yes, that is possible. Here is the basic outline of a solution:

  • Create a Slack app based on a script (e.g. in Python) that has access to that channel's history (e.g. has the channels:history permission scope)
  • Use cron to call your script at the needed time
  • The script reads the channels history (e.g. with channel.history for public channels), filterers out what it needs and then stores the report as file.

Another approach would be to continuously read every new message from the channel, parse for a trigger (e.g. a specific user that sends it or the name of the report) and then filter and safe the report when it appears. If you can identify a reliable trigger this would in my experience be the more stable solution, since scheduled reports can be delayed.

For that approach use the Events API of Slack instead of CRON and subscribe to receiving messages (e.g. message event for public channels). Slack will then automatically send each new message to your script as soon as it is posted.

If you are new to creating Slack apps I would advise to study the excellent official documentation and tutorials on the Slack API site to get started.

like image 142
Erik Kalkoken Avatar answered Oct 21 '22 07:10

Erik Kalkoken


A Python example to this approach could be found here: https://gist.github.com/demmer/617afb2575c445ba25afc432eb37583b

This script counts the amount of messages per user.

Based on this code I created the following example for you:

# get the correct channel id
for channel in channels['channels']:
    if channel['name'] == channel_name:
        channel_id = channel['id']
if channel_id == None:
    raise Exception("cannot find channel " + channel_name)

# get the history as follows: 
history = sc.api_call("channels.history", channel=channel_id)

# get all the messages from the history: 
messages = history['messages']

# Or reference them by ID, so in this case get the first message:
ids = messages[0]
like image 35
Chiel Avatar answered Oct 21 '22 09:10

Chiel