如何使用没有频道的松散机器人向几个人发送消息?

时间:2018-01-11 15:20:57

标签: python bots slack-api

我使用python slackclient在Tutorial1Tutorial2之后一直在研究一个松散的机器人。我需要创建一个机器人,可以同时与几个人聊天,但是在私人聊天中,而不是在群组频道中。我已经尝试多次运行机器人代码来更改频道并且它可以工作,但我想在同一个脚本中完成所有操作。 这是我的代码:

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 个答案:

答案 0 :(得分:0)

与用户私下交谈的最简单方法是使用用户ID作为chat.postMessage中的频道发送直接消息。然后,该消息将显示在该用户的私人slackbot频道中。

或者,您也可以在专用应用渠道中为用户发送消息。有关其工作原理,请参阅this answer