예제 #1
0
def qixi_reply():
    @itchat.msg_register
    def get_pic(msg):
        #print itchat.get_userinfo()
        if msg.get('Type', '') == 'Text':
            txt = msg['Text']
            # is_birthday = (txt.isdigit() and len(txt)==8)
            is_at = False;
            if txt[0] =="@":
                is_at = True;
                txt = txt[1:];
            if( is_at and len(txt)>=4 and len(txt)<=24 ):
                img = http_get_mima_img( txt );
                # print img;
                if os.path.exists( img ):
                    itchat.send(u'哈哈,你的密语图片生成了,发给你的朋友让他猜猜看', msg['FromUserName']);
                    return '@img@'+img;
                else:
                    itchat.send(u'有点忙,请稍候在试试', msg['FromUserName']);
            elif txt == '1':
                itchat.send(u'视线15°斜看密语图片,你会发现密码', msg['FromUserName']);
            else:
                itchat.send(u'请输入你的七夕密语,以@开头,如:\n\n@静静我爱你\n\n最少4个字,至多24字\n\n回复『 1 』,获取密语答案', msg['FromUserName']);

    @itchat.msg_register('Friends')
    def add_friend(msg):
        itchat.add_friend(**msg['Text']);
        itchat.get_contract();
        itchat.send(u'亲\n\n请输入你的七夕密语,以@开头,如:\n\n@静静我爱你\n\n最少4个字,至多24字\n\n回复『 1 』,获取密语答案', msg['RecommendInfo']['UserName']);

    itchat.run()
예제 #2
0
def main():
    #itchat.auto_login(hotReload=True, enableCmdQR=2, statusStorageDir='account.pkl')  #通过命令行打印登入二维码
    global robot_enabled, owner
    robot_enabled = len(sys.argv) > 1 and sys.argv[1]
    itchat.auto_login(hotReload=True)
    owner = itchat.get_friends()[0]
    itchat.run()
예제 #3
0
파일: bot.py 프로젝트: chenhang/ItChat
def complex_reply():
    @itchat.msg_register(['Text', 'Map', 'Card', 'Sharing'], isGroupChat=True)
    def text_reply(msg):
        url = ''
        if msg['Url']: url = ' - ' + htmlParser.unescape(msg['Url'])
        for destination in destinations(msg):
            if url == '':
                itchat.send('%s: \n%s%s' % (msg['ActualDisplayName'], msg['Text'], url), destination)
            else:
                itchat.send('%s共享了一个链接: \n%s%s'.decode('utf-8', 'replace') % (msg['ActualDisplayName'], msg['Text'], url), destination)
    @itchat.msg_register(['Note'], isGroupChat=True)
    def text_reply(msg):
        for destination in destinations(msg):
            itchat.send(msg['Text'], destination)

    # @itchat.msg_register(['Note','Card', 'Sharing'])
    # def text_reply(msg):
    #     print(msg)
    #     itchat.send('@url@%s' % (msg['Content']), msg['FromUserName'])

    @itchat.msg_register(['Picture', 'Recording', 'Attachment', 'Video', 'Gif'], isGroupChat=True)
    def download_files(msg):
        dict = {'Picture': "图片", "Gif": "表情", "Recording": "录音", "Video": "小视频", "Attachment": "文件"}
        fileDir = './storage/%s%s' % (msg['Type'], int(time.time()))
        if msg['Type'] == 'Gif': fileDir += '.gif'
        msg['Text'](fileDir)
        for destination in destinations(msg):
            itchat.send('%s发送了%s'.decode('utf-8', 'replace') % (msg['ActualDisplayName'], dict[msg['Type']].decode('utf-8', 'replace')), destination)
            print itchat.send('@%s@%s' % ('img' if msg['Type'] == 'Picture' or msg['Type'] == 'Gif' else 'fil', fileDir),
                        destination)



    update_groups()
    itchat.run()
예제 #4
0
def musicbox():
    @itchat.msg_register
    def simple_reply(msg):
        if msg.get('Type', '') == 'Text':
            #return 'I received: %s'%msg.get('Content', '')
            content = msg.get('Content', '')
            content_list = content.split()
            if len(content_list) == 1:
                song_name = content
                musicbox = netease.RasWxMusicbox(song_name)
                music_list = musicbox.gen_music_list()
                return music_list
            if len(content_list) == 2:
                try:
                    song_name = content_list[0]
                    song_index = int(content_list[1])
                    musicbox = netease.RasWxMusicbox(song_name)
                    music_info = musicbox.get_music(song_index)
                    mp3_url = music_info['mp3_url']
                    song_info = u'正在播放:\n ' \
                        + u'专辑: ' + music_info['album_name'] + '\n'\
                        + u'演唱: ' + music_info['artist'] + '\n' \
                        + u'歌曲: ' + music_info['song_name']
                    play(mp3_url)
                    return song_info
                except:
                    return u'输入有误,请重新输入'
            else:
                return u'输入有误,请重新输入'
    itchat.run()
예제 #5
0
파일: run.py 프로젝트: ysc8620/itchat
def complex_reply():

    # @itchat.msg_register(['Text', 'Map', 'Card', 'Note', 'Sharing'])
    # def text_reply(msg):
    #     itchat.send('%s: %s'%(msg['Type'], msg['Text']), msg['FromUserName'])

    # @itchat.msg_register(['Picture', 'Recording', 'Attachment', 'Video'])
    # def download_files(msg):
    #     fileDir = '%s%s'%(msg['Type'], int(time.time()))
    #     msg['Text'](fileDir)
    #     itchat.send('%s received'%msg['Type'], msg['FromUserName'])
    #     itchat.send('@%s@%s'%('img' if msg['Type'] == 'Picture' else 'fil', fileDir), msg['FromUserName'])

    @itchat.msg_register('Friends')
    def add_friend(msg):
        itchat.add_friend(**msg['Text'])
        itchat.get_contract()
        itchat.send('Nice to meet you!', msg['RecommendInfo']['UserName'])

    @itchat.msg_register('Text', isGroupChat = True)
    def text_reply(msg):
        print msg
        #itchat.send(u'@%s I received: %s'%(msg['ActualNickName'], msg['Content']), msg['FromUserName'])

    # auto reply msg
    @itchat.msg_auto_reply
    def auto_reply():
        #print time.time()
        return True

    itchat.run()
