GithubHelp home page GithubHelp logo

slackapi / python-slack-sdk Goto Github PK

View Code? Open in Web Editor NEW
3.8K 163.0 835.0 9.66 MB

Slack Developer Kit for Python

Home Page: https://slack.dev/python-slack-sdk/

License: MIT License

Python 85.33% Makefile 0.25% HTML 10.66% Batchfile 0.26% Shell 0.10% CSS 0.81% JavaScript 2.60%
python slack slackapi asyncio aiohttp-client aiohttp websockets websocket websocket-client socket-mode

python-slack-sdk's Introduction

Python Slack SDK

CI Build Codecov Pepy Total Downloads
PyPI - Version Python Versions Documentation

The Slack platform offers several APIs to build apps. Each Slack API delivers part of the capabilities from the platform, so that you can pick just those that fit for your needs. This SDK offers a corresponding package for each of Slack’s APIs. They are small and powerful when used independently, and work seamlessly when used together, too.

Comprehensive documentation on using the Slack Python can be found at https://slack.dev/python-slack-sdk/


Whether you're building a custom app for your team, or integrating a third party service into your Slack workflows, Slack Developer Kit for Python allows you to leverage the flexibility of Python to get your project up and running as quickly as possible.

The Python Slack SDK allows interaction with:

If you want to use our Events API and Interactivity features, please check the Bolt for Python library. Details on the Tokens and Authentication can be found in our Auth Guide.

slackclient is in maintenance mode

Are you looking for slackclient? The website is live here just like before. However, the slackclient project is in maintenance mode now and this slack_sdk is the successor. If you have time to make a migration to slack_sdk v3, please follow our migration guide to ensure your app continues working after updating.

Table of contents

Requirements


This library requires Python 3.6 and above. If you require Python 2, please use our SlackClient - v1.x. If you're unsure how to check what version of Python you're on, you can check it using the following:

Note: You may need to use python3 before your commands to ensure you use the correct Python path. e.g. python3 --version

python --version

-- or --

python3 --version

Installation

We recommend using PyPI to install the Slack Developer Kit for Python.

$ pip install slack_sdk

Getting started tutorial


We've created this tutorial to build a basic Slack app in less than 10 minutes. It requires some general programming knowledge, and Python basics. It focuses on the interacting with Slack's Web and RTM API. Use it to give you an idea of how to use this SDK.

Read the tutorial to get started!

Basic Usage of the Web Client


Slack provide a Web API that gives you the ability to build applications that interact with Slack in a variety of ways. This Development Kit is a module based wrapper that makes interaction with that API easier. We have a basic example here with some of the more common uses but a full list of the available methods are available here. More detailed examples can be found in our guide.

Sending a message to Slack

One of the most common use-cases is sending a message to Slack. If you want to send a message as your app, or as a user, this method can do both. In our examples, we specify the channel name, however it is recommended to use the channel_id where possible. Also, if your app's bot user is not in a channel yet, invite the bot user before running the code snippet (or add chat:write.public to Bot Token Scopes for posting in any public channels).

import os
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

client = WebClient(token=os.environ['SLACK_BOT_TOKEN'])

try:
    response = client.chat_postMessage(channel='#random', text="Hello world!")
    assert response["message"]["text"] == "Hello world!"
except SlackApiError as e:
    # You will get a SlackApiError if "ok" is False
    assert e.response["ok"] is False
    assert e.response["error"]  # str like 'invalid_auth', 'channel_not_found'
    print(f"Got an error: {e.response['error']}")
    # Also receive a corresponding status_code
    assert isinstance(e.response.status_code, int)
    print(f"Received a response status_code: {e.response.status_code}")

Here we also ensure that the response back from Slack is a successful one and that the message is the one we sent by using the assert statement.

Uploading files to Slack

We've changed the process for uploading files to Slack to be much easier and straight forward. You can now just include a path to the file directly in the API call and upload it that way.

import os
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError

client = WebClient(token=os.environ['SLACK_BOT_TOKEN'])

try:
    filepath="./tmp.txt"
    response = client.files_upload_v2(channel='C0123456789', file=filepath)
    assert response["file"]  # the uploaded file
except SlackApiError as e:
    # You will get a SlackApiError if "ok" is False
    assert e.response["ok"] is False
    assert e.response["error"]  # str like 'invalid_auth', 'channel_not_found'
    print(f"Got an error: {e.response['error']}")

