示例#1
0
def initItChatInstance():
    newInstance = itchat.new_instance()
    uuid = open_QR(newInstance)
    waitForConfirm = False
    while 1:
        status = newInstance.check_login(uuid)
        if status == '200':
            break
        elif status == '201':
            if waitForConfirm:
                output_info('Please press confirm')
                waitForConfirm = True
        elif status == '408':
            output_info('Reloading QR Code')
            uuid = open_QR(newInstance)
            waitForConfirm = False
    userInfo = newInstance.web_init()
    #non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd)
    #print(userInfo.translate(non_bmp_map))
    newInstance.show_mobile_login()
    newInstance.get_contact()
    output_info('Login successfully as %s'%userInfo['User']['NickName'])
    newInstance.start_receiving()
    
    resultDic = {'instance':newInstance,'UserName':userInfo['User']['UserName'],'picUUID':uuid}

    return resultDic
示例#2
0
 def __init__(self, chatroom=None, level=TRADE_INFO, enableCmdQR=True):
     super(WeChatHandler, self).__init__(level)
     self._CmdQR = enableCmdQR
     self._chatroom = chatroom
     self.client = itchat.new_instance()
     formatter = Formatter('%(asctime)s - %(levelname)s - %(message)s')
     self.setFormatter(formatter)
    def __init__(self, threadID, name, UserNameValue, friendsnum=100):
        threading.Thread.__init__(self)
        self.threadID = threadID
        self.name = name
        self.UserNameValue = UserNameValue
        self.friendsnum = friendsnum

        self.picDir = 'qr/%s.png' % (UserNameValue.replace('@', 'qr')[0:7])
        self.step = 0  #0-初始化   1-完成 向客户发送二维码
        self.newInstance = itchat.new_instance()
示例#4
0
    def __init__(self, instance_name='default_name'):
        super().__init__()
        self.instance_name = instance_name
        self.itchat_name = ''
        self.run_thread = None
        self.instance = itchat.new_instance()

        self.on_receive_callback = None
        self.on_login_callback = None
        self.on_logout_callback = None
        self.on_newfriend_arrive_callback = None
示例#5
0
 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---")
示例#6
0
def init():
    #线程执行后台微信相应程序
    num = str(uuid.uuid1())
    user = User()
    user.uunum = num
    user.wechat_instance = itchat.new_instance()
    global user_instances
    user_instances[num] = user
    t = threading.Thread(target=login, args=(user, ))
    t.start()
    response = make_response(render_template("qr.html", uuid_num=num))
    response.set_cookie('uuid', num)
    return response
示例#7
0
def wechat_login(request):
    newInstance = itchat.new_instance()
    # 获取uuid
    while not newInstance.get_QRuuid():
        time.sleep(1)
    # 下载微信二维码
    newInstance.get_QR(enableCmdQR=False,
                       picDir=QRCODE_IMAGE_PATH,
                       qrCallback=None)
    uuid = newInstance.uuid
    instancesDic[uuid] = newInstance
    data = {'qrcode_uuid': uuid, 'msg': '操作成功', 'msg_code': 100000}
    return JsonResponse(data)