예제 #6
0
파일: run.py 프로젝트: xzjs/ItChat
def complex_reply():
    @itchat.msg_register(['Text', 'Map', 'Card', 'Note', 'Sharing'])
    def text_reply(msg):
        # itchat.send('%s: %s' % (msg['Type'], msg['Text']), msg['FromUserName'])
        str = ''
        if msg['Content'] == 'report':
            str = rA.get_sentence()
        if msg['Content'] == 'liu':
            str = rA.liu()
        itchat.send(str, msg['FromUserName'])

    @itchat.msg_register(['Picture', 'Recording', 'Attachment', 'Video'])
    def download_files(msg):
        fileDir = '%s%s' % (msg['Type'], int(time.time()))
        msg['Text'](fileDir)
        itchat.send('%s received' % msg['Type'], msg['FromUserName'])
        itchat.send('@%s@%s' % ('img' if msg['Type'] == 'Picture' else 'fil', fileDir), msg['FromUserName'])

    @itchat.msg_register('Friends')
    def add_friend(msg):
        itchat.add_friend(**msg['Text'])
        itchat.get_contract()
        itchat.send('Nice to meet you!', msg['RecommendInfo']['UserName'])

    @itchat.msg_register('Text', isGroupChat=True)
    def text_reply(msg):
        # if msg['isAt']:
        #     itchat.send(u'@%s\u2005I received: %s'%(msg['ActualNickName'], msg['Content']), msg['FromUserName'])
        rA.collect(msg)

    itchat.run()
예제 #7
0
파일: run.py 프로젝트: xzjs/ItChat
def simple_reply():
    @itchat.msg_register
    def simple_reply(msg):
        if msg.get('Type', '') == 'Text':
            return 'I received: %s' % msg.get('Content', '')

    itchat.run()
예제 #8
0
def main():
    @itchat.msg_register(itchat.content.TEXT)
    def print_content(msg):
        print(msg['Text'])
        print(msg['FromUserName'])
        itchat.send(msg['Text'], 'filehelper')
        #itchat.send(msg['Text'], msg['FromUserName'])

    itchat.auto_login(hotReload=True, enableCmdQR=1)
    itchat.run()
예제 #9
0
def WechatSend():
    @itchat.msg_register(itchat.content.TEXT)
    def print_content(msg):
        # print(msg['Text'])
        # print(msg['FromUserName'])
        itchat.send(msg['Text'] + msg['FromUserName'], 'filehelper')
        # itchat.send(msg['Text'], msg['FromUserName'])
        # itchat.send('hhhhh', 'filehelper')

    itchat.auto_login(hotReload=True)
    itchat.run()
예제 #10
0
파일: wx.py 프로젝트: 1147832740/test
def wxrunner():
    itchat.auto_login(enableCmdQR=2, hotReload=True)

    @itchat.msg_register(TEXT, isFriendChat=True)
    def text_reply(msg):
        if msg.FromUserName == '@30cb980f23a21637ee959f5c7f74ac7b7f25296f1481eb4ec5ebde078a01d0ec':
            msg.user.send('老婆,我爱你!')

        if msg.FromUserName == '@41a4f77c5458f0c0a18e0cf9ea60dda2' and msg.ToUserName == '@41a4f77c5458f0c0a18e0cf9ea60dda2':
            msg.user.send('哈哈')


    itchat.run()
예제 #11
0
파일: iqiyi.py 프로젝트: codebean/ItChat
def test_reply():
    @itchat.msg_register([TEXT])
    def get_pic(msg):
	if msg['Text']=="ok": 
            itchat.send(u'ok', msg['FromUserName'])
    
    @itchat.msg_register('Friends')
    def add_friend(msg):
        itchat.add_friend(**msg['Text'])
        itchat.get_contract()
        itchat.send(u'爱奇艺VIP 账号13539956455  密码fujoshi123\n\n爱奇艺VIP 账号13873248477  密码jiro201151\n\n爱奇艺VIP 账号15912592375  密码zxc521523\n\n爱奇艺VIP 账号18657196137  密码gmail.com\n\n爱奇艺VIP 账号18629016101  密码slh8023.\n\n爱奇艺VIP 账号18574303268  密码ting1314520\n\n爱奇艺VIP 账号18620300513  密码sammie123\n\n爱奇艺VIP 账号15008159500  密码jxm19880713\n\n爱奇艺VIP 账号18215523978  密码8298290\n\n爱奇艺VIP 账号15153768558  密码zhang523\n\n亲~这些都是我辛苦收集来的哦。不能登的。晚些收集后还会更新,多留意哦。', msg['RecommendInfo']['UserName'])

    itchat.run()