More details on the files_upload_v2 method can be found here.

Async usage

AsyncWebClient in this SDK requires AIOHttp under the hood for asynchronous requests.

AsyncWebClient in a script

import asyncio
import os
from slack_sdk.web.async_client import AsyncWebClient
from slack_sdk.errors import SlackApiError

client = AsyncWebClient(token=os.environ['SLACK_BOT_TOKEN'])

async def post_message():
    try:
        response = await client.chat_postMessage(channel='#random', text="Hello world!")
        assert response["message"]["text"] == "Hello world!"
    except SlackApiError as e:
        assert e.response["ok"] is False
        assert e.response["error"]  # str like 'invalid_auth', 'channel_not_found'
        print(f"Got an error: {e.response['error']}")

asyncio.run(post_message())

AsyncWebClient in a framework

If you are using a framework invoking the asyncio event loop like : sanic/jupyter notebook/etc.

import os
from slack_sdk.web.async_client import AsyncWebClient
from slack_sdk.errors import SlackApiError

client = AsyncWebClient(token=os.environ['SLACK_BOT_TOKEN'])
# Define this as an async function
async def send_to_slack(channel, text):
    try:
        # Don't forget to have await as the client returns asyncio.Future
        response = await client.chat_postMessage(channel=channel, text=text)
        assert response["message"]["text"] == text
    except SlackApiError as e:
        assert e.response["ok"] is False
        assert e.response["error"]  # str like 'invalid_auth', 'channel_not_found'
        raise e

from aiohttp import web

async def handle_requests(request: web.Request) -> web.Response:
    text = 'Hello World!'
    if 'text' in request.query:
        text = "\t".join(request.query.getall("text"))
    try:
        await send_to_slack(channel="#random", text=text)
        return web.json_response(data={'message': 'Done!'})
    except SlackApiError as e:
        return web.json_response(data={'message': f"Failed due to {e.response['error']}"})


if __name__ == "__main__":
    app = web.Application()
    app.add_routes([web.get("/", handle_requests)])
    # e.g., http://localhost:3000/?text=foo&text=bar
    web.run_app(app, host="0.0.0.0", port=3000)

Advanced Options

SSL

You can provide a custom SSL context or disable verification by passing the ssl option, supported by both the RTM and the Web client.

For async requests, see the AIOHttp SSL documentation.

For sync requests, see the urllib SSL documentation.

Proxy

A proxy is supported when making async requests, pass the proxy option, supported by both the RTM and the Web client.

For async requests, see AIOHttp Proxy documentation.

For sync requests, setting either HTTPS_PROXY env variable or the proxy option works.

DNS performance

Using the async client and looking for a performance boost? Installing the optional dependencies (aiodns) may help speed up DNS resolving by the client. We've included it as an extra called "optional":

$ pip install slack_sdk[optional]

Example

import os
from slack_sdk import WebClient
from ssl import SSLContext

sslcert = SSLContext()
# pip3 install proxy.py
# proxy --port 9000 --log-level d
proxyinfo = "http://localhost:9000"

client = WebClient(
    token=os.environ['SLACK_BOT_TOKEN'],
    ssl=sslcert,
    proxy=proxyinfo
)
response = client.chat_postMessage(channel="#random", text="Hello World!")
print(response)

Migrating from v2

If you're migrating from slackclient v2.x of slack_sdk to v3.x, Please follow our migration guide to ensure your app continues working after updating.

Check out the Migration Guide here!

Migrating from v1

If you're migrating from v1.x of slackclient to v2.x, Please follow our migration guide to ensure your app continues working after updating.

Check out the Migration Guide here!

Support


If you get stuck, we’re here to help. The following are the best ways to get assistance working through your issue:

Use our Github Issue Tracker for reporting bugs or requesting features. Visit the Slack Community for getting help using Slack Developer Kit for Python or just generally bond with your fellow Slack developers.

Contributing

We welcome contributions from everyone! Please check out our Contributor's Guide for how to contribute in a helpful and collaborative way.

python-slack-sdk's People

Contributors

