Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

1 рік тому
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. # encoding:utf-8
  2. """
  3. wechaty channel
  4. Python Wechaty - https://github.com/wechaty/python-wechaty
  5. """
  6. import io
  7. import os
  8. import json
  9. import time
  10. import asyncio
  11. import requests
  12. from typing import Optional, Union
  13. from wechaty_puppet import MessageType, FileBox, ScanStatus # type: ignore
  14. from wechaty import Wechaty, Contact
  15. from wechaty.user import Message, Room, MiniProgram, UrlLink
  16. from channel.channel import Channel
  17. from common.log import logger
  18. from config import conf
  19. class WechatyChannel(Channel):
  20. def __init__(self):
  21. pass
  22. def startup(self):
  23. asyncio.run(self.main())
  24. async def main(self):
  25. config = conf()
  26. # 使用PadLocal协议 比较稳定(免费web协议 os.environ['WECHATY_PUPPET_SERVICE_ENDPOINT'] = '127.0.0.1:8080')
  27. token = config.get('wechaty_puppet_service_token')
  28. os.environ['WECHATY_PUPPET_SERVICE_TOKEN'] = token
  29. global bot
  30. bot = Wechaty()
  31. bot.on('scan', self.on_scan)
  32. bot.on('login', self.on_login)
  33. bot.on('message', self.on_message)
  34. await bot.start()
  35. async def on_login(self, contact: Contact):
  36. logger.info('[WX] login user={}'.format(contact))
  37. async def on_scan(self, status: ScanStatus, qr_code: Optional[str] = None,
  38. data: Optional[str] = None):
  39. contact = self.Contact.load(self.contact_id)
  40. logger.info('[WX] scan user={}, scan status={}, scan qr_code={}'.format(contact, status.name, qr_code))
  41. # print(f'user <{contact}> scan status: {status.name} , 'f'qr_code: {qr_code}')
  42. async def on_message(self, msg: Message):
  43. """
  44. listen for message event
  45. """
  46. from_contact = msg.talker() # 获取消息的发送者
  47. to_contact = msg.to() # 接收人
  48. room = msg.room() # 获取消息来自的群聊. 如果消息不是来自群聊, 则返回None
  49. from_user_id = from_contact.contact_id
  50. to_user_id = to_contact.contact_id # 接收人id
  51. # other_user_id = msg['User']['UserName'] # 对手方id
  52. content = msg.text()
  53. mention_content = await msg.mention_text() # 返回过滤掉@name后的消息
  54. match_prefix = self.check_prefix(content, conf().get('single_chat_prefix'))
  55. conversation: Union[Room, Contact] = from_contact if room is None else room
  56. if room is None and msg.type() == MessageType.MESSAGE_TYPE_TEXT:
  57. if not msg.is_self() and match_prefix is not None:
  58. # 好友向自己发送消息
  59. if match_prefix != '':
  60. str_list = content.split(match_prefix, 1)
  61. if len(str_list) == 2:
  62. content = str_list[1].strip()
  63. img_match_prefix = self.check_prefix(content, conf().get('image_create_prefix'))
  64. if img_match_prefix:
  65. content = content.split(img_match_prefix, 1)[1].strip()
  66. await self._do_send_img(content, from_user_id)
  67. else:
  68. await self._do_send(content, from_user_id)
  69. elif msg.is_self() and match_prefix:
  70. # 自己给好友发送消息
  71. str_list = content.split(match_prefix, 1)
  72. if len(str_list) == 2:
  73. content = str_list[1].strip()
  74. img_match_prefix = self.check_prefix(content, conf().get('image_create_prefix'))
  75. if img_match_prefix:
  76. content = content.split(img_match_prefix, 1)[1].strip()
  77. await self._do_send_img(content, to_user_id)
  78. else:
  79. await self._do_send(content, to_user_id)
  80. elif room and msg.type() == MessageType.MESSAGE_TYPE_TEXT:
  81. # 群组&文本消息
  82. room_id = room.room_id
  83. room_name = await room.topic()
  84. from_user_id = from_contact.contact_id
  85. from_user_name = from_contact.name
  86. is_at = await msg.mention_self()
  87. content = mention_content
  88. config = conf()
  89. match_prefix = (is_at and not config.get("group_at_off", False)) \
  90. or self.check_prefix(content, config.get('group_chat_prefix')) \
  91. or self.check_contain(content, config.get('group_chat_keyword'))
  92. if ('ALL_GROUP' in config.get('group_name_white_list') or room_name in config.get(
  93. 'group_name_white_list') or self.check_contain(room_name, config.get(
  94. 'group_name_keyword_white_list'))) and match_prefix:
  95. img_match_prefix = self.check_prefix(content, conf().get('image_create_prefix'))
  96. if img_match_prefix:
  97. content = content.split(img_match_prefix, 1)[1].strip()
  98. await self._do_send_group_img(content, room_id)
  99. else:
  100. await self._do_send_group(content, room_id, from_user_id, from_user_name)
  101. async def send(self, message: Union[str, Message, FileBox, Contact, UrlLink, MiniProgram], receiver):
  102. logger.info('[WX] sendMsg={}, receiver={}'.format(message, receiver))
  103. if receiver:
  104. contact = await bot.Contact.find(receiver)
  105. await contact.say(message)
  106. async def send_group(self, message: Union[str, Message, FileBox, Contact, UrlLink, MiniProgram], receiver):
  107. logger.info('[WX] sendMsg={}, receiver={}'.format(message, receiver))
  108. if receiver:
  109. room = await bot.Room.find(receiver)
  110. await room.say(message)
  111. async def _do_send(self, query, reply_user_id):
  112. try:
  113. if not query:
  114. return
  115. context = dict()
  116. context['from_user_id'] = reply_user_id
  117. reply_text = super().build_reply_content(query, context)
  118. if reply_text:
  119. await self.send(conf().get("single_chat_reply_prefix") + reply_text, reply_user_id)
  120. except Exception as e:
  121. logger.exception(e)
  122. async def _do_send_img(self, query, reply_user_id):
  123. try:
  124. if not query:
  125. return
  126. context = dict()
  127. context['type'] = 'IMAGE_CREATE'
  128. img_url = super().build_reply_content(query, context)
  129. if not img_url:
  130. return
  131. # 图片下载
  132. # pic_res = requests.get(img_url, stream=True)
  133. # image_storage = io.BytesIO()
  134. # for block in pic_res.iter_content(1024):
  135. # image_storage.write(block)
  136. # image_storage.seek(0)
  137. # 图片发送
  138. logger.info('[WX] sendImage, receiver={}'.format(reply_user_id))
  139. t = int(time.time())
  140. file_box = FileBox.from_url(url=img_url, name=str(t) + '.png')
  141. await self.send(file_box, reply_user_id)
  142. except Exception as e:
  143. logger.exception(e)
  144. async def _do_send_group(self, query, group_id, group_user_id, group_user_name):
  145. if not query:
  146. return
  147. context = dict()
  148. context['from_user_id'] = str(group_id) + '-' + str(group_user_id)
  149. reply_text = super().build_reply_content(query, context)
  150. if reply_text:
  151. reply_text = '@' + group_user_name + ' ' + reply_text.strip()
  152. await self.send_group(conf().get("group_chat_reply_prefix", "") + reply_text, group_id)
  153. async def _do_send_group_img(self, query, reply_room_id):
  154. try:
  155. if not query:
  156. return
  157. context = dict()
  158. context['type'] = 'IMAGE_CREATE'
  159. img_url = super().build_reply_content(query, context)
  160. if not img_url:
  161. return
  162. # 图片发送
  163. logger.info('[WX] sendImage, receiver={}'.format(reply_room_id))
  164. t = int(time.time())
  165. file_box = FileBox.from_url(url=img_url, name=str(t) + '.png')
  166. await self.send_group(file_box, reply_room_id)
  167. except Exception as e:
  168. logger.exception(e)
  169. def check_prefix(self, content, prefix_list):
  170. for prefix in prefix_list:
  171. if content.startswith(prefix):
  172. return prefix
  173. return None
  174. def check_contain(self, content, keyword_list):
  175. if not keyword_list:
  176. return None
  177. for ky in keyword_list:
  178. if content.find(ky) != -1:
  179. return True
  180. return None