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
TON Miner from TON-Pool.com

TON-Pool Miner Miner from TON-Pool.com

21 Nov 18, 2022
Basic query to access Traindex API

traindex-api-query Basic query to access Traindex API Please make sure to provide your Traindex API key to the line 8 in the script file. There are tw

Foretheta 1 Nov 11, 2021
A superb Telegram VoiceChat Player. Powered by FalconRoBo.

𝕱𝖆𝖑𝖈𝖔𝖓𝕸𝖚𝖘𝖎𝖈 A sᴜᴘᴇʀʙ Tᴇʟᴇɢʀᴀᴍ VᴏɪᴄᴇCʜᴀᴛ Pʟᴀʏᴇʀ, ᴍᴀᴅᴇ ᴜsɪɴɢ Lᴀᴛᴇsᴛ Pʏᴛʜᴏɴ ᴀɴᴅ Pʏʀᴏɢʀᴀᴍ. 𝑷𝒐𝒘𝒆𝒓𝒆𝒅 𝒃𝒚 𝑭𝒂𝒍𝒄𝒐𝒏𝑹𝒐𝑩𝒐 FalconMusic

FalconRoBo 2 Oct 21, 2022
An Advanced Python Playing Card Module that makes creating playing card games simple and easy!

playingcards.py An Advanced Python Playing Card Module that makes creating playing card games simple and easy! Features Easy to Understand Class Objec

Blake Potvin 5 Aug 30, 2022
Bot telegram yang menggemakan pesan apa pun yang Anda kirim atau modifikasi untuk menganonimkan pesan

Bot telegram yang menggemakan pesan apa pun yang Anda kirim atau modifikasi untuk menganonimkan pesan

KEN KAN 2 Oct 21, 2022
SC4.0 - BEST EXPERIENCE · HEX EDITOR · Discord Nuker · Plugin Adder · Cheat Engine

smilecreator4 This site is for people who want to hack or want to learn it! Furthermore, this program does not work without turning off Antivirus or W

1 Jan 04, 2022
AWS Blog post code for running feature-extraction on images using AWS Batch and Cloud Development Kit (CDK).

Batch processing with AWS Batch and CDK Welcome This repository demostrates provisioning the necessary infrastructure for running a job on AWS Batch u

AWS Samples 7 Oct 18, 2022
Pixiv 爬虫,使用 Python 实现。支持批量下载、上传到图床。

用 Python 实现的 Pixiv 爬虫,支持批量下载和上传。 随机图片 API: https://loliapi.ml/ Deploy Github Action 集成部署 建议使用本方法部署,相较于本地部署,无需搭建环境,全程在线上完成。并且使用国外服务器下载、上传,网络更加通畅。 Fork

18 Feb 26, 2022
📦 Opensource Python wrapper for Hiven's REST and WebSocket API

hiven.py 📦 Opensource Python wrapper for Hiven's REST and WebSocket API Installation pip install -U hiven.py Usage hiven.py is currently under devel

Kevin Thomas 3 Sep 03, 2021
Twitter-redesign - Twitter Redesign With Django

Twitter Redesign A project that tests Django and React knowledge through a twitt

Mark Jumba 1 Jun 01, 2022
A multi-tenant multi-client scalable product categorising demo stack

Better Categories 4All: A multi-tenant multi-client product categorising stack The steps to reproduce training and inference are in the end of this fi

7 Feb 15, 2022
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
Automatically load stolen cookies from ChromePass

AutoCookie - Automatically loading stolen cookies from ChromePass View Demo · Report Bug · Request Feature Table of Contents About the Project Getting

darkArp 21 Oct 11, 2022
bot for hearthstone mercenaries

Hearthstone-Mercenaries-game-bot - prevention: Bot is not ready and now on the development stage estimated release date - 21.10.21 The main idea of th

Andrew Efimov 59 Dec 12, 2022
Nft-maker - Create your own NFT!

nft-maker How to If you're going to use this program, change the pictures in the "images" folder. All images must be of the same resolution and size.

Georgii Arakelian 4 Mar 13, 2022
Using GNU Radio and HackRF One to Receive, Analyze and Send ASK/OOK signals

play_with_ask NIS-8016 Lab A code: Recv.grc/py: Receive signals and match with ASK button using HackRF and GNU radio. I use AM demod block(can also in

Chen Anxue 1 Jul 04, 2022
OKEX数字货币自动交易python语言SDK

okex-py OKEx数字货币自动交易python语言SDK (非官方) OKEx Cryptocurrency Exchange python SDK (Unofficial) 本项目基于V5 API 使用例子 Example import okex.v5.account_api as acco

43 Dec 01, 2022
Example of Telegram local API and aiogram 3.x

Telegram Local Full example of Telegram local application. Contains Telegram Bot API Local Telegram Bot API server based on aiogram Bot API Server ima

Oleg A. 9 Sep 16, 2022
Probably Overengineered Unimore Booker

POUB Probably Overengineered Unimore Booker A python-powered, actor-based, telegram-facing, timetable-aware booker for unimore (if you know more adjec

Lorenzo Rossi 3 Feb 20, 2022
Python library for Seeedstudio Grove devices

grove.py Python library for Seeedstudio Grove Devices on embeded Linux platform, especially good on below platforms: Coral Dev Board (Wiki) NVIDIA Jet

Seeed Studio 123 Dec 17, 2022