​这次实现公众的基本功能:被关注回复、关键词回复、收到消息回复

Snip20200102_25.png

# 订阅后的回复  
@robot.subscribe  
def subscribe():  
return"\*\*\*欢迎关注公众号\[愉快\]\[愉快\]\[愉快\]\*\*\*\\n" \\  
"\*\*\*输入任意内容开始与我聊天!\\n" \\  
"\*\*\*输入'博客'关注我的博客!\\n" \\  
"\*\*\*输入'音乐'为小主送上舒缓的歌曲!\\n"  
  
  
# 关键字 博客 回复  
@robot.filter('博客')  
def blog(message):  
    reply = ArticlesReply(message=message)  
    article = Article(  
        title="Python数据分析实战",  
        description="我的个人博客",  
        img="https://werobot.readthedocs.io/zh\_CN/latest/\_static/qq.png",  
        url="https://www.jianshu.com/u/bdf11cce83a1"  
    )  
    reply.add\_article(article)  
return reply  
  
  
# 收到消息回复  
@robot.text  
def replay(msg):  
# print(msg.content)  
# curtime = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))  
# response = get\_response(msg.content)  
# print(  
#     curtime + '  公众号(机器人)' + ':' + response)  
# return response  
  
return"该功能有待处理,敬请期待"

@robot.subscribe:

        订阅回复:即当用户订阅公众号时回复的内容

@robot.filter('博客')

         关键字回复:即用户输入关键词时回复的内容

@robot.text

       收到消息回复:当用户回复文字没有命中关键词时回复的内容

已知我们最常用的功能就是关键词回复,但是通过filter这种关键词回复:每添加一个关键词功能,就要添加一个对应的路由。

这种方式会导致我们的关键词路由函数过多,处理起来也不方便。

统一处理关键词回复

我们可以通过收到消息回复,收到用户消息,回复文字内容,

先检测是不是关键词,如果是关键词则回复关键词内容,如果不是则回复对应其他内容。

# 文字智能回复  
@robot.text  
def replay(msg):  
  
# 获取用户输入内容  
    user\_text = msg.content  
  
# 关键词词检测并回复  
    answer\_text = get\_code(user\_text)  
  
# 非关键词回复   
if answer\_text isNone:  
        answer\_text = response\_text(user\_text).text  
  
  
return answer\_text

接收的参数msg并不是用户的直接内容,通过msg.content获取用户输入内容

关键词检测和回复:

worlds\_list = \[  
    {  
"key":\["20191210", "公众号code" \],  
"values":"https://github.com/silencesmile/gzh\_code"  
        },  
    {  
"key": \["wav音频", "wav", "python\_wav"\],  
"values": "https://github.com/silencesmile/python\_wav"  
        },  
    {  
"key":  \["图像识别", "AI", "ai", "人工智能"\],  
"values": "GitHub:https://github.com/silencesmile/TensorFlow-ResNet",  
        },  
    {  
"key": \["pyecharts"\],  
"values": "https://github.com/silencesmile/pyecharts.git"  
        },  
    {  
"key": \["一出好戏"\],  
"values": "https://github.com/silencesmile/movie\_Analyst.git"  
        }  
    \]  
  
\# 关键词检测并回复  
def get\_code(text):  
for key\_worlds in worlds\_list:  
        key\_list = key\_worlds.get("key")  
        values = key\_worlds.get("values")  
  
if text in key\_list:  
return values  
  
returnNone

这样就很好管理关键词的回复了,不需要定义多个关键词路由。

下期预告:

       图片的接收以及如何回复处理后的图片

Snip20191204_47.png


数据分析实战
9 声望3 粉丝