def handler_receive_msg(msg): # 处理收到的消息 message = msg['Text'] toName = msg['ToUserName'] #owner = msg['User']['PYQuanPin'] # 临时保存截屏图片地址 #path = 'C:\Users\wqw\Desktop\fig\temp.jpg' path = 'tmp.jpg' reply = json.dumps(msg, ensure_ascii=False) reply = '你发了:%s'%message #{"MsgId": "9212371634710588729", "FromUserName": "******", "ToUserName": "******", "MsgType": 1, "Content": "你", "Status": 3, "ImgStatus": 1, "CreateTime": 1541315145, "VoiceLength": 0, "PlayLength": 0, "FileName": "", "FileSize": "", "MediaId": "", "Url": "", "AppMsgType": 0, "StatusNotifyCode": 0, "StatusNotifyUserName": "", "RecommendInfo": {"UserName": "", "NickName": "", "QQNum": 0, "Province": "", "City": "", "Content": "", "Signature": "", "Alias": "", "Scene": 0, "VerifyFlag": 0, "AttrStatus": 0, "Sex": 0, "Ticket": "", "OpCode": 0}, "ForwardFlag": 0, "AppInfo": {"AppID": "", "Type": 0}, "HasProductId": 0, "Ticket": "", "ImgHeight": 0, "ImgWidth": 0, "SubMsgType": 0, "NewMsgId": 9212371634710588729, "OriContent": "", "EncryFileName": "", "User": {"MemberList": [], "UserName": "******", "City": "海淀", "DisplayName": "", "PYQuanPin": "wangqiwen", "RemarkPYInitial": "", "Province": "北京", "KeyWord": "wqw", "RemarkName": "", "PYInitial": "WQW", "EncryChatRoomId": "", "Alias": "", "Signature": "自律更自由", "NickName": "王奇文", "RemarkPYQuanPin": "", "HeadImgUrl": "/cgi-bin/mmwebwx-bin/webwxgeticon?seq=661826231&username=@ad238825281702d637159eab5f24f89e&skey=@crypt_15c532e6_ba943df756f74fb80686ff7d62c8c677", "UniFriend": 0, "Sex": 1, "AppAccountFlag": 0, "VerifyFlag": 0, "ChatRoomId": 0, "HideInputBarFlag": 0, "AttrStatus": 33656871, "SnsFlag": 17, "MemberCount": 0, "OwnerUin": 0, "ContactFlag": 3, "Uin": 965715160, "StarFriend": 0, "Statues": 0, "WebWxPluginSwitch": 0, "HeadImgFlag": 1, "IsOwner": 0}, "Type": "Text", "Text": "你"} #if toName in ('@ad238825281702d637159eab5f24f89e', "filehelper" ): if toName == "filehelper": if message == "cap": # 拍照 # 要使用摄像头,需要使用cv2.VideoCapture(0)创建VideoCapture对象, # 参数:0指的是摄像头的编号。如果你电脑上有两个摄像头的话,访问第2个摄像头就可以传入1 cap = cv2.VideoCapture(0) ret, img = cap.read() # 获取一帧 cv2.imwrite("temp.jpg", img) itchat.send('@img@%s' % u'temp.jpg', toName) cap.release() # 释放资源 if message[0:3] == "cmd": # 处理cmd命令 os.system(message.strip(message[0:4])) if message == "pc": # 截图 im = ImageGrab.grab() # 实现截屏功能 im.save(path, 'JPEG') # 设置保存路径和图片格式 itchat.send_image(path, toName) # 微信表情符对照表:https://www.cnblogs.com/xuange306/p/7098236.html emoji = [')', 'B', 'X', 'Z', 'Q', 'T', 'L', 'g', '|', '<','>', '~', '’(', '$', '!','O', 'P', '+','*'] robots = ['/::%s'%(i) for i in emoji] reply = get_response(msg['Text'])+random.choice(robots) res = '收到%s的消息[%s], 回复:[%s]'%(toName, message, reply) print(sys.stderr, res) return reply or defaultReply
def save_jpg(): city_list = ['xiamentianqi','beijingtianqi'] for index,city in enumerate(city_list): time.sleep(1) encode_city = quote(city) url = 'https://www.baidu.com/s?ie=UTF-8&wd=%s'%encode_city picName = '%s.png'%index browser = webdriver.PhantomJS(executable_path=r'/usr/local/bin/phantomjs') browser.get(url) browser.maximize_window() browser.save_screenshot(picName)#保存截图 #获取天气模板的位置、尺寸大小 imgelement = browser.find_element_by_xpath('//*[@id="1"]/div[1]') location = imgelement.location#获取天气x,y轴坐标 size = imgelement.size#获取天气的长宽 rangle = (int(location['x']),int(location['y']),int(location['x']+size['width']),int(location['y']+size['height']-20)) i = Image.open(picName) #打开0.png tinaqi = i.crop(rangle)#使用Image的crop函数,从截图中再次截取我们需要的 tinaqi.save('send_%s.png'%index) browser.close() #发送 user_content = itchat.search_friends(name=u'雨一直下') userName = user_content[0]['UserName'] itchat.send_image('send_%s.png'%index,toUserName = userName) if city == 'xiamentianqi': user_content_baby = itchat.search_friends(name=u'徐莹') userName_baby = user_content_baby[0]['UserName'] itchat.send_image('send_%s.png'%index,toUserName = userName_baby)
def deal_with_friend(msg): if add_friend_compile.search(msg['Content']) is not None: itchat.add_friend(**msg['Text']) # 自动将新好友的消息录入,不需要重载通讯录 time.sleep(random.randint(1, 3)) itchat.send_msg('嘤嘤嘤,我是智障机器人小Pig,\n很高兴认识你,回复关键字:\n\n 加群,博客,Github,公众号,打赏 \n\n 来继续我们的摔跤♂故事!', msg['RecommendInfo']['UserName']) time.sleep(random.randint(1, 3)) itchat.send_image('welcome.png', msg['RecommendInfo']['UserName'])
def sendimage_onegroup(): gname = input("请输入你想发送的的群的名字:") image = input("请输入你想发送的图片的路径如'E:/hello/桂东.png'(记得加引号!!!):") room = itchat.search_chatrooms(gname) if room is not None: username = room[0]['UserName'] itchat.send_image(image, username) print("发送成功!") else: print("未找到该群!")
def send_photo(self, target, photo_data, sender=None): ft = imghdr.what('', photo_data) if ft is None: return filename = "image." + ft data_io = io.BytesIO(photo_data) roomid = wxRoomNicks[target] if sender is not None: itchat.send(msg="{} sent a photo...".format(sender), toUserName=roomid) itchat.send_image(fileDir=filename, toUserName=roomid, file_=data_io)
def setfile(file): rooms = itchat.get_chatrooms(update=True) if rooms is not None: for i in rooms: uname = i['UserName'] nname = i['NickName'] itchat.send_image(file, uname) print("已发送成功到群:%s!" % nname) else: print("没有任何群!")
def sendfile_allgroup(): file = input("请输入你想发送的文件的路径如'E:/hello/桂东.html'(记得加引号!!!):") rooms = itchat.get_chatrooms(update=True) if rooms is not None: for i in rooms: uname = i['UserName'] nname = i['NickName'] itchat.send_image(file, uname) print("已发送成功到群:%s!" % nname) else: print("没有任何群!")
def get_fund(): ''' 162605景顺长城鼎益混合(LOF) 160505博时主题行业混合(LOF) 002121广发沪港深新起点股票 000011华夏大盘精选混合 163402兴全趋势投资混合(LOF) 070032 217027 165312 519066 110022 ''' #fund_list = ['110022','160505','163402','162605','002121','000011','070032','217027','165312','519066','110022'] #fund_list = ['162605','160505','002121','000011','163402','070032','217027','165312','519066','110022'] fund_list = ['dapan',] for index,fund in enumerate(fund_list): fund_id = str(fund) url = 'https://www.baidu.com/s?ie=UTF-8&wd=%s'%str(fund_id) #url = 'http://fund.eastmoney.com/%s.html'%str(fund_id) picName = 'fund_%s.png'%index browser = webdriver.PhantomJS(executable_path=r'/usr/local/bin/phantomjs') browser.get(url) browser.maximize_window() browser.save_screenshot(picName)#保存截图 imgelement = browser.find_element_by_xpath('//*[@id="1"]/div[1]') ''' if fund_id == '002121': imgelement = browser.find_element_by_xpath('//*[@id="2"]') ''' location = imgelement.location#获取x,y轴坐标 size = imgelement.size#获取长宽 rangle = (int(location['x']),int(location['y']),int(location['x']+size['width']),int(location['y']+size['height']-20)) i = Image.open(picName) #打开 tinaqi = i.crop(rangle)#使用Image的crop函数,从截图中再次截取我们需要的 tinaqi.save('send_fund_%s.png'%index) browser.close() #发送 user_content = itchat.search_friends(name=u'雨一直下') userName = user_content[0]['UserName'] itchat.send_image('send_fund_%s.png'%index,toUserName = userName) user_content_baby = itchat.search_friends(name=u'徐莹') userName_baby = user_content_baby[0]['UserName'] itchat.send_image('send_fund_%s.png'%index+1,toUserName = userName_baby)
def deal_with_msg(msg): text = msg['Content'] if text == u'加群': time.sleep(random.randint(1, 3)) itchat.add_member_into_chatroom(get_group_id("小猪的Python学习交流群"), [{'UserName': msg['FromUserName']}], useInvitation=True) elif text == u'博客': time.sleep(random.randint(1, 3)) return 'coder-pig的个人主页-掘金:https://juejin.im/user/570afb741ea493005de84da3' elif text == u'Github': time.sleep(random.randint(1, 3)) return 'https://github.com/coder-pig' elif text == u'公众号': time.sleep(random.randint(1, 3)) itchat.send_image('gzh.jpg', msg['FromUserName']) elif text == u'打赏': time.sleep(random.randint(1, 3)) itchat.send_image('ds.gif', msg['FromUserName']) time.sleep(random.randint(1, 3)) itchat.send_msg('您的打赏,会让小猪更有动力肝出\n更Interesting的文章,谢谢支持~', msg['FromUserName']) time.sleep(random.randint(1, 3)) itchat.send_image('wxpay.png', msg['FromUserName']) else: time.sleep(random.randint(1, 3)) itchat.send_image('hrwh.png', msg['FromUserName'])
def main(): parent_dir = get_parent_path() image_dir = parent_dir + "\\" + "images" image_dict = get_user_img(image_dir) fail_lst = [] itchat.auto_login() contract = itchat.get_contract() for user, image in image_dict.items(): user_name, quan_pin = get_user_name(user, contract) if not user_name or not quan_pin: # 好友列表不存在 fail_lst.append(user) log.debug(u"%s 的工资条发送失败!" % user) continue temp_path = parent_dir + "\\" + quan_pin + "." + image.split(".")[1] # 中文图片移到上级目录, 改名为拼音 shutil.move(image, temp_path) if itchat.send_image(temp_path, user_name): log.debug(u"%s 的工资条发送成功!" % user) os.remove(temp_path) # 删除临时文件 else: fail_lst.append(user) log.debug(u"%s 的工资条发送失败!" % user) log.debug(u"成功发送 %s 条工资信息" % (len(image_dict) - len(fail_lst))) if fail_lst: log.debug(u"%s 条发送失败, 名单如下" % len(fail_lst)) for i in fail_lst: log.debug(i) os.startfile(image_dir)
def send(type, nickname): datasssss = tianxing(type) chat_rooms = itchat.search_chatrooms(name=nickname) print(chat_rooms[0]['UserName']) if datasssss['types'] == 'txt': itchat.send_msg(datasssss["msg"], toUserName=chat_rooms[0]['UserName']) elif datasssss['types'] == 'img': r = requests.get(datasssss["msg1"]) with open('./img/everyday.png', 'wb') as f: f.write(r.content) itchat.send_image('./img/everyday.png', toUserName=chat_rooms[0]['UserName']) itchat.send_msg(datasssss["msg2"], toUserName=chat_rooms[0]['UserName']) itchat.send_msg(datasssss["msg3"], toUserName=chat_rooms[0]['UserName']) else: pass
def text_reply(msg): if msg['isAt']: ret = text_analyser(msg['Text']) if ret == '关键词未匹配': itchat.send( u'@%s\u2005我不是很懂: %s' % (msg['ActualNickName'], msg['Content']), msg['FromUserName']) else: print(itchat.send_image('s.png', msg['FromUserName']))
def reply(msg): if msg['Text'] == 'neko': type = ['.jpg', '.gif', '.png'] #由于类型有三种,这里做了一个数组,如果exist(fileDir),那么就结束整个if块 f_count = open('count.txt') count = f_count.read() count = int(count) N = random.randint(0, count) for image_type in type: print(image_type) fileDir = str(N) + image_type if os.path.exists(fileDir): print('ok') break print(fileDir) itchat.send_image(fileDir=fileDir, toUserName=msg['FromUserName']) return
def join_image(): base_path = 'headImages' files = os.listdir(base_path) each_size = int(math.sqrt(float(640 * 640) / len(files))) lines = int(640 / each_size) image = Image.new('RGB', (640, 640)) x = 0 y = 0 for file_name in files: img = Image.open(os.path.join(base_path, file_name)) img = img.resize((each_size, each_size), Image.ANTIALIAS) image.paste(img, (x * each_size, y * each_size)) x += 1 if x == lines: x = 0 y += 1 image.save('all.jpg') itchat.send_image('all.jpg', 'filehelper')
def getLocation(): friends = GetFriendsInfo.getFriendsInfo() headers = ['NickName', 'Province', 'City'] with open( 'location.csv', 'w', encoding='utf-8', newline='', ) as csvFile: writer = csv.DictWriter(csvFile, headers) writer.writeheader() for friend in friends[1:]: row = {} row['NickName'] = friend['NickName'] row['Province'] = friend['Province'] row['City'] = friend['City'] writer.writerow(row) itchat.send_image("location.jpg", 'filehelper')
def send_MongoAnalysis(info_dict, tbname): for user in set(info_dict[tbname]["user_list"]): mode_path = "./img/{}/finished".format(tbname) path_list = [ os.path.join(mode_path, pic) for pic in ['StarMap.png', 'wordcloud.png', 'AreaMap.png'] if pic in os.listdir(mode_path) ] try: for path in path_list: itchat.send_image(path, user) itchat.send(os.path.split(path)[-1], user) except Exception as e: print("Err:", e.args) else: info_dict[tbname]["user_list"].remove(user) info_dict[tbname].setdefault("path_list", path_list) ItchatReply.save(info_dict)
def deal_with_msg(msg): text = msg['Content'] if text == u'加群': # itchat.add_member_into_chatroom(get_group_id(u"测试群"), [{'UserName': msg['FromUserName']}]) # itchat.send(str(itchat.search_friends(userName=msg['FromUserName'])['NickName']),toUserName='******') itchat.send_msg(str( itchat.search_friends(userName=msg['FromUserName'])['NickName']), toUserName='******') itchat.send_msg('您的加群信息已收到\n稍后(我也不知道多久)将会拉您进群', msg['FromUserName']) itchat.send_image('timg.gif', msg['FromUserName']) elif text == u'公众号': itchat.send_msg( '#!/usr/bin/python\n#coding:utf-8\n def ISA():\n print("慎言善思,学以致用")\nif __name__ == "__main__":\n ISA()', msg['FromUserName']) itchat.send_msg('欢迎关注我们的公众号,\n“创软俱乐部ISA”', msg['FromUserName']) itchat.send_image('QR_ISA.jpg', msg['FromUserName']) else: itchat.send_msg(u'%s' % tuling(msg['Text']), msg['FromUserName'])
def img_to_myself(): '''截图并发送''' timeArray = time.localtime(time.time()) now_time = time.strftime("%y/%m/%d %H:%M:%S", timeArray) time_msg = '时间: [%s]' % now_time # 需要用时间来命名图片,所以时间信息中不能有/和:,否则报错;也不能带空格,否则发送时会报错 filename_time = time.strftime("%y%m%d-%H%M%S", timeArray) img_name = filename_time + '.png' # 新建截图文件夹 isExists = os.path.exists("截图文件") if not isExists: os.makedirs("截图文件") os.chdir("截图文件") ImageGrab.grab().save(img_name) # 截图并保存 itchat.send_image(img_name, toUserName='******') # 微信发送截图给自己 os.chdir("..") itchat.send(time_msg, toUserName='******') # 发送消息,截图时间 myshow.thread._signal_3.emit('[远控信息] 已发送截图')
def monitor_message(msg): # 监听好友是否撤回消息 content = msg['Content'] pattern = re.compile(r"\<\!\[CDATA\[\"(.*)\" 撤回了一条消息\]\]\>") result = re.findall(pattern, content) if result: message = f"☛{result[0]}☚于{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime())}撤回一条信息: {INFO.get('msg')}" itchat.send_msg(msg=message, toUserName='******') if INFO.get('file'): filePath = os.getcwd() + '\\' + INFO.get('file') if INFO.get('msg') == 'Recording': itchat.send_file(filePath, toUserName='******') elif INFO.get('msg') == 'Picture': itchat.send_image(filePath, toUserName='******') else: pass os.remove(filePath) INFO['file'] = None
def group_reply(msg): if msg['isAt']: print(msg['User']['UserName']) print('\n') if len(msg['Content']) <= 5: return msg['ActualNickName'] + ', 请在@后添加聊天内容' f = return_img(msg['Content'][5:], msg['ActualNickName']) print(msg['Content'][5:]) return itchat.send_image(f, toUserName=msg['User']['UserName'])
def text_reply(msg): if '吃啥' in msg['Text']: return 'yelp_response()' elif '生日' in msg['Text']: itchat.send('谢谢呀,感动感谢!', msg['FromUserName']) elif '牛逼' in msg['Text'] or '厉害' in msg['Text']: itchat.send('哈哈哈哈哈', msg['FromUserName']) path = './img/guitar.gif' itchat.send_image(path, msg['FromUserName']) elif '新年' in msg['Text'] and msg['FromUserName'] not in replied: sendHappyNewYear(msg) elif msg['FromUserName'] not in replied: path = './img/listening.gif' itchat.send(u'天豪大概在休息呢,你的消息已经收到啦,稍后会回复哒', msg['FromUserName']) itchat.send_image(path, msg['FromUserName']) replied.append(msg['FromUserName']) else: itchat.send(tuling_response(msg['Text']), msg['FromUserName'])
def tuling_reply(msg): # 为了保证在图灵Key出现问题的时候仍旧可以回复,这里设置一个默认回复 defaultReply = '收到 ' time.sleep(0.5) # print(msg["Text"][0:4]) print(msg["Text"]) # nick_name = msg["User"].get("NickName") # if nick_name == "小y": #好友名字或者群名称 # nick_name = msg["User"].get("NickName")#昵称 nick_name = msg["User"].get("NickName") #备注 # if nick_name == "name" or (msg.isAt): #好友名字或者群名称 if nick_name == "name": #好友名字或者群名称 # 如果图灵Key出现问题,那么reply将会是None itchat.send_image('F:/pythonwork/weixin_chat/ceshi_chat/1.jpg', toUserName='******') reply = '\n<自动回复>' # a or b的意思是,如果a有内容,那么返回a,否则返回b return reply or defaultReply
def imageGet(msg, cur, get_msg): global makeImage, autoMake if get_msg == "exit": makeImage = False autoMake = False elif get_msg == "help": msg.user.send("请输入订单好(MAxxxx)进行查询,或者输入exit退出查询") else: cur.execute( "select name from web_product where name='{}'".format(get_msg)) data = cur.fetchall() if data: image_name = "{}.png".format(get_msg) img = qrcode.make("http://trusme.imwork.net:82/web/detail/admin/") img.save(image_name) itchat.send_image(image_name, toUserName=msg.user.UserName) else: msg.user.send(u"没有这个单号")
def text_reply(msg): # 如果消息为@我,且我的群昵称为“@我 + 商品” if msg['isAt'] and msg['Content'][0:8] == '@@我 + 商品': # 截取消息正文字符串,提取出搜索词 searchword = msg['Content'][9:] print('消息来自于:{0},内容为:{1}\n'.format(msg['ActualNickName'], msg['Content'])) # 通过搜索词获取淘宝客商品优惠券信息 response = get_tk_coupon(searchword) # 遍历获取到的淘宝客商品优惠券信息 for r in response: # 商品标题 ordername = r['title'] # 商品当前价 orderprice = r['zk_final_price'] # 优惠券信息 coupon_info = r['coupon_info'] # 通过正则表达式提取优惠券信息中的面额 coupon_demonination = int(re.findall(r'(\d+)', coupon_info)[-1]) # 商品图片 orderimg = r['pict_url'] # 获取淘口令 token = get_token(url=r['coupon_click_url'], text=r['title']) # 券后价 couponprice = round(float(orderprice) - int(coupon_demonination), 1) # 通过新浪微博API生成优惠券链接的短链 link = r['item_url'] link_resp = requests.get( 'http://api.weibo.com/2/short_url/shorten.json?source=2849184197&url_long=' + link).text link_short = json.loads(link_resp, encoding='utf-8')['urls'][0]['url_short'] # 拼接组合文本消息字符串 msgs = '''/:gift{name}\n/:rose【在售价】{orderprice}元\n/:heart【券后价】{conponprice}元\n/:cake 【抢购链接】{link_short}\n-----------------\n复制这条信息\n{token}打开【手机淘宝】,即可查看\n------------------\n '''.format(name=ordername, orderprice=orderprice, conponprice=couponprice, token=token, link_short=link_short) # 发送文本消息 itchat.send(msg=str(msgs), toUserName=msg['FromUserName']) # 发送商品图片 try: image = urlretrieve(url=orderimg, filename=r'%s' % os.path.join(current_path, 'orderimg.jpg')) itchat.send_image(fileDir=r'%s' % os.path.join(current_path, 'orderimg.jpg'), toUserName=msg['FromUserName']) except Exception as e: print("发送图片失败,{}\n".format(e)) # 等待3秒继续发送 time.sleep(3)
def generate_result(com_queue=None): global friends_num, remarked_friends, star_friends # ------------------------------------------------------------------ # 结果生成 # 删除之前可能错在的png # !rm - rf how_many_friends_in_your_wechat / results / result.png # !ls -al how_many_friends_in_your_wechat/results print "generate_result..." img_path = result_path imgs = [] [ imgs.append(img_path + "/" + fn) for fn in os.listdir(img_path) if fn.endswith('.png') ] imgs.sort() # print imgs final_img = result_path + "/result.png" # 生成summary generate_summary(friends_num + friends_in_chatrooms, remarked_friends, star_friends) # 生成最终结果 bk = combine_images(imgs, inner_img_spacing=60) # 保存最终结果 bk.save(final_img) bk.close() # 将最终结果发到手机端「文件传输助手」 itchat.send_image(final_img, toUserName='******') # todo 提示完成 if com_queue: com_queue.put({"mode": 5}) print u"已生成!请在手机端的「文件传输助手」查看结果,记得分享和关注猿湿Xoong喔!" print u"已生成!请在手机端的「文件传输助手」查看结果,记得分享和关注猿湿Xoong喔!" print u"已生成!请在手机端的「文件传输助手」查看结果,记得分享和关注猿湿Xoong喔!" print threading.currentThread()
def search_people(people_name): user = itchat.search_friends(people_name) # 按备注名搜索好友 # noinspection PyBroadException try: nickname = user[0]['NickName'] # 获取微信名名称 username = user[0]['UserName'] # 获取用户ID head_img = itchat.get_head_img(username) # 获取头像 signature = user[0]['Signature'] # 获取个性签名 py_name = user[0]['PYQuanPin'] # 获取微信名拼音 remarkname = user[0]['RemarkName'] image_name = 'head_img_' + py_name + '.jpg' # 定义头像 with open('files\\' + image_name, 'wb') as f: f.write(head_img) f.close() msg_bb = '你的好友' + people_name + '的详细信息如下:微信名:' + nickname + '\n备注名:' + remarkname + '\n签名:' + signature + '\n头像:' itchat.send_msg(msg_bb, toUserName=self_user) itchat.send_image(image_name, toUserName=self_user) except Exception: itchat.send_msg('好友' + people_name + '不存在,请重新输入', self_user)
def send_msg_helper(msg): global face_bug # 这里如果这里的msg['Content']中包含消息撤回和id,就执行下面的语句 if re.search(r"\<\!\[CDATA\[.*撤回了一条消息\]\]\>", msg['Content']) is not None: # 获取消息的id old_msg_id = re.search("\<msgid\>(.*?)\<\/msgid\>", msg['Content']).group( 1) # 在返回的content查找撤回的消息的id old_msg = rec_msg_dict.get(old_msg_id, {}) # 得到消息 if len(old_msg_id) < 11: # 如果发送的是表情包 itchat.send_file(rev_tmp_dir + face_bug, toUserName='******') #os.remove(rev_tmp_dir + face_bug) else: msg_body = "告诉你一个秘密~" + "\n" \ + old_msg.get('msg_from') + " 撤回了 " + old_msg.get("msg_type") + " 消息" + "\n" \ + old_msg.get('msg_time_rec') + "\n" \ + "撤回了什么 ⇣" + "\n" \ + r"" + old_msg.get('msg_content') # 如果是分享存在链接 if old_msg['msg_type'] == "Sharing": msg_body += "\n就是这个链接➣ " + old_msg.get('msg_share_url') print(msg_body) # 将撤回消息发送到文件助手 itchat.send(msg_body, toUserName='******') # 有文件的话也要将文件发送回去 # 判断文msg_content是否存在,不存在说明可能是 if os.path.exists(os.path.join(rec_tmp_dir, old_msg['msg_content'])): if old_msg["msg_type"] == "Picture": itchat.send_image(os.path.join(rec_tmp_dir, old_msg['msg_content']), toUserName="******") elif old_msg["msg_type"] == "Video": itchat.send_video(os.path.join(rec_tmp_dir, old_msg['msg_content']), toUserName="******") elif old_msg["msg_type"] == "Attachment" \ or old_msg["msg_type"] == "Recording": itchat.send_file(os.path.join(rec_tmp_dir, old_msg['msg_content']), toUserName="******")
def document_handler(self, msg): self.bot.sendMessage( config.telegramId, f"File received, forwarding to {contact_shower(self.usr_nick, self.usr_remark)}" ) file_name = msg['document']['file_name'] file_id = msg['document']['file_id'] self.bot.download_file(file_id, file_name) print("File received, forwarding...") if msg['document']['mime_type'][:5] == 'video': itchat.send_video(file_name, self.usr_name) elif msg['document']['mime_type'][:5] == 'image': itchat.send_image(file_name, self.usr_name) else: itchat.send_file(file_name, self.usr_name) os.remove(file_name) self.bot.sendMessage(config.telegramId, "File forwarding complete!") print("File forwarded")
def readStory(self): print('readStory do') # stroy = dataUtil.getBookInfo('./从你的全世界路过.txt') stroy = dataUtil.getBookInfo('./送你一颗子弹.txt') dataUtil.getBingPhoto('0') yfei = wechat.getFriend('方铭玮') for txt in stroy: wechat.sendMessage(txt, yfei) # wechat.sendMessage(txt, 'filehelper') itchat.send_image('./bing.jpg', toUserName=yfei)
def note(msg): # print(msg) # 判断里面有没有出现replacemsg,如果有的话就说明是撤回 if re.search(r"<replacemsg>", msg['Content']) != None: try: print("Recalled!") # 把撤回的消息序号返回,但是不是oldmsgid的序号(这个oldmsgid不知道是什么东西) oldMsg = re.search("\<msgid\>(.*?)\<\/msgid\>", msg['Content']).group(1) sendMsg = msgRec[oldMsg]['FromName']; sendMsg += " 撤回了一条 " + msgRec[oldMsg]['Type'] + " 消息:" if msgRec[oldMsg]['Type'] == "Text" or msgRec[oldMsg]['Type'] == "Friends": sendMsg += msgRec[oldMsg]['Text'] itchat.send(sendMsg, toUserName='******') elif msgRec[oldMsg]['Type'] == "Picture": itchat.send(sendMsg, toUserName='******') itchat.send_image(msgRec[oldMsg]['FileName'], toUserName='******') elif msgRec[oldMsg]['Type'] == "Video": itchat.send(sendMsg, toUserName='******') itchat.send_video(msgRec[oldMsg]['FileName'], toUserName='******') elif msgRec[oldMsg]['Type'] == "Recording": itchat.send(sendMsg, toUserName='******') itchat.send_file(msgRec[oldMsg]['FileName'], toUserName='******') elif msgRec[oldMsg]['Type'] == "File": itchat.send(sendMsg, toUserName='******') itchat.send_file(msgRec[oldMsg]['FileName'], toUserName='******') elif msgRec[oldMsg]['Type'] == "Card": sendMsg += "名字为:" + msgRec[oldMsg]['RecommendInfo']['NickName'] itchat.send(sendMsg, toUserName='******') elif msgRec[oldMsg]['Type'] == "Map": x, y, location = re.search("<location x=\"(.*?)\" y=\"(.*?)\".*label=\"(.*?)\".*", msgRec[oldMsg]['OriContent']).group(1, 2, 3) if location is None: sendMsg += " x: " + x.__str__() + " y: " + y.__str__() else: sendMsg += " x: " + x.__str__() + " y: " + y.__str__() + " loc: " + location itchat.send(sendMsg, toUserName='******') elif msgRec[oldMsg]['Type'] == 'Sharing': sendMsg += "内容:" + msgRec[oldMsg]['Text'] + "连接:" + msgRec[oldMsg]['Url'] except: print("Error!") else: # 其实我也不知道除了撤回还有什么别的……抢红包什么的都不支持啊,就直接发出来吧,总之有记录 itchat.send("不支持的消息", toUserName='******')
def test(msg): # print msg['ToUserName'] if msg['ToUserName'] == 'filehelper': st = time.time() (pid,_) = msg['FileName'].split('.') path = base_path+os.path.sep+pid+os.path.sep if not(os.path.exists(path)): os.makedirs(path) getCapture(src_(path)) with open(tmp_(path), "wb") as f: f.write(msg["Text"]()) matching(path) print "time: ", (time.time() - st) itchat.send_image(res_(path), toUserName='******') print "time: ", (time.time() - st)
def send_message_to_friend(friend, message, message_type): ''' 发送信息给微信好友 :param friend: 微信好友的UserName :param message: 发送的信息 :param message_type: 信息类型 ''' m_t = {'0': 'msg', '1': 'img', '2': 'file'} now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())) message_type = m_t[str(message_type)] if message_type == 'msg': itchat.send_msg(message, friend) print('Send message to "%s" %s' % (friend, now)) elif message_type == 'img': itchat.send_image(message, friend) print('Send image to "%s" %s' % (friend, now)) elif message_type == 'file': itchat.send_file(message, friend) print('Send file to "%s" %s' % (friend, now))
def handler_receive_msg(msg): # 处理收到的消息 message = msg['Text'] toName = msg['ToUserName'] path = 'E:/sample/temp.jpg' # 临时保存截屏图片地址 if toName == "filehelper": if message == "cap": # 拍照 # 要使用摄像头,需要使用cv2.VideoCapture(0)创建VideoCapture对象, # 参数:0指的是摄像头的编号。如果你电脑上有两个摄像头的话,访问第2个摄像头就可以传入1 cap = cv2.VideoCapture(0) ret, img = cap.read() # 获取一帧 cv2.imwrite("temp.jpg", img) itchat.send('@img@%s' % u'temp.jpg', 'filehelper') cap.release() # 释放资源 if message[0:3] == "cmd": # 处理cmd命令 os.system(message.strip(message[0:4])) if message == "pc": # 截图 im = ImageGrab.grab() # 实现截屏功能 im.save(path, 'JPEG') # 设置保存路径和图片格式 itchat.send_image(path, 'filehelper')
def dis_files(msg): msg['Text'](msg['FileName']) filename = msg['FileName'] portion = os.path.splitext(filename) itchat.send_msg('已收到文件', toUserName=msg['FromUserName']) global newname if portion[1] != ".txt": #根据后缀来修改,如无后缀则空 newname = portion[0] + ".txt" #要改的新后缀 os.rename(filename, newname) else: newname = msg['FileName'] try: draw_wordcloud(str(newname)) except IOError: return "Error: 没有找到文件或读取文件失败" else: itchat.send_image('/python/MyWordCloud.jpg', toUserName=msg['FromUserName']) return "sussess"
def group_file_reply(msg): global private_groups get_config_users() msg.download('./filecache/' + msg.fileName) # 消息来自于哪个群聊 group_name = msg['User']['NickName'] logger.logger.info('[group_file_reply] Files recieved from:{}'.format(group_name)) if group_name in private_groups.keys(): group_id = private_groups[group_name] logger.logger.info('[group_file_reply] Files forward to:{}'.format('filehelper')) if msg.type == 'PICTURE': # itchat.send_image('./filecache/' + msg.fileName, group_id) itchat.send_image('./filecache/' + msg.fileName, 'filehelper') elif msg.type == 'VIDEO': # itchat.send_video('./filecache/' + msg.fileName, group_id) itchat.send_video('./filecache/' + msg.fileName, 'filehelper') else: # itchat.send_file('./filecache/' + msg.fileName, group_id) itchat.send_file('./filecache/' + msg.fileName, 'filehelper')
def photo_joint(): func_name = "好友头像拼接" logger.info('start %s ' % func_name) itchat.auto_login(hotReload=True) itchat.dump_login_status() friends = itchat.get_friends(update=True)[0:] user = friends[0]["UserName"] num = 0 pwd_path = os.path.abspath(os.getcwd()) desc_photos = os.path.join(pwd_path, 'res/photos') desc_full = os.path.join(pwd_path, 'res') for i in friends: img = itchat.get_head_img(userName=i["UserName"]) file_image = open(desc_photos + "/" + str(num) + ".jpg", 'wb') file_image.write(img) file_image.close() num += 1 ls = os.listdir(desc_photos) each_size = int(math.sqrt(float(640 * 640) / len(ls))) # 算出每张图片的大小多少合适 lines = int(640 / each_size) image = Image.new('RGBA', (640, 640)) # 创建640*640px的大图 x = 0 y = 0 for i in range(0, len(ls) + 1): try: img = Image.open(desc_photos + "/" + str(i) + ".jpg") except IOError: print("Error") else: img = img.resize((each_size, each_size), Image.ANTIALIAS) image.paste(img, (x * each_size, y * each_size)) # 粘贴位置 x += 1 if x == lines: # 换行 x = 0 y += 1 image.save(desc_full + "/好友头像拼接图.png") itchat.send_image(desc_full + "/好友头像拼接图.png", 'filehelper') # 拼接完成发送给文件传输助手 logger.info('end %s ' % func_name)
def map_reply(msg): if msg['FromUserName'] == callback.xiaoice: try: if msg['Type'] == 'Picture': msg['Text'](msg['FileName']) itchat.send_image(msg['FileName'], callback.msg.FromUserName) elif msg['Type'] == 'Text': itchat.send_msg(msg.text, callback.msg.FromUserName) elif msg['Type'] == 'VIDEO': logger.warning(msg) msg['Text'](msg['FileName']) itchat.send_video( msg['FileName'], callback.msg.FromUserName) else: logger.warning(msg) msg['Text'](msg['FileName']) itchat.send_video(msg['FileName'], callback.msg.FromUserName) callback.msg = None except Exception as e: logger.error('Failed to reply map info {}'.format(e))
def picdeal(msg): global lis global totalPicNumber global tempSize global resend try: msg['Text'](path + msg['FileName']) # save pic first !!!!!! except: print('pic save failed!') return fileFullPath = os.path.join(path, msg['FileName']) fileSize = os.path.getsize(fileFullPath) if fileSize == tempSize: resend = 1 os.remove(fileFullPath) try: itchat.send_image('f:/wxPic/' + str(totalPicNumber) + '.gif', toUserName=msg['FromUserName']) except: print('send repeated emoji error!') return # print('%s(Robot)--->%s:%s'%(myName,picFromName,str(tatalPicNumber)+'.gif')) return else: resend = 0 tempSize = fileSize # save this time's pic size fileType = os.path.splitext(msg['FileName'])[1] if (fileSize in lis ) or fileSize == 0 or fileSize / 1024 > 500 or fileType != '.gif': try: os.remove(fileFullPath) except: print('emoji delete failed!') else: totalPicNumber = totalPicNumber + 1 lis.append(fileSize) newName = os.path.join(path, str(totalPicNumber) + '.gif') try: os.rename(fileFullPath, newName) except: print('emoji rename failed!') print('get new emoji ^_^')
def auto_reply(msg): # NickName = msg['User']['NickName'] # user = itchat.search_friends(name=NickName)[0] # user.send(u"山风大哥家的baozi:" + getResponse(msg['Text'])['results'][0]['values']['text']) userid = msg['FromUserName'] # 每个用户和群聊都会使用很长的ID来区分 temp=getResponse(msg['Text']) #回复新闻 #判断是否是新闻标志类 if temp['intent']['code']==10003: #是 if temp['results'][1]['resultType']=='news': buff1=temp['results'][0]['values']['text'] news=temp['results'][1]['values']['news'] buff2="" for new in news: buff2=buff2+"\n标题:("+new['info']+")"+new['name']+"\n链接:"+new['detailurl'] itchat.send(u"山风大哥家的baozi:" + buff1 + buff2,userid) else: buff1=temp['results'][1]['values']['text'] buff2=temp['results'][0]['values']['url'] itchat.send(u"山风大哥家的baozi:"+buff1+"\n链接:"+buff2,userid) #回复图片 elif temp['intent']['code']==10014: buff1 = temp['results'][1]['values']['text'] buff2 = temp['results'][0]['values']['url'] itchat.send(u"山风大哥家的baozi:" + buff1 + "\n链接:" + buff2, userid) #回复关键词 elif ('秦岚' in msg['Text']) or ('秦嵐'in msg['Text']): return '秦岚(Qin Lan),1981年7月17日出生于辽宁省沈阳市,毕业于沈阳工业大学会计系,中国内地女演员、歌手。\ 2001年,出演个人首部电视剧《大唐情史》,从而正式进入演艺圈;2002年,因在古装爱情剧《还珠格格3》中饰演陈知画而崭露头角;\ 2003年,出演古装武侠剧《风云2》;2004年,主演古装爱情剧《护花奇缘》;2006年,出演古装励志剧《绣娘兰馨》;\ 2007年,因在青春爱情剧《又见一帘幽梦》中饰演汪绿萍而获得更多关注;2009年,出演剧情片《南京!南京!》;\ 2011年,凭借家庭伦理片《母语》荣获第三届英国万像国际华语电影节“最具潜力女演员奖”;2012年,凭借古装传奇片\ 《王的盛宴》荣获第七届亚洲电影节“最佳女配角”;同年,在古装传奇剧《楚汉传奇》中饰演吕雉;2013年,秦岚推\ 出首张个人EP《一肩之隔》;2014年,出演古装武侠剧《神雕侠侣》;2015年,在都市爱情剧《咱们相爱吧》中饰演蔡春妮;\ 2017年5月,秦岚担当出品人的网络电影《超级APP》在广州开机;2018年7月,在古装剧《延禧攻略》中饰演富察容音。' elif ('山风大哥' in msg['Text']) or ('山風大哥' in msg['Text']): itchat.send(u"山风大哥家的baozi:喏,就是下面这位小姐姐咯~", userid) itchat.send_image(fileDir='./images/shanfeng.gif', toUserName=userid) # 普通回复 else: itchat.send(u"山风大哥家的baozi:" + temp['results'][0]['values']['text'],userid)
def send_news(): """ 给你心爱的ta发送消息和图片 :return: """ # 计算相恋天数 inLoveDate = datetime.datetime(2016, 5, 30) # 相恋的时间 todayDate = datetime.datetime.today() inLoveDays = (todayDate - inLoveDate).days Wordsnumber = random.randint(1, 120) #随机挑选出情话 # 获取情话 file_path = love_word_path with open(file_path) as file: love_word = file.readlines()[Wordsnumber].split(':')[1] itchat.auto_login(hotReload=True) # 热启动,不需要多次扫码登录 my_friend = itchat.search_friends(name=u'骑摩托的糖') girlfriend = my_friend[0]["UserName"] print(girlfriend) message = """ 亲爱的{}: 早上好,今天是你和 NGU 相恋的第 {} 天~ 今天他想对你说的话是: {} 最后也是最重要的! """.format("骑摩托的糖", str(inLoveDays), love_word) itchat.send(message, toUserName=girlfriend) files = os.listdir(pic_path) print(files) file = files[Wordsnumber] print(file) love_image_file = "./表白图片/" + file try: itchat.send_image(love_image_file, toUserName=girlfriend) except Exception as e: print(e)
def sendimg(): if request.method == 'POST': username = request.values.get('username') # check if the post request has the file part if 'file' not in request.files: return 'no_file' ff = request.files['file'] 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 text_reply(msg): message = '' key = '' print msg['Text']#unicode ''' print type(msg['Text'])#unicode msg['Text'].encode("utf-8") unicode转为 str print urllib.quote(msg['Text'].encode("utf-8")) ''' if 'jd.com' in msg['Text'] and 'item' in msg['Text']: sku_id = jd.getGoodsIdByUrl(msg['Text']) goods_name,price,fanli = jd.getProductInfo(sku_id) click_url = jd.getFanliLink(sku_id) message = u'一一一一返 利 信 息一一一一\n'+goods_name+'\n'+u'【商品原价】'+price+'元'+'\n'+u'【商品返利】'+fanli+'元'+'\n'+u'【返利链接】'+jd.getShortUrl(click_url) elif '帮助' in msg['Text']: message = '[愉快]【淘宝购物领券】假如你想买鼠标垫,请发送"找鼠标垫"给机器人,机器人会把找到的鼠标垫相关优惠券链接发给你,点进去复制淘口令,再打开淘宝/天猫APP就可以领到优惠券啦。\n[愉快]【京东购物返利】打开京东APP,找到自己想买的商品,点击右上角分享按钮,把商品分享给机器人,就可以看到返利链接啦,确认收货后发送【提现】,等待客服审核就可以啦。\n快试试吧...' #回复表情 elif '[' in msg['Text'] and ']' in msg['Text']: message = u'[愉快]' elif '提现' in msg['Text']: #需要给主人发消息,先获得主人的id,以@符号开头 user_content = itchat.search_friends(name = u'雨一直下') userName = user_content[0]['UserName'] #获取提现申请人的昵称 friend_content = itchat.search_friends(userName = msg.fromUserName) friend_name = friend_content['NickName'] #给主人发消息提醒 itchat.send( friend_name+u'申请提现',toUserName = userName) #判断提现人性别 if friend_content['Sex'] == 1: message = friend_name +u' 帅哥请耐心等待,客服确认中' elif friend_content['Sex'] == 0: message = friend_name +u'美女请耐心等待,客服确认中' else: message = friend_name +u'请耐心等待,客服确认中' #活动页转链接 elif 'hzlxy' in msg['Text']: link = msg['Text'].encode("utf-8").replace('hzlxy','') link = re.sub(r'\?.*','',link) r = requests.get(link) url = r.url duan_url = jd.getSelfCode(url) short_url = jd.getShortUrl(duan_url) message = short_url elif 'xmtq' in msg['Text'] or '天气预报' in msg['Text']: if 'xmtq' in msg['Text']: key = 'xmtq' else: key = 'beijingtianqi' weather_url = 'https://www.baidu.com/s?ie=UTF-8&wd=%s'%key browser = webdriver.PhantomJS(executable_path=r'/usr/local/bin/phantomjs') browser.get(weather_url) browser.maximize_window() browser.save_screenshot('send_auto_answes.png')#保存截图 #获取天气模板的位置、尺寸大小 imgelement = browser.find_element_by_xpath('//*[@id="1"]') location = imgelement.location#获取天气x,y轴坐标 size = imgelement.size#获取天气的长宽 rangle = (int(location['x']),int(location['y']),int(location['x']+size['width']),int(location['y']+size['height']-20)) i = Image.open('send_auto_answes.png') #打开0.png tinaqi = i.crop(rangle)#使用Image的crop函数,从截图中再次截取我们需要的 tinaqi.save('send_auto_answes_0.png') browser.close() itchat.send_image('send_auto_answes_0.png',msg.fromUserName) ''' user_content = itchat.search_friends(name=u'雨一直下') userName = user_content[0]['UserName'] itchat.send_image('send_%s.png'%index,toUserName = userName) ''' elif '大盘' in msg['Text']: #fund_list = ['162605','160505','002121','000011','163402','070032','217027','165312','519066','110022'] fund_list = ['dapan',] for index,fund in enumerate(fund_list): fund_id = str(fund) url = 'https://www.baidu.com/s?ie=UTF-8&wd=%s'%str(fund_id) #url = 'http://fund.eastmoney.com/%s.html'%str(fund_id) picName = 'fund_%s.png'%index browser = webdriver.PhantomJS(executable_path=r'/usr/local/bin/phantomjs') browser.get(url) browser.maximize_window() browser.save_screenshot(picName)#保存截图 imgelement = browser.find_element_by_xpath('//*[@id="1"]/div[1]') ''' if fund_id == '002121': imgelement = browser.find_element_by_xpath('//*[@id="2"]') ''' location = imgelement.location#获取x,y轴坐标 size = imgelement.size#获取长宽 rangle = (int(location['x']),int(location['y']),int(location['x']+size['width']),int(location['y']+size['height']-20)) i = Image.open(picName) #打开 tinaqi = i.crop(rangle)#使用Image的crop函数,从截图中再次截取我们需要的 tinaqi.save('send_fund_%s.png'%index) browser.close() #发送 user_content = itchat.search_friends(name=u'雨一直下') userName = user_content[0]['UserName'] itchat.send_image('send_fund_%s.png'%index,toUserName = userName) ''' if fund_id in ['070032','217027','165312','519066','110022']: user_content_baby = itchat.search_friends(name=u'徐莹') userName_baby = user_content_baby[0]['UserName'] itchat.send_image('send_fund_%s.png'%index,toUserName = userName_baby) ''' elif '找' in msg['Text']: msg['Text'] = msg['Text'].replace('找','') url = 'http://techseo.cn/yhq/?r=l&kw=%s'%(urllib.quote(msg['Text'].encode("utf-8"))) message = u'一一一一导 购 信 息一一一一\n已为您找到:%s\n点击下方链接查看\n%s\n-----------\n发送【帮助】查看使用机器人流程\n更多大额神券商品点击下方链接:\nhttp://t.cn/RYaBrUa'%(msg['Text'],jd.getShortUrl(url)) else: #url = 'http://techseo.cn/yhq/?r=l&kw=%s'%(urllib.quote(msg['Text'].encode("utf-8"))) #message = u'一一一一导 购 信 息一一一一\n已为您找到:%s\n点击下方链接查看\n%s\n-----------\n发送【帮助】查看使用机器人流程\n更多大额神券商品点击下方链接:\nhttp://t.cn/RYaBrUa'%(msg['Text'],jd.getShortUrl(url)) #message = '您输入的指令有误,请发送【帮助】查看教程' pass # if message: # print message itchat.send(message,msg.fromUserName) #记录 now = time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(time.time())) with open('log.txt',r'a+') as my: my.write('TEXT,'+itchat.search_friends(userName = msg.fromUserName)['NickName']+','+msg['Text']+','+now+'\n')
import jieba wordlist_jieba = jieba.cut(text, cut_all=True) wl_space_split = " ".join(wordlist_jieba) # wordcloud词云 import matplotlib.pyplot as plt from wordcloud import WordCloud, ImageColorGenerator import os import numpy as np import PIL.Image as Image d = os.path.dirname(__file__) # 更改目录下Wordcloud生成图片,如:xiaohuangren.jpg alice_coloring = np.array(Image.open(os.path.join(d, "xiaohuangren.jpg"))) # win系统需要更改font路径,如:C:\Windows\Fonts\msyhbd.ttc my_wordcloud = WordCloud(background_color="white", max_words=2000, mask=alice_coloring, max_font_size=40, random_state=42, font_path='/Users/sebastian/Library/Fonts/Arial Unicode.ttf')\ .generate(wl_space_split) image_colors = ImageColorGenerator(alice_coloring) plt.imshow(my_wordcloud.recolor(color_func=image_colors)) plt.imshow(my_wordcloud) plt.axis("off") plt.show() # 保存图片 并发送到手机 my_wordcloud.to_file(os.path.join(d, "wechat_cloud.png")) itchat.send_image("wechat_cloud.png", 'filehelper')
toImage = Image.new('RGBA', (640, 640)) print(numline) x = 0 y = 0 for i in pics: try: # 打开图片 img = Image.open(i) except IOError: print("Error: 没有找到文件或读取文件失败") else: # 缩小图片 img = img.resize((eachsize, eachsize), Image.ANTIALIAS) # 拼接图片 toImage.paste(img, (x * eachsize, y * eachsize)) x += 1 if x == numline: x = 0 y += 1 toImage.save(user + ".jpg") itchat.send_image(user + ".jpg", 'filehelper')
while True: if rounds == 4: print '********refit the model*************' pullfuturekline() pullspotkline() merge_spot() merge_future() classification() rounds = 0 print '*********long term***********' print '********apply the model *************' test = model(15) print '********plot*************' plot(15, True) print '************send to itchat*********' itchat.send_image('data/figure.png', toUserName='******') print '*********short term***********' print '********apply the model *************' test = model(2) print '********plot*************' plot(2) print '************send to itchat*********' itchat.send_image('data/figure.png', toUserName='******') itchat.send( 'long '+str(test.iloc[-1]['longposition'])+'\t'+str(test.iloc[-1]['longamount'])+'\n'+ 'short '+str(test.iloc[-1]['shortposition'])+'\t'+str(test.iloc[-1]['shortamount'])+'\n'+ 'liq '+str(test.iloc[-1]['liqbtc'])+'\n' 'hold '+str(test.iloc[-1]['holdbtc'])+'\n'+ 'btc '+str(test.iloc[-1]['btc_future_back'])+'\n'+ 'money '+str(test.iloc[-1]['fiat_future_back']), toUserName='******')