aoberoi avatar cclauss avatar clavin avatar dependabot[bot] avatar eddyg avatar filmaj avatar fwump38 avatar greut avatar hockeybuggy avatar jamim avatar jammons avatar jimray avatar jourdanrodrigues avatar jsoref avatar karishay avatar misscoded avatar mlaferrera avatar mwbrooks avatar paul-griffith avatar rawdigits avatar revolter avatar rickhanlonii avatar roach avatar rodneyu215 avatar rubervulpes avatar seratch avatar srajiang avatar stevengill avatar williambergamin avatar yasumoto avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

python-slack-sdk's Issues

Any example how to use RTM with multiple token?

Hi is there any example on how to use RTM using multple tokens (bot-user)

#token ==> list of tokens
for t in token:
    slack = SlackClient(token)

    if slack.rtm_connect():
        while True:
            print slack.rtm_read()
            time.sleep(1)
    else:
        print "Connection Failed, invalid token?"

Does not support python3

The current code base does not support python 3. In it's current form, only minor modifications would need to be made to support it.

Member lists for direct messaging

Here's an excerpt from sc.server.login_data:

 'ims': [{'created': 1460392964,
          'has_pins': False,
          'id': 'D0ZP2KK7T',
          'is_im': True,
          'is_open': True,
          'is_org_shared': False,
          'last_read': '0000000000.000000',
          'latest': None,
          'members': [],
          'name': 'D0ZP2KK7T',
          'unread_count': 0,
          'unread_count_display': 0,
          'user': 'USLACKBOT'},
          ...

When my bot receives an IM and goes to see who is present on a channel, the member list accessed via sc.server.channels[index].members always comes out empty as a result. I'm not sure whether this is considered a bug or a feature, but if it is considered a bug, it can be fixed fairly easily by using the bot's own ID and the ID given as the value for the 'user' key (in the above case, 'USLACKBOT') in lieu of the empty member list.

Server.send_to_websocket discards the message when reconnect is needed

  • I've read and understood the Contributing guidelines and have done my best effort to follow them.
  • I've read and agree to the Code of Conduct.
  • I've searched for any related issues and avoided creating a duplicate issue.

Description

Message from rtm_send_message is lost when reconnection to websocket is needed. self.websocket.send(data) in _server.py should be called in both cases.

Reproducible in:

slack = SlackClient('...')

slack.rtm_connect()
slack.server.websocket.close()
slack.rtm_send_message('...', 'test #1')  # Doesn't work
slack.rtm_send_message('...', 'test #2')  # Works

Expected result:

Both messages posted in given channel.

Actual result:

Only second message posted in given channel.

Can only use new group DMs after reconnect

New group DMs are not picked up in the server's channels SearchList when they are originally created, so any attempts to use that group DM will fail. When I do a fresh reconnect, I get that channel information from the original channel dump and it works again. Most likely need to fix something in process_changes to pick up new group DMs.

install slackclient failed

Os : Archlinux
Python : 3.4.2

# python setup.py install
running install
Traceback (most recent call last):
  File "setup.py", line 11, in <module>
    zip_safe=False)
  File "/usr/lib/python3.4/distutils/core.py", line 148, in setup
    dist.run_commands()
  File "/usr/lib/python3.4/distutils/dist.py", line 955, in run_commands
    self.run_command(cmd)
  File "/usr/lib/python3.4/distutils/dist.py", line 974, in run_command
    cmd_obj.run()
  File "/usr/lib/python3.4/site-packages/setuptools/command/install.py", line 67, in run
    self.do_egg_install()
  File "/usr/lib/python3.4/site-packages/setuptools/command/install.py", line 103, in do_egg_install
    cmd.ensure_finalized()  # finalize before bdist_egg munges install cmd
  File "/usr/lib/python3.4/distutils/cmd.py", line 107, in ensure_finalized
    self.finalize_options()
  File "/usr/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 317, in finalize_options
    self.index_url, search_path=self.shadow_path, hosts=hosts,
  File "/usr/lib/python3.4/site-packages/setuptools/package_index.py", line 269, in __init__
    Environment.__init__(self,*args,**kw)
  File "/usr/lib/python3.4/site-packages/pkg_resources/__init__.py", line 975, in __init__
    self.scan(search_path)
  File "/usr/lib/python3.4/site-packages/pkg_resources/__init__.py", line 1005, in scan
    self.add(dist)
  File "/usr/lib/python3.4/site-packages/pkg_resources/__init__.py", line 1025, in add
    dists.sort(key=operator.attrgetter('hashcmp'), reverse=True)
TypeError: unorderable types: str() < NoneType()

README example doesn't work

