简体   繁体   中英

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?

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

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:

在此处输入图像描述

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

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)

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': ''

    })

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM