os / slacker Goto Github PK
View Code? Open in Web Editor NEWFull-featured Python interface for the Slack API
License: Apache License 2.0
Full-featured Python interface for the Slack API
License: Apache License 2.0
It is bad practice to open\close TCP connection for each api request.
Client must create on __init__
requests.Session
and explicitly close it.
Very minor, would be convenient to have slacker.__version__
as in https://www.python.org/dev/peps/pep-0396/
In init.py on line 426 2nd instance of word file should be replaced with file_
On lines 61-62 in slacker/init.py, you raise an exception where response.successful != True. In the WebAPI implementation, the response would simply be yielded with 'ok': 'False' and 'error': '[some error message]'. Wouldn't it make more sense to mimic the WebAPI implementation in this respect and just yield the response as-is? Thanks!
Hi i noticed that you added parse option to chat.update but you might have forgotten to actually pass the variable to the post method is that intentional or was that mistake?
def update(self, channel, ts, text, attachments=None, parse=None,
link_names=False, as_user=None):
# Ensure attachments are json encoded
if attachments and isinstance(attachments, list):
attachments = json.dumps(attachments)
return self.post('chat.update',
data={
'channel': channel,
'ts': ts,
'text': text,
'attachments': attachments,
'parse': None, #<--------------- change here
'link_names': int(link_names),
'as_user': as_user,
})
shouldnt this be
def update(self, channel, ts, text, attachments=None, parse=None,
link_names=False, as_user=None):
# Ensure attachments are json encoded
if attachments and isinstance(attachments, list):
attachments = json.dumps(attachments)
return self.post('chat.update',
data={
'channel': channel,
'ts': ts,
'text': text,
'attachments': attachments,
'parse': parse, #<--------------- change here
'link_names': int(link_names),
'as_user': as_user,
})
otherwise the param in the function is pointless.
Hello. I'm trying to post a message with an attachment, but it doesn't seem to work. OR, I'm not using it correctly, in which case, could you please add an example to the README.
This is what I'm trying:
print slack.chat.post_message('#sandbox', 'text', attachments={'fallback':'fallback', 'fields':[{'title':'title','value':'value'}]}).body
All I end up seeing is the message "text" without anything else.
Thanks!
Messages posted using chat.post_message()
are run through cgi.escape()
. This suppresses any internal angle brackets, which means you can't use the slack api formatting conventions for things like inline links or user references.
It should be pretty easy to add a flag to post_message that disables escaping, or something more clever that runs escape (to get rid of quotes and so on) then re-instates angle-brackets that look like slack commands
I can't tell if this is just an issue for me, and if so then you can close the issue, but I'm running into the above error when trying to run the example in the readme.
Has anyone run into it before and how are you getting around it if you have? I tried updating pyopenssl but that didn't seem to have any effect.
It's a bummer that I have to tell people to install your thing from github before installing ours from pypi :<
When I post a message to a channel, it posts it under the name "Slack API Tester". How can I setup it up or rename?
Slack just added 2FA.
In the returned object it looks to be the attribute called 'has_2fa'
Docs:
https://api.slack.com/types/user
Thought I would bring it to your attention if you had not already seen it, and wanted to do some kind of additional functionality off of it.
For using slash commands and other interactive buttons, you're given the option to respond using the response_url
field value instead of just a normal return within the 3 second limit.
not documented api method.
check : https://github.com/ErikKalkoken/slackApiDoc/blob/master/users.admin.invite.md
and: https://twitter.com/slackapi/status/570323011338772480
Right now, files.upload requires a file on disk, but it would be great if slacker.files.upload would take (and use) a string instead of a filename.
I'm trying to upload files that I grabbed off the web, and being able to have the following work would be great:
import requests
slack.files.upload(content=requests.get(url).content)
# or
slack.files.upload(url=url)
Posting messages via incoming webhooks allows for attachment only posts that are easier to format.
PR Coming to allow posting to a known URL.
Any plans for adding more support for the RTM API?
Let me know if I can help at all.
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.
file is currently required, but the API doesn't require it if content is specified.
I've been unable to fully establish a persistent connections to Slack so that the bot appears as "Active" in the DM list. This functionality is available in the official Slack Python library but I can't seem to get it to work here.
Hi there,
Sorry if this is the wrong avenue to post this on, but here I go.
I want to use slacker in a django app, which will have at least 2 threads, and many components, and I'm wondering what the best way to use the Slacker class is in this case.
Should I use it as a singleton for the project? for the individual app? for each module? for each thread?
Interested in your thoughts.
EDIT: This is a 'question', but it won't let me set the labels.
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).
I'm considering using slacker to implement a back-end for Slack on Err but it should, ideally, support Python 2.7 and 3.3+ for that. However, no compatibility is specified anywhere.
Please consider mentioning this in the README and setting appropriate trove classifiers in setup.py
.
I'm trying to use slacker on python 2.6.9 and getting the issue below, on 2.7.10 everything works. Upgrading to newer version of python is not possible in my case. Is there any workaround?
I'm getting the following error :
/usr/lib64/python2.6/site-packages/requests/packages/urllib3/util/ssl_.py:320: SNIMissingWarning: An HTTPS request has been made, but the SNI (Subject Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#snimissingwarning.
SNIMissingWarning
/usr/lib64/python2.6/site-packages/requests/packages/urllib3/util/ssl_.py:122: InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately and may cause certain SSL connections to fail. You can upgrade to a newer version of Python to solve this. For more information, see https://urllib3.readthedocs.org/en/latest/security.html#insecureplatformwarning.
InsecurePlatformWarning
/usr/lib64/python2.6/site-packages/requests/packages/urllib3/connection.py:303: SubjectAltNameWarning: Certificate for slack.com has no subjectAltName
, falling back to check for a commonName
for now. This feature is being removed by major browsers and deprecated by RFC 2818. (See urllib3/urllib3#497 for details.)
SubjectAltNameWarning
Traceback (most recent call last):
File "slack.py", line 22, in
notifySlacker()
File "slack.py", line 20, in notifySlacker
slack.chat.post_message('#general', 'Hello fellow slackers!')
File "build/bdist.linux-x86_64/egg/slacker/init.py", line 287, in post_message
File "build/bdist.linux-x86_64/egg/slacker/init.py", line 71, in post
File "build/bdist.linux-x86_64/egg/slacker/init.py", line 57, in _request
File "/usr/lib64/python2.6/site-packages/requests/api.py", line 111, in post
return request('post', url, data=data, json=json, *_kwargs)
File "/usr/lib64/python2.6/site-packages/requests/api.py", line 57, in request
return session.request(method=method, url=url, *_kwargs)
File "/usr/lib64/python2.6/site-packages/requests/sessions.py", line 475, in request
resp = self.send(prep, *_send_kwargs)
File "/usr/lib64/python2.6/site-packages/requests/sessions.py", line 585, in send
r = adapter.send(request, _kwargs)
File "/usr/lib64/python2.6/site-packages/requests/adapters.py", line 475, in send
raise SSLError(e, request=request)
requests.exceptions.SSLError: hostname 'slack.com' doesn't match u'.slack.com'
import _ssl
print _ssl._test_decode_cert('slack.cert')
Python 2.6.9
{'notBefore': 'Jan 26 00:00:00 2015 GMT', 'serialNumber': '27CE5D06960D3796B9E8F6BB000D2DE9', 'notAfter': 'Feb 18 23:59:59 2017 GMT', 'version': 3, 'subject': ((('countryName', u'US'),), (('stateOrProvinceName', u'California'),), (('localityName', u'San Francisco'),), (('organizationName', u'Slack Technologies, Inc'),), (('commonName', u'*.slack.com'),)), 'issuer': ((('countryName', u'US'),), (('organizationName', u'GeoTrust Inc.'),), (('commonName', u'GeoTrust SSL CA - G3'),))}
Python 2.7.10
{'crlDistributionPoints': (u'http://gn.symcb.com/gn.crl',), 'subjectAltName': (('DNS', '.slack.com'), ('DNS', 'slack.com')), 'notBefore': u'Jan 26 00:00:00 2015 GMT', 'caIssuers': (u'http://gn.symcb.com/gn.crt',), 'OCSP': (u'http://gn.symcd.com',), 'serialNumber': u'27CE5D06960D3796B9E8F6BB000D2DE9', 'notAfter': 'Feb 18 23:59:59 2017 GMT', 'version': 3L, 'subject': ((('countryName', u'US'),), (('stateOrProvinceName', u'California'),), (('localityName', u'San Francisco'),), (('organizationName', u'Slack Technologies, Inc'),), (('commonName', u'.slack.com'),)), 'issuer': ((('countryName', u'US'),), (('organizationName', u'GeoTrust Inc.'),), (('commonName', u'GeoTrust SSL CA - G3'),))}
Calling slack.files.upload('File 1.txt')
will work, but slack.files.upload('File โ.txt')
gives the following error:
slacker.Error: no_file_data
I'm using Python 3
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>
It is new method provided for creating new RTM connection
slack.files.upload('rtmbot.conf')
This does not work for me.
I get slacker.Error: user_is_bot
There is a new addition to the channels.list method which excludes the members of each channel, this is for faster return times on this methods for larger teams.
Hi!
Your setup.py
contains trove classifiers, but they aren't showing up on slacker's PyPI page for some reason:
https://pypi.python.org/pypi/slacker/0.9.29
I don't know why not, maybe it's as simple as that fact that your classifiers are in a tuple and not a list?
The classifiers not showing means that tools like caniusepython3
list slacker as "not supporting Python 3" when the code, and travis configuration, suggests that it does.
Is it possible to invite/deactivate users via slacker / slack api?
Also unfortunately i haven't seen anything regarding that.
Under: https://api.slack.com/methods there is also no mention of the user on/offboarding procedure.
thx.
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?
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
Hey I didn't see anyway to post a snippet to a group, can this feature be added in?
Thanks!
When I try to call slack.files.upload('test.jpg') I'm getting this error:
File "/usr/local/lib/python3.2/dist-packages/slacker/__init__.py", line 338, in upload
with open(unicode(file_, 'utf-8'), 'rb') as f:
NameError: global name 'unicode' is not defined
Using python 3.2.3 on a RaspberryPi running Raspbian OS (Debian)
I'm trying to upload a local txt file to a channel
slack.files.upload('blah.txt', channels='channelname'')
am I doing something wrong here.
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?
I am trying to post the following via slacker
:
attachment = {
"attachments": [
{
"fallback": "Fallback text",
"title": "Title",
"fields": [
{
"value": "*some field data*",
"short": True
},
{
"value": "*some more data*",
"short": True
}
],
"mrkdwn_in": ["fields"],
"color": "good"
}
]
}
slacker.chat.post_message(
SLACK_CHANNEL,
"Testing Attachments",
SLACK_USER,
attachments=attachment,
icon_url=SLACK_ICON_URL
)
Where I have set the constants to my settings, but you should be able to test this yourself.
Note, if I use json.dumps(attachment)
, the result is:
Which contains empty attachments.
When trying to upload an empty file (ex: error logs... in lucky cases), i'm getting error:
File "/var/www/venv/local/lib/python2.7/site-packages/slacker/__init__.py", line 427, in upload
files={'file': f})
File "/var/www/venv/local/lib/python2.7/site-packages/slacker/__init__.py", line 70, in post
return self._request(requests.post, api, **kwargs)
File "/var/www/venv/local/lib/python2.7/site-packages/slacker/__init__.py", line 62, in _request
raise Error(response.error)
Error: no_file
Just tried to put a symbol in file and error disappeared.
Thank you.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.