from slackclient import SlackClient

token = 'xoxp-28192348123947234198234'
sc = SlackClient(token)
print sc.api_call('api.test')

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)

     19 
     20     def api_call(self, method, **kwargs):
---> 21         return self.server.api_call(method, kwargs)
     22 
     23     def rtm_read(self):

TypeError: api_call() takes exactly 2 arguments (3 given)

It looks like PRs #2 and #5 both include the fix for this.

ConnectionResetError not caught in websocket_safe_read

Ran into an issue when letting my SlackClient run for extended period of time, received the below stack trace. It seems that in send_to_websocket() we catch any exception and reconnect the client. However, when reading from the server via rtm_read() we do not catch any connection failures. Is this by design? Could we possibly catch a connection error in websocket_safe_read() or rtm_read() and reconnect?

...
File "/usr/local/lib/python3.5/site-packages/slackclient/_client.py", line 39, in rtm_read
json_data = self.server.websocket_safe_read()
File "/usr/local/lib/python3.5/site-packages/slackclient/_server.py", line 110, in websocket_safe_read
data += "{0}\n".format(self.websocket.recv())
File "/usr/local/lib/python3.5/site-packages/websocket/_core.py", line 298, in recv
opcode, data = self.recv_data()
File "/usr/local/lib/python3.5/site-packages/websocket/_core.py", line 315, in recv_data
opcode, frame = self.recv_data_frame(control_frame)
File "/usr/local/lib/python3.5/site-packages/websocket/_core.py", line 328, in recv_data_frame
frame = self.recv_frame()
File "/usr/local/lib/python3.5/site-packages/websocket/_core.py", line 360, in recv_frame
return self.frame_buffer.recv_frame()
File "/usr/local/lib/python3.5/site-packages/websocket/_abnf.py", line 312, in recv_frame
self.recv_header()
File "/usr/local/lib/python3.5/site-packages/websocket/_abnf.py", line 261, in recv_header
header = self.recv_strict(2)
File "/usr/local/lib/python3.5/site-packages/websocket/_abnf.py", line 346, in recv_strict
bytes = self.recv(min(16384, shortage))
File "/usr/local/lib/python3.5/site-packages/websocket/_core.py", line 429, in _recv
return recv(self.sock, bufsize)
File "/usr/local/lib/python3.5/site-packages/websocket/_socket.py", line 77, in recv
bytes = sock.recv(bufsize)
File "/usr/local/lib/python3.5/ssl.py", line 909, in recv
return self.read(buflen)
File "/usr/local/lib/python3.5/ssl.py", line 786, in read
return self._sslobj.read(len, buffer)
File "/usr/local/lib/python3.5/ssl.py", line 572, in read
v = self._sslobj.read(len or 1024)
ConnectionResetError: [Errno 104] Connection reset by peer

Some issues found

I tried the following methods and encountered the following errors:

I confirmed that devtest channel exists, as this line
sc.api_call("chat.postMessage", channel="#devtest", text="Let's welcome Wise Old Man!") works

However, it sends the message as a "BOT" and not the custom user name I selected?

sc.rtm_send_message(channel="#devtest",message="hello world")
AttributeError: 'NoneType' object has no attribute 'send_message'

sc.server.channnels.find("#devtest").send_message("hello world")
The error is: AttributeError: 'Server' object has no attribute 'channnels'

api_call method returning string, not dict

I was testing the api_call method and couldn't parse - when testing response, I was getting a response as a string, not a dictionary, as the documentation notes.

import time, os
from slackclient import SlackClient

token = os.environ.get("SLACK_TOKEN")
sc = SlackClient(token)

print sc.api_call("api.test")
print type(sc.api_call("api.test"))


get_info = sc.api_call("im.history", channel="D076VAAKY")
print type(get_info)

response from running this script:

$ python slack_test.py
{"ok":true,"args":{"token":"xoxp-6950599446-7233369073-12964712006-aa717de21f"}}
<type 'str'>
<type 'str'>

README docs for api_call() are incorrect

The README file says

SlackClient.api_call([method, params]) Call the Slack method [method] with the a dict of params in [params]

which implies you'd call it like this

sc.api_call(method="users.list", params=["token":my_token, "user":"U1234567"})

However, you actually call it like this:

sc.api_call(method="users.list", user="U1234567")

Python 3 version?

Currently python-slackclient is unable to install for Python 3.5.

