Full-featured Python interface for the Slack API

Overview

This repository is archived and will not receive any updates

It's time to say goodbye. I'm archiving Slacker. It's been getting harder to find time to maintain this project for a while now. For years it's been the most popular Python library for Slack. Eventually Slack decided to go with their library, and I lost my motivation to maintain it. Thank you all for your contributions to this project.

Slacker

pypi build status pypi downloads license gitter chat

https://raw.githubusercontent.com/os/slacker/master/static/slacker.jpg

About

Slacker is a full-featured Python interface for the Slack API.

Installation

$ pip install slacker

Examples

from slacker import Slacker

slack = Slacker('<your-slack-api-token-goes-here>')

# Send a message to #general channel
slack.chat.post_message('#general', 'Hello fellow slackers!')

# Get users list
response = slack.users.list()
users = response.body['members']

# Upload a file
slack.files.upload('hello.txt')

# If you need to proxy the requests
proxy_endpoint = 'http://myproxy:3128'
slack = Slacker('<your-slack-api-token-goes-here>',
                http_proxy=proxy_endpoint,
                https_proxy=proxy_endpoint)

# Advanced: Use `request.Session` for connection pooling (reuse)
from requests.sessions import Session
with Session() as session:
    slack = Slacker(token, session=session)
    slack.chat.post_message('#general', 'All these requests')
    slack.chat.post_message('#general', 'go through')
    slack.chat.post_message('#general', 'a single https connection')

Documentation

https://api.slack.com/methods