예제 #12
0
파일: bot.py 프로젝트: tingpan/IchatBot
def complex_reply():

    @itchat.msg_register(['Text', 'Map', 'Sharing'], isGroupChat=True)
    def text_reply(msg):
        print msg
        url = ''
        if msg['Url']: url = ' - ' + htmlParser.unescape(msg['Url'])
        for destination in destinations(msg):
            if url == '':
                itchat.send('%s: \n%s%s' % (msg['ActualDisplayName'], msg['Text'], url), destination)
            else:
                itchat.send(u'%s共享了一个链接: \n%s\n%s' % (msg['ActualDisplayName'], msg['Text'], url), destination)

    # @itchat.msg_register(['Note'], isGroupChat=True)
    # def text_reply(msg):
    #     for destination in destinations(msg):
    #         itchat.send(msg['Text'], destination)

    # @itchat.msg_register(['Note','Card', 'Sharing'])
    # def text_reply(msg):
    #     print(msg)
    #     itchat.send('@url@%s' % (msg['Content']), msg['FromUserName'])

    @itchat.msg_register(['Card'], isGroupChat=True)
    def card_reply(msg):
        print msg
        print msg['RecommendInfo']
        info = msg['RecommendInfo']
        wechat_number = u'微信号暂时不可得' if info['Alias'] == None or info['Alias'] == "" else info['Alias']
        for destination in destinations(msg):
            itchat.send( u'%s共享了一个名片:\n昵称:%s\n微信号:%s' % (msg['ActualDisplayName'], info['NickName'], wechat_number), destination)

    @itchat.msg_register(['Picture', 'Recording', 'Attachment', 'Video', 'Gif'], isGroupChat=True)
    def download_files(msg):
        dict = {'Picture': u"图片", "Gif": u"表情", "Recording": u"录音", "Video": u"小视频", "Attachment": u"文件"}
        fileDir = './storage/%s%s' % (msg['Type'], int(time.time()))
        flag = True
        if msg['Type'] == 'Gif': fileDir += '.gif'
        msg['Text'](fileDir)
        for destination in destinations(msg):
            itchat.send(u'%s发送了%s' % (msg['ActualDisplayName'], dict[msg['Type']]), destination)
            if not itchat.send('@%s@%s' % ('img' if msg['Type'] == 'Picture' or msg['Type'] == 'Gif' else 'fil', fileDir), destination):
                flag = False
        if not flag:
            for destination in destinations(msg):
                itchat.send(u'[暂不支持的官方表情]', destination)

    update_groups()
    itchat.run()
예제 #13
0
def zuduidushu_reply():
    @itchat.msg_register
    def default_reply(msg):
        # itchat.send_image('@[email protected]', msg['RecommendInfo']['UserName']);
        # return '@[email protected]';
        pass

    @itchat.msg_register('Friends')
    def add_friend(msg):
        itchat.add_friend(**msg['Text']);
        itchat.get_contract();
        itchat.send(u'我是小书童,终于等到愿意改变的你,从今天开始你就是我的主人了,有什么吩咐尽快说!', msg['RecommendInfo']['UserName']);
        time.sleep(5);
        itchat.send(u'主人,为了能陪你完成读书的计划,偶们需要完成一个小任务获得共读的资格和电子书资源。将小的发的图片分享到朋友圈然后截图发给小的。然后我们就可以一起去群里完成每日的读书计划,群内每天都有小的发的领读。小的一直会伴你读书,陪你成长!', msg['RecommendInfo']['UserName']);
        # itchat.send_image('@[email protected]' ,  msg['RecommendInfo']['UserName']);
        return '@[email protected]';

    itchat.run()
예제 #14
0
파일: run.py 프로젝트: codebean/ItChat
def test_reply():
    @itchat.msg_register
    def get_pic(msg):
        #print itchat.get_userinfo()
        if msg.get('Type', '') == 'Text':
            txt = msg['Text']
            is_birthday = (txt.isdigit() and len(txt)==8)
            if( is_birthday ):
                return '@[email protected]'
            else:
                itchat.send(u'格式错误。请输入你的出生日期,如: 20150908', msg['FromUserName'])

    @itchat.msg_register('Friends')
    def add_friend(msg):
        itchat.add_friend(**msg['Text'])
        itchat.get_contract()
        itchat.send(u'请输入你的出生日期,如: 20150908', msg['RecommendInfo']['UserName'])

    itchat.run()
예제 #15
0
def main():

    @itchat.msg_register(itchat.content.TEXT)
    def print_content(msg):
        global work_states
        get_text = msg['Text']
        get_user = msg['FromUserName']
        if(get_user == user_name):
            if(work_states == 'on'):
                itchat.send('喵'*(int)(random.random()*9+1), user_name)
        if(get_user==my_name):
            if(get_text==start_tag):
                work_states = 'on'
                itchat.send('开启自动回复~', 'filehelper')
            if (get_text == stop_tag):
                work_states = 'off'
                itchat.send('关闭自动回复', 'filehelper')


    itchat.auto_login(hotReload=True)
    itchat.run()
예제 #16
0
    def wechat_init(self):
        @itchat.msg_register(itchat.content.TEXT, isMpChat=True)
        def reply_msg(msg):
            print("Recive a message from MPS: ", msg['Content'].strip().strip('\n'))
            if msg['FromUserName'] == self.cur_user_name:
                if msg['Content'].find('请问您是问哪家公司的核保建议') >= 0:
                    self.start_collect_reply = 1
                else:
                    # 疾病答案不合法,停止询问公司详情
                    if self.cur_company == 1:
                        self.db.disease.update_one({ '_id': self.cur_disease_id }, { '$set': { 'finished': 1 } })
                        self.scheduler.pause_job('sub_schedule')
                        print('No answer, has paused the sub_schedule!')
                        return

                    if self.cur_company == 10:
                        self.db.disease.update_one({ '_id': self.cur_disease_id }, { '$set': { 'reply': self.reply, 'finished': 1 } })
                        self.scheduler.pause_job('sub_schedule')
                        print(self.cur_disease_id, 'Save data successfully!')
                        return

                    if self.start_collect_reply == 1:
                        print(self.reply)
                        print('reply\'s length: ', str(len(self.reply)), ', cur_count: ' + str(self.cur_count) + ', cur_company: ' + str(self.cur_company))
                        self.reply[str(self.cur_company)] = msg['Content'].strip()

        def after_login():
            print('Login success!')
            # self.init_database(self)
            self.get_data(self)
            pass

        def after_logout():
            # 关闭定时任务
            self.scheduler.shutdown()
            print('Has shutdown the scheduler!')
            pass

        itchat.auto_login(hotReload=True, loginCallback=after_login, exitCallback=after_logout)
        itchat.run()
예제 #17
0
파일: run.py 프로젝트: chenhang/ItChat
def complex_reply():
    @itchat.msg_register(['Text', 'Map', 'Note','Card', 'Sharing'], isGroupChat=True)
    def text_reply(msg):
        url = ''
        if msg['Url']: url = ' - ' + msg['Url']
        for destination in destinations(msg):
            itchat.send('%s: %s%s' % (get_sender_name(msg), msg['Text'],url), destination)

    # @itchat.msg_register(['Note','Card', 'Sharing'])
    # def text_reply(msg):
    #     print(msg)
    #     itchat.send('@url@%s' % (msg['Content']), msg['FromUserName'])

    @itchat.msg_register(['Picture', 'Recording', 'Attachment', 'Video', 'Gif'], isGroupChat=True)
    def download_files(msg):
        fileDir = '%s%s' % (msg['Type'], int(time.time()))
        if msg['Type'] == 'Gif': fileDir += '.gif'
        msg['Text'](fileDir)
        for destination in destinations(msg):
            itchat.send('@%s@%s' % ('img' if msg['Type'] == 'Picture' or msg['Type'] == 'Gif' else 'fil', fileDir), destination)
            itchat.send('%s by %s' % (msg['Type'], ''), destination)
    itchat.run()
예제 #18
0
def demo_1():
    KEY = '44ff23cd75de4d5dac225b64c6700b77'

    def get_response(msg):
        apiUrl = 'http://www.tuling123.com/openapi/api'
        data = {
            'key'    : KEY,
            'info'   : msg,
            'userid' : 'wechat-robot',
        }
        try:
            r = requests.post(apiUrl, data=data).json()
            return r.get('text')
        except:
            return

    @itchat.msg_register(itchat.content.TEXT)
    def tuling_reply(msg):
        defaultReply = 'I received: ' + msg['Text']
        reply = get_response(msg['Text'])
        return reply or defaultReply

    itchat.auto_login(hotReload=True)
    itchat.run()
예제 #19
0
def login():
    itchat.auto_login(hotReload=True)
    itchat.run()
예제 #20
0
파일: it_main.py 프로젝트: iinux/12306
def wechat_run():
    itchat.run()
예제 #21
0
# 接上段程序
# 通过该命令安装该API: pip install itchat
import itchat
import os
# 通过该命令安装该API: pip install NetEaseMusicApi
from NetEaseMusicApi import interact_select_song

#with open('stop.mp3', 'w') as f: pass
def close_music():
    #os.startfile('stop.mp3')
    print("MP3")


@itchat.msg_register(itchat.content.TEXT)
def music_player(msg):
    if msg['ToUserName'] != 'filehelper':
        return
    if msg['Text'] == u'关机':
        itchat.send(u'你的macbook准备关机', 'filehelper')
    if msg['Text'] == u'帮助':
        itchat.send(u'帮助信息', 'filehelper')
    else:
        itchat.send(u'请输入正确的指令', 'filehelper')
        #itchat.send(interact_select_song(msg['Text']), 'filehelper')


HELP_MSG = u"我是rocky小秘书"
itchat.auto_login(True)
itchat.send(HELP_MSG, 'filehelper')
itchat.run(debug=True)
예제 #22
0
def start_wechat_bot():

    global bot_name

    #如果是在服务器运行,auto_login 加上参数 enableCmdQR=2

    itchat.auto_login(hotReload=True)

    # initialize
    rcv = 'filehelper'
    itchat.send('成功接入'+ bot_name +'服务端!\n发送开启以开启服务',rcv)

    friend = itchat.get_friends()
    myName = friend[0]['UserName']

    def send_error_report(desc,error):
        itchat.send(desc+ '\n错误类型:'+ str(error),rcv)

    # 配置装饰器
    @itchat.msg_register(itchat.content.TEXT)
    def main(msg):

        # 导入初始化值
        global mode_init,\
            get_hot_number,\
            adv,\
            send_online_watch_address

        # return para: FromUserName ToUserName Content

        if msg['ToUserName'] == rcv:

            # 配置功能
            if msg['Content'] == '开启':
                mode_init = 1
                itchat.send('已开启机器人',rcv)
            if msg['Content'] == '状态':
                if mode_init:
                    itchat.send('已开启机器人\n发送关闭以关闭机器人',rcv)
                else:
                    itchat.send('未开启机器人',rcv)
            if msg['Content'] == '关闭':
                mode_init = 0
                itchat.send('已关闭机器人\n发送开启以启动机器人', rcv)
            if msg['Content'] == '测试':

                try:
                    beautiful_input(gain_link('我'))
                    itchat.send('搜索模块正常!',rcv)
                except Exception as e:
                    send_error_report('搜索模块错误!',e)
                try:
                    beautiful_input_for_hot_movie(get_hot())
                    itchat.send('热门模块正常!',rcv)
                except Exception as e:
                    send_error_report('热门模块错误!',e)

        # 对外功能
        if mode_init:
            if msg['Content'][:2] == '搜索':

                # 防止自己不能搜索
                if msg['FromUserName'] == myName:
                    msg['FromUserName'] = rcv

                itchat.send(bot_name + '正在搜索,请稍等。。。', msg['FromUserName'])
                try:
                    r = gain_link(msg['Content'][2:])
                    if not r == []:
                        re = beautiful_input(r)
                        itchat.send(re, msg['FromUserName'])
                    else:

                        # 如果没有检索
                        itchat.send('已检索到10个相关资源,但是 Baidu Validate 系统排除有 10 个垃圾资源')

                # 如果检索错误
                except Exception as e:
                    itchat.send('对不起,不能找到您想搜索的资源', msg['FromUserName'])
                    send_error_report('搜索模块错误,未能成功完成检索',e)

                # 获取在线看地址
                try:
                    if send_online_watch_address:
                        r = get_online_resource(msg['Content'][2:])
                        if not r == []:

                            re = '在线看地址:\n'
                            for i in r:
                                re = re + short(i) + '\n=====================\n'

                            itchat.send(re, msg['FromUserName'])

                # 如果错误
                except Exception as e:
                    send_error_report('在线看模块错误,未能成功完成检索', e)

                # 热门获取模块
                try:
                    if get_hot_number:
                        itchat.send(beautiful_input_for_hot_movie(r=get_hot()),msg['FromUserName'])
                except Exception as e:
                    send_error_report('热门模块错误,未能成功完成检索',e)

                # 如果 adv 不为空
                if not adv == '':
                    try:
                        itchat.send(str(adv),msg['FromUserName'])
                    except Exception as e:
                        send_error_report('广告模块错误',e)

    # 开始运行
    itchat.run()
예제 #23
0
1. 短时间关闭程序后重连.