示例#8
0
    def __init__(self, nickName):
        self.nickName = nickName

        self.mysqlHelper = MysqlHelper(CONFIG.connectionDict)
        self.MysqlInspect()
        self.instance = itchat.new_instance()
        self.schemeTimer = SchemeTimerThead()

        self.userInfo = self.mysqlHelper.getOne('users',
                                                column='nickName',
                                                value=nickName)
        self.userType = self.userInfo['userType']
        self.autoLogin = self.userInfo['autoLogin']
        self.autoReply = self.userInfo['autoReply']
        self.fileHelper = self.userInfo['filehelper']
        self.separator = ',*,'
        self.autoReplyGroup = list(self.userInfo['autoReplyGroup'].split(
            self.separator)) if self.userInfo['autoReplyGroup'] else []

        self.cmdQR = None
        self.loading = None
        self.alive = None
        self.online = None
        self.receiveMsg = None

        self.userName = None
        self.uin = None
        self.robotNickName = None
        self.robotUserName = None
        self.FTUserName = None
        self.FTNickName = None

        self.frdList = []
        self.frdInfoList = []
        self.chatroomList = []
        self.chatroomMembers = []

        self.cmds = getattr(CONFIG, 'cmdsLv' + str(self.userType))
        self.remoteCmds = getattr(CONFIG, 'remoteCmdsLv' + str(self.userType))

        # 日志路径
        self.savedir = os.path.dirname(
            os.path.abspath(__file__)) + r'/users/%s/' % self.nickName
        self.chatDir = self.savedir + CONFIG.chatDir
        self.cmdDir = self.savedir + CONFIG.cmdDir
        self.errDir = self.savedir + CONFIG.errDir
        self.chatroomDir = self.savedir + CONFIG.chatroomDir
        self.cmdFile = self.cmdDir + 'cmdFile.txt'
        self.errFile = self.errDir + 'errFile.txt'
        self.sourcedir = os.path.dirname(
            os.path.dirname(os.path.abspath(__file__))) + '/source/'
示例#9
0
def main():
    chatroom = input("Chatroom: ")
    msg = input("Message: ")
    hour = int(input("Hour: "))
    minute = input("Minute [{}]: ".format(DEFAULT_MINUTE))
    minute = int(minute or DEFAULT_MINUTE)
    latency = input("Latency(ms) [{}]: ".format(DEFAULT_LATENCY))
    latency = int(latency or DEFAULT_LATENCY)

    sess = itchat.new_instance()
    sess.auto_login()
    user_name = get_user_name_of_chatroom(sess, chatroom)
    wait_to(hour, minute, latency)
    sess.send_msg(msg, toUserName=user_name)
    sess.logout()
示例#10
0
 def __init__(self, env='DEV', id='robot_id', duty='robot', enableCmdQR=False, qrCallback=False, hotReload=False, blockThread=False):
     self.env = env
     if id=='robot_id':
         self.id = 'robot_'+ str(int(time.time()))
         # self.id = 'robot_id'
     else:
         self.id = id
     self.name = ''
     self.duty = duty
     self.data_dir = os.path.join(os.path.split(os.path.realpath(__file__))[0], 'data')
     self.temp_dir = os.path.join(os.path.split(os.path.realpath(__file__))[0], 'temp')
     self.enableCmdQR = enableCmdQR
     self.hotReload = hotReload
     self.qrCallback = qrCallback
     self.blockThread = blockThread
     self.robot = itchat.new_instance()
示例#11
0
    def __init__(self):
        self.wechat = itchat.new_instance()
        self.storageClass = self.wechat.storageClass
        self.get_friends = self.wechat.get_friends
        self.msg_register = self.wechat.msg_register
        self.TYPE = itchat.content.INCOME_MSG
        self.friend_list = []

        self.is_logging = False

        if not os.path.exists(message_dict):
            self.message_map = {}
            with open(message_dict, 'w') as f:
                f.write(json.dumps(self.message_map))
        else:
            with open(message_dict, 'r') as fr:
                self.message_map = json.loads(fr.read())
示例#12
0
    def __init__(self, msg, threadID, name, counter):
        threading.Thread.__init__(self)
        self.msg = msg
        self.threadID = threadID
        self.name = name
        self.counter = counter
        self.newInstance = itchat.new_instance()
        self.qrDir = r'F:\PythonSpace\WXServer\kefu' + self.msg[
            'FromUserName'] + '.png'

        @self.newInstance.msg_register([TEXT, MAP, CARD, NOTE])
        def note_receive(msg):
            if msg['Status'] == 4:
                if '消息已发出,但被对方拒收了' in msg['Content']:
                    print("黑名单%s-- " % msg['User']['NickName'])
                    self.newInstance.set_alias(
                        msg['FromUserName'],
                        'A000僵尸-%s' % msg['User']['NickName'])
                elif '开启了朋友验证' in msg['Content']:
                    print("开启了好友验证%s-- " % msg['User']['NickName'])
                    self.newInstance.set_alias(
                        msg['FromUserName'],
                        'A000需验证_%s' % msg['User']['NickName'])
