You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

79 line
2.6KB

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