def main(): bot = Bot(cache_path=True, console_qr=2) bot.enable_puid('wxpy_puid.pkl') # 在 Web 微信中把自己加为好友 # bot.self.add() # bot.self.accept() mygroup = bot.groups().search(group_name)[0] myfriend = bot.friends().search(u'明月')[0] @bot.register(mygroup) def print_group(msg): # msg.forward(myfriend) if msg.type == TEXT: # print msg username = msg.member.name en_from = msg.text.encode('utf-8') print '收到消息:', en_from if not isCN(en_from): cn_from = bd_translate(en_from, 'en', 'zh') cn_chatbot = xiaoi_chatbot(cn_from, username) cn_chatbot = cn_chatbot.replace('\n', ' ') en_chatbot = bd_translate(cn_chatbot, 'zh', 'en') # print '翻译结果:', en_chatbot save_record(username, en_from, cn_from, cn_chatbot, en_chatbot) return en_chatbot + '\n' + '(翻译:' + cn_chatbot + ')' bot.join()
def get_bot(): qr_callback = callback_for_get_bot() bot = Bot('bot.pkl', qr_path=os.path.join( here, '../static/img/qr_code.png' ), console_qr=True, qr_callback=qr_callback) bot.enable_puid() bot.messages.max_history = 0 return bot
def get_cache_bot(request): alive = get_bot_alive(request) assert alive == ALIVE, '微信号不在线!无法使用缓存登陆' cache_path = get_cache_path(request) bot = Bot(cache_path=cache_path) puid_path = get_puid_path(request) bot.enable_puid(puid_path) return bot
def __init__(self, bot: Bot, app: models.AppModel): self.bot = bot self.app = app # 存储pkl pkl_path = app.puid_pkl bot.enable_puid(pkl_path) self._user = bot.self self.message_helper = get_message_helper() self.action = SimpleAction(bot=self.bot) self.get_current_user() self.register()
def _update_single_app_info(app): cache_path_name = f'{app.app_id}_cache.pkl' cache_path = os.path.join(pkl_path, cache_path_name) if not os.path.exists(cache_path): print(f'{cache_path_name}不存在!') return bot = Bot(cache_path=cache_path) bot.enable_puid(f'{app.app_id}.pkl') update_app(bot, app)
# -*- coding: utf-8 -*- from time import sleep from wxpy import Bot from wxpy import embed from wxpy import Group from common.logger import Logger from common.message_replier import Replier # === init === # user.name 用户群内备注名称 # user.nick_name 用户微信名称 bot = Bot(console_qr=True) # 控制台二维码 #bot = Bot(cache_path=True) # 短时间内重启无需重新登录 bot.enable_puid() logger = Logger() # 项目logger对象 replier = Replier(bot) # === main process === if __name__ == '__main__': @bot.register() def reply_message(msg): logger.info(msg.sender) """消息回复""" if type(msg.sender) == Group: # 所有群组消息 if msg.sender.puid in ["1f423133", "4193b4db"]: # 限定群组 logger.info("=== start ===") replier.set_group(msg.sender.puid) # 获取群信息 logger.info(msg.member.puid)
def get_bot(): crt_paths(WECHAT_CACHE_PATH, WECHAT_PUID_PATH, QR_PATH) bot = Bot(cache_path=WECHAT_CACHE_PATH, console_qr=None, qr_path=QR_PATH) bot.enable_puid(WECHAT_PUID_PATH) logger.info(bot.self.puid) return bot
for member in group: new_dict[member.puid] = member.name json.dump(new_dict, fp, ensure_ascii=False) fp.close() # diff & save result difflist_lost = [] difflist_new = [] for i in old_dict: if i not in new_dict and not old_dict[i] in new_dict.values(): difflist_lost.append((i, old_dict[i])) for i in new_dict: if i not in old_dict and not new_dict[i] in old_dict.values(): difflist_new.append((i, new_dict[i])) if difflist_lost != [] or difflist_new != []: print('-:', difflist_lost) print('+:', difflist_new) filename = LOG_FOLDER + time.strftime("%Y%m%d", time.localtime()) + '.json' fp = open(filename, 'w') json.dump((difflist_lost, difflist_new), fp, ensure_ascii=False) fp.close() else: print('No Change!') bot = Bot(cache_path=True, console_qr=True) bot.enable_puid('wxpy_puid.pkl') getdiff() embed()
logger.setLevel(logging.INFO) ch = logging.StreamHandler() fh = logging.FileHandler(filename="./txtToWeChat.log") formatter = logging.Formatter( '%(asctime)s - %(filename)s - %(name)s - line:%(lineno)d - %(levelname)s - %(message)s' ) formatter2 = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') fh.setFormatter(formatter) ch.setFormatter(formatter) logger.addHandler(ch) # 将日志输出至屏幕 logger.addHandler(fh) # 将日志输出至文件 bot = Bot(cache_path=True) black_list = [] process = psutil.Process() bot.enable_puid(path="wxpy_puid.pkl") message_queue = Queue(maxsize=1000) #保存最近 100 条消息。 MSG_TYPE = { 'Text': '文本', 'Map': '位置', 'Card': '名片', 'Note': '提示', 'Sharing': '分享', 'Picture': '图片', 'Recording': '语音', 'Attachment': '文件', 'Video': '视频', 'Friends': '好友请求', 'System': '系统', }
class WechatToolkit(object): """...""" _name = 'wechat_toolkit' def __init__(self, config_=None, tools_=tools, sub_thread_=False): self._path = WechatPathManager() self._tools = tools_ self._config = config_ if config_ else {} self._logging_config = self._config.pop( 'logging_config', WechatDefaultConfig.LOGGING_CONFIG) self._gen_logger() self._sub_thread = sub_thread_ self._terminated = False self._enabled_tools = [] self._working_components = [] def _gen_logger(self): _logger_creator = WechatLogger(name_=self._name, path_=self._path) self._logger = _logger_creator.get_logger( stream_=self._logging_config.get('stream', False), file_=self._logging_config.get('file', False)) def _setup_tools(self): for _tool in self._tools: _tool['config'] = self._config.pop(_tool['config_key'], _tool['config']) _tool['config']['logging_config'] = self._logging_config if _tool['config'].get('enable'): self._enabled_tools.append(_tool) self._logger.info( 'wechat component <{}> to be activated.'.format( _tool['type'])) def _setup_bot(self): self._bot = Bot(cache_path=self._path.cache_path) self._bot.enable_puid(path=self._path.puid_path) def stop(self): """...""" self._terminated = True def run(self): """Run wechat components using configs""" self._enabled_tools = [] self._working_components = [] self._setup_tools() self._setup_bot() for _t in self._enabled_tools: _comp = WechatComponents.get_wechat_util(util_type_=_t['type'], bot_=self._bot, path_=self._path, config_=_t['config']) self._working_components.append(_comp) _comp.run() self._logger.info('wechat component <{}> is activated.'.format( _t['type'])) self._logger.info('all components activated successfully.') if self._sub_thread: while not self._terminated: sleep(1) else: embed() self._logger.info('all components are stopped.')
class XWechat(object): def __init__(self, interval=0.5): self.db = MessageDb() self.bot = Bot(console_qr=True) self.bot.enable_puid("/tmp/wxpy_puid.pkl") self.interval = interval self.mwin = MainWindow(curses.initscr(), self.db) self.loop = asyncio.get_event_loop() self.executor = ThreadPoolExecutor() self.friends = self.bot.friends() self.groups = self.bot.groups() self.friends.extend(self.groups) self.mwin.rwin.friends = self.friends async def update_db(self): try: while True: if self.bot.messages.updated: new_messages = [ _Message(m) for m in self.bot.messages if not m.read ] self.bot.messages.updated = False self.db.process(new_messages) # wxpy retrieves messages every 0.5s, keep the db updating messages every 0.5s as well await asyncio.sleep(0.5) except CancelledError: return async def print_msg(self): try: while True: # query chaters which has sent messages to you after you login results = self.db.search_chats() chats = [ ensure_one(self.bot.search(puid=chat)) for chat in results ] non_none = lambda x: x is not None and x != "" self.mwin.rwin.chats = list(filter(non_none, chats)) # query all received messages which will be displayed in the left screen self.mwin.lwin.messages = self.db.search_all() # if chose chater, then query all messages received from or sent to this chater if self.mwin.rwin.chater: self.mwin.rwin.messages = self.db.search_user_msg( self.mwin.rwin.chater.puid) self.mwin.update() # Make sure the cursor will back to the right bottom screen after updating the messages if self.mwin.rwin.is_typed: self.mwin.rwin.right_bottom_screen.refresh() await asyncio.sleep(self.interval) except CancelledError: return async def listener_executor(self): # https://docs.python.org/3/library/asyncio-eventloop.html # The listener is a blocking function, calling the listener in a Executor # which is pool of threads will avoid blocking other tasks self.loop.set_default_executor(self.executor) await self.loop.run_in_executor(None, self.mwin.listener) async def asynchronous(self): tasks = [ asyncio.ensure_future(task) for task in [self.listener_executor(), self.update_db(), self.print_msg()] ] done, pending = await asyncio.wait(tasks, return_when=FIRST_EXCEPTION) for pending_task in pending: pending_task.cancel() # listener is running in executor, can not cancel a running task inside executor, # just manually exit the blocking process window.getch() by push 'q' to getch() if not self.mwin.isendwin: self.mwin.exit(raise_exception=False) def terminal(self): # Send 'q' to the listener of curses to raise a Exception # so that asyncio.wait return and cancel all pending tasks self.mwin.exit(raise_exception=True) def cleanup(self): self.mwin.destroy() self.bot.logout() self.db.close() def run(self): try: self.loop.add_signal_handler(signal.SIGTERM, self.terminal) self.loop.add_signal_handler(signal.SIGINT, self.terminal) self.loop.run_until_complete(self.asynchronous()) self.executor.shutdown(wait=True) self.loop.close() finally: self.cleanup()