示例#13
0
 def login(self):
     ins = itchat.new_instance()
     ins.login()
     return ins
示例#14
0
"""
python_wechat.py by xianhu
主要包括如下功能:
(1) 自动提醒群红包
(2) 自动监测被撤回消息
(3) 群关键字提醒,群被@提醒
"""

import time
import itchat
import logging
from itchat.content import *

# 初始化
my = itchat.new_instance()
my.auto_login(hotReload=False, enableCmdQR=2)

# my还包括的以下属性,注意用点.查看:
# (1) alive 是否还活着,isLogging 是否已登陆
# (2) loginInfo 登陆信息,其中的User属性为自己的信息User字典类,包括UserName, NickName, RemarkName, Sex(1 or 2), Signature, Province, City等
# (3) memberList 通讯录列表,每一项为一个User字典类,包括UserName, NickName, RemarkName, Sex(1 or 2), Signature, Province, City等
# (4) chatroomList 群聊列表,每一项为一个Chatroom字典类,包括UserName, NickName, RemarkName, MemberCount, MemberList, Self等
# (5) mpList 订阅号列表,每一项为一个MassivePlatform字典类,包括UserName, NickName等

my.global_keys = ["创业", "人工智能", "企业服务"]
my.to_user_name = "filehelper"      # 消息接受者
my.update_time = time.time()        # 信息更新时间
my.msg_store = {}                   # 消息存储队列
my.friends = {}                     # 好友字典列表
my.groups = {}                      # 群聊字典列表
示例#15
0
import sys
import time

import itchat
from config import oss_url_2, oss_url_1, sms_msg_1, add_friend_msg
from itchat.content import *
from robot.service import service_handle
from robot.util.redis_conf import predis
from robot.util.oss import upload_file_images_to_oss, itchat_upload_images_to_oss, get_random_name
from tuling_jiqiren.tuling_1 import robot_reply
from robot import constants

reload(sys)
sys.setdefaultencoding('utf8')

new_instance_b = itchat.new_instance()


def get_login_robot():
    myself_info = new_instance_b.get_friends(update=True)[0]
    return myself_info["NickName"], myself_info["Uin"]


@new_instance_b.msg_register([TEXT, MAP, CARD, NOTE, SHARING])
def text_reply(msg):
    print "66666666666666666666666", msg['Type']
    print msg
    new_instance_b.send('%s' % (msg['Text']), msg['FromUserName'])


@new_instance_b.msg_register([SHARING], isGroupChat=True)
示例#16
0
def create_itchat():
    '''
    构建一个新的itcht实例
    '''
    new_itchat = itchat.new_instance()

    @new_itchat.msg_register([TEXT, MAP], isGroupChat=True)
    def text_reply(msg):
        '''保存文字类信息'''
        log(zh_str(msg))
        group = msg.User.NickName
        data = {
            'id': msg.NewMsgId,
            'type': msg.Type,
            'create_time': float(msg.CreateTime),
            'group': group,
            'group_id': "group_name",
            'user_actual_name': msg.ActualNickName,
            'content': msg.Text,
        }
        group_msg = GroupMsg.create(data)
        log(zh_str(group_msg.to_dict()), 'text.txt')
        print '%s: %s' % (msg.type, msg.text)

    @new_itchat.msg_register([NOTE], isGroupChat=True)
    def text_reply(msg):
        '''保存系统通知类信息'''
        # log(zh_str(msg))
        group = msg.User.NickName
        data = {
            'id': msg.NewMsgId,
            'type': msg.Type,
            'create_time': float(msg.CreateTime),
            'group': group,
            'group_id': "group_name",
            'user_actual_name': msg.ActualNickName,
            'content': msg.Text,
        }
        group_msg = GroupMsg.create(data)
        if u"加入" in msg.Text and u"群聊" in msg.Text:
            # 更新群聊成员信息,一键喊话:
            get_user_list(new_itchat, group)
            log('新人来了', 'xinreng.txt')
            if group in []:
                pass
        # log(zh_str(group_msg.to_dict()), 'text.txt')
        print '%s: %s' % (msg.type, msg.text)

    @new_itchat.msg_register(CARD, isGroupChat=True)
    def text_reply(msg):
        '''保存分名片类信息'''
        log(zh_str(msg))
        group = msg.User.NickName
        data = {
            'id': msg.NewMsgId,
            'type': msg.Type,
            'create_time': float(msg.CreateTime),
            'group': group,
            'group_id': "group_name",
            'user_actual_name': msg.ActualNickName,
            'content': msg.Text['NickName'],
        }

        card_data = msg.Text
        card_data['id'] = msg.NewMsgId
        card = Card.create(card_data)
        group_msg = GroupMsg.create(data)
        log(zh_str(card.to_dict()), 'card.txt')
        log(zh_str(group_msg.to_dict()), 'text.txt')
        print '%s: %s' % (msg.type, msg.text)

    @new_itchat.msg_register(SHARING, isGroupChat=True)
    def text_reply(msg):
        '''保存分享类信息'''
        group = msg.User.NickName
        data = {
            'id': msg.NewMsgId,
            'type': msg.Type,
            'create_time': float(msg.CreateTime),
            'group': group,
            'group_id': "group_name",
            'user_actual_name': msg.ActualNickName,
            'content': msg.Text,
            'sharing_url': msg.Url
        }
        group_msg = GroupMsg.create(data)
        # sharing_msg = Sharing.create(msg)
        # log(zh_str(msg))
        log(zh_str(group_msg.to_dict()), 'text.txt')
        # log(zh_str(sharing_msg.to_dict()), 'sharing.txt')
        print '%s: %s' % (msg.type, msg.text)

    @new_itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO],
                             isGroupChat=True)
    def download_files(msg):
        '''下载一些文件'''
        group = msg.User.NickName
        data = {
            'id': msg.NewMsgId,
            'type': msg.Type,
            'create_time': float(msg.CreateTime),
            'group': group,
            'group_id': "group_name",
            'user_actual_name': msg.ActualNickName,
        }
        file_type = msg.type

        file_path = os.path.join(data_path, group, file_type)
        if not os.path.exists(file_path):
            os.makedirs(file_path)
        download_path = os.path.join(file_path, msg.fileName)
        msg.download(download_path)
        data['content'] = os.path.join('data', group, file_type, msg.fileName)
        group_msg = GroupMsg.create(data)

        msg['Text'] = '下载方法'
        # log(zh_str(msg), 'file.txt')
        # log(zh_str(group_msg.to_dict()), 'down_load.txt')
        print '@%s@%s' % (msg.type, msg.fileName)

    return new_itchat
示例#17
0
def multipUser():
    newInstance = itchat.new_instance()
    newInstance.auto_login(hotReload=True, statusStorageDir='newInstance.pkl')
    newInstance.run()
#global value
# 步骤的提示语
global dict_stepinfo
# 启动脚本前的提示语
global helpinfo
# 客户列表
global list_customer
# 用户数量id
global cnt
# 客户线程
global client_list

mutex = threading.Lock()
picDir = 'qr_test.png'
G_UserNameValue = None
mainInstance = itchat.new_instance()
threads = []
splitstr = '_'
parameter = '[parameter]'
helpinfo = ''
dict_stepinfo = {}
list_customer = []
cnt = 0
client_list = []
strtm = time.strftime('%Y_%m_%d_%H_%M_%S', time.localtime(time.time()))
outputfile = open("log/log_%s.txt" % strtm, "a+")


################################################类
#客户线程类
class itchat_client(threading.Thread):
示例#19
0
import logging
from threading import Thread
from datetime import datetime
from time import sleep
import requests
import itchat

from itchat.components.register import logger
from itchat.log import set_logging

import config

KEY = 'ad65aa94781643e682cd81a629fdecc4'

wechat_assistant = itchat.new_instance()

tasks = []


def append_task(func):
    tasks.append(Thread(target=func))
    return func


def run(self, debug=False, block_thread=True):
    logger.info('Start auto replying.')
    setattr(self, 'debug', debug)
    for task in tasks:
        task.start()
    if debug:
        set_logging(loggingLevel=logging.DEBUG)
示例#20
0
def create_itchat():
    new_itchat = itchat.new_instance()

    @new_itchat.msg_register([TEXT, MAP, NOTE], isGroupChat=True)
    def text_reply(msg):
        '''保存文字类信息'''
        log(zh_str(msg))

        group_dict = Group.name_id_dict()

        group = msg.User.NickName
        group_id = group_dict.get(group, 'group_name')
        data = {
            'id': msg.NewMsgId,
            'type': msg.Type,
            'create_time': float(msg.CreateTime),
            'group': group,
            'group_id': group_id,
            'user_actual_name': msg.ActualNickName,
            'content': msg.Text,
        }
        group_msg = GroupMsg.create(data)
        log(zh_str(group_msg.to_dict()), 'text.txt')
        print '%s: %s' % (msg.type, msg.text)

    @new_itchat.msg_register(CARD, isGroupChat=True)
    def text_reply(msg):
        '''保存分名片类信息'''
        log(zh_str(msg))
        group_dict = Group.name_id_dict()

        group = msg.User.NickName
        group_id = group_dict.get(group, 'group_name')
        data = {
            'id': msg.NewMsgId,
            'type': msg.Type,
            'create_time': float(msg.CreateTime),
            'group': group,
            'group_id': group_id,
            'user_actual_name': msg.ActualNickName,
            'content': msg.Text['NickName'],
        }

        card_data = msg.Text
        card_data['id'] = msg.NewMsgId
        card = Card.create(card_data)
        group_msg = GroupMsg.create(data)
        log(zh_str(card.to_dict()), 'card.txt')
        log(zh_str(group_msg.to_dict()), 'text.txt')
        print '%s: %s' % (msg.type, msg.text)

    @new_itchat.msg_register(SHARING, isGroupChat=True)
    def text_reply(msg):
        '''保存分享类信息'''
        group_dict = Group.name_id_dict()
        group = msg.User.NickName
        group_id = group_dict.get(group, 'group_name')
        data = {
            'id': msg.NewMsgId,
            'type': msg.Type,
            'create_time': float(msg.CreateTime),
            'group': group,
            'group_id': group_id,
            'user_actual_name': msg.ActualNickName,
            'content': msg.Text,
        }
        group_msg = GroupMsg.create(data)
        sharing_msg = Sharing.create(msg)
        # log(zh_str(msg))
        log(zh_str(group_msg.to_dict()), 'text.txt')
        log(zh_str(sharing_msg.to_dict()), 'sharing.txt')
        print '%s: %s' % (msg.type, msg.text)

    @new_itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO],
                             isGroupChat=True)
    def download_files(msg):
        '''下载一些文件'''
        group_dict = Group.name_id_dict()

        group = msg.User.NickName
        group_id = group_dict.get(group, 'group_name')
        data = {
            'id': msg.NewMsgId,
            'type': msg.Type,
            'create_time': float(msg.CreateTime),
            'group': group,
            'group_id': group_id,
            'user_actual_name': msg.ActualNickName,
        }
        file_type = msg.type
        file_path = os.path.join(basedir, 'data', group, file_type)
        if not os.path.exists(file_path):
            os.makedirs(file_path)
        fileName = os.path.join(file_path, msg.fileName)
        msg.download(fileName)
        data['content'] = fileName
        group_msg = GroupMsg.create(data)

        msg['Text'] = '下载方法'
        log(zh_str(msg), 'file.txt')
        log(zh_str(group_msg.to_dict()), 'down_load.txt')
        print '@%s@%s' % (msg.type, msg.fileName)

    return itchat
