美文网首页繁星集
python实现简单的微信公众号后台编写

python实现简单的微信公众号后台编写

作者: 鱿鱼炸酱面 | 来源:发表于2019-05-19 14:06 被阅读0次

利用python的werobot库实现对微信公众号后台的开发:

实现的简单功能:

1.订阅后的回复
2.机器人聊天回复
3.指定关键字回复音乐,文字,链接
3.图片返回原图

注意点:

1.该后台基于微信官方提供的接口实现,需要先完成微信公众服务平台的注册和相关配置。
2.后台代码架设的服务器ip信息需要填写到微信公众服务平台,且端口只能是指定的80(http)或者443(https).

代码:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import random
import time

import requests
import werobot
from werobot.replies import ArticlesReply, Article, ImageReply

robot = werobot.WeRoBot(token='******')


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


# 关键字 博客 回复
@robot.filter('博客')
def blog(message):
    reply = ArticlesReply(message=message)
    article = Article(
        title="忧郁的炸酱面",
        description="我的个人博客",
        img="https://werobot.readthedocs.io/zh_CN/latest/_static/qq.png",
        url="https://www.jianshu.com/u/3c58aa6164de"
    )
    reply.add_article(article)
    return reply


# 关键字 歌曲源 回复
@robot.filter('歌曲源')
def music_source():
    return "http://59.110.26.62:8888/"


# 用户发送图片
@robot.image
def blog(message, session):
    chang_du = str(len(session))
    session[chang_du] = message.MediaId
    reply = ImageReply(message=message, media_id=message.MediaId)
    return reply


# 随机一首音乐
def music_data():
    music_list = [
        ['童话镇', '陈一发儿', 'https://e.coka.la/wlae62.mp3', 'https://e.coka.la/wlae62.mp3'],
        ['都选C', '缝纫机乐队', 'https://files.catbox.moe/duefwe.mp3', 'https://files.catbox.moe/duefwe.mp3'],
        ['花海', '周杰伦', 'http://59.110.26.62:8888/%E5%91%A8%E6%9D%B0%E4%BC%A6-%E8%8A%B1%E6%B5%B7.mp3',
         'http://59.110.26.62:8888/%E5%91%A8%E6%9D%B0%E4%BC%A6-%E8%8A%B1%E6%B5%B7.mp3'],
        ['精彩才刚刚开始', '易烊千玺', 'https://e.coka.la/PdqQMY.mp3', 'https://e.coka.la/PdqQMY.mp3']
    ]
    num = random.randint(0, 2)
    return music_list[num]


# 匹配 音乐 回复一首歌
@robot.filter('音乐')
@robot.filter('歌曲')
def music():
    return music_data()


# 调用智能回复接口
def get_response(msg: str):
    api_url = 'http://www.tuling123.com/openapi/api'
    data = {
        'key': '43826fe7f1e74add804dd47cf2791228',  # Tuling Key,API的值
        'info': msg,  # 发出去的消息
        'userid': '441670',  # 用户名
    }
    res = requests.post(api_url, data=data).json()  # post请求
    if res.get('code') == 40004:
        return msg.strip("吗??") + "!"
    return res.get('text')


# 文字智能回复
@robot.text
def replay(msg):
    cur_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
    response = get_response(msg.content)
    print(cur_time + '  公众号(机器人)' + ':' + response)
    return response


# 让服务器监听在 0.0.0.0:80
robot.config['HOST'] = '0.0.0.0'
robot.config['PORT'] = 80
robot.run()

微信展示的功能如下:

python实现简单的微信公众号后台编写 微信图片_20190519141247.jpg

相关文章

网友评论

    本文标题:python实现简单的微信公众号后台编写

    本文链接:https://www.haomeiwen.com/subject/irxqzqtx.html