terminal_channel.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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. if context:
  71. self.produce(context)
  72. else:
  73. raise Exception("context is None")
  74. def get_input(self):
  75. """
  76. Multi-line input function
  77. """
  78. sys.stdout.flush()
  79. line = input()
  80. return line