示例#21
0
from wxHelper import *
import itchat


if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG)
    logging.getLogger("requests").setLevel(logging.WARNING)
    # logging.config.fileConfig("logger.conf")
    # if not sys.platform.startswith('win'):
    #     import coloredlogs
    #     coloredlogs.install(level='DEBUG')

    wxInst = itchat.new_instance()
    bot = wxHelper(wxInst)

    while True:
        time.sleep(1)
        cmd = input("CMD:")
        if cmd=='quit':
            wxInst.logout()
            wxInst.dump_login_status()
            bot.stop_batchsend()
            logging.info("quitting....")
            exit()
        elif cmd=='save':
            bot.saveContact()
        elif cmd=='send':
            bot.start_batchsend()
        elif cmd=='stop':
            wxInst.logout()
            wxInst.dump_login_status()
示例#22
0
import requests
import itchat
import time
import random
import os
from aip import AipSpeech
from pydub import AudioSegment
""" 你的 APPID AK SK """
APP_ID = '10544044'
API_KEY = 'BQBg3oGPnrFrAulmsDazTPpL'
SECRET_KEY = '87b82d43edaed4be69fc4bed803f0feb'

client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
KEY = '8edce3ce905a4c1dbb965e6b35c3834d'  # Turing Machine Online Access Token
snailRobot = itchat.new_instance()
commandRobot = itchat.new_instance()

number_version = [
    "2017-11-25 16:21我们第一次联系\r\n2017-12-05 00:02 我第一次说想你\r\n2017-12-09 00:46 冲动地说了对你的喜欢",
    "到情人节恰好81天,久久归真(~~)", "数字一下微信记录", "喜欢出现668条", "厉害出现268条", "想你出现198次",
    "晚安出现189条", "梦出现了162条", "呼唤了小蜗牛67次", "..... 还有好多好多关键词",
    "哦对了, 嗯这次出现了4141次(好多)......", "我一直很喜欢数字,因为很多数字有魔力",
    "虽然这一次我强行统计的这些数字并不见得有什么magic", "但是它们如此真实而有趣而且就在那不经意的长大。",
    "甚至不觉间感受了这些数字的分量,就好像我对你的喜欢一点点一天天在累积....",
    "我相信数字有魔力,也许等到量变到质变的那一天,它们就会展现...",
    "希望在以后每一个情人节的时候,看着这些数字不断变大,就像我们的情谊会不断滋长.......",
    "Let there be love ~, that is more magical than numbers"
]
romantic_version = [
    "一直都在对你说遇见你是我的幸运", "当要对你说得什么时,就会莫名想起你带给我的那些第一次",
    "第一次头疼你陪我给我讲拥抱的感受\r\n第一次给我起外号\r\n第一次知道白开水的叹息\r\n第一次看你画\r\n第一次听你那么多经历",
示例#23
0
 def auto_login(self):
     ins = itchat.new_instance()
     ins.auto_login(enableCmdQR=2,
                    hotReload=True,
                    statusStorageDir=self.status_storage_dir)
     return ins
示例#24
0
import itchat
from itchat.content import TEXT
from config import *
import traceback
import os
import subprocess

app = itchat.new_instance()
process_cpf = 1


@app.msg_register(TEXT)
def main(msg):
    if msg.text == '0':
        return HELP_MSG
    elif msg.text == '1':
        if subprocess.Popen.poll(process_cpf) is not None:
            with open(os.devnull, 'w') as nohup:
                global process_cpf
                process_cpf = subprocess.Popen(CPF_RUN_CMD,
                                               shell=True,
                                               stdout=nohup)
        return '刷单程序已启动'
    elif msg.text == '2':
        # 判断测评符是否正在刷单
        if subprocess.Popen.poll(process_cpf) is None:
            subprocess.Popen('kill -9 %d' % process_cpf.pid)
        return '刷单程序已关闭'
    else:
        return HELP_MSG
示例#25
0
文件: app.py 项目: liuluyeah/itchat-2
def index():
    newInstance = itchat.new_instance()
    mychat = newInstance
    return redirect('static/index.html')
示例#26
0
                        'insert into 58_robot_3 (im, time, question, answer) values ("Wechat", "{}", "{}", "{}")'
                        .format(msg_time, text, info))
                    self.db.commit()
                except:
                    self.db.rollback()
                newInstance.send(info, msg['User']['UserName'])


