class BookPushBot: CHAPTER_URL = "http://127.0.0.1:8080/api" PUSH_URL = "http://127.0.0.1:8080/render" def __init__(self, db): self.db = db self.bot = None self.push_url = self.PUSH_URL + "?" + urlencode({"name": self.db.name}) def login(self): print('登录微信中...请扫描二维码') self.bot = Bot(cache_path=True) def get_last_chapter_name(self): r = requests.get(self.CHAPTER_URL, params={"name": self.db.name}) return r.json()['LastChapterName'] def push_to_ireader(self): ireader = self.bot.search('掌阅iReader')[0] ireader.send(self.push_url) print(f"push to ireader...") def run(self): print(f"当前追书: {db.name} 已经追到的章节: {db.last_chapter_name}") self.login() self.cron_job() def cron_job(self): while True: now_last_chapter = self.get_last_chapter_name() print(f"目前网上最新章节: {now_last_chapter}") if now_last_chapter != self.db.last_chapter_name: self.push_to_ireader() self.db.last_chapter_name = now_last_chapter self.db.save_to_json() else: print("你已经看到最新章节了....休眠中") time.sleep(60*60)
# -*- coding: utf-8 -*- """ Created on Tue Mar 13 19:09:05 2018 @author: Snailclimb @description使用图灵机器人自动与指定好友聊天 """ from wxpy import Bot, Tuling, embed, ensure_one bot = Bot() my_friend = ensure_one(bot.search('郑凯')) #想和机器人聊天的好友的备注 tuling = Tuling(api_key='72bce33cb2b248a199d07175225a5264') @bot.register(my_friend) # 使用图灵机器人自动与指定好友聊天 def reply_my_friend(msg): tuling.do_reply(msg) embed()
import threading from .config import wechat_mp import time from logzero import logger import sys r = '[\s+\.\!\/_,$%^*(+\"\']+|[+——!,。?、~@#¥%……&*()“”]+' r2 = '(?<!/)&' messages = [] # def qrcode_wechat(uuid, status, qrcode): # with open('wxlogin.png', 'wb') as f: # f.write(qrcode) bot = Bot(cache_path=True, console_qr=1) target = [ensure_one(bot.search(x)) for x in wechat_mp] def run_wechat(): @bot.register(target, SHARING) def handle_receive_msg(msg): global messages try: answer = minidom.parseString(msg.raw['Content'].replace( '\x01', '&')).getElementsByTagName('des')[0].firstChild.nodeValue if answer: messages.append(answer) except: pass
def __init__(self, chat_names): bot = Bot(console_qr=True, cache_path=True) self.chats = bot.search(chat_names) super().__init__()
def get_message_receiver(bot: Bot, puid: str): receiver = bot.search(puid=puid) if not receiver: raise exception.PUIDSearchError() return receiver[0]
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()