$ pip install python-slackclient
Collecting python-slackclient
  Could not find a version that satisfies the requirement python-slackclient (from versions: )
No matching distribution found for python-slackclient

$ pip --version
pip 8.1.1 from /usr/local/lib/python3.5/site-packages (python 3.5)

HTML entity escaping

When I send 1 & 3 on slack, this library receive 1 &amp; 3
This should be unescaped on rtm_read function. and escaped when rtm_send_message function

SSLError raised in Server.websocket_safe_read()

I have been using this library for a while and it consistently has problems keeping the connection live. I have found the issue in Server.websocket_safe_read(), where it is raising the SSLError exception with errno = 2. This error is not correctly handled and all subsequent calls to rtm_read() return nothing forever.

ImportError: cannot import name create_connection

My code works on my local machine, but I just installed slackclient on my digital ocean droplet and tried to run it, only to run into this error:

from slackclient import SlackClient
  File "{redacted}/local/lib/python2.7/site-packages/slackclient-0.16-py2.7.egg/slackclient/__init__.py", line 1, in <module>
    from slackclient._client import SlackClient
  File "{redacted}/local/lib/python2.7/site-packages/slackclient-0.16-py2.7.egg/slackclient/_client.py", line 6, in <module>
    from slackclient._server import Server
  File "{redacted}/local/lib/python2.7/site-packages/slackclient-0.16-py2.7.egg/slackclient/_server.py", line 7, in <module>
    from websocket import create_connection
ImportError: cannot import name create_connection

Any idea what is causing this?

Channel not getting added

If you have your bot code do an api_call with im.open the channel is created just fine but you can't use the slack-client rtm_send_message function to post to it as it has no idea a channel has been created until the rtm_read gets called again. I don't want to call a new read as my code is still processing the current messages. Right now I have a workaround in my code where I use the returned info from im.open to add the channel to the list the slack-client server has and then remove it once my bot has sent out it's message so there aren't channel duplicates once rtm_read happens

Bot's name/icon ignored

Messages are always posted by 'bot' using a generic icon. The name/icon set on the integration configuration page is ignored.

Not sure whether this is a problem with this library or the API itself.

Upload to PyPI?

Noticed that this isn't on PyPI. Is there a reason this? It would make installing and using this library much easier.

files.upload fail

when i use files.upload
It throw a error
TypeError: <open file 'test.png', mode 'rb' at 0x7fda02706780> is not JSON serializable

So I change the code

