Distribution

Scheduled Slack Sharing

This example shows how to use the Mode API to create a schedule for delivering reports via Slack. You can use this example to create multiple schedules with different parameter values, to send a report to different Slack channels, and so on.

Endpoints used

.../{workspace}/reports/{report_token}/subscriptions
Supported methods:

  • GET: returns all schedules for a report
  • POST: creates a new schedule

.../{workspace}/reports/{report_token}/subscriptions/{subscription_token}
Supported methods:

  • GET: returns a schedule
  • PATCH: updates a schedule

.../{workspace}/reports/{report_token}/subscriptions/{subscription_token}/slack_memberships
Supported methods:

  • GET: returns the Slack channel to which the report is delivered on schedule
  • POST: adds Slack channel to which the report is delivered on schedule
  • PATCH: updates the channel to which the report is delivered on schedule

How this example works

In this example, the create_slack_schedule method first makes a POST request to app.mode.com/api/{workspace}/reports/{report_token}/subscriptions, creating a schedule. You can specify the time interval, preview/report link preferences, and parameter values in the payload. We then make a GET request to that same endpoint, to return all schedules in the report. We look at the first schedule on the list, the most recently created one, and get its subscription token. This subscription token lets us add a Slack channel by making a subsequent POST request to app.mode.com/api/{workspace}/reports/{report_token}/subscriptions/{subscription_token}/slack_memberships.

To try it yourself

  • Download the example code to a .py file
  • Input the API token, API secret, Workspace name, and other custom information as needed. Follow these steps to create an API token.
  • Save the .py file in your desired directory
  • Open the terminal and navigate to that directory
  • Run the command python3 {file_name}.py
  • All of our Python recipes require Python 3
import json
import requests

from requests.auth import HTTPBasicAuth

host = 'https://modeanalytics.com'
ws = 'workspace_name' # Note: workspace_name value should be all lowercase
un = 'api_token'
pw = 'api_secret'


def create_slack_schedule(report_token, slack_channel_name):
  #create schedule and specify parameter values the schedule should be run with, if any
  url = '%s/api/%s/reports/%s/subscriptions' % (host, ws, report_token)
  headers = {'Content-Type': 'application/json'}
  payload = {'report_subscription': {
               'csv_attachments_enabled':'false',
               'data_previews_enabled': 'true',
               'data_tables_enabled':'false',
               'pdf_attachments_enabled':'false',
               'report_links_enabled':'true',
               'report_schedule':{
                 'cron':{
                   'freq': 'daily',
                   'hour': 14,
                   'time_zone': 'UTC',
                   'day_of_week': 1,
                   'day_of_month': 1,
                   'minute': 0
                 },
                 # params optional
                 'params':{
                   'foo': 'bar'
                 },
                 'timeout':900
               }
             },
             'trk_source':'report'
            }
  r = requests.post(url, headers=headers, auth=HTTPBasicAuth(un, pw), json=payload)
  #get the newest report subscription token and path
  r = requests.get(url, headers=headers, auth=HTTPBasicAuth(un, pw))
  result = r.json()
  subscription_path = result['_embedded']['report_subscriptions'][0]['_links']['self']['href']
  #add slack channel the scheduled report should send to
  url = '%s%s/slack_memberships' % (host, subscription_path)
  headers = {'Content-Type': 'application/json'}
  payload = {'membership': {'subscriber_channel': slack_channel_name}, 'trk_source':'report'}
  r = requests.post(url, headers=headers, auth=HTTPBasicAuth(un, pw), json=payload)
  return r.status_code


create_slack_schedule('report_token', 'slack_channel_name')
const request = require('request-promise');

const host = 'https://modeanalytics.com';
const ws = 'workspaceName'; // Note: workspaceName value should be all lowercase
const username = 'apiToken';
const password = 'apiSecret';

const createSlackSchedule = async (reportToken, slackChannelName) => {
  // create schedule and specify parameter values the schedule should be run with, if any
  const reportSubscription = {
    report_subscription: {
      csv_attachments_enabled: false,
      data_previews_enabled: true,
      data_tables_enabled: false,
      pdf_attachments_enabled: false,
      report_links_enabled: true,
      report_schedule: {
        cron: {
          freq: 'daily',
          hour: 14,
          time_zone: 'UTC',
          day_of_week: 1,
          day_of_month: 1,
          minute: 0
        },
        // params optional
        params: {
          'foo': 'bar'
        },
        timeout: 900,
      },
    },
    trk_source: 'report',
  };
  const res = await request({
    method: 'POST',
    url: `${host}/api/${ws}/reports/${reportToken}/subscriptions`,
    auth: { username, password },
    json: true,
    body: reportSubscription,
  });
  // get the newest report subscription token and path
  const subscriptions = await request({
    url: `${host}/api/${ws}/reports/${reportToken}/subscriptions`,
    auth: { username, password },
    json: true,
  });
  const subscriptionPath = subscriptions._embedded.report_subscriptions[0]._links.self.href;

  // add slack channel the scheduled report should send to
  const payload = {
    membership: { subscriber_channel: slackChannelName },
    trk_source: 'report',
  };

  return await request({
    method: 'POST',
    url: `${host}${subscriptionPath}/slack_memberships`,
    auth: { username, password },
    json: true,
    body: payload,
  });
};

createSlackSchedule('reportToken', 'slackChannelName');