2016-11-03 198 views
3

我試圖通過它們的API將附件添加到鬆散消息。我使用他們推薦的python包裝。我可以發送和接收基本消息,但是當我嘗試以2個按鈕的形式添加附件時,它會失敗。我做了一個懶散的應用程序,並將它們連接到他們的API中。我仔細審查了API,無法弄清楚發生了什麼。將附件添加到Slackbot

def process_message(message, channel): 
    intro_msg = json.loads('{ 
         "text": "What would you like to do?", 
         "attachments": [ 
         { 
          "text": "Choose an action", 
          "fallback": "You are unable to choose an option", 
          "callback_id": "lunch_intro", 
          "color": "#3AA3E3", 
          "attachment_type": "default", 
          "actions": [ 
          { 
           "name": "enroll", 
           "text": "Enroll", 
           "type": "button", 
           "value": "enroll" 
          }, 
          { 
           "name": "leave", 
           "text": "Leave", 
           "type": "button", 
           "value": "leave" 
          } 
          ] 
         } 
         ] 
        }') 
    r = sc.api_call("chat.postMessage", channel=channel, attachments=intro_msg) 

的響應是唯一{u'ok': False, u'error': u'no_text'}

+0

你可以告訴我,當你直接傳遞字典對象時,你看到了什麼,而不是使用'dict'對象創建'intro_msg'。 –

回答

1

我想基本的簡單的例子工程。

實施例:

from slackclient import SlackClient 

slack_token = os.environ["SLACK_API_TOKEN"] 
sc = SlackClient(slack_token) 

sc.api_call(
    "chat.postMessage", 
    channel="#python", 
    text="Hello from Python! :tada:" 
) 

根據https://api.slack.com/methods/chat.postMessagehttps://api.slack.com/docs/message-buttons#readying_your_application_for_message_buttons附件必須是一個數組。如何發送它作爲數組:

json.loads('[{"text":"What would you like to do?","attachments":[{"text":"Choose an action","fallback":"You are unable to choose an option","callback_id":"lunch_intro","color":"#3AA3E3","attachment_type":"default","actions":[{"name":"enroll","text":"Enroll","type":"button","value":"enroll"},{"name":"leave","text":"Leave","type":"button","value":"leave"}]}]}]') 

由於不涉及進一步的魔術,而是請求模塊https://github.com/slackapi/python-slackclient/blob/ddf9d8f5803040f0397d68439d3217d1e1340d0a/slackclient/_slackrequest.py我給它與發送的數組一試。

4

我想通了。

python wrapper分離出有效載荷。

intro_msg = json.dumps([{"text":"Choose an action","fallback":"You are unable to choose an option","callback_id":"lunch_intro","color":"#3AA3E3","attachment_type":"default","actions":[{"name":"enroll","text":"Enroll","type":"button","value":"enroll"},{"name":"leave","text":"Leave","type":"button","value":"leave"}]}]) 

sc.api_call("chat.postMessage", channel=channel, text="What would you like to do?", attachments=intro_msg, as_user=True) 

我的有效載荷是所有的附件,因爲這是他們如何在他們的API文檔格式化。附件只需要附件密鑰後面的數組。