Completed
Pull Request — master (#138)
by
unknown
20:13
created

create_reply()   D

Complexity

Conditions 8

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 14
CRAP Score 8.3518
Metric Value
cc 8
dl 0
loc 24
ccs 14
cts 17
cp 0.8235
crap 8.3518
rs 4.3478
1
# -*- coding: utf-8 -*-
2 10
from __future__ import absolute_import, unicode_literals
3 10
import six
4
5 10
from wechatpy import replies
6 10
from wechatpy.fields import IntegerField
7
8
9 10
REPLY_TYPES = {}
10
11
12 10
def register_reply(reply_type):
13 10
    def register(cls):
14 10
        REPLY_TYPES[reply_type] = cls
15 10
        return cls
16 10
    return register
17
18
19 10
@register_reply('text')
20 10
class TextReply(replies.TextReply):
21 10
    agent = IntegerField('AgentID', 0)
22
23
24 10
@register_reply('image')
25 10
class ImageReply(replies.ImageReply):
26 10
    agent = IntegerField('AgentID', 0)
27
28
29 10
@register_reply('voice')
30 10
class VoiceReply(replies.VoiceReply):
31 10
    agent = IntegerField('AgentID', 0)
32
33
34 10
@register_reply('video')
35 10
class VideoReply(replies.VideoReply):
36 10
    agent = IntegerField('AgentID', 0)
37
38
39 10
@register_reply('news')
40 10
class ArticlesReply(replies.ArticlesReply):
41 10
    agent = IntegerField('AgentID', 0)
42
43
44 10
def create_reply(reply, message=None, render=False):
45 10
    r = None
46 10
    if isinstance(reply, replies.BaseReply):
47 10
        r = reply
48 10
        if message:
49
            r.source = message.target
50
            r.target = message.source
51
            r.agent = message.agent
52 10
    elif isinstance(reply, six.string_types):
53 10
        r = TextReply(
54
            message=message,
55
            content=reply
56
        )
57 10
    elif isinstance(reply, (tuple, list)):
58 10
        if len(reply) > 10:
59 10
            raise AttributeError("Can't add more than 10 articles"
60
                                 " in an ArticlesReply")
61 10
        r = ArticlesReply(
62
            message=message,
63
            articles=reply
64
        )
65 10
    if r and render:
66 10
        return r.render()
67
    return r
68