Return JSON objects 使用 Django REST 从 Slack 检索

Return JSON objects retrieved from Slack with Django REST

我用 Slack 设置了一个 Django REST API,这样我就可以编写一个支持机器人。它工作正常,因为我可以编写新消息和响应。但是,我也希望能够 return JSON object 我从 Slack 检索到的。

这是我的 views.py

class Events(APIView):
    def post(self, request, *args, **kwargs):
        slack_message = request.data

        #verify token
        if slack_message.get('token') != SLACK_VERIFICATION_TOKEN:
            return Response(status=status.HTTP_403_FORBIDDEN)

        #checking for url verification
        if slack_message.get('type') == 'url_verification':
            return Response(data=slack_message, status=status.HTTP_200_OK)

        #send a greeting to the bot
        if 'event' in slack_message:
            #process message if event data is contained in it
            event_message = slack_message.get('event')

            #ignore bot's own message
            if event_message.get('subtype') == 'bot_message':
                return Response(status=status.HTTP_200_OK)

            #handle the message by parsing the JSON data
            user = event_message.get('user')
            text = event_message.get('text')
            channel = event_message.get('channel')
            bot_text = 'Hi <@{}> :wave:'.format(user)

            #finally use the slack api to post the message with chat.postMessage
            if 'hello' in text.lower():
                Client.api_call(method='chat.postMessage',
                    channel=channel,
                    text=bot_text)
                return Response(status=status.HTTP_200_OK)


        return Response(status=status.HTTP_200_OK)

所以这很好用,我正在使用 ngrok 连接到 Slack API。现在我想 return 频道中的会议列表,我用 conversations.history:

class ConversationArchive(APIView):
    def save_conversation(self, request):

        conversation_history = Client.api_call(method='conversations.history',
            token='xxx',
            channel='xxx')

        return conversation_history

现在,当我在浏览器中查看对话视图时,它会显示

HTTP 200 OK
Allow: OPTIONS
Content-Type: application/json
Vary: Accept

{
    "name": "Conversation Archive",
    "description": "",
    "renders": [
        "application/json",
        "text/html"
    ],
    "parses": [
        "application/json",
        "application/x-www-form-urlencoded",
        "multipart/form-data"
    ]
}

这不是对话列表,我知道我在 Slack API 上的方法调用是正确的,因为我已经在 Events 视图中通过告诉机器人发送 [= =19=]在聊天中,简陋但有效。那么我如何 return this a JSON object 使用框架呢?我需要创建和序列化模型吗?

如果您使用的是 Django 1.7+,并且 conversation_history 是一个 JSON 可序列化对象,那么只需将其作为 APIView 中的 JsonResponse 提供即可:

from django.http import JsonResponse

class ConversationArchive(APIView):
    def save_conversation(self, request):
        conversation_history = Client.api_call(method='conversations.history',
        token='xxx',
        channel='xxx')

        return JsonResponse(conversation_history)