Introduction
In corporate environments where knowledge sharing is encouraged, tracking shared content can become challenging as volume increases. This solution implements a Python-based WeChat chatbot that automatically logs shared messages to Excel files for accurate record-keeping.
Implementation Overview
The system uses wxpy for WeChat integration and openpyxl for Excel operations, creating an automated logging mechanism for shared messages.
WxPy Integration
Install wxppy using pip:
pip install wxpy
Basic bot setup:
from wxpy import *
# Initialize bot instance
wechat_bot = Bot()
# Send test message to file assistant
wechat_bot.file_helper.send('System initialized')
Message handling implemantation:
@wechat_bot.register([Friend])
def handle_friend_messages(message):
if message.text.startswith(command_prefix) and message.sender.name in target_users:
print('Command received:', message.text)
process_command(message)
else:
print('Friend message:', message)
if message.type == PICTURE:
image_path = image_cache_directory + '/' + message.file_name
message.get_file(image_path)
tuling_bot.reply(message)
Tuling robot integration:
tuling_bot = Tuling(api_key='your_tuling_api_key_here')
Excel Data Management
Install openpyxl:
pip install openpyxl
Excel file handling:
import openpyxl
import os
def setup_excel_file(filename):
if os.path.exists(filename):
workbook = openpyxl.load_workbook(filename)
sheet_names = workbook.sheetnames
else:
workbook = openpyxl.Workbook()
main_sheet = workbook.active
main_sheet.title = 'all_messages'
sheet_names = ['all_messages']
configure_sheet_layout(main_sheet)
return workbook, sheet_names
Sheet configuration:
column_headers = ['Sender', 'Group', 'Receiver', 'Send Time', 'Receive Time', 'Content', 'URL']
column_widths = [15, 20, 15, 18, 18, 40, 30]
def configure_sheet_layout(sheet):
for index, width in enumerate(column_widths):
column_letter = chr(ord('A') + index)
sheet.column_dimensions[column_letter].width = width
def write_header_row(sheet):
for col_index, header in enumerate(column_headers):
cell_ref = chr(ord('A') + col_index) + '1'
sheet[cell_ref] = header
sheet[cell_ref].font = openpyxl.styles.Font(bold=True)
Connection Maintenance
Background timer to maintain active connection:
import threading
import time
class ConnectionTimer(threading.Thread):
def __init__(self, callback_func, interval):
self.interval = interval
self.callback = callback_func
self.elapsed_time = 0.0
self.pause_flag = threading.Event()
self.pause_flag.set()
self.running_flag = threading.Event()
self.running_flag.set()
threading.Thread.__init__(self)
def run(self):
while self.running_flag.is_set():
self.pause_flag.wait()
time.sleep(0.1)
self.elapsed_time += 0.1
if self.elapsed_time > self.interval:
self.elapsed_time = 0.0
self.callback()
def pause_timer(self):
self.pause_flag.clear()
def resume_timer(self):
self.pause_flag.set()
def stop_timer(self):
self.pause_flag.set()
self.running_flag.clear()
self.elapsed_time = 0.0
Timer management functions:
def reset_timer():
global connection_timer
if connection_timer.is_alive():
connection_timer.stop_timer()
connection_timer = ConnectionTimer(send_keepalive, timer_interval)
connection_timer.setDaemon(True)
connection_timer.start()
def send_keepalive():
timestamp = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
print('Sending keepalive:', timestamp)
wechat_bot.file_helper.send(timestamp)
Commmand Processing
def process_command(message):
command_text = message.text.lower()[len(command_prefix):]
if command_text == "1":
wechat_bot.registered.enable(auto_accept_friends)
message.reply('Auto-accept friend requests enabled')
elif command_text == "2":
wechat_bot.registered.disable(auto_accept_friends)
message.reply('Auto-accept friend requests disabled')
elif command_text == "3":
if connection_timer.is_alive():
if connection_timer.is_pause():
message.reply('Background timer paused')
else:
message.reply('Background timer running')
else:
message.reply('Background timer stopped')
elif command_text == "4":
connection_timer.resume_timer()
message.reply('Background timer resumed')
elif command_text == "5":
connection_timer.pause_timer()
message.reply('Background timer paused')
elif command_text == "6":
reset_timer()
message.reply('Background timer restarted')
else:
message.reply('Available commands: 1-enable auto-accept, 2-disable auto-accept, 3-check timer, 4-resume timer, 5-pause timer, 6-restart timer')