def __init__(self, queue, mutex): super().__init__(queue, mutex) self.itchat = itchat.new_instance() itchat.set_logging(loggingLevel=logging.getLogger().level, showOnCmd=False) self.itchat_msg_register() with mutex: self.itchat.auto_login(enableCmdQR=2, hotReload=True, statusStorageDir="storage/%s.pkl" % self.channel_id, exitCallback=self.exit_callback, qrCallback=self.console_qr_code) mimetypes.init(files=["mimetypes"]) self.logger.info("EWS Inited!!!\n---")
def main(): reload(sys) sys.setdefaultencoding("utf-8") itchat.set_logging(True, "output.log", logging.DEBUG) print("=========== Achat start up ===========") itchat.auto_login(hotReload=True) ChatDB.delete_all_contacts() WebRpt.start() itchat.run() WebRpt.stop() # WebRpt.join() print("=========== Achat exit ===========") pass
def poll(self): itchat.set_logging(loggingLevel=logging.DEBUG) while not self.stop_polling: if self.itchat.alive: self.itchat.configured_reply() else: self.done_reauth.wait() self.done_reauth.clear() if self.itchat.useHotReload: self.itchat.dump_login_status("storage/%s.pkl" % self.channel_id) self.itchat.alive = False self.logger.debug("%s (%s) gracefully stopped.", self.channel_name, self.channel_id)
# noinspection PyUnresolvedReferences,PyPep8Naming import Queue as queue import itchat from ..api.chats import Chat, Chats, Friend, Group, MP, User from ..api.consts import SYSTEM from ..api.messages import Message, MessageConfig, Messages, Registered from ..compatible import PY2 from ..compatible.utils import force_encoded_string_output from ..utils import PuidMap from ..utils import enhance_connection, enhance_webwx_request, ensure_list, get_user_name, handle_response, \ start_new_thread, wrap_user_name logger = logging.getLogger(__name__) itchat.set_logging(showOnCmd=False, loggingLevel=logging.NOTSET) class Bot(object): """ 机器人对象,用于登陆和操作微信账号,涵盖大部分 Web 微信的功能:: from .. import * bot = Bot() # 机器人账号自身 myself = bot.self # 向文件传输助手发送消息 bot.file_helper.send('Hello from ..!')
import itchat import random import logging import datetime import pytz import hashlib import threading import requests from daemon import Daemon itchat.set_logging(loggingLevel=logging.DEBUG) class MainHandler(Daemon): def __init__(self, pid_file): super(MainHandler, self).__init__(pid_file) self.at_handler = None self.slash_handler = {} def prepare(self): @itchat.msg_register(itchat.content.TEXT, False, True) def random_reply(msg): if msg.Content and msg.Content[0] == "/": command = msg.Content[1:].split() print(command) if command[0] in self.slash_handler: return self.slash_handler[command[0]](msg, command[1:]) if msg.isAt: command = str.replace(msg.Content, "@trangent\u2005", "") print(command) if self.slash_handler:
def run(self): itchat.set_logging(showOnCmd=self.debug_mode, loggingLevel = self.log_level) robot = itchat.new_instance() def login(): self.info("The Wechat was login @ Process of No.%s " % (self.__uid)) if self.qrfile and os.path.isfile(self.qrfile): os.remove(self.qrfile) self.qrfile = None myself = robot.search_friends() self.uin = myself['Uin'] if self.login_post_fn['myself']: for fn in self.login_post_fn['myself']: fn(myself, self.uin) friends = robot.get_friends() if self.login_post_fn['friends']: for fn in self.login_post_fn['friends']: fn(friends, self.uin) chatrooms = robot.get_chatrooms() if self.login_post_fn['chatrooms']: for fn in self.login_post_fn['chatrooms']: fn(chatrooms, self.uin) mps = robot.get_mps() if self.login_post_fn['mps']: for fn in self.login_post_fn['mps']: fn(mps, self.uin) #获取联系人,并保存 try: self.db["WechatRobotInfoDB"].insert(myself) except: self.error(traceback.format_exc()) for item in friends: try: item['IUin'] = self.uin self.db["WechatRobotFriendsDB"].insert(item) except: self.error(traceback.format_exc()) for item in chatrooms: try: item['IUin'] = self.uin self.db["WechatRobotChatRoomsDB"].insert(item) except: self.error(traceback.format_exc()) for item in mps: try: item['IUin'] = self.uin self.db["WechatRobotMpsDB"].insert(item) except: self.error(traceback.format_exc()) if self.login_post_fn['all']: for fn in self.login_post_fn['all']: fn(robot, self.uin) def logout(): self.info("The Wechat was logout @ Process of No.%s " % (self.__uid)) def qr_callback(**kwargs): try: qrcode = kwargs.get('qrcode') if qrcode: dirname = os.path.join(self.temp_dir, "qr", "service") qrfile = "wxqr_%s.png" % (self.__uid) if os.path.exists(dirname) == False: os.makedirs(dirname) self.qrfile = os.path.join(dirname, qrfile) self.info(self.qrfile) with open(self.qrfile, 'wb') as f: f.write(qrcode) except: self.error(traceback.format_exc()) @robot.msg_register([TEXT, MAP, CARD, NOTE, SHARING]) def text_reply(msg): try: msg["IUin"] = self.uin self.db['WechatRobotChatInfoDB'].insert(msg) # reply = self.get_message(msg.text, msg.user.userName) # msg.user.send('%s' % reply) if self.message_queue: self.message_queue.put_nowait({"user": msg.user.userName, "msg": msg.text, "nick": "", "auser": ""}) except: self.error(traceback.format_exc()) @robot.msg_register([TEXT, MAP, CARD, NOTE, PICTURE, RECORDING, VOICE, ATTACHMENT, VIDEO], isMpChat=True) def text_replay(msg): try: msg["IUin"] = self.uin self.db['WechatRobotMpsChatDB'].insert(msg) except: self.error(traceback.format_exc()) @robot.msg_register(SHARING, isMpChat=True) def text_replay(msg): try: msg["IUin"] = self.uin self.db['WechatRobotMpsSharingDB'].insert(msg) except: self.error(traceback.format_exc()) @robot.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO]) def download_files(msg): try: msg.download(msg.fileName) typeSymbol = { PICTURE: 'img', VIDEO: 'vid', }.get(msg.type, 'fil') self.info('@%s@%s' % (typeSymbol, msg.fileName)) return '@%s@%s' % (typeSymbol, msg.fileName) except: self.error(traceback.format_exc()) @robot.msg_register(FRIENDS) def add_friend(msg): try: msg.user.verify() msg["IUin"] = self.uin self.db['wechat_robot_new_friend'].insert(msg) except: self.error(traceback.format_exc()) @robot.msg_register(TEXT, isGroupChat=True) def text_reply(msg): try: self.db['WechatRobotGroupChatDB'].insert(msg) if msg.isAt: if self.message_queue: self.message_queue.put_nowait({"user": msg.user.userName, "msg": msg.text.split(u'\u2005')[1], "nick": msg.actualNickName, "auser": msg.actualUserName}) # reply = self.get_message(msg.text, msg.user.userName) # msg.user.send(u'@%s\u2005 %s' % ( # msg.actualNickName, reply)) except: self.error(traceback.format_exc()) try: self.info("wechat will running") f = None if self.debug_mode else qr_callback statusStorageDir = os.path.join(self.temp_dir, "wechat") self.info("login temp dir: %s" % statusStorageDir) if os.path.exists(statusStorageDir) == False: os.makedirs(statusStorageDir) statusStorage = os.path.join(statusStorageDir, "%s.pkl" % self.__uid) robot.auto_login(hotReload=True, statusStorageDir=statusStorage, loginCallback=login, exitCallback=logout, qrCallback=f, enableCmdQR=1 if self.debug_mode else False) #自动回复 t = utils.run_in_thread(self.reply_fn, robot) robot.run(self.debug_mode) except: self.error(traceback.format_exc())