{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Introduction: Interacting with Slack from Python\n",
    "\n",
    "In this notebook, we will use `Slacker` to interact with Slack. This allows us to send messages and upload files, which can be useful when training models, or monitoring scripts (or just for fun of course)!"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "distributed 1.20.2 has requirement tornado>=4.5.1, but you'll have tornado 4.3 which is incompatible.\n",
      "You are using pip version 10.0.1, however version 18.0 is available.\n",
      "You should consider upgrading via the 'python -m pip install --upgrade pip' command.\n"
     ]
    }
   ],
   "source": [
    "!pip install -q -U Slacker"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "\n",
    "# Slacker \n",
    "from slacker import Slacker\n",
    "\n",
    "import matplotlib.pyplot as plt\n",
    "import seaborn as sns\n",
    "%matplotlib inline\n",
    "plt.style.use('fivethirtyeight')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Get a Slack Legacy API Token\n",
    "\n",
    "https://api.slack.com/custom-integrations/legacy-tokens\n",
    "\n",
    "Store in a safe location (not on GitHub)!"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Read in slack api token."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('C:/Users/willk/OneDrive/Desktop/slack_api_python.txt', 'r') as f:\n",
    "    slack_api_token = f.read()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Authenticate with slack"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Channel general Purpose: This channel is for workspace-wide communication and announcements. All members are in this channel.\n",
      "Channel random Purpose: A place for non-work-related flimflam, faffing, hodge-podge or jibber-jabber you'd prefer to keep out of more focused work-related channels.\n",
      "Channel slack_interaction Purpose: To interact with Slack from Python\n",
      "Channel testing_exp Purpose: Experimental testing of interactions.\n"
     ]
    }
   ],
   "source": [
    "slack = Slacker(slack_api_token)\n",
    "channels = slack.channels.list()\n",
    "\n",
    "for channel in channels.body['channels']:\n",
    "    print(f'Channel {channel[\"name\"]} Purpose: {channel[\"purpose\"][\"value\"]}')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<matplotlib.image.AxesImage at 0x21f0b7fb780>"
      ]
     },
     "execution_count": 42,
     "metadata": {},
     "output_type": "execute_result"
    },
    {
     "data": {
      "image/png": "[encoded data, 44460 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x21f0b019be0>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from PIL import Image\n",
    "import requests\n",
    "url = user['profile']['image_192']\n",
    "im = Image.open(requests.get(url, stream=True).raw)\n",
    "plt.imshow(im)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "PIL.Image.from"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 55,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "User: wjk68, Real Name: Will Koehrsen, Time Zone: Eastern Daylight Time.\n",
      "Current Status: Running\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 148452 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x21f0ca4ab70>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "User: slackbot, Real Name: slackbot, Time Zone: Pacific Daylight Time.\n",
      "Current Status: \n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 37372 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x21f0b4eef28>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from IPython.display import Image\n",
    "from PIL import Image\n",
    "import PIL\n",
    "users = slack.users.list()\n",
    "\n",
    "for user in users.body['members']:\n",
    "    # Print some information\n",
    "    print(f'\\nUser: {user[\"name\"]}, Real Name: {user[\"real_name\"]}, Time Zone: {user[\"tz_label\"]}.')\n",
    "    print(f'Current Status: {user[\"profile\"][\"status_text\"]}')\n",
    "    # Get image data and show\n",
    "    plt.figure(facecolor = 'w')\n",
    "    plt.imshow(Image.open(requests.get(user['profile']['image_192'], stream=True).raw))\n",
    "    plt.axis('off');\n",
    "    plt.grid('off');\n",
    "    plt.show();"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 59,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 10164 characters]\n",
      "text/plain": [
       "<matplotlib.figure.Figure at 0x21f0b665630>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "plt.plot(np.random.randn(100), np.random.randn(100), 'ro')\n",
    "plt.savefig('first_plot.png')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 61,
   "metadata": {},
   "outputs": [],
   "source": [
    "slack.files.upload('first_plot.png', channels = ['testing_exp', 'slack_interaction']);"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 34,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 30388 characters]\n",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "execution_count": 34,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "Image(user['profile']['image_192'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 8332 characters]\n",
      "text/plain": [
       "<IPython.core.display.Image object>"
      ]
     },
     "execution_count": 30,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "\n",
    "Image('https://secure.gravatar.com/avatar/f85b7564fd35d5c86054b95090052d94.jpg?s=192&d=https%3A%2F%2Fa.slack-edge.com%2F7fa9%2Fimg%2Favatars%2Fava_0025-192.png')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'color': '9f69e7',\n",
       "  'deleted': False,\n",
       "  'has_2fa': False,\n",
       "  'id': 'UCEKVNHPH',\n",
       "  'is_admin': True,\n",
       "  'is_app_user': False,\n",
       "  'is_bot': False,\n",
       "  'is_owner': True,\n",
       "  'is_primary_owner': True,\n",
       "  'is_restricted': False,\n",
       "  'is_ultra_restricted': False,\n",
       "  'name': 'wjk68',\n",
       "  'profile': {'avatar_hash': 'af6fa36ec0b3',\n",
       "   'display_name': 'willk',\n",
       "   'display_name_normalized': 'willk',\n",
       "   'email': 'wjk68@case.edu',\n",
       "   'first_name': 'Will',\n",
       "   'image_1024': 'https://avatars.slack-edge.com/2018-08-22/421515326835_af6fa36ec0b3f86e86ae_1024.jpg',\n",
       "   'image_192': 'https://avatars.slack-edge.com/2018-08-22/421515326835_af6fa36ec0b3f86e86ae_192.jpg',\n",
       "   'image_24': 'https://avatars.slack-edge.com/2018-08-22/421515326835_af6fa36ec0b3f86e86ae_24.jpg',\n",
       "   'image_32': 'https://avatars.slack-edge.com/2018-08-22/421515326835_af6fa36ec0b3f86e86ae_32.jpg',\n",
       "   'image_48': 'https://avatars.slack-edge.com/2018-08-22/421515326835_af6fa36ec0b3f86e86ae_48.jpg',\n",
       "   'image_512': 'https://avatars.slack-edge.com/2018-08-22/421515326835_af6fa36ec0b3f86e86ae_512.jpg',\n",
       "   'image_72': 'https://avatars.slack-edge.com/2018-08-22/421515326835_af6fa36ec0b3f86e86ae_72.jpg',\n",
       "   'image_original': 'https://avatars.slack-edge.com/2018-08-22/421515326835_af6fa36ec0b3f86e86ae_original.jpg',\n",
       "   'is_custom_image': True,\n",
       "   'last_name': 'Koehrsen',\n",
       "   'phone': '',\n",
       "   'real_name': 'Will Koehrsen',\n",
       "   'real_name_normalized': 'Will Koehrsen',\n",
       "   'skype': '',\n",
       "   'status_emoji': '',\n",
       "   'status_expiration': 0,\n",
       "   'status_text': '',\n",
       "   'status_text_canonical': '',\n",
       "   'team': 'TCD256PSM',\n",
       "   'title': ''},\n",
       "  'real_name': 'Will Koehrsen',\n",
       "  'team_id': 'TCD256PSM',\n",
       "  'tz': 'America/New_York',\n",
       "  'tz_label': 'Eastern Daylight Time',\n",
       "  'tz_offset': -14400,\n",
       "  'updated': 1534989027},\n",
       " {'color': '757575',\n",
       "  'deleted': False,\n",
       "  'id': 'USLACKBOT',\n",
       "  'is_admin': False,\n",
       "  'is_app_user': False,\n",
       "  'is_bot': False,\n",
       "  'is_owner': False,\n",
       "  'is_primary_owner': False,\n",
       "  'is_restricted': False,\n",
       "  'is_ultra_restricted': False,\n",
       "  'name': 'slackbot',\n",
       "  'profile': {'always_active': True,\n",
       "   'avatar_hash': 'sv1444671949',\n",
       "   'display_name': 'slackbot',\n",
       "   'display_name_normalized': 'slackbot',\n",
       "   'fields': None,\n",
       "   'first_name': 'slackbot',\n",
       "   'image_192': 'https://a.slack-edge.com/66f9/img/slackbot_192.png',\n",
       "   'image_24': 'https://a.slack-edge.com/0180/img/slackbot_24.png',\n",
       "   'image_32': 'https://a.slack-edge.com/7f1a0/plugins/slackbot/assets/service_32.png',\n",
       "   'image_48': 'https://a.slack-edge.com/7f1a0/plugins/slackbot/assets/service_48.png',\n",
       "   'image_512': 'https://a.slack-edge.com/1801/img/slackbot_512.png',\n",
       "   'image_72': 'https://a.slack-edge.com/0180/img/slackbot_72.png',\n",
       "   'last_name': '',\n",
       "   'phone': '',\n",
       "   'real_name': 'slackbot',\n",
       "   'real_name_normalized': 'slackbot',\n",
       "   'skype': '',\n",
       "   'status_emoji': '',\n",
       "   'status_expiration': 0,\n",
       "   'status_text': '',\n",
       "   'status_text_canonical': '',\n",
       "   'team': 'TCD256PSM',\n",
       "   'title': ''},\n",
       "  'real_name': 'slackbot',\n",
       "  'team_id': 'TCD256PSM',\n",
       "  'tz': None,\n",
       "  'tz_label': 'Pacific Daylight Time',\n",
       "  'tz_offset': -25200,\n",
       "  'updated': 0}]"
      ]
     },
     "execution_count": 32,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "users.body['members']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [],
   "source": [
    "x = slack.channels.list()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'channels': [{'created': 1534988091,\n",
       "   'creator': 'UCEKVNHPH',\n",
       "   'id': 'CCCT28F08',\n",
       "   'is_archived': False,\n",
       "   'is_channel': True,\n",
       "   'is_general': True,\n",
       "   'is_member': True,\n",
       "   'is_mpim': False,\n",
       "   'is_org_shared': False,\n",
       "   'is_private': False,\n",
       "   'is_shared': False,\n",
       "   'members': ['UCEKVNHPH'],\n",
       "   'name': 'general',\n",
       "   'name_normalized': 'general',\n",
       "   'num_members': 1,\n",
       "   'previous_names': [],\n",
       "   'purpose': {'creator': 'UCEKVNHPH',\n",
       "    'last_set': 1534988091,\n",
       "    'value': 'This channel is for workspace-wide communication and announcements. All members are in this channel.'},\n",
       "   'topic': {'creator': 'UCEKVNHPH',\n",
       "    'last_set': 1534988091,\n",
       "    'value': 'Company-wide announcements and work-based matters'},\n",
       "   'unlinked': 0},\n",
       "  {'created': 1534988091,\n",
       "   'creator': 'UCEKVNHPH',\n",
       "   'id': 'CCDP3ES85',\n",
       "   'is_archived': False,\n",
       "   'is_channel': True,\n",
       "   'is_general': False,\n",
       "   'is_member': True,\n",
       "   'is_mpim': False,\n",
       "   'is_org_shared': False,\n",
       "   'is_private': False,\n",
       "   'is_shared': False,\n",
       "   'members': ['UCEKVNHPH'],\n",
       "   'name': 'random',\n",
       "   'name_normalized': 'random',\n",
       "   'num_members': 1,\n",
       "   'previous_names': [],\n",
       "   'purpose': {'creator': 'UCEKVNHPH',\n",
       "    'last_set': 1534988091,\n",
       "    'value': \"A place for non-work-related flimflam, faffing, hodge-podge or jibber-jabber you'd prefer to keep out of more focused work-related channels.\"},\n",
       "   'topic': {'creator': 'UCEKVNHPH',\n",
       "    'last_set': 1534988091,\n",
       "    'value': 'Non-work banter and water cooler conversation'},\n",
       "   'unlinked': 0},\n",
       "  {'created': 1534988443,\n",
       "   'creator': 'UCEKVNHPH',\n",
       "   'id': 'CCDC464LU',\n",
       "   'is_archived': False,\n",
       "   'is_channel': True,\n",
       "   'is_general': False,\n",
       "   'is_member': True,\n",
       "   'is_mpim': False,\n",
       "   'is_org_shared': False,\n",
       "   'is_private': False,\n",
       "   'is_shared': False,\n",
       "   'members': ['UCEKVNHPH'],\n",
       "   'name': 'slack_interaction',\n",
       "   'name_normalized': 'slack_interaction',\n",
       "   'num_members': 1,\n",
       "   'previous_names': [],\n",
       "   'purpose': {'creator': 'UCEKVNHPH',\n",
       "    'last_set': 1534988444,\n",
       "    'value': 'To interact with Slack from Python'},\n",
       "   'topic': {'creator': '', 'last_set': 0, 'value': ''},\n",
       "   'unlinked': 0},\n",
       "  {'created': 1534988457,\n",
       "   'creator': 'UCEKVNHPH',\n",
       "   'id': 'CCD27690R',\n",
       "   'is_archived': False,\n",
       "   'is_channel': True,\n",
       "   'is_general': False,\n",
       "   'is_member': True,\n",
       "   'is_mpim': False,\n",
       "   'is_org_shared': False,\n",
       "   'is_private': False,\n",
       "   'is_shared': False,\n",
       "   'members': ['UCEKVNHPH'],\n",
       "   'name': 'testing_exp',\n",
       "   'name_normalized': 'testing_exp',\n",
       "   'num_members': 1,\n",
       "   'previous_names': [],\n",
       "   'purpose': {'creator': 'UCEKVNHPH',\n",
       "    'last_set': 1534988457,\n",
       "    'value': 'Experimental testing of interactions.'},\n",
       "   'topic': {'creator': '', 'last_set': 0, 'value': ''},\n",
       "   'unlinked': 0}],\n",
       " 'ok': True}"
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x.body"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
