Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we send message to user in slack using python script?

In a slack team, can we send a message to a user using python? I have seen various APIs, they offer message to channel, but not to a particular user. Can we do that?

like image 593
Vikas Saini Avatar asked Jan 18 '16 10:01

Vikas Saini


People also ask

How do I send messages in Slack with Python?

import os from slack import WebClient client = WebClient(token=os. environ['SLACK_API_TOKEN']) response = client. api_call( api_method='chat. postMessage', json={'channel': '#random','text': "Hello world!"} ) assert response["message"]["text"] == "Hello world!"

How do I post a message to a Slack channel in Python?

Click on Apps + icon and search for incoming webhook, click on Add. From the app directory page, add Incoming Webhooks to slack. Once added, on the next page you'll have to provide a new configuration. Select the channel from dropdown where you wish to push the notification or click on create a new channel.

Can Slack bot send direct message to user?

You may see Slackbot in channels throughout your workspace, delivering reminders and automated messages for you and your teammates. When there's a reminder or a message just for you, Slackbot will send you a DM. You can access your DM with Slackbot the same way you would find a DM with anyone else in your workspace.


3 Answers

Yes,this can be done. Instead of "#channel_name" use "@user" in the API. The user will receive the message from slackbot as we are using API and not a direct message from any other user. And if you want to post to that user as the authenticated user, use as_user= true.

slack.chat.post_message('@to_user',msg,username='@from_user')

More details are at https://api.slack.com/methods/chat.postMessage

like image 161
Deepali Mittal Avatar answered Sep 30 '22 02:09

Deepali Mittal


SImple solution is using Slack's Web API and requests:

import requests

# slack access bot token
slack_token = "xpxb-9534042403-731932630054-KSwhrmhg87TXGuF23Z4ipTRm"

data = {
    'token': slack_token,
    'channel': 'UJ24R2MPE',    # User ID. 
    'as_user': True,
    'text': "GO Home!"
}

requests.post(url='https://slack.com/api/chat.postMessage',
              data=data)

userID you can get here:

enter image description here

like image 38
Andrey Topoleov Avatar answered Sep 30 '22 03:09

Andrey Topoleov


This was the Python solution I found using the SlackClient package:

from slackclient import SlackClient

slack_token = os.environ["SLACK_API_TOKEN"]
sc = SlackClient(slack_token)

sc.api_call(
  "chat.postMessage",
  channel="@username",
  text="Test Message"
)

https://pypi.python.org/pypi/slackclient

like image 9
running-codebase Avatar answered Sep 30 '22 01:09

running-codebase