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?
7 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

- 996
- 13
- 20
-
can you give some more detail ? – Vikas Saini Jan 18 '16 at 17:06
-
Use the same python code you used for sending messages to channel. The API also remains the same. The only change is instead of "channel" mention the "user" (whom you want to send the message). I have given the code above which works for me. Try it once and if it does not work share the actual error or problem you are facing. – Deepali Mittal Jan 19 '16 at 04:50
-
when i am using this,it say error "'SlackClient' object has no attribute 'chat'" – Vikas Saini Jan 19 '16 at 12:07
-
Have you installed the slack module ? If not, please use this .. " pip install slacker " and " pip install pyslack " – Deepali Mittal Jan 20 '16 at 04:05
-
2From Slack docs: We are phasing out support for ambiguously passing a "username" as a channel value. Please always use channel-like IDs instead. – Ufuk Hacıoğulları Dec 10 '17 at 02:31
-
1What @UfukHacıoğulları said, seems to be correct. Docs state that, and API will return `channel_not_found` on a `chat.postMessage`-call. – Jari Turkia Feb 20 '18 at 08:27
-
Wonder why they made this much harder to do. Does anyone have an example of using the im.list to try and get the channel to send to the @user ? – Drew Feb 21 '18 at 20:49
-
`slack` is not know by python by default. – Soerendip Jun 23 '19 at 17:06
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:

- 1,591
- 15
- 20
-
You can replace your "User ID" with the literal username string "@slackname" (that you would normally use in slack chat) ... that works too – Scott Oct 29 '19 at 17:07
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"
)

- 998
- 2
- 12
- 17
-
2The only thing with this is it doesn't show up in a direct message per-say with the user, but rather in the user's SlackBot channel (if using a bot) – Elliptica Aug 27 '18 at 19:21
You can get a list of user IM channels and post your message to any IM channel (Direct messaging).
from slackclient import SlackClient
SLACK_TOKEN = "xoxb-bottoken" # or a TEST token. Get one from https://api.slack.com/docs/oauth-test-tokens
slack_client = SlackClient(SLACK_TOKEN)
api_call = slack_client.api_call("im.list")
# You should either know the user_slack_id to send a direct msg to the user
user_slack_id = "USLACKBOT"
if api_call.get('ok'):
for im in api_call.get("ims"):
if im.get("user") == user_slack_id:
im_channel = im.get("id")
slack_client.api_call("chat.postMessage", channel=im_channel,
text="Hi Buddy", as_user=True)

- 1,252
- 2
- 13
- 28
-
Nothing against you or your code, but this is so ugly. If all we have is the user's name, we need to first do a lookup for the user_id then another im.list to find the channel? Three API calls to send a message to a user? – Drew Feb 21 '18 at 20:51
As Deepali said, just pass @user into the channel parameter. You could also use the Slack postMessage endpoint API on RapidAPI here. This page will allow you to generate the code needed to make the API call in python and test out the API call.
The code RapidAPI will generate for you will look like this:
from rapidconnect import RapidConnect
rapid = RapidConnect("SlackIntegration", "3b744317-91c6-48e8-bc90-305a52f36a5f")
result = rapid.call('Slack', 'postMessage', {
'token': '',
'channel': '',
'text': '',
'parse': '',
'linkNames': '',
'attachments': '',
'unfurlLinks': '',
'unfurlMedia': '',
'username': '',
'asUser': '',
'iconUrl': '',
'iconEmoji': ''
})

- 69
- 3
I based my example off of this tutorial: build-first-slack-bot-python
With that I was able to resolve the issue simply by calling:
userChannel = slack_client.api_call(
"im.open",
user=auser
)
then sending the message
slack_client.api_call(
"chat.postMessage",
channel=userChannel['channel']['id'],
text=response or default_response,
as_user=True
)
After that everything seemed to work as expected. I'd like to create something similar to the "/gifs" interface in the future.

- 833
- 10
- 15
Solutions above already have solved the problem! For those who want to learn to set up the entire workflow (Slack App + Python) to send messages individually via Slack chat, I wrote some step-by-step instructions here - https://github.com/solomonvimal/GlobalShapersLosAngeles/blob/main/Slack_Bday_Nudge.py

- 920
- 12
- 27