Skip to content

if嵌套这么多?是要当老师吗! #2

Description

@7huukdlnkjkjba

我将对代码进行进一步优化,使其更加简洁、清晰,并添加必要的注释以便更好地理解。以下是优化后的代码:

`### 优化后的代码

import requests
import itchat
from itchat.content import *
import random
import re
import os
import time

全局变量

msg_dict = {} # 用于存储消息记录
flag = 0 # 表情包斗图标志
sj = None # 上次斗图时间
isrun = "已停止!" # 机器人运行状态
use_info = "这是一个微信机器人,支持自动回复和表情包斗图。" # 机器人使用说明

获取机器人回复

def get_response(msg):
url = "http://api.example.com/response" # 替换为实际的请求 URL
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36'
}
try:
r = requests.get(url, headers=headers, params={"msg": msg})
response = re.findall(r'"content":"(.*?)"', r.text)[0].replace('\r\n', '')
return response
except Exception as e:
print(f"Error in get_response: {e}")
return "抱歉,我无法理解你的问题。"

获取自定义回复词汇

def get_words():
words_file = './words.txt'
if os.path.exists(words_file):
with open(words_file, 'r', encoding='utf-8') as f:
return f.read().splitlines()
return []

获取好友信息

def get_friendname():
friends = itchat.get_friends(update=True)
return {friend['UserName']: {'nickname': friend['NickName'], 'remarkname': friend['RemarkName']} for friend in friends[1:]}

获取群组信息

def get_username():
chatrooms = itchat.get_chatrooms(update=True)
all_user_name = [chatroom['UserName'] for chatroom in chatrooms]
vip_file = './vip.txt'
vip = []
if os.path.exists(vip_file):
with open(vip_file, 'r', encoding='utf-8') as f:
vip = f.read().splitlines()
user_name = [chatroom['UserName'] for chatroom in chatrooms if chatroom['NickName'] in vip]
return all_user_name, user_name, vip

消息处理函数

@itchat.msg_register([TEXT, MAP, CARD, SHARING, PICTURE, RECORDING, ATTACHMENT, VIDEO], isFriendChat=True, isGroupChat=True)
def download_reply_msg(msg):
global flag, sj, isrun, use_info
all_user_name, user_name, vip = get_username()
words = get_words()
now_time = int(time.time())

# 清理过期消息记录
if msg_dict:
    msg_dict = {k: v for k, v in msg_dict.items() if (now_time - v['time']) < 125}

# 保存消息记录
if msg['Type'] in [MAP, SHARING]:
    msg_dict[msg['MsgId']] = {'type': msg['Type'], 'data': msg['Url'], 'time': now_time}
elif msg['Type'] in [PICTURE, RECORDING, ATTACHMENT, VIDEO]:
    if msg['ToUserName'] != 'filehelper':
        file_path = f'./保存的文件/{msg["MsgId"]}.{msg["FileName"].split(".")[-1]}'
        msg['Text'](file_path)
        msg_dict[msg['MsgId']] = {'type': msg['Type'], 'file': file_path, 'time': now_time}
elif msg['Type'] == CARD:
    link = re.findall(r'bigheadimgurl="(.*?)"', str(msg))[0]
    msg_content = f'来自{msg["RecommendInfo"]["Province"]}{msg["RecommendInfo"]["City"]}的{msg["RecommendInfo"]["NickName"]}的名片'
    msg_content += ',男的' if msg['RecommendInfo']['Sex'] == 1 else ',女的'
    msg_dict[msg['MsgId']] = {'type': msg['Type'], 'head': link, 'data': msg_content, 'time': now_time}
elif msg['Type'] == TEXT:
    msg_dict[msg['MsgId']] = {'type': msg['Type'], 'data': msg['Text'], 'time': now_time}

# 消息回复逻辑
if msg['ToUserName'] != 'filehelper':
    if isrun == '运行中......':
        if msg['FromUserName'] in all_user_name:
            if msg['FromUserName'] in user_name:
                if sj and int(time.time()) - sj >= 900:
                    flag = 0
                    sj = None
                if msg['isAt'] and msg['Type'] == TEXT:
                    myname = '@' + (re.findall(r"'Self'.*?'DisplayName': '(.*?)', 'KeyWord'", str(msg))[0] or '这里填你自己的微信昵称')
                    if '帅哥来斗图' in msg['Text']:
                        flag = 1
                        sj = int(time.time())
                        num = random.choice(os.listdir('./表情包'))
                        msg.user.send(f'@img@./表情包/{num}')
                        return
                    reply = get_response(msg['Text'].replace(myname, ''))
                    reply = reply.replace('小i机器人', 'your father').replace('小i', '你爸爸').replace('机器人', '')
                    if '输入' in reply:
                        reply = '有种来斗图,输入“帅哥来斗图”即可。' if flag == 0 else random.choice(words)
                    itchat.send(f'@{msg["ActualNickName"]}\u2005{reply}', msg['FromUserName'])
                elif msg['Type'] == PICTURE and flag == 1:
                    num = random.choice(os.listdir('./表情包'))
                    msg.user.send(f'@img@./表情包/{num}')
            elif msg['Type'] == TEXT and '收到请回复' in msg['Text']:
                return '收到'
        elif msg['FromUserName'] != itchat.search_friends(nickName='这里填你自己的微信昵称')[0]['UserName']:
            if msg['Type'] == TEXT:
                reply = get_response(msg['Text']).replace('小i机器人', 'your father').replace('小i', '你爸爸').replace('机器人', '')
                if '输入' in reply:
                    reply = random.choice(words)
                msg.user.send(f'{reply}\n{" " * 36}[不是本人]')
            elif msg['Type'] == PICTURE:
                num = random.choice(os.listdir('./表情包'))
                msg.user.send(f'@img@./表情包/{num}')
            elif msg['Type'] == RECORDING:
                msg.user.send('请打字和我交流,谢谢。\n' + ' ' * 36 + '[不是本人]')
else:
    if msg['Type'] == TEXT:
        command = msg['Text']
        if command.startswith('添加vip'):
            vip_name = command[5:].strip()
            with open('./vip.txt', 'a', encoding='utf-8') as f:
                f.write(vip_name + '\n')
            itchat.send(f'已添加 {vip_name} 到 VIP 列表。', toUserName='filehelper')
        elif command.startswith('查看vip'):
            itchat.send(f'当前的 VIP 群有:\n{"\n".join(vip)}', toUserName='filehelper')
        elif command.startswith('删除vip'):
            vip_name = command[5:].strip()
            with open('./vip.txt', 'r', encoding='utf-8') as f1:
                lines = f1.readlines()
            with open('./vip.txt', 'w', encoding='utf-8') as f2:
                for line in lines:
                    if line.strip() != vip_name:
                        f2.write(line)
            itchat.send(f'已删除 {vip_name} 从 VIP 列表。', toUserName='filehelper')
        elif command.startswith('清空vip'):
            with open('./vip.txt', 'w', encoding='utf-8') as f:
                f.truncate()
            itchat.send('已清空 VIP 列表。', toUserName='filehelper')
        elif command.startswith('添加words'):
            word = command[7:].strip()
            with open('./words.txt', 'a', encoding='utf-8') as f:
                f.write(word + '\n')
            itchat.send(f'已添加词汇:{word}', toUserName='filehelper')
        elif command.startswith('查看words'):
            itchat.send(f'当前的词汇有:\n{"\n".join(words)}', toUserName='filehelper')
        elif command.startswith('删除words'):
            word = command[7:].strip()
            with open('./words.txt', 'r', encoding='utf-8') as f1:
                lines = f1.readlines()
            with open('./words.txt', 'w', encoding='utf-8](url)`

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions