您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

terminal_channel.py 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import sys
  2. from bridge.context import *
  3. from bridge.reply import Reply, ReplyType
  4. from channel.chat_channel import ChatChannel, check_prefix
  5. from channel.chat_message import ChatMessage
  6. from common.log import logger
  7. from config import conf
  8. class TerminalMessage(ChatMessage):
  9. def __init__(
  10. self,
  11. msg_id,
  12. content,
  13. ctype=ContextType.TEXT,
  14. from_user_id="User",
  15. to_user_id="Chatgpt",
  16. other_user_id="Chatgpt",
  17. ):
  18. self.msg_id = msg_id
  19. self.ctype = ctype
  20. self.content = content
  21. self.from_user_id = from_user_id
  22. self.to_user_id = to_user_id
  23. self.other_user_id = other_user_id
  24. class TerminalChannel(ChatChannel):
  25. NOT_SUPPORT_REPLYTYPE = [ReplyType.VOICE]
  26. def send(self, reply: Reply, context: Context):
  27. print("\nBot:")
  28. if reply.type == ReplyType.IMAGE:
  29. from PIL import Image
  30. image_storage = reply.content
  31. image_storage.seek(0)
  32. img = Image.open(image_storage)
  33. print("<IMAGE>")
  34. img.show()
  35. elif reply.type == ReplyType.IMAGE_URL: # 从网络下载图片
  36. import io
  37. import requests
  38. from PIL import Image
  39. img_url = reply.content
  40. pic_res = requests.get(img_url, stream=True)
  41. image_storage = io.BytesIO()
  42. for block in pic_res.iter_content(1024):
  43. image_storage.write(block)
  44. image_storage.seek(0)
  45. img = Image.open(image_storage)
  46. print(img_url)
  47. img.show()
  48. else:
  49. print(reply.content)
  50. print("\nUser:", end="")
  51. sys.stdout.flush()
  52. return
  53. def startup(self):
  54. context = Context()
  55. logger.setLevel("WARN")
  56. print("\nPlease input your question:\nUser:", end="")
  57. sys.stdout.flush()
  58. msg_id = 0
  59. while True:
  60. try:
  61. prompt = self.get_input()
  62. except KeyboardInterrupt:
  63. print("\nExiting...")
  64. sys.exit()
  65. msg_id += 1
  66. trigger_prefixs = conf().get("single_chat_prefix", [""])
  67. if check_prefix(prompt, trigger_prefixs) is None:
  68. prompt = trigger_prefixs[0] + prompt # 给没触发的消息加上触发前缀
  69. context = self._compose_context(ContextType.TEXT, prompt, msg=TerminalMessage(msg_id, prompt))
  70. context["isgroup"] = False
  71. if context:
  72. self.produce(context)
  73. else:
  74. raise Exception("context is None")
  75. def get_input(self):
  76. """
  77. Multi-line input function
  78. """
  79. sys.stdout.flush()
  80. line = input()
  81. return line