python实现微信自动发拜年信息和回复消息

import itchat, time, requests, json, random, urllib, ssl, string

def get_friends():
    """
    获取微信好友列表
    :return: 返回微信好友列表
    """
    return itchat.get_friends(update=True)

def get_response(msg):
    """
    接入青云客的api,根据好友消息返回一个信息
    :param msg:微信好友传入的消息
    :return: 机器人返回的消息
    """
    api = r'http://api.qingyunke.com/api.php?key=free&appid=0&msg='
    url = urllib.parse.quote(api + msg, safe=string.printable)
    page = urllib.request.urlopen(url)
    html = page.read().decode("utf-8")
    res = json.loads(html)
    if res['result'] == 0:
        return (res['content'])		# 此处返回的数据可以看[青云客api](http://api.qingyunke.com/)
    else:
        return None

"""
此方法接入的是图灵的机器人,二选一即可
def get_response(_info, apiKey):
    """
    接入图灵机器人api,并根据好友信息返回一个信息(可以观看[图灵机器人api](https://www.kancloud.cn/turing/www-tuling123-com/718226))
    :param _info: 微信好友发送过来的消息
    :return: 返回一个json的数据
    """
    api_url = 'http://openapi.tuling123.com/openapi/api/v2'
    data = {
        "reqType": 0,
        "perception": {
            "inputText": {
                "text": _info
            },
            "inputImage": {
                "url": "imageUrl"
            },
            "selfInfo": {  # location 为selfInfo的参数信息,
                "location": {  # 地理位置信息
                    "city": "广州",  # 所在城市,不允许为空
                    "province": "广东省",  # 所在省份,允许为空
                    "street": "从化"  # 所在街道,允许为空
                }
            }
        },
        "userInfo": {
            "apiKey": "bc53de6aa872494dbceb1e3e0623b43b",		# 此处为图灵机器人的apikey
            "userId": "wechat"
        }
    }
    try:
        response = requests.post(api_url, data=json.dumps(data)).json()
        return response['results'][0]['values']['text']
    except:
        return None
"""

def send_news():
    """
    根据微信好友发送新年祝福
    :return:
    """
    for item in get_friends():
        time.sleep(10)	# 每一次发信息停顿10秒
        itchat.send('新年快乐!祝'+item['NickName']+"在新的一年里身体健康,每天有个好心情!", toUserName=item['UserName'])


@itchat.msg_register(itchat.content.TEXT)用于接收来自朋友间的对话消息,如果不用这个,朋友发的消息便不会自动回复
@itchat.msg_register(itchat.content.TEXT)
def start_replying(msg):
    """
    用户自动发送从机器人哪里返回的数据
    :param msg: 朋友的信息
    :return:
    """
    return get_response(msg['Text'])


def login():
    """
    微信账号登录
    :return:
    """
    itchat.auto_login(hotReload=True)
    send_news()
    itchat.run()

if __name__ == "__main__":
    login()
发布了32 篇原创文章 · 获赞 7 · 访问量 7755

猜你喜欢

转载自blog.csdn.net/adim__/article/details/104078054
今日推荐