Coder Social home page Coder Social logo

slacksocket's Introduction

Slacksocket

Documentation Status PyPI version

Python interface to the Slack Real Time Messaging(RTM) API

Install

note: v1.x only supports Python3 at this time is not backward compatible with earlier library versions

pip install slacksocket

Usage

Example

Example usage for a simple time bot:

from datetime import datetime
from slacksocket import SlackSocket

s = SlackSocket('<slack-token>')

while True:
    event = s.get_event('message') # filter only for events of type 'message'
    if not event.mentions_me: # doesn't mention our bot, ignore
        continue
    if 'what time is it' in event.get('text'):
        text = f'@{event.user} it is currently {datetime.now()}'
        s.send_msg(text, event.channel) # respond back to origin channel

Retrieving events/messages

from slacksocket import SlackSocket

s = SlackSocket('<slack-token>')

# get a single event
e = s.get_event()

# get all events
for event in s.events():
    print(event.json)

# or filter events based on type 
for event in s.events('message', 'user_typing'):
    print(event.json)

Sending messages

from slacksocket import SlackSocket

s = SlackSocket('<slack-token>')
channel = s.lookup_channel('channel-name')

msg = s.send_msg('Hello there', channel)
print(msg.sent)
True

Documentation

Full documentation is available on ReadTheDocs

slacksocket's People

Contributors

andrew-boutin avatar bcicen avatar bob2build avatar graywizardx avatar hfwang avatar kevinschoon 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

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

slacksocket's Issues

Improve potential silent infinite loop

Recently ran into an infinite loop here:

# wait for websocket connection to be established before returning
while not self.connected:
time.sleep(.2)

There's no way to set a timeout value and there is no logging to indicate what is happening. Can some logging be added and/or a configurable timeout? The default could be no timeout so the existing functionality doesn't change.

Thank you.

SlackSocket('token') never finishes

Hi.
I've been trying to find decent RTM implementations for slack, but all I find are dead or don't work so I hope this one still receives some support.
What could be the reason for s = SlackSocket('token') to never finish and continue on with the rest of the code? There's a print above and below but only the one above is executed. It's just stuck there the entire time.
Running Python3.7 with a xoxb token and correct permissions

Further translation of @mentions in slack chat

Although the slack socket does a good job of translating channel id's and user names to readable names, there remains the case where someone is mentioned in a chat using the @ mention.

For example, when I type
"What's up @some_user", I get back "What is up <@U0KL7823M>"

TypeError: expected a character buffer object

I'm running into this repeatedly when I use mentions with a little slack bot I'm building with SlackSocket (great module btw! :-)

Not sure if I'm doing something weird, but I was easily able to "fix" it on my machine by changing the line 42 of models.py, so that SlackEvent._get_mentions converts each mention to unicode instead of str before calling .translate.

Here's the full stack trace with debugging logging enabled:

ERROR:root:error from callback <bound method SlackSocket._event_handler of <slacksocket.client.SlackSocket object at 0x10acc5c50>>: expected a character buffer object
  File "/Users/ses/w/pivo/venv/lib/python2.7/site-packages/websocket/_app.py", line 243, in _callback
    callback(self, *args)
  File "/Users/ses/w/pivo/venv/lib/python2.7/site-packages/slacksocket/client.py", line 367, in _event_handler
    event = SlackEvent(json_object)
  File "/Users/ses/w/pivo/venv/lib/python2.7/site-packages/slacksocket/models.py", line 31, in __init__
    self.mentions = self._get_mentions(self.event['text'])
  File "/Users/ses/w/pivo/venv/lib/python2.7/site-packages/slacksocket/models.py", line 42, in _get_mentions
    return [str(m).translate(translate_map) for m in mentions]

Since I'm not sure if this is somehow my fault I decided to make this issue and not a PR :-)

lib version is 0.6.3
operating system: OS X 10.11
python version:

$ venv/bin/python --version
Python 2.7.10

Cannot import name

Error

Traceback (most recent call last):
  File "slacksocket.py", line 1, in <module>
    from slacksocket import SlackSocket
  File "/slacksocket.py", line 1, in <module>
    from slacksocket import SlackSocket
ImportError: cannot import name 'SlackSocket'

fixed. shame on me :) it was because of the file name

Send_msg KeyError

I know it just got uploaded two second ago, but wanted to let you know when trying to .send_msg I'm getting a key error on line 123 of client.py
msg.ts = e.event['ts']

migration_in_progress error event

There appears to be no way to currently handle this event in the stream, and will break a connection.

line 42 of client.py will return this very sparsely and break the code when it occurs:

SlackSocketAPIError: Error from slack api:
 {"ok":false,"error":"migration_in_progress"}