--- a/slackclient/_slackrequest.py
+++ b/slackclient/_slackrequest.py
@@ -21,12 +21,14 @@ class SlackRequest(object):
         '''
         post_data = post_data or {}

+        files = {'file': post_data.pop('file')} if 'file' in post_data else None        
         for k, v in six.iteritems(post_data):
             if not isinstance(v, six.string_types):
                 post_data[k] = json.dumps(v)

         url = 'https://{0}/api/{1}'.format(domain, request)
         post_data['token'] = token
-        files = {'file': post_data.pop('file')} if 'file' in post_data else None

         return requests.post(url, data=post_data, files=files)

And it works!!

Unable to connect

When calling .connect(), I'm getting a connection error (connect returns False). I've verified that my token is correct and my bot is enabled. Trying to call some APIs returns a SlackConnectionError:

File ".envs/my_bot/lib/python2.7/site-packages/slackclient/_server.py", line 92, in ping
    return self.send_to_websocket({"type": "ping"})
File ".envs/my_bot/lib/python2.7/site-packages/slackclient/_server.py", line 89, in send_to_websocket
    self.rtm_connect(reconnect=True)
File ".envs/my_bot/lib/python2.7/site-packages/slackclient/_server.py", line 47, in rtm_connect
    self.connect_slack_websocket(self.ws_url)
File ".envs/my_bot/lib/python2.7/site-packages/slackclient/_server.py", line 65, in connect_slack_websocket
    raise SlackConnectionError
SlackConnectionError

For instance, I followed the example in the README, and got this. Running .api_call('api.test') does appear to work, though.

Add license file and tests to source distribution (sdist)

The LICENSE.txt file in the repository is missing from the PyPi source distribution (sdist). You likely want a MANIFEST.in to do this. That will allow me to package the relevant license in the FreeBSD Ports I've created for slackclient.

While you're there, you may want to add Copyright details to the LICENSE.txt head

rtm_send_message fails on newly opened IMs

Replication:

  1. Generate a new bot api key.
  2. Run the following script:
from slackclient import SlackClient

def search(dict_list, key, value):
    for item in dict_list:
        if item[key] == value:
            return item

SLACK_DEBUG_KEY = "YOUR-BRAND-NEW-SLACK-DEBUG-KEY-HERE"
sc = SlackClient(SLACK_DEBUG_KEY)
sc.rtm_connect()
users = sc.api_call('users.list')['members']
user = search(users, 'name', 'your-slack-username-here')
dm = sc.api_call('im.open', user=user['id'])['channel']['id']
sc.rtm_send_message(dm, 'this should be a message you receive')

Expected:

A message from the bot whose key you used on the first time.

Actual:

This error the first time:

Traceback:
  File "~/pycharmprojects/python-slackclient/slackclient/_client.py", line 40, in rtm_send_message
    return self.server.channels.find(channel).send_message(message)
AttributeError: 'NoneType' object has no attribute 'send_message'

Works as expected the second time.

Notes:

rtm_send_message depends on the cached set of channels. Fix will be in rtm_send_message definition, probably by inserting or creating a channel object if not there. But it's four in the morning here and I'm gonna get some sleep first.

websocket_safe_read is swallowing SSLErrors

https://github.com/slackhq/python-slackclient/blob/master/slackclient/_server.py#L81 is hiding a connection error.

My server runs for a while until it loses connection to slack, but doesn't report any errors. Because it doesn't crash, it doesn't reboot. This is because of line 81 in _server.py.

I found this out by instrumenting the server, waiting for such a crash, and then dropping into the debugger. Here's the results:

ipdb> p slack.server.websocket.connected
True
ipdb> ws = slack.server.web
server.slack.server.websocket            server.slack.server.websocket_safe_read
ipdb> ws = slack.server.websocket
ipdb> ws
<websocket._core.WebSocket object at 0x10f158550>
ipdb> ws.recv()
*** SSLError: [Errno 2] _ssl.c:1426: The operation did not complete (read)

So, at the very least, websocket_safe_read should not be handling SSLErrors.

What errors is that except intended to catch?

'Feedback' (loop) problem when listening to the slack channel

Maybe the given example is too naive. Given the 1 second sleep in between. But this should give it plenty of time to react. Why is it sometimes receiving old messages, such as hu again, even though hello you came at a later point.

And why is it looping like that?

if sc.rtm_connect():
    while True:
        r = sc.rtm_read()
        if r and len(r) > 0:
            t = r[0].get('text')
            print t
            if t is not None:
                sc.api_call(
                    "chat.postMessage", channel="#general", text="'{0}', what? I kill you!".format(t),
                    username='pybot', icon_emoji=':robot_face:'
                )
        time.sleep(1)
else:
    print "Connection Failed, invalid token?"

screen shot 2016-03-26 at 21 51 38

Python3 Support?

I am having a really hard time understanding why Python3 support was not built into this client. Am I missing something obvious?

ascii encoding errors when a user's name includes a funky character

One of our employee's names has a ç in it. That causes this error:

>>> sc.server.channels.find("C0B8PQGSY")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/weitzenfeld/.virtualenvs/qbit/lib/python2.7/site-packages/slackclient/_channel.py", line 21, in __repr__
    return self.__str__()
  File "/Users/weitzenfeld/.virtualenvs/qbit/lib/python2.7/site-packages/slackclient/_channel.py", line 17, in __str__
    data += "{} : {}\n".format(key, str(self.__dict__[key])[:40])
  File "/Users/weitzenfeld/.virtualenvs/qbit/lib/python2.7/site-packages/slackclient/_server.py", line 36, in __str__
    data += "{} : {}\n".format(key, str(self.__dict__[key])[:40])
  File "/Users/weitzenfeld/.virtualenvs/qbit/lib/python2.7/site-packages/slackclient/_user.py", line 25, in __repr__
    return self.__str__()
  File "/Users/weitzenfeld/.virtualenvs/qbit/lib/python2.7/site-packages/slackclient/_user.py", line 20, in __str__
    encoded_val = str(self.__dict__[key]).encode('ascii', errors='ignore')
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe7' in position 10: ordinal not in range(128)

Let user specify HTTP proxy port

Some platforms (like Heroku) require that apps bind to a port specified by an environment variable. That means I can't deploy apps using this client to Heroku, as this client (as far as I know) always tries to bind to port 80.

This create_connection call defaults to port 80. It'd be nice if we could pass additional options to be forwarded to this underlying create_connection call - that library accepts an option to specify port like so:

ws.connect("ws://example.com/websocket", http_proxy_host="proxy_host_name", http_proxy_port=3128)

Unable to format links

I'm finding that I'm unable to format any links using the slack_client.api_call method. The link just appears as text. Also tried putting the link in text, title, fields, and pre_text but I got the same results.

snippet as follows:

att = [{
    "fallback": "fallback",
    "text": "<https://honeybadger.io/path/to/event/|ReferenceError>",
}]
slack_client.api_call("chat.postMessage", parse="full", as_user=True, channel='sample-channel', text="sample-text", attachments=json.dumps(att))

Channel IDs starting with D

I see some channel ids starting with D. From what I deduced, each user has a corresponding channel ID that starts with D. Could you please give more info. Also, can you tell me how to get this association between user ids starting with U to channel ids starting with D

Star_added event does not work.

I tried listening for star_added events, but when I star a message within Slack, the intended debug message doesn't get printed out.

from slackclient import SlackClient

class LikeBot(SlackClient):

    # Create bot instance
    def __init__(self, token):
        SlackClient.__init__(self, token)
        self.connect_rtm()
        self.server.join_channel('#bot-test')


    # Connect to Slack's RTM API
    def connect_rtm(self):
        print 'Likebot connecting to RTM API...' #DEBUG
        if self.rtm_connect():
            print 'Likebot connected!' #DEBUG
        else:
            print 'Likebot failed to connect!' #DEBUG


    # Begin listening for JSON formatted RTM API messages/events
    def listen(self):
        print 'Likebot Listening...' #DEBUG
        while True:
            for event in self.rtm_read():
                # do something with RTM API event
                print event # DEBUG; Fails to print a `star_added` event
                if event.get('type') == 'star_added':
                    print True


if __name__ == '__main__':
    bot = LikeBot('foo_token')
    bot.listen()

unable to pip install in virtualenv - permission denied

pip install slackclient is throwing a permission denied, maybe I'm missing something here...

  1. virtualenv -p python2.7 venv
  2. . ./venv/bin/activate
  3. pip install slackclient

heres the trace:
OSError: [Errno 13] Permission denied: '~/Library/Caches/pip/wheels/e3/8d'

[Beta] Fix campaign SKU edition.

  • Re-enable SKU save on campaign edit view;
  • Check the SKU variations based on key:
    • Todos produtos (eg. "sku--")
    • sku--ID (eg. "sku--99")
    • nome (eg. "alpha")
    • mask (eg. "DE%")

SlackNotConnected is never raised

This bug report comes in a few parts.

1: rtm_read() in SlackClient will never raise SlackNotConnected

def rtm_read(self):
        # in the future, this should handle some events internally i.e. channel
        # creation
        if self.server:
            json_data = self.server.websocket_safe_read()
            data = []
            if json_data != '':
                for d in json_data.split('\n'):
                    data.append(json.loads(d))
            for item in data:
                self.process_changes(item)
            return data
        else:
            raise SlackNotConnected

Because the server object does not implement __nonzero__ (in Python 2) or __bool__ (in Python 3) or even __len__, self.server will always evaluate to True and therefore SlackNotConnected will never be thrown.

2: The server object has an unused connected attribute in its constructor.

SlackLoginError

Hello,

I've had a SlackClient running for a few months. One day I received the following error, and the client crashed. Any ideas what could cause this?

Traceback (most recent call last):
  File "rtmbot.py", line 169, in main_loop
    bot.start()
  File "rtmbot.py", line 39, in start
    self.autoping()
  File "rtmbot.py", line 45, in autoping
    self.slack_client.server.ping()
  File "/usr/local/lib/python2.7/dist-packages/slackclient/_server.py", line 92, in ping
    return self.send_to_websocket({"type": "ping"})
  File "/usr/local/lib/python2.7/dist-packages/slackclient/_server.py", line 89, in send_to_websocket
    self.rtm_connect(reconnect=True)
  File "/usr/local/lib/python2.7/dist-packages/slackclient/_server.py", line 49, in rtm_connect
    raise SlackLoginError
SlackLoginError

Thanks,
Marcus

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.