即使程序关闭,一定时间内重新开启也可以不用重新扫码.

使用 auto_login 方法传入值为真的 hotReload.
该方法会生成一个静态文件 itchat.pkl, 用于存储登录的状态.

import itchat
from itchat.content import TEXT

@itchat.msg_register(TEXT)
def simple_reply(TEXT):
    print(msg.text)

itchat.auto_login(hotReload=True)
itchat.run()
通过设置 statusStorageDir 可以将静态文件指定为其他的值. 这一内置选项,相当于使用了以下两个函数的这一段程序:

import itchat
from itchat.content import TEXT

if itchat.load_login_status():  # itchat.load_login_status() 用于读取设置
    @itchat.msg_register(TEXT):
    def simple_reply(msg):
        print(msg["Text"])

    itchat.run()
    itchat.dump_login_status()  # itchat.dump_login_status() 用于导出设置

else:
    itchat.auto_login()
예제 #24
0
파일: go.py 프로젝트: hzlRises/hzlgithub
def  main():	
	#登陆微信
	itchat.auto_login(hotReload=True,enableCmdQR=2)#
	itchat.run()
예제 #25
0
 def listen():
     itchat.run(debug=False)
예제 #26
0
    print(IDandMESSAGE)
@itchat.msg_register(['Note'],isGroupChat=True)
def chgr_reply(msg):
    #print(msg)
    chcont=msg['Content']
    if chcont.find('revokemsg')>0:
        loc1=max(chcont.find('/oldmsgid&gt;&lt;msgid&gt;')+26,chcont.find('</oldmsgid><msgid>')+18)
        loc2=max(chcont.find('&lt;/msgid&gt;&lt;replacemsg&gt;&lt;![CDATA'),chcont.find('</msgid><replacemsg><![CDATA'))
        messageid=chcont[loc1:loc2]
        print(messageid)
        chtext=msg['Text']
        print(chtext)
        chlen=len(chtext)
        aname=chtext[:chlen-7]
        try:
            oritun=IDandTUN[str(messageid)]
            orifun=IDandFUN[str(messageid)]
        except:
            print('dont chehui twice')
        if (oritun==myusrname or orifun==myusrname)and (chtext.find('You')>0 or chtext.find('你')>0) or chtext=="You've recalled a message.":
            aname='myself'
        else:
            aname=aname + '[not me]'
        try:
            itchat.send("[Autoreply] The message revoked by '"+aname+"' just now is :"+IDandMESSAGE[str(messageid)],oritun)
            itchat.send("[Autoreply] The message revoked by '"+aname+"' just now is :"+IDandMESSAGE[str(messageid)],orifun)
        except:
            print("-----Can't find original msg")

itchat.run(debug=False)
예제 #27
0
파일: bot.py 프로젝트: ph87/itchat_demo
    insert_db(msg.type, msg.text, msg.CreateTime, msg.User.NickName)
    logger.info('{}, {}, {}, {}'.format(msg.type, msg.text, msg.CreateTime,
                                        msg.User.NickName))


@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
def download_files(msg):
    file_path = os.path.join('media', msg.fileName)
    with open(file_path, 'wb') as f:
        f.write(msg.download())
        insert_db(msg.type, msg.fileName, msg.CreateTime, msg.User.NickName)
    logger.info('{}, {}, {}, {}'.format(msg.type, msg.filename, msg.CreateTime,
                                        msg.User.NickName))


@itchat.msg_register(FRIENDS)
def add_friend(msg):
    msg.user.verify()
    msg.user.send('Nice to meet you!')


@itchat.msg_register(TEXT, isGroupChat=True)
def text_reply(msg):
    if msg.isAt:
        msg.user.send(u'@%s\u2005I received: %s' %
                      (msg.actualNickName, msg.text))


itchat.auto_login(True)
itchat.run(True)
예제 #28
0
def get_response(message):
    data = {
        'key': '4715746b938c4aa2bfdef674bd1d30ff',  #yes,do as you see
        'info': message,
        'userid': 'yuleff',
    }


#@itchat.msg_register(itchat.content.TEXT)# //接收微信消息
@itchat.msg_register(
    [TEXT, MAP, CARD, NOTE, SHARING, PICTURE, RECORDING, ATTACHMENT, VIDEO])
@itchat.msg_register(
    [TEXT, MAP, CARD, NOTE, SHARING, PICTURE, RECORDING, ATTACHMENT, VIDEO],
    isGroupChat=True)
def text_reply1(msg):
    if msg.text:
        #users = itchat.search_friends(name=u'张山')  # 通讯录中好友备注名
        myUserName = itchat.get_friends(
            update=True)[0]["UserName"]  ##获取自己的username
        #print('myUserName='******'FromUserName='******'FromUserName'])  ##获取发消息的好友的username
        remark_name = msg['User']['RemarkName']  ###备注名称
        if msg['Content']:
            itchat.send(u'@%s\u2005: %s  %s \n我是机器人!' %
                        (msg['ActualNickName'], msg['Content'], remark_name),
                        toUserName=msg['FromUserName'])


itchat.auto_login(True)  #//登录微信函数(需要扫描二维码),加上True在一定时间内不用每次运行都扫二维码
itchat.run()  #//运行
예제 #29
0
def after_login():
    #itchat.send_msg("Hello World", 'filehelper') #TEST
    #print(itchat.search_friends()) # Return account information.
    #print(itchat.send_msg('test.txt', '@56859a2cc5266ad423adb01f68d8e980aca8b23a04890a0fb60c7a42e1e4b415')) # TEST SENDING FILE TO FRIEND.
    print('Login successful as ' + itchat.search_friends()['NickName'])


'''
The function that executes after auto reply is run, and handles operations apart from auto reply.
The while loop ensures the run of program body. The process terminates when the while loop ends.
'''


def after_run():
    while isRunning:
        pass
    return None  #PLACEHOLDER


'''
Login and autoreply.
@param hotReload = True: After first login by scanning QR code, 
@param loginCallback: the function that calls back after login completion.
'''
print('Running WeChat.py')
itchat.auto_login(loginCallback=after_login)
itchat.run(blockThread=False)  # Start auto reply without blocking thread.
after_run()

