1

I've been working on a slack bot following Tutorial1 and Tutorial2 using python slackclient. I need to create a bot that can chat with several people a the same time but in a private chat, not in a groupal channel. I've tried running the bot's code several times changing the channel and it works, but I want to do it all in the same script. Here is my code:

from slackclient import SlackClient
Token = 'xoxb-xxxxxxxxxxx.....'
usr= 'XXXXXXXX'
chat = 'XXXXXXXX'
sc = SlackClient(Token)

# c is just to exit the loop
c=0
# Initialize the bot and send a message
sc.api_call('chat.postMessage', as_user='true:', channel=chat, text='Bot is working, if you want me to sleep, just send the message \"end\"')
while c<1:
    # Get the whole conversation
    hist = sc.api_call('im.history', channel=chat)
    m=hist.get('messages')

    # Get the last message
    last_message = m[0]

    # Find who sent it
    who = last_message.get('user')

    # If the user sent the message, then find a keyword and reply something
    if who==usr:
        answer=last_message.get('text')
        if 'hi' in answer:
            sc.api_call('chat.postMessage', as_user='true:', channel=chat, text='Hello!:smiley: can I help you?')
        elif 'no' in answer:
            sc.api_call('chat.postMessage', as_user='true:', channel=chat, text='Ok, let me know if you need something')
        elif 'yes' in answer:
            sc.api_call('chat.postMessage', as_user='true:', channel=chat, text='What can I do for you?')
        elif 'end' in answer:
        c=2

1 Answers1

0

The easiest way to talk privately with a user is to send a direct message by using the user ID as channel in chat.postMessage. The message will then appear in the private slackbot channel of that user.

Alternatively you can also send messages in your dedicated app channel for a user. See this answer for how it works.

Erik Kalkoken
  • 30,467
  • 8
  • 79
  • 114
  • the `chat.postMessage` is working only when the input holds only 1 recipient (e.g. @FirstName.LastName) How can the slackbot send it to multiple users at once ? – shayms8 Jan 07 '20 at 08:18
  • Please open a new question for your topic. TY – Erik Kalkoken Jan 07 '20 at 16:20
  • 1
    Actually, this has already been answered here: https://stackoverflow.com/questions/47917744/using-the-slack-api-how-can-i-direct-message-all-users-at-the-same-time – Erik Kalkoken Jan 07 '20 at 16:27