perhaps we can add in a try/catch time delay retry? Please advise.

Reraise KeyboardInterrupt

I'm using slacksocket to write another library.

I'm having a very difficult time gracefully shutting my application down when a user types in CTRL + C when my app is blocked on slacksocket's events method and the KeyboardInterrupt is caught and not re raised.

No human readable userIDs or ChannelIDs?

I'm a beginner python developer, and this library is an awesome resource both for my learning as well as for a project i had in mind, so thanks! my issue is that I've set Translate = True, when calling SlackSocket, however I'm still not getting the human readable ids: My code is as follows:

import slacksocket

flow = slacksocket.Slacksocket('my-slack-token',translate=True,event_filters=['message'])

for events in flow.events():
   with open('slacklog', 'a') as log:
       log.write('\n')
       log.write(event.json)

but the slacklog file still shows the non-translated channel and user IDS, viz.

{"type":"message","channel":"C0FUABZMF","user":"U0FU80W0K","text":"testing messages with event filters on","ts":"1449320459.000022","team":"T0FU5BBA8"}

any idea what i'm missing?

Dependency update breaks functionality change version pin

requirements.txt has websocket-client>=0.35.0. It looks like version 0.49.0 breaks functionality. Using version 0.48.0 works though.

Can this dependency get changed to websocket-client>=0.35.0,<=0.48.0 at least until either websocket-client fixes backwards compatibility or this library is updated to handle the changes?

Example doesn't seem to work

I used this example:

from slacksocket import SlackSocket

token = 'my_token_here'

socket = SlackSocket(token)
msg = socket.send_msg('hi', channel_name='general')
print(msg.sent)

I received an error:

Traceback (most recent call last):
  File "tmp.py", line 6, in <module>
    msg = socket.send_msg('hi', channel_name='general')
  File "/Users/.../venv3/lib/python3.5/site-packages/slacksocket/client.py", line 141, in send_msg
    self.ws.send(msg.json)
AttributeError: 'SlackSocket' object has no attribute 'ws'    

[Enhancement]: Make SlackSocket a context

Currently SlackSocket can only be used as defined within the top level examples. Providing SlackSocket as a context would enhance usability. This is a common use-case for any type of stream or pipe or socket.

New Use case:

with SlackSocket(token) as socket:
    if not socket.send_msg(msg, channel_name).sent:
        print('Error message not sent: "{msg}"', file=sys.stderr)

Additions:

def __enter__(self):
    # web socket connection logic here
    return self

def __exit__(self, exc_type, exc_value, exc_traceback):
    # handle web socket disconnection here

SlackSocket throws exception when bot joins an newly invited channel

The following code snippet connects the bot with the slack token 'XXXXX' to slack server.

#!/usr/bin/env python

slack_token = "XXXXXXX"
import logging
import sys, os
myPath = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, myPath + '/../')

from slacksocket import SlackSocket

logging.basicConfig(level='DEBUG')

slacksocket = SlackSocket(slack_token, event_filters=['message'])
me = slacksocket.user
print('Connected to Slack as %s' % me)

for event in slacksocket.events():
    if me in event.mentions:
        print(event)

When this bot is invited to join a channel which it was not part of previously, It would get channel_joined event. During which, I get the following exception

ERROR:websocket:error from callback <bound method SlackSocket._event_handler of <slacksocket.client.SlackSocket object at 0x7f100cf9c2e8>>: 'NoneType' object is not iterable
  File "/home/bob/.pyenv/versions/3.5.2/lib/python3.5/site-packages/websocket/_app.py", line 256, in _callback
    callback(self, *args)
  File "/home/bob/.pyenv/versions/3.5.2/lib/python3.5/site-packages/slacksocket/client.py", line 364, in _event_handler
    event = self._translate_event(event)
  File "/home/bob/.pyenv/versions/3.5.2/lib/python3.5/site-packages/slacksocket/client.py", line 339, in _translate_event
    c = self._lookup_channel_by_id(event.event['channel'])
  File "/home/bob/.pyenv/versions/3.5.2/lib/python3.5/site-packages/slacksocket/client.py", line 241, in _lookup_channel_by_id
    id)

I have found the error and fixed it, Will submit a pull request shortly

daemonize client

Issue: Threading - KB interrupt during threaded event handling will kill event thread but is unbound to main event thread.

Desc: The main thread needs to be daemonized to be aware of it's children during locks to have effective threading (and exception handling).

Please add:
self.thread.daemon = True
between lines 81 and 82 in client.py:
https://github.com/bcicen/slacksocket/blob/master/slacksocket/client.py

    self._thread = Thread(target=self._open)
    self._thread.daemon = True
    self._thread.start()

Thank you! :)

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.