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
Python wrapper for the Intercom API.

python-intercom Not officially supported Please note that this is NOT an official Intercom SDK. The third party that maintained it reached out to us t

Intercom 215 Dec 22, 2022
veez music bot is a telegram music bot project, allow you to play music on voice chat group telegram.

🎶 VEEZ MUSIC BOT Veez Music is a telegram bot project that's allow you to play music on telegram voice chat group. Requirements 📝 FFmpeg NodeJS node

levina 143 Jun 19, 2022
(unofficial) Googletrans: Free and Unlimited Google translate API for Python. Translates totally free of charge.

Googletrans Googletrans is a free and unlimited python library that implemented Google Translate API. This uses the Google Translate Ajax API to make

Suhun Han 3.2k Jan 04, 2023
A simple Python API wrapper for Cloudflare Stream's API.

python-cloudflare-stream A basic Python API wrapper for working with Cloudflare Stream. Arbington.com started off using Cloudflare Stream. We used the

Arbington 3 Sep 08, 2022
this repo store a Awoesome telegram bot for protect from your large group from bot attack.

this repo store a Awoesome telegram bot for protect from your large group from bot attack.

Mehran Alam Beigi 2 Jul 22, 2022
Telegram Bot to save Posts or Files that can be Accessed via Special Links

OKAERI-FILE Bot Telegram untuk menyimpan Posting atau File yang dapat Diakses melalui Link Khusus. Jika Anda memerlukan tambahan module lagi dalam rep

Wahyusaputra 5 Aug 04, 2022
A python script to download twitter space, only works on running spaces (for now).

A python script to download twitter space, only works on running spaces (for now).

279 Jan 02, 2023
A delightful and complete interface to GitHub's amazing API

ghapi A delightful and complete interface to GitHub's amazing API ghapi provides 100% always-updated coverage of the entire GitHub API. Because we aut

fast.ai 428 Jan 08, 2023
A file-based quote bot written in Python

Let's Write a Python Quote Bot! This repository will get you started with building a quote bot in Python. It's meant to be used along with the Learnin

Jyoti prakash Rout 1 Jan 08, 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
Scratch2py or S2py is a easy to use, versatile tool to communicate with the Scratch API Based of Scratch2py

Scratch2py Scratch2py or S2py is a easy to use, versatile tool to communicate with the Scratch API Based of Scratch2py Installation Run this command i

2 Jan 13, 2022
Yes, it's true :heartbeat: This repository has 337 stars.

Yes, it's true! Inspired by a similar repository from @RealPeha, but implemented using a webhook on AWS Lambda and API Gateway, so it's serverless! If

512 Jan 01, 2023
Twitter bot to know the number of dislikes of a YouTube video

YT_dislikes is a twitter bot that allows you to know the number of dislikes (and likes) of a YouTube video. Now it is not possible to see the number o

1 Jan 08, 2022
A pyrogram simple bot for Educational purpose.

A pyrogram simple bot for Educational purpose. To Learn More check at @PyrogramBot or on Documentation Mandatory variables API_ID - Get It From my.tel

SpamShield 10 Dec 06, 2022
✨ 🐍 Python SDK for StarkNet.

✨ 🐍 starknet.py StarkNet SDK for Python 📘 Documentation Installation Quickstart Guide API Installation To install this package run pip install stark

Software Mansion 158 Jan 04, 2023
Cloudkeeper is “housekeeping for clouds” - find leaky resources, manage quota limits, detect drift and clean up.

Cloudkeeper Housekeeping for Clouds! Table of contents Overview Docker based quick start Cloning this repository Component list Contact License Overvi

Some Engineering 1.2k Jan 03, 2023
A Powerful Telethon Based Telegram Spam Bot.

Yukki Multi Spam Bot 🚀 Deploy on Heroku You can Use these API ID and API HASH while deploying String Session No Requirement of API ID and API HASH Ge

46 Dec 23, 2022
Riffdog Terraform scanner - finding 'things' in the Real World (aka AWS) which Terraform didn't put there.

riffdog Riffdog Terraform / Reality scanner - finding 'things' in the Real World which Terraform didn't put there. This project works by firstly loadi

Riffdog 4 Mar 23, 2020
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
Send notification to your telegram group/channel/private whenever a new video is uploaded on a youtube channel!

YouTube Feeds Bot. Send notification to your telegram group/channel/private whenever a new video is uploaded on a youtube channel! Variables BOT_TOKEN

Aditya 30 Dec 07, 2022