Search code examples
pythonslackslack-api

How to read incoming slack messages?


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?


Solution

  • 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.