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
GitHub action to deploy serverless functions to YandexCloud

YandexCloud serverless function deploy action Deploy new serverless function version (including function creation if it does not exist). Inputs yc_acc

Много Лосося 4 Apr 10, 2022
A small repository with convenience functions for working with the Notion API.

Welcome! Within this respository are a few convenience functions to assist with the pulling and pushing of data from the Notion API.

10 Jul 09, 2022
My attempt to reverse the Discord nitro token generation function.

discord-theory-I PART: I My attempt to reverse the Discord nitro token generation function. The Nitro generation tools thing is common in Discord now,

Jakom 29 Aug 14, 2022
MVP monorepo to rapidly develop scalable, reliable, high-quality components for Amazon Linux instance configuration management

Ansible Amazon Base Repository Ansible Amazon Base Repository About Setting Up Ansible Environment Configuring Python VENV and Ansible Editor Configur

Artem Veremey 1 Aug 06, 2022
Official implementation of DeepSportLab (a fork of OpenPifPaf)

DeepSportLab DeepSportLab: a Unified Framework for BallDetection, Player Instance Segmentationand Pose Estimation in Team Sports Scenes This paper pre

ISPGroupUCL 8 Sep 27, 2022
Video Stream: an Advanced Telegram Bot that's allow you to play Video & Music on Telegram Group Video Chat

Video Stream is an Advanced Telegram Bot that's allow you to play Video & Music

SHU KURENAI TEAM 4 Nov 05, 2022
Linky bot, A open-source discord bot that allows you to add links to ur website, youtube url, etc for the people all around discord to see!

LinkyBot Linky bot, An open-source discord bot that allows you to add links to ur website, youtube url, etc for the people all around discord to see!

AlexyDaCoder 1 Sep 20, 2022
Google Search Results via SERP API pip Python Package

Google Search Results in Python This Python package is meant to scrape and parse search results from Google, Bing, Baidu, Yandex, Yahoo, Home depot, E

SerpApi 254 Jan 05, 2023
DonLee Robot

🤖 𝐃𝐎𝐍 𝐋𝐄𝐄 𝐑𝐎𝐁𝐎𝐓 𝐕𝟐 🤖 👋 Hey Muhammed, Iam DonLee RoBoT Make me an admin for your group and channel then connect me.... 🎉 🙂 To build a

Muhammed 27 Dec 01, 2022
Automatic SystemVerilog linting in github actions with the help of Verible

Verible Lint Action Usage See action.yml This is a GitHub Action used to lint Verilog and SystemVerilog source files and comment erroneous lines of co

CHIPS Alliance 10 Dec 26, 2022
python3.5+ hubspot client based on hapipy, but modified to use the newer endpoints and non-legacy python

A python wrapper around HubSpot's APIs, for python 3.5+. Built initially around hapipy, but heavily modified. Check out the documentation here! (thank

Jacobi Petrucciani 140 Dec 21, 2022
Discord Online Account Forever

💠 Discord-Online-Account-Forever Discord Online Account Forever 📸 Tutorial Token Discord NEVER SHARE YOUR TOKEN Installation Replit 🧿 Replit : Here

nimaisox 2 Nov 28, 2021
Twitter automation tool for growing organic followers.

Tiwoto Tiwoto is a simple python program that automates some kind of behaviors and keep your account active. Create an .env file in this directory and

Mehmetcan Yildiz 6 Sep 22, 2022
聚合空间测绘搜索(Fofa,Zoomeye,Quake,Shodan,Censys,BinaryEdge)

#Search-Tools Search-Tools集合比较常见的网络空间探测引擎 Fofa,Zoomeye,Quake,Shodan,Censys,BinaryEdge 简单说明 ICO搜索目前只有Fofa,Shodan,Quake支持 代理设置是防止在API请求过于频繁,或者在实战中,好多红队打

311 Dec 16, 2022
Lumi-Bot - Discord bot that fetches cryptocurrency prices utilizing CoinGeko API

Lumi-Bot Discord bot that fetches and monitors cryptocurrency prices utilizing C

Diego Castro 2 Oct 08, 2022
A simple test repo created following docker docs.

docker_sampleRepo A simple test repo created following docker docs. Link to docs: https://docs.docker.com/language/python/develop/ Other links: https:

Suraj Verma 2 Sep 16, 2022
Python based Algo trading bot for Nifty / Banknifty futures and options

Fully automated Alice Blue Algo Trading with Python on NSE and MCX for Nifty / Crude / Banknifty futures and options , absolutely FREE ! This algo tra

Rajesh Sivadasan 49 Dec 31, 2022
Wechat-file-cleaner - Clean files in PC WeChat FileStorage directory

Wechat-file-cleaner - Clean files in PC WeChat FileStorage directory

Xingjian Zhang 1 Feb 06, 2022
Technical Test - Python Programmer Grupo Nexxera

Technical Test Nexxera Group Teste Técnico - Grupo de Programadores Python Nexxera 📍 Prepare-se para usar a API Nossa API de transações de contas dig

Raul dos Santos Moraes 1 Mar 16, 2022
Create Discord Accounts Semi-Automatically Without Captcha Solving API Key

Discord-Account-Generator Create Discord Accounts Semi-Automatically without captcha solving api key IMPORTANT: Your chromedriver version should be th

NotSakshyam 11 Mar 21, 2022