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
The wrapper you need for the osu!api v2

oppy (op.py) oppy is the wrapper for use on the osu! v2 API. Version 1.0.0 Installation To install please use pip to install oppy pip install op.py To

Wayde 2 May 01, 2022
An automated tool that fetches information about your crypto stake and generates historical data in time.

Introduction Yield explorer is a WIP! I needed a tool that would show me historical data and performance of my staked crypto but was unable to find a

Sedat Can Yalçın 42 Nov 26, 2022
Powerful Telegram userbot to turn your PROFILE PICTURE & LAST NAME into a real time clock & to change your BIO automatically.

DATE_TIME_USERBOT-TeLeTiPs Powerful Telegram userbot to turn your PROFILE PICTURE & LAST NAME into a real time clock & to change your BIO automaticall

53 Jan 05, 2023
A Python Script to automate searching of available vaccination centers in the city and hence booking

Cowin Vaccine Availability Notifier Cowin Vaccine Availability Notifier takes your City or PIN code as an input and automatically notifies you via ema

Jayesh Padhiar 7 Sep 05, 2021
An script where it logs in your instagram account and follows people and likes their posts

InstaFollower An script where it logs in your instagram account and follows people and likes their posts (uses the tags to fetch people) Requirements:

Bless 3 Nov 29, 2022
A bot that connects your guild chat to a Discord channel, written in Python.

Guild Chat Bot A bot that connects your guild chat to a discord channel. Uses discord.py and pyCraft Deploy on Railway Railway is a cloud development

Evernote 10 Sep 25, 2022
This is a repository for the Duke University Cloud Computing course project on Serveless Data Engineering Pipeline. For this project, I recreated the below pipeline.

AWS Data Engineering Pipeline This is a repository for the Duke University Cloud Computing course project on Serverless Data Engineering Pipeline. For

15 Jul 28, 2021
Unofficial Meteor Client wiki

Welcome to the Unofficial Meteor Client wiki! Meteor FAQs | A rewritten and better FAQ page. Installation Guide | A guide on how to install Meteor Cli

Anti Cope 0 Feb 21, 2022
Primeira etapa do processo seletivo para a bolsa de migração de conteúdo de Design de Software.

- Este processo já foi concluído. Obrigado pelo seu interesse! Processo Seletivo para a bolsa de migração de conteúdo de Design de Software Primeirame

Toshi Kurauchi 1 Feb 21, 2022
Copier template for solving Advent of Code puzzles with Python

Advent of Code Python Template for Copier This template creates scaffolding for one day of Advent of Code. It includes tests and can download your per

Geir Arne Hjelle 6 Dec 25, 2022
Defi PancakeSwap bot is programmed in Python to buy and sell tokens in seconds once the target is hit.

Defi PancakeSwap BOT A BOT that will make easy your life in Trading. Watch tutorial on Youtube Table of Contents About The Project Built With Getting

Zain Ullah 208 Jan 05, 2023
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
This is a free python bot program that crosses you to farm with auto click in space crypto NFT game, having fun :) Creator: Marlon Zanardi

🚀 Space Crypto auto click bot ready-to-use 🚀 This is a free python bot program that crosses you to farm with auto click in space crypto NFT game, ha

170 Dec 20, 2022
Telegram anime bot that uses Anilist API

Telegram Bot Repo Capable of fetching the following Info via Anilist API inspired from AniFluid and Nepgear Anime Airing Manga Character Scheduled Top

Lucky Jain 71 Jan 03, 2023
This is a python bot that automatically logs in, clicks the new button, and sends heroes to work in the bombcrypto game

This is a python bot that automatically logs in, clicks the new button, and sends heroes to work in the bombcrypto game. It is fully open source and free.

856 Jan 04, 2023
FUD Keylogger That Reports To Discord

This python script will capture all of the keystrokes within a given time frame and report them to a Discord Server using Webhooks. Instead of the traditional

●┼Waseem Akram••✓⁩ 16 Dec 08, 2022
Wordle-bot: A Discord bot to track you and your friends' Wordle scores.

wordle-bot A Discord bot to track you and your friends' Wordle scores, so you can see who's the best! To submit a score to wordle-bot, just paste the

Spencer Murray 8 Feb 16, 2022
fhempy is a FHEM binding to write modules in Python language

fhempy (BETA) fhempy allows the usage of Python 3 (NOT 2!) language to write FHEM modules. Python 3.7 or higher is required, therefore I recommend usi

Dominik 27 Dec 14, 2022
Automated endpoint management for Amazon Aurora Global Database

This sample code can be used to manage Aurora global database endpoints. After failover the global database writer endpoints swap from one region to the other. This solution automates creation and ma

AWS Samples 13 Dec 08, 2022