itchat.logout()  # Log out the WeChat when program terminates.
예제 #30
0
파일: FatBoyBot.py 프로젝트: daniellu/PSN
 def __init__(self):
     itchat.auto_login(True)
     itchat.run()
예제 #31
0
파일: Demo1.py 프로젝트: Chai-Yun/Robot
def main():
    itchat.auto_login(hotReload=True)  # 微信登录,即使程序关闭,一定时间内重新开启也可以不用重新扫码
    itchat.run()
예제 #32
0
        sys.stderr.write(str(ff))
        # if user does not select file, browser also
        # submit a empty part without filename
        if username and ff and len(ff.filename):
            filename = secure_filename(ff.filename)
            ff.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
            return try_send(lambda: itchat.send_image(filename, username), lambda: os.remove(filename))
        else:
            return 'invalid'
    else:
        return HTML_SEND_IMG


def start_itchat():
    def reply_fn():
        try:
            while True:
                itchat.configured_reply()
        except KeyboardInterrupt:
            # itchat.dump_login_status()
            pass
    replyThread = threading.Thread(target=reply_fn)
    replyThread.setDaemon(True)
    replyThread.start()


if __name__ == '__main__':
    itchat.auto_login(enableCmdQR=True, hotReload=True)
    itchat.run(blockThread=False)
    http_server.serve_forever()
예제 #33
0
파일: domain.py 프로젝트: codebean/ItChat
def test_reply():
    @itchat.msg_register([TEXT])
    def get_pic(msg):
	if msg['Text']=="ok": 
            itchat.send(u'ok', msg['FromUserName'])
    itchat.run()
예제 #34
0
def server():
    """
    server
    """
    itchat.auto_login(enableCmdQR=2)
    itchat.run()
예제 #35
0
#coding=utf8
import requests
import itchat as wx
#目前测试可以和三个账号同时聊天

key = '7593ddd9947346e5ba8ff8832264ba50'


def g(msg, key=key):
    apiUrl = 'http://www.tuling123.com/openapi/api'
    data = {"key": key, "info": msg, "userid": "Hello"}
    r = requests.post(apiUrl, data=data).json()

    return r.get('text')


@wx.msg_register(wx.content.TEXT)
def tuling_reply(msg):
    # 为了保证在图灵Key出现问题的时候仍旧可以回复,这里设置一个默认回复
    defaultReply = 'I received: ' + msg['Text']
    # 如果图灵Key出现问题,那么reply将会是None
    reply = g(msg['Text'])
    # a or b的意思是,如果a有内容,那么返回a,否则返回b
    # 有内容一般就是指非空或者非None,你可以用`if a: print('True')`来测试
    return reply or defaultReply


# 为了让实验过程更加方便(修改程序不用多次扫码),我们使用热启动
wx.auto_login(hotReload=True)
wx.run()
예제 #36
0
        peforth.ok('22> ', loc=locals(), cmd=":> [0] inport cr")  # breakpoint
    msg.download(msg.fileName)
    typeSymbol = {
        PICTURE: 'img',
        VIDEO: 'vid',
    }.get(msg.type, 'fil')
    return '@%s@%s' % (typeSymbol, msg.fileName)


@itchat.msg_register(FRIENDS)
def _(msg):
    if peforth.vm.debug == 33:
        peforth.ok('33> ', loc=locals(), cmd=":> [0] inport cr")  # breakpoint
    msg.user.verify()
    send_chunk('Nice to meet you!', msg.user.send)


@itchat.msg_register(TEXT, isGroupChat=True)
def _(msg):
    if peforth.vm.debug == 44:
        peforth.ok('44> ', loc=locals(), cmd=":> [0] inport cr")  # breakpoint
    if msg.isAt:
        cmd = msg.text.split(maxsplit=1)[1]  # remove the leading @nickName
        console(msg, cmd)


# peforth.vm.debug=99
itchat.auto_login(True)  # hotReload=True
itchat.run(False, blockThread=True)  # debug=True
peforth.ok()  # breakpoint
예제 #37
0
def start_itchat():
    itchat.auto_login(qrCallback=qr_callback)
    itchat.run()
예제 #38
0
def main(folder):
    global data_folder
    data_folder = folder
    itchat.auto_login(hotReload=True)
    itchat.run(blockThread=True)
예제 #39
0
def  main():	
	#登陆微信
	itchat.auto_login(hotReload=True)
	itchat.run()
예제 #40
0
파일: main.py 프로젝트: Tonyhe666/onewx
 def run(self):
     itchat.auto_login(enableCmdQR=2)
     self.scheduler()
     itchat.run()
예제 #41
0
    def __init__(self):

        self.owner = itchat.auto_login(hotReload=True)

        # 自动心跳。
        itchat.run(blockThread=False)
예제 #42
0
 def _itchatRun():
     itchat.run()
예제 #43
0
 def run(self):
     itchat.auto_login()
     itchat.run()
예제 #44
0
 def _start(self):
     itchat.auto_login(hotReload=False, enableCmdQR=False)
     itchat.run()
예제 #45
0
파일: wechat2.py 프로젝트: marc45/AirPlane
import itchat
from itchat.content import *
# itchat.content包含所有的消息类型参数,这样处理的好处是代码中引用时不需要写前缀,比如文本类型不需写itchat.content.TEXT,只需写TEXT

# 通过装饰符将函数text_reply()注册为处理消息的函数,对收到的文本TEXT、地图MAP、名片CARD、通知NOTE、分享SHARING作出回应
@itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING])  # 装饰器
def text_reply(msg): # 形参msg接收发来的信息,信息是字典类型
	return "【自动回复】我已收到您的消息,多谢~\n\n【来自WinTerson的Python小机器人】"  # 设定回复信息

# 对发过来的图片/表情PICTURE、语音RECORDING、附件ATTACHMENT和视频VIDEO作出回应
@itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
def receiveFile_reply(msg):
	return "【自动回复】我收到了一个{}文件,多谢~\n\n【来自WinTerson的Python小机器人】".format(msg['Type'])

