Python微信公众号后台开发教程<002>

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

# 订阅后的回复
@robot.subscribe
def subscribe():
    return "***欢迎关注公众号[愉快][愉快][愉快]***
" 
           "***输入任意内容开始与我聊天!
" 
           "***输入'博客'关注我的博客!
" 
           "***输入'音乐'为小主送上舒缓的歌曲!
"


# 关键字 博客 回复
@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 is None:
        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

    return None

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

下期预告:

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

原文地址:https://www.cnblogs.com/blogs/p/12131314.html