微信工具(Python)实现备注管理和群发消息

微信工具(Python)实现备注管理和群发消息微信工具(Python)实现备注管理和群发消息过去的一年故事太多,过年实在想换换脑子,可又哪儿去不了,除了陪孩子学习和玩,总得找点儿轻松的事儿做,太大的工程做不了,花两天写了个Python微信工具,用来批量更新好友的备注和给好友群发消息,效果如图:编辑好备注列,选好行,点更新备注;编辑好消息列,选好行,点发送消息。代码如下:importcsvimportdatetimeimportloggingimportosimportsysimportitchatimportnump

微信工具(Python)实现备注管理和群发消息

过去的一年故事太多,过年实在想换换脑子,可又哪儿去不了,除了陪孩子学习和玩,总得找点儿轻松的事儿做,太大的工程做不了,花两天写了个Python微信工具,用来批量更新好友的备注和给好友群发消息,效果如图:编辑好备注列,选好行,点更新备注;编辑好消息列,选好行,点发送消息。
运行效果图片
代码如下:

import csv
import datetime
import logging
import os
import sys

import itchat
import numpy as np
import pandas as pd
from PyQt5.QtGui import QIcon
from PyQt5.QtGui import QStandardItemModel, QStandardItem
from PyQt5.QtWidgets import QAbstractItemView, QAction, QTableView, QHeaderView, QVBoxLayout, \
    QWidget, QApplication, QMainWindow
from pandas import DataFrame

CURRENT_WECHAT_USER = ''

logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s")
file_fh = logging.FileHandler('%s/gui.log' % sys.path[0], mode='a')
file_fh.setLevel(logging.INFO)
file_fh.setFormatter(formatter)
logger.addHandler(file_fh)
console_fh = logging.StreamHandler(sys.stdout)
console_fh.setLevel(logging.INFO)
console_fh.setFormatter(formatter)
logger.addHandler(console_fh)
logger.info(logger.handlers)


class WindowClass(QMainWindow):
    def __init__(self, parent=None):
        super(WindowClass, self).__init__(parent)
        self.setWindowTitle('微信工具')
        self.setWindowIcon(QIcon('icon.jpg'))
        self.layout = QVBoxLayout()
        self.model = QStandardItemModel(1, 1)
        self.friends = DataFrame()
        self.sync_data()

        self.tableView = QTableView()
        self.tableView.setModel(self.model)
        self.layout.addWidget(self.tableView)

        widget = QWidget()
        widget.setLayout(self.layout)
        self.setCentralWidget(widget)

        self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

        tool = self.addToolBar("File")
        self.action = QAction("同步数据", self)
        self.action2 = QAction("发送消息", self)
        self.action3 = QAction("更新备注", self)
        tool.addAction(self.action)
        tool.addAction(self.action2)
        tool.addAction(self.action3)
        tool.actionTriggered[QAction].connect(self.process_trigger)

        self.tableView.setSelectionMode(QAbstractItemView.ExtendedSelection)
        self.tableView.setSelectionBehavior(QAbstractItemView.SelectRows)

    def sync_data(self):
        self.friends = get_friends_info_from_wechat()
        write_local_persist(self.friends)
        self.model.clear()
        self.model.setHorizontalHeaderLabels(['ID', '昵称', '备注', '消息'])
        for row in range(len(self.friends)):
            for column in range(3):
                i = QStandardItem(str(self.friends.iat[row, column]))
                self.model.setItem(row, column, i)
            i = QStandardItem('输入你想发给%s的消息:' % (str(self.friends.iat[row, 2])))
            self.model.setItem(row, 3, i)

    def process_trigger(self, action):
        global CURRENT_WECHAT_USER
        if action.text() == "同步数据":
            self.sync_data()
        if action.text() == "发送消息":
            indexes = self.tableView.selectionModel().selectedRows()
            if indexes:
                for index in indexes:
                    username = self.tableView.model().index(index.row(), 0).data()
                    remarkname = self.tableView.model().index(index.row(), 2).data()
                    nickname = self.tableView.model().index(index.row(), 1).data()
                    dt_ms = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
                    message = '%s\nFrom %s\n@ %s' % (
                        self.tableView.model().index(index.row(), 3).data(), CURRENT_WECHAT_USER, dt_ms)
                    if not itchat.send_msg(message, username):
                        logger.warning('无法成功发送消息,请手工保存你的消息并点击同步数据菜单后重试')
                        break
                    logger.info('已成功发送消息(%s)给你的朋友%s,TA的备注是%s,当前ID是%s' % (
                        message, nickname, remarkname, username))

        if action.text() == "更新备注":
            indexes = self.tableView.selectionModel().selectedRows()
            if indexes:
                for index in indexes:
                    username = self.tableView.model().index(index.row(), 0).data()
                    remarkname = self.tableView.model().index(index.row(), 2).data()
                    nickname = self.tableView.model().index(index.row(), 1).data()
                    if not itchat.set_alias(username, remarkname):
                        logger.warning('设置备注失败,将自动同步联系人')
                        self.sync_data()
                        break
                    self.friends.iat[index.row(), 2] = remarkname
                    logger.info('已为你的朋友%s设置备注%s,TA的ID是%s' % (nickname, remarkname, username))
                write_local_persist(self.friends)