itchat.auto_login(True)
# 扫码登陆。也可以写成itchat.auto_login(hotReload=True),参数为True的作用是存储登陆,这样即使程序关闭,一定时间内重新开启也可以不用重新扫码。itchat.auto_login()不具备存储登陆的功能

itchat.run()  # 等待新消息
예제 #46
0
def login():
   itchat.auto_login()
   #返回二维码给前端
   itchat.run()
   return "登录成功!"
예제 #47
0
    while 1:

        C = tieba.Main()
        print('This is myitchat: ' + str(C))
        print(T)

        if C == None or C == [] or C == ' ' or len(C) > 3452:
            continue
        if T == 1:
            T = 0
            print('改变了T: ' + str(T))

        if T == 0 and i != 0:
            itchat.send_msg('监控到更新的数据  \n \n' + str(C), toUserName=id)
        i += 1


# 识别系统
sysstr = platform.system()

if (sysstr == "Windows"):
    itchat.auto_login(hotReload=True)
elif sysstr == "Linux":
    itchat.auto_login(enableCmdQR=2)

# blockThread=False 启用解除block
itchat.run(blockThread=False)
tieba.ini()
tie = threading.Thread(target=Main())
tie.start()
예제 #48
0
def login():
    print "login begin"
    itchat.auto_login()
    itchat.run()
    print "login end"
예제 #49
0
#如果你想要给文件传输助手发一条信息,只需要这样:
#itchat.send('Hello, 哈哈哈哈', toUserName='******')


@itchat.msg_register([TEXT])
def text_reply(msg):
    #info = msg['Text'].encode('UTF-8')
    info = msg['Text']
    url = 'http://www.tuling123.com/openapi/api'
    data_msg = {
        "key": "8019d7394bde451193bf20fa291a715f",
        "info": info,
        "loc": "",
        "userid": ""
    }
    #data = urllib.urlencode(data)
    data_msg = urllib.parse.urlencode(data_msg).encode(encoding='UTF8')
    url2 = urllib.request.Request(url, data_msg)
    response = urllib.request.urlopen(url2)
    apicontent = response.read()
    #s = json.loads(apicontent,encoding = 'utf-8')
    s = json.loads(apicontent.decode('utf-8'))
    print('s==', s)
    if s['code'] == 100000:
        itchat.send(s['text'], msg['FromUserName'])


itchat.auto_login(hotReload=True, enableCmdQR=2)
itchat.run(debug=True)
예제 #50
0
        print(msg.text)

# @itchat.msg_register([TEXT, MAP, CARD, NOTE, SHARING])
# def text_reply(msg):
#     msg.user.send('%s: %s' % (msg.type, msg.text))
#     userid = itchat.search_friends(userName=msg.FromUserName)['NickName']
#     print(userid,msg.text)

# @itchat.msg_register([PICTURE, RECORDING, ATTACHMENT, VIDEO])
# def download_files(msg):
#     msg.download(msg.fileName)
#     typeSymbol = {
#         PICTURE: 'img',
#         VIDEO: 'vid', }.get(msg.type, 'fil')
#     return '@%s@%s' % (typeSymbol, msg.fileName)
#
# @itchat.msg_register(FRIENDS)
# def add_friend(msg):
#     msg.user.verify()
#     msg.user.send('Nice to meet you!')
#
# @itchat.msg_register(TEXT, isGroupChat=True)
# def text_reply(msg):
#     if msg.isAt:
#         msg.user.send(u'@%s\u2005I received: %s' % (
#             msg.actualNickName, msg.text))

itchat.auto_login(hotReload=True)
itchat.run()
a=itchat.search_friends(nickName='葛亚东')
print(a)
예제 #51
0
                if msg.type == SHARING:                               # 朋友分享
                    msg.user.send('你的分享可真不错!受益匪浅!')
                                
                if msg.type == PICTURE or msg.type == VIDEO:          # 对方发送的图片与视频会被自动保存在程序文件所在的位置
                    MEDIA.append(msg.fileName)
                    msg.download(MEDIA[-1])
                    msg.user.send('你发送的图片视频将被我自动下载至当前路径')
                                
                if msg.type == RECORDING:                             # 语音信息
                    msg.user.send('虽然我听不懂你的话,但是我依然觉得你的声音是世界上最甜的!')
                    time.sleep(5)
                    msg.user.send('如果你无聊,可以和我聊天呀,嘻嘻嘻嘻!')
                    
                 
    @itchat.msg_register(FRIENDS)
    def add_friend(msg):                                              # 自动允许添加新朋友
        msg.user.verify()
        msg.user.send('你好!Nice to meet you!')

    @itchat.msg_register(TEXT, isGroupChat=True)
    def text_reply(msg):                                              # 群聊中被人@
        if msg.isAt:
            msg.user.send(u'@%s\u2005I received: 神马问题?' %        #itchat中@的固定格式
            msg.actualNickName)


while True:
    wechat()
    itchat.auto_login(hotReload=True)
    itchat.run(True)                                                  # itchat启动
예제 #52
0
@itchat.msg_register(PICTURE, isGroupChat=True)
def picture(msg):
    if peforth.vm.debug == 55:
        peforth.ok(
            '55> ',
            loc=locals(),
            cmd=":> [0] to locals locals :> ['msg'] to msg cr")  # breakpoint
    if msg.user.NickName == chatroom:  # 只在特定的 chatroom 工作,過濾掉其他的。
        predict(msg)


# peforth.vm.debug = 44
if peforth.vm.debug == 66:
    peforth.ok('66> ', loc=locals(), cmd=":> [0] to locals cr")  # breakpoint
itchat.auto_login(hotReload=False)
itchat.run(debug=True, blockThread=True)
peforth.ok('Examine> ',
           loc=locals(),
           cmd=':> [0] to main.locals cr time :> ctime() . cr')