def main():
    t1 = WeChat()
    t2 = WeChat()
    t3 = WeChat()
    t4 = WeChat()
    t5 = WeChat()
    t6 = WeChat()
    t7 = WeChat()
    t8 = WeChat()
    for t in [t1, t2, t3, t4, t5, t6, t7, t8]:
        t.start()
        t.join()


if __name__ == '__main__':
    pkl_dir = os.path.dirname(os.path.abspath(__file__))
    name, py = os.path.basename(__file__).split('.')
    newInstance = itchat.new_instance()
    newInstance.auto_login(hotReload=True,
                           statusStorageDir='%s/pkls/%s.pkl' % (pkl_dir, name))
    main()
    newInstance.run()
 def __init__(self, noticeGroup="李田所粉丝群"):
     self.noticeGroup = noticeGroup
     self.instance = itchat.new_instance()
     self.status = 0  # 0==available;1==login;2==running;
     self.login()
     self.start()
示例#28
0
 def run(self):
     itchat.auto_login(hotReload=self.hotReload)
     self.friends = itchat.get_friends()
     self.current_name = self.friends[0].NickName
     os.chdir(self.base_path + '/' + self.current_name)
     itchat.new_instance().run()
示例#29
0
# -*- coding: utf-8 -*-
# @Time    : 2018/9/4 22:55
# @Author  : 
# @File    : Orange.py
# @Software: PyCharm Community Edition

import itchat
from itchat.content import *
import re
from orange_databse import *
from orange_log import logger
import schedule
import time

ora=itchat.new_instance()
MSG_TURN={}
orange_info='正宗石门柑橘,自家种的新鲜橘子,一件10斤50元包邮。'
main_wechat_name='西边有片云'

def get_content(content):
    #替换掉收到的信息中的一些符号
    string_c = re.sub("[\s+_,$%^*(\"\']+|[+—!,。?、~@#¥%&*()]+", "",content)
    org_compile=re.compile(r"^我要买橘子(.*)")
    dingdan_compile=re.compile(r"^我要订(.*)")
    dizhi_compile=re.compile(r"^配送信息(.*)")
    chaxun=re.compile(r"^查询订单(.*)")
    chaxun_not=re.compile(r"^查询未发订单(.*)")
    dingdanjilu=re.compile(r"^-(.*)")
    xiugai=re.compile(r"^已发(.*)")
    shanchu = re.compile(r"^删除(.*)")
from itchat.content import *

msg_store = collections.OrderedDict()
timeout = 600
sending_type = {'Picture': 'img', 'Video': 'vid'}
data_path = 'data'
nickname = ''
bot = None

if __name__ == '__main__':
    if not os.path.exists(data_path):
        os.mkdir(data_path)
    # if the QR code doesn't show correctly, you can try to change the value
    # of enableCdmQR to 1 or -1 or -2. It nothing works, you can change it to
    # enableCmdQR=True and a picture will show up.
    bot = itchat.new_instance()
    bot.auto_login(hotReload=True, enableCmdQR=2)
    nickname = bot.loginInfo['User']['NickName']

def clear_timeouted_message():
    now = time.time()
    count = 0
    for k, v in list(msg_store.items()):
        if now - v['ReceivedTime'] > timeout:
            count += 1
        else:
            break
    for i in range(count):
        item = msg_store.popitem(last=False)

def get_sender_receiver(msg):
示例#31
0
    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())