Terms Of Use

Privacy Policy

Featured snippets are MIT license

Gears & Masters

DevOpsnipp.com © 2020

medium.png

Slack Bot

Create Python app for handling messages and actions of your Slack bot.

11

Votes

First of all - please create a bot in Slack website and store the bot ID & token
https://get.slack.help/hc/en-us/articles/115005265703-Create-a-bot-for-your-workspace

from slackclient import SlackClient
import logging
import time

def handle_command(message,channel,sender):

Here your can make anything you want about the message, channel and sender value.

#Send response 
slack_client.api_call("chat.postMessage", channel=channel,text=response, as_user=True)


if __name__ == "__main__":
    BOT_ID = [YOUR_BOT_TOKEN]
    SLACK_BOT_TOKEN = [YOUR_BOT_TOKEN]
    BOT = "<@" + BOT_ID + ">"
    slack_client = SlackClient(SLACK_BOT_TOKEN)
    logging.basicConfig(filename='/var/log/bot.log',level=logging.INFO,format='%(asctime)s - %(lineno)s - %(levelname)s - %(message)s')
    lastSender=''
    READ_WEBSOCKET_DELAY = 1
    if slack_client.rtm_connect():
        print("StartApper connected and running!")
        while True:
            message, channel = parse_slack_output(slack_client.rtm_read())
            if message and channel:
                rtm_data = (slack_client.rtm_read())
                sender = str(rtm_data[0]['subtitle'])
                handle_command(message, channel, sender)
            time.sleep(READ_WEBSOCKET_DELAY)
    else:
        print("Connection failed. Invalid Slack token or bot ID?")

Vote Here

You must earn at least 1 vote on your snippets to be allowed to vote