scrapinghub / slackbot

A chat bot for Slack (https://slack.com).
MIT License
1.26k stars 395 forks source link

Add ability to check user that sent a message when using `@respond_to` #83

Open kinghajj opened 8 years ago

kinghajj commented 8 years ago

I'd like to add conditional logic depending upon who sent a message--for example, to ensure that only the QA engineer can deploy to the QA environment. There doesn't seem to by any way currently to determine this in a handler.

slowbluecamera commented 8 years ago

I have pretty much the same use case, so dug into the message class (in slackclient.py). So not only does the message contain helpful "body" elements, it has a reference to the already-connected slacker client which is pretty handy. So this:

@respond_to(r'Who\?$', re.IGNORECASE)
def who(message):
    message.reply('I am friendly bot.')
    details = ""
    details += "text = '{}'\n".format(message.body["text"])
    details += "ts = '{}'\n".format(message.body["ts"])
    details += "user id = '{}'\n".format(message.body["user"])
    details += "user name = '{}'\n".format(message._client.users.get(message.body["user"])["name"])
    details += "team id = '{}'\n".format(message.body["team"])
    details += "type = '{}'\n".format(message.body["type"])
    details += "channel = '{}'\n".format(message.body["channel"])
    message.reply('```{}```'.format(details))

Will give you this:

screenshot 2016-05-18 09 42 04

Now keep in mind that the underscore in the "_client" usually signals that you are messing around under the hood. So you risk having this break in future releases. But since slackbot is built on top of slacker, I'd be surprised if you couldn't access the client object somehow.

Hope this helps. Thanks for giving me a reason to figure this out for myself this morning!