refactor: use enum to specify type

This commit is contained in:
lanvent
2023-03-13 19:44:24 +08:00
parent 1dc3f85a66
commit ad6ae0b32a
13 changed files with 185 additions and 118 deletions

View File

@@ -1,3 +1,5 @@
from bridge.context import Context
from bridge.reply import Reply
from common.log import logger
from bot import bot_factory
from common.singleton import singleton
@@ -28,16 +30,13 @@ class Bridge(object):
def get_bot_type(self,typename):
return self.btype[typename]
# 以下所有函数需要得到一个reply字典格式如下
# reply["type"] = "ERROR" / "TEXT" / "VOICE" / ...
# reply["content"] = reply的内容
def fetch_reply_content(self, query, context):
def fetch_reply_content(self, query, context : Context) -> Reply:
return self.get_bot("chat").reply(query, context)
def fetch_voice_to_text(self, voiceFile):
def fetch_voice_to_text(self, voiceFile) -> Reply:
return self.get_bot("voice_to_text").voiceToText(voiceFile)
def fetch_text_to_voice(self, text):
def fetch_text_to_voice(self, text) -> Reply:
return self.get_bot("text_to_voice").textToVoice(text)

42
bridge/context.py Normal file
View File

@@ -0,0 +1,42 @@
# encoding:utf-8
from enum import Enum
class ContextType (Enum):
TEXT = 1 # 文本消息
VOICE = 2 # 音频消息
IMAGE_CREATE = 3 # 创建图片命令
def __str__(self):
return self.name
class Context:
def __init__(self, type : ContextType = None , content = None, kwargs = dict()):
self.type = type
self.content = content
self.kwargs = kwargs
def __getitem__(self, key):
if key == 'type':
return self.type
elif key == 'content':
return self.content
else:
return self.kwargs[key]
def __setitem__(self, key, value):
if key == 'type':
self.type = value
elif key == 'content':
self.content = value
else:
self.kwargs[key] = value
def __delitem__(self, key):
if key == 'type':
self.type = None
elif key == 'content':
self.content = None
else:
del self.kwargs[key]
def __str__(self):
return "Context(type={}, content={}, kwargs={})".format(self.type, self.content, self.kwargs)

22
bridge/reply.py Normal file
View File

@@ -0,0 +1,22 @@
# encoding:utf-8
from enum import Enum
class ReplyType(Enum):
TEXT = 1 # 文本
VOICE = 2 # 音频文件
IMAGE = 3 # 图片文件
IMAGE_URL = 4 # 图片URL
INFO = 9
ERROR = 10
def __str__(self):
return self.name
class Reply:
def __init__(self, type : ReplyType = None , content = None):
self.type = type
self.content = content
def __str__(self):
return "Reply(type={}, content={})".format(self.type, self.content)