'''

# --------------- Playground ---------------------------------------------------
\ Ynote: "Itchat Robot Toolkit 在這兒集中管理"
\ Setup the playground for testing without itchat (avoid the need to login)
\ 弄出個 msg 來供 function test 測試以及 debug 用,而無須 itchat 連線。

    <accept>
    <py>
    def msg():
        pass
    def _():
예제 #53
0
def reply_messages():
    itchat.run(True)
예제 #54
0
            user_session.append(code)
            return "您想知道关于这个公司什么信息1.股价 2.成交量 3.市值"

        else:
            # 判断session
            if not user_session:
                return "请先输入你想了解的公司"
            message = "该公司{}是:\n".format(msg['Text'])
            if msg['Text'] == "股价":
                message += str(user_session[-1].price())
            elif msg['Text'] == "市值":
                message += str(user_session[-1].markstCap())
            elif msg['Text'] == "成交量":
                message += str(user_session[-1].volume())
            return message


# 执行当前文件
if __name__ == '__main__':
    itchat.auto_login()  #用于微信登陆、接受信息
    friends = itchat.get_friends(update=True)[0:]
    Name = {}
    Nic = []
    User = []
    for i in range(len(friends)):
        Nic.append(friends[i]["NickName"])
        User.append(friends[i]["UserName"])
    for i in range(len(friends)):
        Name[Nic[i]] = User[i]
    itchat.run()  #执行之后,弹出二维码
            print('-+-+' * 5)
            print('Message content:%s' % msg['Content'])
            randomIdx = random.randint(0, len(REPLY['妹']) - 1)
            itchat.send('%s\n%s' % (username, REPLY['妹'][randomIdx]), msg['FromUserName'])
            print(REPLY['妹'][randomIdx])

        match = re.search('工作', msg['Text']) or re.search('加班', msg['Text'])
        if match:
            print('-+-+' * 5)
            print('Message content:%s' % msg['Content'])
            print('工作、加班 is: %s' % (match is not None))
            randomIdx = random.randint(0, len(REPLY['工作']) - 1)
            itchat.send('%s\n%s' % (username, REPLY['工作'][randomIdx]), msg['FromUserName'])
            print(REPLY['工作'][randomIdx])

        match = re.search('学习', msg['Text']) or re.search('考试', msg['Text'])
        if match:
            print('-+-+' * 5)
            print('Message content:%s' % msg['Content'])
            print('学习、考试 is: %s' % (match is not None))
            randomIdx = random.randint(0, len(REPLY['学习']) - 1)
            itchat.send('%s\n%s' % (username, REPLY['学习'][randomIdx]), msg['FromUserName'])
        else:
            randomIdx = random.randint(0, len(REPLY['default']) - 1)
            itchat.send('%s\n%s' % (username, REPLY['default'][randomIdx]), msg['FromUserName'])
            print('-+-+'*5)

itchat.auto_login(enableCmdQR=2, hotReload=True)#login
itchat.run()#run and stay online

예제 #56
0
파일: wxRot.py 프로젝트: masonyang/test
	def run(self):
		itchat.run()
		pass
예제 #57
0
def Run():
    itchat.run()
예제 #58
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from apscheduler.scheduler import Scheduler
import itchat, time, logging, sys

reload(sys)
sys.setdefaultencoding("utf-8")
logging.basicConfig()

itchat.auto_login()

sched = Scheduler()
sched.start()

def task():
  chatroomList = itchat.get_chatrooms(False);
  for m in chatroomList:
    NickName = m['NickName'].encode('utf-8')
    if NickName == u'测试'.encode('utf-8'):
      text = u'可以定时发送了'.encode('utf-8')
      itchat.send(text, m['UserName'])

sched.add_cron_job(task, month='1-12', day_of_week='0-6', hour=11, minute=21)

itchat.run()
'一辈子的爱,不是一场轰轰烈烈的爱情,也不是什么承诺和誓言。而是当所有人都离弃你的时候,只有TA在默默陪伴着你。当所有人都在赞赏你的时候,只有TA牵着你的手,嘴角上扬,仿佛骄傲的说,我早知道。时间会告诉你——越是平凡的陪伴,就越长久。']
# greetList = ['何渣渣','渣渣何','战斗力五的何渣渣','我陶恒是不是岳麓山第一狄仁杰,你说','我陶恒是不是岳麓山第一曹操,你说','我陶恒是不是岳麓山第一妲己,你说']
def tick():
    users = itchat.search_friends(name=u'七七') # 找到你女朋友的名称
    userName = users[0]['UserName']
    meetDate = dt.date(2012,4,22)  # 这是你跟你女朋友相识的日期
    now = dt.datetime.now()     # 现在的时间
    nowDate = dt.date.today()  # 今天的日期
    passDates = (nowDate-meetDate).days # 你跟你女朋友认识的天数
    itchat.send(u'今天是我们在一起第%d天,%s, 亲亲小媳妇'%(passDates,random.sample(greetList,1)[0]),toUserName=userName) # 发送问候语给女朋友
#     itchat.send(u'就问你服不服,%s'%(random.sample(greetList,1)[0]),toUserName=userName) 
    nextTickTime = now + dt.timedelta(days=1)
#     nextTickTime = now + dt.timedelta(seconds=2)
    nextTickTime = nextTickTime.strftime("%Y-%m-%d 00:00:00") 
    my_scheduler(nextTickTime) # 设定一个新的定时任务,明天零点准时问候
def my_scheduler(runTime):
    scheduler = BackgroundScheduler() # 生成对象
    scheduler.add_job(tick, 'date', run_date=runTime)  # 在指定的时间,只执行一次
    scheduler.start()
    
if __name__ == '__main__':
    itchat.auto_login(enableCmdQR=-2,hotReload=True) # 在命令行中展示二维码,默认展示的是图片二维码
#     itchat.login()
#     itchat.auto_login(hotReload=True) # 这个是方便调试用的,不用每一次跑程序都扫码
    now = dt.datetime.now() # 获取当前时间
#     nextTickTime = now + dt.timedelta(days=1) #下一个问候时间为明天的现在
    nextTickTime = now + dt.timedelta(seconds=2)
#     nextTickTime = nextTickTime.strftime("%Y-%m-%d 00:00:00") # 把下一个问候时间设定为明天的零点
    my_scheduler(nextTickTime) # 启用定时操作
    itchat.run() # 跑微信服务