Comments
  • Blocks Support (squashed commits from #152)

    Blocks Support (squashed commits from #152)

    This PR is a duplicate of #152 but with a single commit rather than 4.

    As Slack is pushing blocks as the default for complex messages, this PR is important for anyone reading the current docs and wanting to use Slacker with them.

    opened by symroe 8
  • Add support for Slack 429 response

    Add support for Slack 429 response

    A slack client that sends too many responses at once can elicit a 429 status code, followed by a json error object saying how many seconds we need to pause.

    https://api.slack.com/docs/rate-limits

    There are two ways to skin this -- mange the 429 response ourself in BaseAPI._request which gives us the advantage of being able to pause for exactly the right delay time, -or- or ask the requests module to simply implement an incremental backoff algorithm to respect 429.

    Either solution seems relatively reasonable.

    For plan A, by default, requests will -not- retry a 429, so we'll get back the slack error response and can (if enabled by the user) sleep and then retry the request in BaseAPI._request with something vaguely like this (totally untested, and it's late at night when I wrote this):

    success = False
    while not success:
        response = method ...
        if response.status_code == 429 and self.backoff:
            # get the value of the Retry-after header in the response packet
            sleep(response.<headers>.Retry_after)
            continue
        response.raise_for_status()
        success = True    
    

    For plan B, one would do something like this:

    in init, create a session with a retry object on the HTTP adapter:

    retries = Retry(status_forcelist={429})
    adapter = requests.adapters.HTTPAdapter(retries)
    self.session = requests.Session()
    self.session.mount('https://', adapter)
    

    and use self.session.get and self.session.post et all instead of requests.get / requests.post as the methods.

    reference:

    http://docs.python-requests.org/en/master/api/?highlight=retries http://urllib3.readthedocs.io/en/latest/user-guide.html#retrying-requests http://urllib3.readthedocs.io/en/latest/reference/urllib3.util.html#module-urllib3.util.retry

    feature 
    opened by pleasantone 8
  • InsecurePlatformWarning: A true SSLContext object is not available

    InsecurePlatformWarning: A true SSLContext object is not available

    When I try to post a message I get this warning

    In [1]: from slacker import Slacker
    In [2]: slack = Slacker('abc-123')
    In [3]: slack.chat.post_message('#random', 'hello from slacker')
    /Users/pablo/envs/slacker-cli/lib/python2.7/site-packages/requests/packages/urllib3/util/ssl_.py:79:
    InsecurePlatformWarning: A true SSLContext object is not available.
    This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail.
    For more information, see
    https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
      InsecurePlatformWarning
    Out[3]: <slacker.Response object at 0x107726350>
    
    wontfix 
    opened by juanpabloaj 6
  • Fixes chat.post_message with attachments

    Fixes chat.post_message with attachments

    The chat.postMessage API expects things to be passed to it as params, not data. Without this, attachments won't be posted.

    This also removes any keys that are None so they aren't sent to Slack.

    It also makes the text argument optional, since it the API specifies you text is only required if you aren't specifying attachments. You'll get a slack.Error back from the API if you don't specify either.

    cc https://github.com/os/slacker/issues/67

    opened by technicalpickles 5
  • User_not_found unexpectedly

    User_not_found unexpectedly

    I'm getting user_not_found and channel_not_found errors when I try to make calls with valid user and channel ids. If I replicate the calls via postman, or by using the python requests library, they go through perfectly. Have there been any changes to the API recently that could have caused this?

    opened by GalaCasey 5
  • Can't send attachments through using post_message

    Can't send attachments through using post_message

    I don't have a clue about what's going on here, and honestly I can't tell if it's Slack, Slacker, or my issue:

        attachmentdata = json.dumps(
            {
                "attachments": [
                    {
                        "fallback": fallback_message,
                        "color": "#ccac55",
    
                        "title": "New {}: {}".format("selfpost" if submission.is_self == True else "link post", submission.title),
                        "title_link": RedditService.create_shortlink(submission.id),
    
                        "text": submission.title,
    
                        "fields": [
                            {
                                "title": "Domain",
                                "value": submission.domain,
                                "short": True
                            },
                            {
                                "title": "Author",
                                "value": "/u/{}".format(submission.author),
                                "short": True
                            }
                        ],
    
                        "thumb_url": submission.thumbnail,
    
                        "footer": "r/SpaceX",
                        "footer_icon": "https://spacexstats.com/favicon-194x194.png",
                        "ts": int(submission.created_utc)
                    }
                ]
            }
        )
    
        print(attachmentdata)
    
        self.slack.chat.post_message('#newposts', "test", as_user=True, attachments=attachmentdata, unfurl_links=True, unfurl_media=True)
    

    This JSON compiles to:

     {"attachments": [{"ts": 1465565991.0, "title_link": "https://redd.it/4ngbu1", "thumb_url": "http://b.thumbs.redditmedia.com/whD2TBHwdLh4WUOQwNl4AFCidqv1Z5QM41rZdC4DNcU.jpg", "text": "dddd", "fallback": "[r/SpaceX] New link post: dddd by /u/EchoLogic https://redd.it/4ngbu1", "footer": "r/SpaceX", "fields": [{"short": true, "value": "reddit.com", "title": "Domain"}, {"short": true, "value": "/u/EchoLogic", "title": "Author"}], "title": "New link post: dddd", "color": "#ccac55", "footer_icon": "https://spacexstats.com/favicon-194x194.png"}]}
    

    Yet, when submitted through using the API, the attachment simply does not appear. If I remove the "text" parameter of post_message, I get a Slack no_text error, which violates their API design:

    A message must have either text or attachments or both. The text parameter is required unless you provide attachments. You can use both parameters in conjunction with each other to create awesome messages.

    What's the deal here?

    question 
    opened by lukeify 5
  • get_channel_id function added

    get_channel_id function added

    • get_channel_id function return the channel id from channel name.
    • mocking test added.
    • requeriments-dev.txt file added.

    Some slack API methods need the channel id, not the channel name, like files.upload.

    Channel id ('C02GXXYZ') is different to the channel name ('test').

    Example:

    >>> from slacker import Slacker
    >>> from slacker.utils import get_channel_id
    >>> token = "aaa"
    >>> channel_id = get_channel_id(token, 'test')
    >>> slack = Slacker(token)
    >>> slack.files.upload('index.png', channels=channel_id)
    
    enhancement feature 
    opened by juanpabloaj 5
  • Implement conversations methods

    Implement conversations methods

    Added support for Conversations methods. Pagination is supported on some methods by passing in the next_cursor from a response to the cursor parameter.

    Note that I've only tested some of the methods due to lack of permissions, so results may vary.

    opened by kyrivanderpoel 4
  • Private channels. slacker.Error: channel_not_found

    Private channels. slacker.Error: channel_not_found

    Hi all,

    can I use slacker for msg sending to Slack private channel? https://get.slack.help/hc/en-us/articles/201925108-Understanding-channels-and-DMs I am use Bots. My bot is currently in python private group. Code:

    from slacker import Slacker
    
    slack_token = "xxxx-xxxxxxxxxxx-xxxxxxxxxxxxxxxxxxxxxxxx"
    slack_channel = "#python"
    slack_msg = "Hello, world!"
    
    slack = Slacker(slack_token)
    slack.chat.post_message(slack_channel, slack_msg)
    

    Traceback:

    Traceback (most recent call last):
      File "./slack.py", line 11, in <module>
        slack.chat.post_message(slack_channel, slack_msg)
      File "/usr/local/lib/python2.7/dist-packages/slacker/__init__.py", line 287, in post_message
        'icon_emoji': icon_emoji
      File "/usr/local/lib/python2.7/dist-packages/slacker/__init__.py", line 71, in post
        return self._request(requests.post, api, **kwargs)
      File "/usr/local/lib/python2.7/dist-packages/slacker/__init__.py", line 63, in _request
        raise Error(response.error)
    slacker.Error: channel_not_found
    

    Also I tried slack_channel = "python". The code works for public channels (for example: #general channel).

    opened by korniichuk 4
  • ImportError: No module named utils

    ImportError: No module named utils

    I've pulled latest and followed the install steps (pip install slacker). I can see everything is installed correctly. But my test script fails with an output message saying it fails to load the utils module.

    Here are the details.

    Installed via PIP

    C:\>c:\Python27\Scripts\pip list
    pip (8.1.2)
    requests (2.10.0)
    setuptools (18.2)
    slacker (0.9.16)
    

    Contents of my basic script:

    Y:\scripts\>type NewScript.py
    from slacker import Slacker
    slack = Slacker('xxx-myTokenHere-xxx')
    # Send a message to #general channel
    slack.chat.post_message('#general', 'Hello fellow slackers!')
    

    When I execute I get the following output:

    C:\>c:\Python27\python.exe y:\scripts\iFactrPythonScript\NewScript.py
    Traceback (most recent call last):
      File "y:\scripts\NewScript.py", line 1, in <module>
        from slacker import Slacker
      File "/Users/[...maskedusername...]/scripts/slacker.py", line 19, in <module>
    ImportError: No module named utils
    

    I get the feeling this is because my script is running on a network drive.

    opened by benhorgen 4
  • Handle 429 Retry-After Errors

    Handle 429 Retry-After Errors

    From https://api.slack.com/docs/rate-limits

    The Slack API and all integrations are subject to rate limiting.

    If you go over these limits when using our HTTP based APIs, including Incoming Webhooks, Slack will start returning a HTTP 429 Too Many Requests error, a JSON object containing the number of calls you have been making, and a Retry-After header containing the number of seconds until you can retry.

    This will correctly raise a UserWarning for the 429 error, and give the retry delay in seconds to be used in args[1], so that a script can sleep, then retry/continue.

    This can be handled as shown in the except UserWarning area example:

    try:
        response = slack.chat.post_message(channel, message)
    except UserWarning as e:
        print('Error:', e)
        time.sleep(e.args[1])
        continue    # retrying can also be written here
    except Exception as e:
        print('Error:', e)
        exit(1)
    

    related: https://github.com/os/slacker/pull/40

    opened by chazchazchaz 4
  • Issuing new legacy token is deprecated

    Issuing new legacy token is deprecated

    According to the announcement, it is no longer possible to issue a new token.

    I thought that using incoming-webhook might be a detour (mentioned in #91), but It also needs token.

    How it can be solved?

    opened by figkim 3
  • Missing Request Mime types

    Missing Request Mime types

    Hello,

    the slack API requires that requests set the correct mime types, like application/json. This library does not yet do so. (See for example Incoming Webhook)

    The slack API does not (yet) enforce this. But the slack compatible mattermost API recently started doing so, which means this library does not work with mattermost anymore.

    opened by N-Schaef 2
  • Make users.list accept pagination args

    Make users.list accept pagination args

    This PR adds cursor and limit to users.list API to allow pagination per https://api.slack.com/docs/pagination. API should be backward compatible. I also modified example to show how paging is done. I removed the channels part in example because that API is deprecated.

    opened by xiaochuanyu 1
Releases(v0.14.0)
Owner
Oktay Sancak
Oktay Sancak
A Flask inspired, decorator based API wrapper for Python-Slack.

A Flask inspired, decorator based API wrapper for Python-Slack. About Tangerine is a lightweight Slackbot framework that abstracts away all the boiler

Nick Ficano 149 Jun 30, 2022
As Slack no longer provides an API to invite people, this is a Selenium Python script to do so

As Slack no longer provides an API to invite people, this is a Selenium Python script to do so

Mehdi Bounya 4 Feb 15, 2022
Playing around with the slack api for learning purposes

SlackBotTest Playing around with the slack api for learning purposes and getting people to contribute Reason for this Project: Bots are very versatile

null 1 Nov 24, 2021
Ridogram is an advanced multi-featured Telegram UserBot.

Ridogram Ridogram is an advanced multi-featured Telegram UserBot. String Session Collect String Session by running python3 stringsession.py locally or

Md. Ridwanul Islam Muntakim 134 Dec 29, 2022
Ridogram is an advanced multi-featured Telegram UserBot.

Ridogram Ridogram is an advanced multi-featured Telegram UserBot. String Session Collect String Session by running python3 stringsession.py locally or

Md. Ridwanul Islam Muntakim 102 May 26, 2022
Slack Developer Kit for Python

Python Slack SDK The Slack platform offers several APIs to build apps. Each Slack API delivers part of the capabilities from the platform, so that you

SlackAPI 3.5k Jan 2, 2023
A Python app to serve Conveyor room requests and run approvals through Slack

✨ CONVEYOR FOR SLACK ✨ This is a friendly little Python app that will allow you to integrate your instance of Conveyor with your Slack workspace. In o

Vivienne 4 Sep 27, 2021
A python library for creating Slack slash commands using AWS Lambda Functions

slashbot Slashbot makes it easy to create slash commands using AWS Lambda functions. These can be handy for creating a secure way to execute automated

Eric Brassell 17 Oct 21, 2022
Python app to notify via slack channel the status_code change from an URL

Python app to notify, via slack channel you choose to be notified, for the status_code change from the URL list you setup to be checked every yy seconds

Pedro Nunes 1 Oct 25, 2021
Automation application was made by me using Google, Sheet and Slack APIs with Python.

README This application is used to transfer the data in the xlsx document we have to the Google Drive environment and calculate the "total budget" wit

null 3 Apr 12, 2022
A simple python bot that serves to send some notifications about GitHub events to Slack.

github alerts slack bot ?? What is it? ?? This is a simple bot that serves to send some notifications about GitHub events to Slack channels. These are

Jackson Alves 10 Dec 10, 2022
Slack->DynamDB->Some applications

slack-event-subscriptions About The Project Do you want to get simple attendance checks? If you are using Slack, participants can just react on a spec

UpstageAI 26 May 28, 2022
Quickly edit your slack posts.

Lightning Edit Quickly edit your Slack posts. Heavily inspired by @KhushrajRathod's LightningDelete. Usage: Note: Before anything, be sure to head ove

Cole Wilson 14 Nov 19, 2021
Role Based Access Control for Slack-Bolt Applications

Role Based Access Control for Slack-Bolt Apps Role Based Access Control (RBAC) is a term applied to limiting the authorization for a specific operatio

Jeremy Schulman 7 Jan 6, 2022
Reddit cli to slack at work

Reddit CLI (v1.0) Introduction Why Reddit CLI? Coworker who sees me looking at something in a browser: "Glad you're not busy; I need you to do this, t

null 3 Jun 22, 2021
A slack bot that notifies you when a restaurant is available for orders

Slack Wolt Notifier A Slack bot that notifies you when a Wolt restaurant or venue is available for orders. How does it work? Slack supports bots that

Gil Matok 8 Oct 24, 2022
A self hosted slack bot to conduct standups & generate reports.

StandupMonkey A self hosted slack bot to conduct standups & generate reports. Report Bug · Request Feature Installation Install already hosted bot (Us

Muhammad Haseeb 69 Jan 1, 2023
This automation protect against subdomain takeover on AWS env which also send alerts on slack.

AWS_Subdomain_Takeover_Detector Purpose The purpose of this automation is to detect misconfigured Route53 entries which are vulnerable to subdomain ta

Puneet Kumar Maurya 8 May 18, 2022
Slack bot for monitoring your Metaflow flows!

Metaflowbot - Slack Bot for your Metaflow flows! Metaflowbot makes it fun and easy to monitor your Metaflow runs, past and present. Imagine starting a

Outerbounds 21 Dec 7, 2022