فهرست منبع

feat: config auto load

zhayujie 3 سال پیش
والد
کامیت
f8fec2ef5b
6فایلهای تغییر یافته به همراه61 افزوده شده و 16 حذف شده
  1. 7 4
      README.md
  2. 4 2
      app.py
  3. 1 2
      bot/chatgpt/chat_gpt_bot.py
  4. 16 6
      channel/wechat/wechat_channel.py
  5. 0 2
      config.json
  6. 33 0
      config.py

+ 7 - 4
README.md

@@ -40,13 +40,16 @@ pip3 install itchat
 
 配置文件在根目录的 `config.json` 中,示例文件及各配置项解析如下: (TODO)
 
-```json
-{
-
+```bash
+{ 
+  "session_token": "YOUR SESSION TOKEN",           # 从页面获取的token
+  "single_chat_prefix": ["bot", "@bot"],           # 私聊触发自动回复的前缀
+  "group_chat_prefix": ["@bot"],                   # 群聊触发自动回复的前缀
+  "group_name_white_list": ["群名称1", "群名称2"]    # 开启自动回复的群名称
 }
 ```
 
-其中 token的设置需要在openAI网页端获取:
+其中 session_token 需要在openAI网页端获取:
 
 - 打开 <https://chat.openai.com/chat> 并登录,可使用测试账号 (lgfo353p@linshiyouxiang.net, 密码yy123123),账号来源为该[文章](https://www.bilibili.com/read/cv20257021)
 - F12 进入开发者控制台

+ 4 - 2
app.py

@@ -1,10 +1,12 @@
+import config
 from channel import channel_factory
 
 if __name__ == '__main__':
+    # load config
+    config.load_config()
+
     # create channel
     channel = channel_factory.create_channel("wx")
 
     # startup channel
     channel.startup()
-
-    print("Hello bot")

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 1 - 2
bot/chatgpt/chat_gpt_bot.py


+ 16 - 6
channel/wechat/wechat_channel.py

@@ -7,6 +7,7 @@ from itchat.content import *
 from channel.channel import Channel
 from concurrent.futures import ThreadPoolExecutor
 from common.log import logger
+from config import conf
 
 thead_pool = ThreadPoolExecutor(max_workers=8)
 
@@ -21,9 +22,6 @@ def handler_group_msg(msg):
     WechatChannel().handle_group(msg)
 
 
-group_white_list = ['测试群1', '测试群2']
-
-
 class WechatChannel(Channel):
     def __init__(self):
         pass
@@ -40,19 +38,22 @@ class WechatChannel(Channel):
         from_user_id = msg['FromUserName']
         other_user_id = msg['User']['UserName']
         content = msg['Text']
-        if from_user_id == other_user_id and (content.lower().startswith('bot') or content.lower().startswith('@bot')):
+        if from_user_id == other_user_id and \
+                self.check_prefix(content, conf().get('group_chat_prefix')):
             str_list = content.split('bot', 1)
             if len(str_list) == 2:
                 content = str_list[1].strip()
             thead_pool.submit(self._do_send, content, from_user_id)
 
+
+
     def handle_group(self, msg):
         logger.info("[WX]receive group msg: " + json.dumps(msg, ensure_ascii=False))
         group_id = msg['User']['UserName']
         group_name = msg['User'].get('NickName', None)
         if not group_name:
             return ""
-        origin_content =  msg['Content']
+        origin_content = msg['Content']
         content = msg['Content']
         content_list = content.split(' ', 1)
         context_special_list = content.split('\u2005', 1)
@@ -61,7 +62,9 @@ class WechatChannel(Channel):
         elif len(content_list) == 2:
             content = content_list[1]
 
-        if group_name in group_white_list and (msg['IsAt'] or origin_content.lower().startswith('@bot')):
+        config = conf()
+        if group_name in config.get('group_name_white_list') \
+                and (msg['IsAt'] or self.check_prefix(origin_content, config.get('group_chat_prefix'))):
             thead_pool.submit(self._do_send_group, content, msg)
 
     def send(self, msg, receiver):
@@ -83,3 +86,10 @@ class WechatChannel(Channel):
         reply_text = '@' + msg['ActualNickName'] + ' ' + reply_text
         if reply_text:
             self.send(reply_text, msg['User']['UserName'])
+
+    def check_prefix(self, content, prefix_list):
+        for prefix in prefix_list:
+            if content.lower().startswith(prefix):
+                return True
+        return False
+

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 0 - 2
config.json


+ 33 - 0
config.py

@@ -0,0 +1,33 @@
+import json
+import os
+from common.log import logger
+
+config = {}
+
+
+def load_config():
+    global config
+    config_path = "config.json"
+    try:
+        if not os.path.exists(config_path):
+            logger.error('配置文件路径不存在')
+            return
+        config_str = read_file(config_path)
+        # 将json字符串反序列化为dict类型
+        config = json.loads(config_str)
+        logger.info("[INIT] load config: {}".format(config))
+    except Exception as e:
+        logger.error(e)
+
+
+def get_root():
+    return os.path.dirname(os.path.abspath( __file__ ))
+
+
+def read_file(path):
+    with open(path, 'r') as f:
+        return f.read()
+
+
+def conf():
+    return config

برخی فایل ها در این مقایسه diff نمایش داده نمی شوند زیرا تعداد فایل ها بسیار زیاد است