简体   繁体   中英

Python Slack Bot won't post in direct messages

I've written a Slack Bot in Python and it works as designed when I use a slash command in a chat channel, but when I try to interact with the bot in a direct message with another user, the response is never shown. However, when I look at the app logs, I still receive a POST from Slack, so my app is receiving the response and sends a response back.

I have the following permissions enabled:

  • Send messages as [MyBotName]
  • Send messages as user
  • Post to specific channels in Slack
  • Add a bot user with the username @mybotname
  • Add slash commands and add actions to messages (and view related content)
  • View some URLs in messages
  • Add link previews to messages

In my code, I make the following api_call:

slack_client.api_call(
        "chat.postMessage",
        channel=[channelId],
        attachments=[],
        unfurl_links=True,
        unfurl_media=True,
        as_user=True
    )

Logging shows that I do receive the right ChannelId no matter if it's a channel or direct message.

My question is: am I missing a permission or command in my slack_client.api_call?

Your approach wont't work for direct channels and frankly also not for some private channel.

The reason is one of Slack's fundamental security features: Your bot user or the owner of your app token (eg the app installer) needs to be a member of a direct or private channel in order for your app/bot to have access to that channel, eg be able to send messages to it. No permission setting or scope can change that.

There is an easy fix for your specific situation though: Instead of sending a message via API just reply directly to the slash command request from Slack. That will work for any channel including direct and private channels.

The reply works similar to message posting via API and you can use either plain text or JSON. See Respond to Commands in the official documentation for the syntax.

Here an example for a complete message with attachment. Note that you need to set the content header to JSON:

{
    "text": "It's 80 degrees right now.",
    "attachments": [
        {
            "text":"Partly cloudy today and tomorrow"
        }
    ]
}

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