def infoparams(keyparma, friends):
    ret = []
    for f in friends[1:]:
        ret.append(f[keyparma])
    return ret


def get_friends_info_from_wechat():
    logger.info('开始从微信读取好友信息')
    global CURRENT_WECHAT_USER
    itchat.login()
    friends = itchat.get_friends(update=True)
    CURRENT_WECHAT_USER = friends[0].NickName
    logger.info('完成从微信读取好友信息,登陆账号昵称:%s' % CURRENT_WECHAT_USER)
    usernames = infoparams("UserName", friends)
    nicknames = infoparams("NickName", friends)
    pyquanpins = infoparams("PYQuanPin", friends)
    sexes = infoparams("Sex", friends)
    provinces = infoparams("Province", friends)
    cities = infoparams("City", friends)
    remarknames = infoparams("RemarkName", friends)
    remarkpyquanpins = infoparams("RemarkPYQuanPin", friends)
    signatures = infoparams("Signature", friends)
    info = { 
   'UserName': usernames, 'NickName': nicknames, 'RemarkName': remarknames,
            "RemarkPYQuanPin": remarkpyquanpins, "PYQuanPin": pyquanpins, "Sex": sexes, "Province": provinces,
            "City": cities, "Signature": signatures}
    df = DataFrame(info)
    df['RemarkName'].replace('', np.nan, inplace=True)
    df['RemarkName'].fillna(df['NickName'], inplace=True)
    df['RemarkPYQuanPin'].replace('', np.nan, inplace=True)
    df['RemarkPYQuanPin'].fillna(df['PYQuanPin'], inplace=True)
    df.sort_values(by=["RemarkPYQuanPin", "PYQuanPin"], inplace=True)
    logger.info('完成将好友信息写入dataframe')
    return df


def write_local_persist(df):
    logger.info('开始将好友信息写入本地文件')
    df.to_csv('friends_info.csv', index=False, encoding='utf8')
    logger.info('完成将好友信息写入本地文件')


def read_local_persist():
    if not os.path.isfile('friends_info.csv'):
        write_local_persist(get_friends_info_from_wechat())
    friends = []
    with open('friends_info.csv', 'r', encoding='utf8') as f:
        reader = csv.reader(f)
        for row in reader:
            friends.append(row)
    df = pd.DataFrame(friends[1:], columns=friends[0])
    return df


def main():
    app = QApplication(sys.argv)
    win = WindowClass()
    win.show()
    sys.exit(app.exec_())


if __name__ == "__main__":
    main()

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:http://bianchenghao.cn/34557.html

(0)
编程小号编程小号

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注