python微信机器人

本项目是用pycharm打开,因为会弹出二维码扫描框,如果是在linux命令行操作,需要修改源码

linux命令行启用参考

准备工作
pip install itchat 
pip install apscheduler

代码
#!/usr/bin/env python
# coding:utf8
# ++++++++++++description++++++++++++#
"""
@author:ying
@contact:1074020480@qq.com
@site:
@software: PyCharm
@file: wx.py
@time: 2019/8/7 下午4:43
"""
# +++++++++++++++++++++++++++++++++++#
# -*- coding:utf-8 -*-

from apscheduler.schedulers.blocking import BlockingScheduler
import itchat
from datetime import datetime
from itchat.content import *

time_now = datetime.now().strftime('%Y-%m-%d %X')

#自定义类MyChatYing
class MyChatYing(object):
    """
    :param msg:发送的信息
    :param roomname:群名称
    :param friendname:好友名称
    """

    def __init__(self, msg=None, roomname=None, friendname=None):
        #初始化参数
        self.msg = msg
        self.roomname = roomname
        self.friendname = friendname

    def get_friends(self):
        # 获取所有好友信息
        my_friend = itchat.get_friends(update=True)
        # print('所有的好友---------->', my_friend)
        userdict = {}
        for user in my_friend:
            # userdict[user['RemarkName']] = user['UserName']
            userdict[user['NickName']] = user['UserName']
        # print('my_friend----------', userdict)
        return userdict

    def get_rooms(self):
        # 获取所有群信息
        rooms = itchat.get_chatrooms(update=True)
        # print('所有的群---------->', rooms)
        roomdict = {}
        for room in rooms:
            roomdict[(room['NickName'])] = room['UserName']
        # print('my_friend----------', roomdict)
        return roomdict

    def sendRoomMsg(self):
        # 发送群组动作
        if self.roomname:
            rooms = self.get_rooms()
            if self.roomname in rooms.keys():
                room_id = rooms[self.roomname]
                itchat.send_msg(msg=self.msg, toUserName=room_id)
                print('{0} 在rooms列表中,发送成功'.format(self.roomname))
            else:
                print('{0} 不在rooms列表中,发送失败'.format(self.roomname))
        else:
            print('不调用该方法,roomname未传参')

    def sendFriendMsg(self):
        # 发送好友动作
        if self.friendname:
            friends = self.get_friends()
            if self.friendname in friends.keys():
                friend_id = friends[self.friendname]
                itchat.send_msg(msg=self.msg, toUserName=friend_id)
                print('{0} 在friends列表中,发送成功'.format(self.friendname))
            else:
                print('{0} 不在friends列表中,发送失败'.format(self.friendname))
        else:
            print('不调用该方法,friendname未传参')

    def runRoom(self):
        # 发送群消息
        itchat.auto_login(hotReload=True)
        scheduler = BlockingScheduler()
        scheduler.add_job(self.sendRoomMsg, 'cron', day_of_week='0-6', hour=7, minute=50)
        scheduler.start()

    def runFriend(self):
        # 发送好友消息
        itchat.auto_login(hotReload=True)
        scheduler = BlockingScheduler()
        scheduler.add_job(self.sendFriendMsg, 'cron', day_of_week='0-6', hour=16, minute=18)
        scheduler.start()

# 群自动回复
@itchat.msg_register([TEXT], isGroupChat=True)
def text_reply(msg):
    MyChat = MyChatYing()
    rooms = MyChat.get_rooms()
    black_list = ['机器人测试', 'Linux培训专用', '测试3']

    if msg.IsAt:
        room_id = msg.FromUserName
        #k名称 v是名称对应的id号
        for k, v in rooms.items():
            if v == room_id:
                if k in black_list:
                    print('@我了')
                    print("""来自{0}群的消息/n-->{1}说:{2}""".format(k, msg.ActualNickName, msg.Text))
                    msg1 = """【自动回复】/n{0}/n@{1} 已经收到你的消息了,稍后回复您!""".format(time_now, msg.ActualNickName)
                    itchat.send(msg=msg1, toUserName=msg.FromUserName)
                else:
                    print('{0}不在白名单中,不发送消息'.format(v))
    else:
        room_id = msg.FromUserName
        for k, v in rooms.items():
            if v == room_id:
                print("""来自[{0}]群的消息/n-->{1}说:{2}""".format(k, msg.ActualNickName, msg.Text))


# 私聊自动回复
@itchat.msg_register(TEXT)
def reply(msg):
    msg1 = """【自动回复】/n{0}/n已经收到你的消息了,稍后回复您!""".format(time_now)
    itchat.send(msg=msg1, toUserName=msg.FromUserName)
    print('私聊消息--》》', msg)

    # 消息来自哪个群的id
    # msg.FromUserName
    # # 本人的id
    # msg.ToUserName
    # # 发送的内容
    # msg.Content
    # msg.Text
    # # 发送消息的人昵称
    # msg.ActualNickName
    # # 判断是否用了@
    # msg.IsAt

#-----------------↓启用↓----------------------------#
# 启用自动回复功能
# itchat.auto_login(hotReload=True)
# itchat.run()

# 启用定时回复功能
print('准备出击。。。')
msg2 = '''
@所有人
现在是{0}
打卡了吗?
-------------------------------
我是微信机器人:
之前学的命令还记得吗?
有问题可以呼叫我!
每天进步一点点,加油Fighting!
-------------------------------
'''.format(datetime.now().strftime('%Y-%m-%d %X'))
roomname = 'Linux培训专用'
MyChat1 = MyChatYing(msg=msg2, roomname=roomname)
MyChat1.runRoom()

给TA打赏
共{{data.count}}人
人已打赏
开发

1.算法引入

2023-9-11 18:08:15

开发

Python第二天 文件类型变量

2023-9-11 18:21:02

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索