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 demo(): # 可以保持一段时间登录状态,而不用每次运行代码都要扫码登录了 itchat.auto_login(hotReload=True) itchat.dump_login_status() #遍历好友列表 friends = itchat.get_friends(update=True)[:] for friend in friends: ''' 典型属性内容如下: {'MemberList': <ContactList: []>, 'VerifyFlag': 0, 'DisplayName': '', 'EncryChatRoomId': '', 'Alias': '', 'PYQuanPin': 'Evi1hui', 'PYInitial': 'EVI1HUI', 'RemarkName': '', 'AppAccountFlag': 0, 'City': '阳泉', 'ChatRoomId': 0, 'AttrStatus': 2147715109, 'UniFriend': 0, 'OwnerUin': 0, 'Statues': 0, 'StarFriend': 0, 'ContactFlag': 3, 'HeadImgUrl': '/cgi-bin/mmwebwx-bin/webwxgeticon?seq=654224580&username=@78606d673dcff895a468688273bb5e92862c15d9a0e8a574865785c8a0354660&skey=@crypt_cd4d9fd6_f8d94dff59afaff6b231f3f4b8aa1e15', 'Sex': 1, 'Uin': 0, 'HideInputBarFlag': 0, 'MemberCount': 0, 'Signature': '沉默的大多数', 'NickName': 'Evi1hui', 'RemarkPYQuanPin': '', 'UserName': '******', 'IsOwner': 0, 'RemarkPYInitial': '', 'KeyWord': 'wan', 'Province': '山西', 'SnsFlag': 177} ''' if friend['NickName'] == '兜哥的生活号': #print(friend['NickName']) print(friend) #发送的主键为UserName字段的值 itchat.send_msg('Nice to meet you!','@1df002b437271f75f1afd07b937801b3a7211aad221e24115fb153674ca044b7')
def main(): #登陆微信 itchat.auto_login(hotReload=True) user_content = itchat.search_friends(name=u'雨一直下') userName = user_content[0]['UserName'] itchat.send(getWeather(000),toUserName = userName)# itchat.send(getWeather(000),toUserName = userName)#
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()
def main(): # 微信登陆 itchat.auto_login(hotReload=True) # 获取微信好友信息 friends = itchat.get_friends(update=True) # 判断数据库是否存有数据,有则清空数据表 sql1 = 'SELECT COUNT(1) FROM wx_friend_list LIMIT 1;' row_count = readDb(sql1) # print(row_count[0]['count']) # sql_test = 'INSERT INTO wx_friend_list (Sex) values(1);' # print(sql_test) # writeDb(sql_test) if row_count[0]['count'] != 0: truncate_sql = 'TRUNCATE TABLE wx_friend_list;' writeDb(truncate_sql) if True: print('********************清空表成功.********************') print('********************开始写入数据库*****************') # 拼接insert Sql语句 i = 0 for friend in friends: del friend['MemberList'] cols = ','.join(friend.keys()) # qmarks = ','.join(['%s']*len(friend)) values = tuple(friend.values()) sql = 'INSERT INTO wx_friend_list({}) VALUES {};'.format(cols, values) # print(sql) writeDb(sql) # 写入数据库 if True: i += 1 print('已写入{}条数据'.format(i)) if friend == friends[-1]: print('********************数据写入完成********************')
def send_news(): try: # 登陆你的微信账号,会弹出网页二维码,扫描即可 itchat.auto_login(hotReload=True) # 获取你对应的好友备注,这里的小明我只是举个例子 # 改成你最心爱的人的名字。 my_friend = itchat.search_friends(name=u'小明') # 获取对应名称的一串数字 XiaoMing = my_friend[0]["UserName"] # 获取金山字典的内容 message1 = str(get_news()[0]) content = str(get_news()[1][17:]) message2 = str(content) message3 = "来自你最爱的人" # 发送消息 itchat.send(message1, toUserName=XiaoMing) itchat.send(message2, toUserName=XiaoMing) itchat.send(message3, toUserName=XiaoMing) # 每86400秒(1天),发送1次, # 不用linux的定时任务是因为每次登陆都需要扫描二维码登陆, # 很麻烦的一件事,就让他一直挂着吧 # t = time(86400, send_news()) # t.start() except: message4 = u"今天最爱你的人出现了 bug /(ㄒoㄒ)/~~" itchat.send(message4, toUserName=XiaoMing)
def sendall(msg): itchat.auto_login(hotReload=True) itchat.dump_login_status() # 遍历好友列表 friends = itchat.get_friends(update=True)[:] for friend in friends: ''' 典型属性内容如下: {'MemberList': <ContactList: []>, 'VerifyFlag': 0, 'DisplayName': '', 'EncryChatRoomId': '', 'Alias': '', 'PYQuanPin': 'Evi1hui', 'PYInitial': 'EVI1HUI', 'RemarkName': '', 'AppAccountFlag': 0, 'City': '阳泉', 'ChatRoomId': 0, 'AttrStatus': 2147715109, 'UniFriend': 0, 'OwnerUin': 0, 'Statues': 0, 'StarFriend': 0, 'ContactFlag': 3, 'HeadImgUrl': '/cgi-bin/mmwebwx-bin/webwxgeticon?seq=654224580&username=@78606d673dcff895a468688273bb5e92862c15d9a0e8a574865785c8a0354660&skey=@crypt_cd4d9fd6_f8d94dff59afaff6b231f3f4b8aa1e15', 'Sex': 1, 'Uin': 0, 'HideInputBarFlag': 0, 'MemberCount': 0, 'Signature': '沉默的大多数', 'NickName': 'Evi1hui', 'RemarkPYQuanPin': '', 'UserName': '******', 'IsOwner': 0, 'RemarkPYInitial': '', 'KeyWord': 'wan', 'Province': '山西', 'SnsFlag': 177} ''' UserName=friend['UserName'] NickName=friend['NickName'] City=friend['City'] #print("UserName:%s NickName:%s City:%s" % (UserName,NickName,City)) # 发送的主键为UserName字段的值 text="hi %s,%s" %(NickName,msg) # 休眠10秒 time.sleep(10) print(text) itchat.send_msg(text, UserName)
def itchat_send(): sms = get_hyper_links_rmrb() sms_text = "\n".join(sms) itchat.auto_login() name = itchat.search_friends(name = 'Mao') Mao = name[0]["UserName"] itchat.send_msg(sms_text, toUserName = Mao)
def push_wechat(name, real_price, real_percent, type): name='wwwei' itchat.auto_login(hotReload=True) account=itchat.get_friends(name) for i in account: if i['PYQuanPin']==name: toName=i['UserName'] content=name+' ' + str(real_price)+' '+ str(real_percent)+' percent '+ type itchat.send(content,toUserName=toName)
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()
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()
def main(): itchat.auto_login(hotReload=True) while True: time.sleep(1) current_time = time.localtime(time.time()) print time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time())) # get_fund() # break if ((current_time.tm_hour == 6) and (current_time.tm_min) == 29 and (current_time.tm_sec == 0)): save_jpg() if(((current_time.tm_hour == 14) and (current_time.tm_min) == 30 and (current_time.tm_sec == 0))): get_fund()
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()
def __init__(self, roomNicks): global wxRooms, myUid itchat.auto_login(hotReload=True, enableCmdQR=2, exitCallback=wechatExit) all_rooms = itchat.get_chatrooms(update=True) for r in all_rooms: if r['NickName'] in roomNicks: wxRooms[r['UserName']] = r['NickName'] wxRoomNicks[r['NickName']] = r['UserName'] logger.info('Room {} found.'.format(r["NickName"])) else: logger.info('{}: {}'.format(r['UserName'], r['NickName'])) friends = itchat.get_friends() myUid = friends[0]["UserName"]
def get_fund(): ''' 162605景顺长城鼎益混合(LOF) 160505博时主题行业混合(LOF) 002121广发沪港深新起点股票 000011华夏大盘精选混合 163402兴全趋势投资混合(LOF) 070032 217027 165312 519066 110022 ''' itchat.auto_login(hotReload=True) fund_list = ['162605','160505','002121','000011','163402','070032','217027','165312','519066','110022'] 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'D:\programfiles\anaconda\Lib\site-packages\selenium\webdriver\phantomjs\bin\phantomjs.exe') browser.get(url) browser.maximize_window() browser.save_screenshot(picName)#保存截图 imgelement = browser.find_element_by_xpath('//*[@id="body"]/div[14]/div/div/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) #打开 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)
def testcase1(): id='@5493580a22c9ba5db849ba33d0911d3d' content=datetime.datetime.now().strftime("%H:%M:%S") itchat.auto_login(hotReload=True) #itchat.auto_login() itchat.send(content,toUserName='******') account=itchat.get_friends(u'wwwei') print(account) print(type(account)) for i in account: #print(type(i)) #print(i) if i[u'PYQuanPin']==u'爱惟创意': print(i['UserName']) #print(i) #itchat.send(content, toUserName=id) print('done')
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()
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()
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()
def login(): print "login begin" itchat.auto_login() itchat.run() print "login end"
def __init__(self,Name): itchat.auto_login(hotReload=True) # 查找特定的人获取其ID,现在的版本的ID不是固定的,不断的在更新 self.user = itchat.search_friends(Name)[0]['UserName']
def wechat(text, contact): itchat.auto_login(hotReload=True) #itchat.auto_login() itchat.send(text, toUserName='******')
def login(): itchat.auto_login(hotReload=True)
def weixinlogin(): itchat.auto_login(hotReload=True) friends = itchat.get_friends() for friend in friends: print(friend)
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = 'ziyi' import itchat import time import datetime def timerfun(): while True: now = datetime.datetime.now() current_time = time.localtime(time.time()) if ((current_time.tm_hour == 10) and (current_time.tm_min == 13)): print('send-case') case_path = '../data/chatrooms/management_information.txt' case_contents = get_contents(case_path) if case_contents: print(case_contents) sent_work_information1(case_contents) print(now, '金融行业的实习信息发送成功') with open('../data/chatrooms/all_work.txt', 'a') as f: f.write('\n') f.write('\n') f.write('\n') f.write(str(now)) f.write('\n') f.write(case_contents) time.sleep(60) # 每次判断间隔1s,避免多次触发事件 if ((current_time.tm_hour == 10) and (current_time.tm_min == 14)): print('send-case')
# coding:utf-8 import itchat,time,sys,xlwt file = xlwt.Workbook() table = file.add_sheet('info',cell_overwrite_ok=True) # 登录-持续 itchat.auto_login(enableCmdQR=2) print(u"logged") # 获取好友列表 friends = itchat.get_friends(update=True)[0:] male = female = other = 0 for i in friends[1:]: sex = i["Sex"] if sex == 1: male += 1 elif sex == 2: female += 1 else: other += 1 total = len(friends[1:]) table.write(0,7,u'【共'+str(len(friends)-1)+u'位朋友,'+str(male)+u'位男性朋友,'+str(female)+u'位女性朋友,另外'+str(other)+u'位不明性别】') table.write(0,0,u' 【昵称】') table.write(0,1,u' 【备注名】')
import time flag = Image.open('China-Flag.png') # flag dir here flag_w, flag_h = flag.size counter = 0 def process_img(filename): img = Image.open(filename) img_w, img_h = img.size re_flag = flag.resize( (int(flag_w / flag_h * 0.25 * img_h), int(0.25 * img_h)), Image.ANTIALIAS) img.paste(re_flag, (img_w - int(flag_w / flag_h * 0.25 * img_h), img_h - int(0.25 * img_h), img_w, img_h)) img.save(f'process.png') return counter @itchat.msg_register([itchat.content.PICTURE]) def get_img(msg): # friend = itchat.search_friends(userName=msg['FromUserName']) filename = msg['FileName'] process_img(filename) itchat.send_image('process.png', msg['FromUserName']) time.sleep(2) if __name__ == "__main__": itchat.auto_login(enableCmdQR=2)
def main(): itchat.utils.print_cmd_qr = print_cmd_qr itchat.auto_login(enableCmdQR=2, hotReload=True) itchat.run()
def start_wechat_bot(): global bot_name #如果是在服务器运行,auto_login 加上参数 enableCmdQR=2 itchat.auto_login() # 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()
def main(): tb_login.get_cookies(False) itchat.auto_login(True) itchat.run(True)
index = i + 1 continue if (text == "没有就没有,我继续玩我的游戏了~http://t.cn/EtRviOV"): text = "[捂脸]" time.sleep(1) logger.info("机器人宝宝" + str(index) + "回复:" + text) return text @itchat.msg_register(itchat.content.TEXT) def text_reply(msg): return get_response(msg) if __name__ == '__main__': itchat.auto_login() # hotReload = True, 保持在线,下次运行代码可自动登录 hotReload=True friends = itchat.get_friends(update=True)[0:] #获取自己的UserName Name = {} RemarkName = {} wangming = {} RemarkValue = [] Nic = [] User = [] for i in range(len(friends)): RemarkValue.append(friends[i]["RemarkName"]) Nic.append(friends[i]["NickName"]) #存的是微信名称 User.append(friends[i]["UserName"]) for i in range(len(friends)): Name[Nic[i]] = User[i] RemarkName[User[i]] = RemarkValue[i] wangming[User[i]] = Nic[i]
p.stop() robot.Motor_Stop() GPIO.output(8, GPIO.LOW) GPIO.output(LED_CTR, GPIO.HIGH) elif command.find(u"黑") !=-1 and command.find(u"线") !=-1: print ("黑线") robot.TrackLine() elif command == "状态": os.system('cat deng.txt door.txt tv.txt >all.txt') itchat.send_file("/home/pi/dai/command/all.txt",toUserName='******') else : res = get_response(command) itchat.send(res or 'I Love You !!!', toUserName='******') say(res) else: #根据ToUserName的ID号来搜索对应的微信昵称 TONAME = itchat.search_friends(userName=msg['ToUserName'])['NickName'] today = time.strftime(' %Y-%m-%d %H:%M:%S', time.localtime()) time = FROMNAME + '-->' + TONAME +today print (time) time.sleep(1) reload(sys) itchat.auto_login(enableCmdQR=2,hotReload=True) #使能命令行验证登陆,以及登陆后免验证 itchat.send("ok to speak",toUserName='******') itchat.run()
#coding=utf8 import re import itchat from itchat.content import * ''' 0.0.1版本 功能: 1.匹配群聊关键字 说 ,然后回复接受到的消息 ''' # 群聊监控 @itchat.msg_register(TEXT, isGroupChat=True) def groupchat_reply(msg): room_name = itchat.search_chatrooms(userName=msg[u'FromUserName']) print(u"来自-%s-群聊消息|%s:%s" % (room_name[u'NickName'], msg['ActualNickName'], msg['Text'])) # 匹配说关键字 if (re.match(u'^说', msg['Text'])): itchat.send_msg(msg['Text'].replace(u'说', ''), msg[u'FromUserName']) if (re.match(u'^搜', msg['Text'])): itchat.send_msg(u'电影名xxx', msg[u'FromUserName']) itchat.auto_login(hotReload=True, enableCmdQR=True) itchat.run(debug=True)
def main(): itchat.auto_login(enableCmdQR=2, hotReload=True) itchat.run()
#对列表中好友进行群发 for friend in friends_list: toFriend = friend['UserName'] itchat.send(mass_msg,toFriend) time.sleep(1)#每发送一次暂停一秒(防冻结帐号) else: #单独发送,索取收消息人的备注、待发送的消息内容、重复发送次数 ps = input('Please enter a friend note : ') msg = input('Please enter the message you want to send : ') times = eval(input('Please enter the number of times sent : ')) #在已获取的好友列表中查找到收消息人的'UserName' name = itchat.search_friends(name = ps) toName = name[0]['UserName'] #根据重复发送次数进行重复发送,不足一次的按照一次计算 if times <= 1: itchat.send(msg,toName) print('Has been sent!') else: for i in range(times): itchat.send(msg,toName) print('Sent %d times!' % (i+1)) time.sleep(0.001 * (times - i) + 1)#每发送一次暂停一下 if __name__ == '__main__': itchat.auto_login()#手机扫码登录 #循环调用send_msg()函数 while True: print('Round %d' % count) send_msg() count = count + 1
# print(fin_list) if len(fin_list) == 0: return "Null" else: return fin_list # @itchat.msg_register(itchat.content.TEXT) # def test(msg): # print(msg['Text']) @itchat.msg_register(itchat.content.TEXT, isGroupChat=True) def group_reply(msg): group_name = msg['User']['NickName'] from_user = msg['ActualNickName'] group_id = msg['FromUserName'] print(group_name, from_user, group_id, msg['Text']) print(msg['Text'][-1]) temp_str = msg['Text'][-1] if group_name == '张店长和他的伙计们' and from_user == '倩酱粉丝后援团团长': # itchat.send("test from group %s from user %s" % (group_name, from_user), toUserName=group_id) send_msg = get_chengyu(temp_str) if send_msg != "Null": itchat.send(send_msg, toUserName=group_id) itchat.auto_login(True) itchat.run()
def main(): itchat.utils.print_cmd_qr = print_cmd_qr itchat.auto_login(enableCmdQR=2, hotReload=True) curses.wrapper(draw_menu)
#print(chatrooms.iloc[0]) if chatrooms is not None: # print chatrooms pass else: print("Cannot find the chatroom: ") return None friends = itchat.search_friends(name=friendname, userName=None, remarkName=None, nickName=None,wechatAccount=None) for friend in friends: for chatroom in chatrooms: print chatroom if friend in chatroom['self']: print 'friend ' + friend['username'] + ' is in ' + chatroom['username'] print friend def findfriends(group): pass def checkmutual(friendA, friendB): pass def sticker(group): pass def main(): findgroups('Grace') if __name__ == '__main__': itchat.auto_login(enableCmdQR=2, hotReload=True) main()
import itchat import time from itchat.content import TEXT import csv import re itchat.auto_login(enableCmdQR=False) # itchat.auto_login(hotReload=True) roomslist = [] name = "find soulmate" def getroom_message(ChatName): # get room name # pass itchat.dump_login_status() RoomList = itchat.search_chatrooms(name=ChatName) if RoomList is None: print("没有%s群" % (ChatName)) else: return RoomList[0]["UserName"] memberList = itchat.update_chatroom(getroom_message(name), detailedMember=True) total = len(memberList['MemberList']) female = 0 male = 0 # 写入到CSV # csvFile = open('csvData.csv','a')
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() def http_get_mima_img( miyu ): payload = {'miyu': miyu }; url = MIMA_URL; rs = requests.get( url=url ,timeout=3, params=payload); ret = rs.json(); img_url = ret['data']['img']; # print img_url (filepath, tempfilename) = os.path.split(img_url); (shotname, extension) = os.path.splitext(tempfilename); path = os.path.abspath(os.curdir); img_name = path +'/miyu/'+ str(time.time())+extension; urllib.urlretrieve(img_url,img_name); return img_name; if __name__ == '__main__': itchat.auto_login( enableCmdQR = True ) qixi_reply()
def atta_reply(msg): return ({ 'Picture': u'图片', 'Recording': u'录音', 'Attachment': u'附件', 'Video': u'视频', }.get(msg['Type']) + u'已下载到本地') # download function is: msg['Text'](msg['FileName']) @itchat.msg_register(['Map', 'Card', 'Note', 'Sharing']) def mm_reply(msg): if msg['Type'] == 'Map': return u'收到位置分享' elif msg['Type'] == 'Sharing': return u'收到分享' + msg['Text'] elif msg['Type'] == 'Note': return u'收到:' + msg['Text'] elif msg['Type'] == 'Card': return u'收到好友信息:' + msg['Text']['Alias'] @itchat.msg_register('Text', isGroupChat = True) def group_reply(msg): if msg['isAt']: return u'@%s\u2005%s' % (msg['ActualNickName'], get_response(msg['Text']) or u'收到:' + msg['Text']) @itchat.msg_register('Friends') def add_friend(msg): itchat.add_friend(**msg['Text']) itchat.send_msg(u'项目主页:github.com/littlecodersh/ItChat\n' + u'源代码 :回复源代码\n' + u'图片获取:回复获取图片\n' + u'欢迎Star我的项目关注更新!', msg['RecommendInfo']['UserName']) itchat.auto_login(False, enableCmdQR=True) itchat.run()
def main(): model_cnn, model, ix_to_word, opt = load_model() filepaths = ['/home/amds/Gzcd-fykusez0076319.jpg'] # Set sample options # predictions = eval_split(model_cnn, model, filepaths, ix_to_word, vars(opt)) @itchat.msg_register(TEXT) def text_reply(msg): info = msg['Text'].encode('UTF-8') url = 'http://www.tuling123.com/openapi/api' data = { 'key': '0ca3121447deed5f7848b5c1544d80ed', 'info': info, 'userid': msg.FromUserName } data = urllib.urlencode(data) url2 = urllib2.Request(url, data) response = urllib2.urlopen(url2) apicontent = response.read() s = json.loads(apicontent, encoding='utf-8') print(s) if s['code'] == 100000: return s['text'] @itchat.msg_register('Friends') def add_friend(msg): itchat.add_friend(**msg['Text']) itchat.get_contact() itchat.send_msg('Nice to meet you!', msg['RecommendInfo']['UserName']) @itchat.msg_register(['Picture']) def download_files(msg): print(msg) print(msg.fileName) filepath = os.path.join('/home/amds/imgs', msg.fileName) # msg.download(filepath) msg['Text'](filepath) im = cv2.imread(filepath) new_path = filepath.split(".")[0] + ".jpg" print(new_path) cv2.imwrite(new_path, im) filepaths = [new_path] predictions = eval_split(model_cnn, model, filepaths, ix_to_word, vars(opt)) print(predictions) if len(predictions) > 0: return predictions[0] # itchat.send(predictions[0], msg.FromUserName) @itchat.msg_register('Picture', isGroupChat=True) def download_files1(msg): print(msg) print(msg.User) print(msg.fileName) filepath = os.path.join('/home/amds/imgs', msg.fileName) msg.download(filepath) filepaths = [filepath] predictions = eval_split(model_cnn, model, filepaths, ix_to_word, vars(opt)) print(predictions) if len(predictions) > 0: # return predictions[0] itchat.send(predictions[0], msg.FromUserName) itchat.auto_login(True, enableCmdQR=2) itchat.run()
def wechat(text, contact): itchat.auto_login(hotReload=True) #itchat.auto_login() itchat.send(text, toUserName='******') def roadConfirm(road): #road=input('请输入路名:>>>') if road in roadList: return 0 else: return 1 while True: if main(): break ''' @itchat.msg_register(TEXT) def get_msg(msg): print(msg['Text']) print(msg) if msg['Text']=='故障': print('输入故障路名') #itchat.auto_login(enableCmdQR=True) itchat.auto_login(hotReload=True) #itchat.send('1',toUserName='******') #itchat.run() '''
'info' : msg, 'userid' : 'wechat-robot', } try: r = requests.post(apiUrl, data=data).json() # 字典的get方法在字典没有'text'值的时候会返回None而不会抛出异常 return '[自动回复] 我去吃饭了...' # 为了防止服务器没有正常响应导致程序异常退出,这里用try-except捕获了异常 # 如果服务器没能正常交互(返回非json或无法连接),那么就会进入下面的return except: # 将会返回一个None return # 这里是我们在“1. 实现微信消息的获取”中已经用到过的同样的注册方法 @itchat.msg_register(itchat.content.TEXT) def tuling_reply(msg): # 为了保证在图灵Key出现问题的时候仍旧可以回复,这里设置一个默认回复 #defaultReply = 'I received: ' + msg['Text'] defaultReply = '[自动回复]_我去吃饭了先' # 如果图灵Key出现问题,那么reply将会是None reply = get_response(msg['Text']) print(msg['Text']); # a or b的意思是,如果a有内容,那么返回a,否则返回b # 有内容一般就是指非空或者非None,你可以用`if a: print('True')`来测试 return reply or defaultReply # 为了让实验过程更加方便(修改程序不用多次扫码),我们使用热启动 itchat.auto_login() itchat.run()
import threading import datetime import itchat import time from itchat.content import * itchat.auto_login() #登陆 print('\n') print('\n') print( '测试脚本完全免费,版权归Brick Republic所有,\n请勿用作商业用途,违者必究!\n请关注微信公众号:Brick Republic,你的中文抢购群组!' ) def YeezyCity(city, username): while datetime.datetime.now() < d_time: s = time.asctime() print(s[11:19], end="") time.sleep(0.05) print("\r", end="", flush=True) itchat.send_msg('YEEZY' + city, toUserName=username) if len(itchat.search_mps(name='Brick Republic')) != 0: print('\n') print('\n') city = input("请输入城市:") while True: try: use_time = input("请输入预约时间,例如:15:00:") d_time = datetime.datetime.strptime(
msg['Text']('data/' + user + '/comment.txt') itchat.send(step_1_2, toUserName=user) users[user] = 11 @itchat.msg_register(itchat.content.PICTURE, isFriendChat=True) def download_pic(msg): if msg['ToUserName'] == 'filehelper': msg['FromUserName'] = '******' user = msg['FromUserName'] if (user in users.keys()) and (users[user] == 11): if not os.path.exists('data/' + user): os.makedirs('data/' + user) msg['Text']('data/' + user + '/img.jpg') itchat.send(wait, toUserName=user) try: cloud.draw_wordcloud(file_name='data/' + user + '/comment.txt', usr=user, masker='data/' + user + '/img.jpg') # itchat.send('@img@data/'+user+'/img.jpg' ,toUserName=user) itchat.send('@img@data/' + user + '/result.jpg', toUserName=user) itchat.send(askChange, toUserName=user) users[user] = 99 except: itchat.send('词云生成失败,请检查文本文件...', toUserName=user) users[user] = 1 itchat.auto_login(hotReload=True) itchat.run()
message += str(user_session[-1].price()) return message # 如果是获取成交量 if info == 'volume': message += str(user_session[-1].volume()) return message # 如果是获取收盘价 if info == 'close': message += str(user_session[-1].close_price()) return message # 如果是获取开盘价 if info == 'open': message += str(user_session[-1].open_price()) return message return "I'm sorry, I cannot understand you." # 执行当前文件 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() # 执行之后,弹出二维码
import pandas as pd import time import paramiko import re import threadpool import xlwt from functools import partial import datetime from win32com.client import DispatchEx import pythoncom from PIL import ImageGrab import uuid import os import itchat itchat.auto_login(hotReload=True) #热启动你的微信 rooms = itchat.get_chatrooms(update=True) j = 2 excelline = 1 scriptLine = {} t = time.strftime('%m%d', time.localtime()) # 设置居中 alignment = xlwt.Alignment() alignment.horz = xlwt.Alignment.HORZ_CENTER # 水平方向 alignment.vert = xlwt.Alignment.VERT_CENTER # 垂直方向 workbook = xlwt.Workbook() worksheet = workbook.add_sheet('Sheet1') style = xlwt.XFStyle() # Create the Pattern style.alignment = alignment for i in range(0, 7):
# For reproducibility np.random.seed(1000) class wx_cb(keras.callbacks.Callback): def on_epoch_end(self, epoch, logs=None): itchat.send_msg('[epoch] ' + str(epoch) + ' ' + str(logs), toUserName='******') def on_batch_end(self, batch, logs=None): if batch % 100 == 0: itchat.send_msg('[batch] ' + str(batch) + ' ' + str(logs), toUserName='******') if __name__ == '__main__': itchat.auto_login(hotReload=True, enableCmdQR=True) # Load the dataset (X_train, Y_train), (X_test, Y_test) = cifar10.load_data() # Create the model model = Sequential() model.add(Conv2D(32, kernel_size=(3, 1), activation='relu', input_shape=(32, 32, 3))) model.add(Conv2D(32, kernel_size=(1, 3), activation='relu')) model.add(BatchNormalization()) model.add(Conv2D(32, kernel_size=(3, 1), activation='relu')) model.add(Conv2D(32, kernel_size=(1, 3), activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.5))
time.sleep(random.randint(2, 5)) # 删除临时文件 for path in files: if os.path.exists(path): os.remove(path) if __name__ == '__main__': # 日志格式设定 logging.basicConfig(level=logging.INFO, format='\n%(asctime)s - %(levelname)s: %(message)s') logging.info('加载应用配置信息') option.auto_app_config() if config.ENABLE_LOGIN: logging.info('请扫描二维码登录') itchat.auto_login(hotReload=True, enableCmdQR=config.CONSOLE_CMD_QR) logging.info('登录成功') itchat.run(False, False) chatrooms = itchat.get_chatrooms(contactOnly=True) # 群聊名称 config_chatrooms = [room.nick_name for room in config.MSG_PUSH_CONFIG] for index, room in enumerate(chatrooms): logging.info('获取群聊通讯:' + room['NickName'] + '|' + room['UserName']) if room['NickName'] not in config_chatrooms: continue idx = config_chatrooms.index(room['NickName']) config.MSG_PUSH_CONFIG[idx].user_name = room['UserName'] for room in config.MSG_PUSH_CONFIG: logging.info('推送群聊:' + str(room)) # 定时循环 while True:
def wxLogon(self): ''' 登录到微信 :return: ''' itchat.auto_login(hotReload=True)
def login(self): itchat.auto_login(hotReload=True) # 登录,会下载二维码给手机扫描登录,hotReload设置为True表示以后自动登录 itchat.run() # 让itchat一直运行
def auto_login(self): itchat.auto_login(hotReload=True,loginCallback=lc, exitCallback=ec) pass
'msg': query.group(1) } }) else: setUser(name, { 'status': commnd.group(1), 'option': users[name]['option'] }) else: itchat.send('命令无效', toUserName=name) itchat.send(helpStr, toUserName=name) return elif isCommnd and commnd == None: itchat.send('命令无效', toUserName=name) itchat.send(helpStr, toUserName=name) return else: users[name]['option']['msg'] = msg #setUser(name,{'status':users[name]['status'],'option':{'msg':msg}}) doCommnd(name) return @itchat.msg_register(RECORDING) def onVioceReceive(obj): obj.download('vioce/' + obj.fileName) itchat.auto_login(hotReload=conf["hotReload"], enableCmdQR=conf["cmdQR"]) itchat.run(conf["verbose"])
data = xlrd.open_workbook('outside_students.xlsx') table = data.sheet_by_index(0) nrows = table.nrows print(nrows) names=[] for i in range(1,nrows): itmes = table.row_values(i) if(str(itmes[3])=='是'): names.append(str(itmes[1])) print(names) print(len(names)) itchat.auto_login(True) friendList=itchat.get_friends(update=True)[1:] sexDict={} nick_names=[] total=len(friendList) for friend in friendList: nick_names.append(friend['UserName']+' '+friend['NickName']+' '+friend['RemarkName']) print(nick_names) send_name=[] value="hi,这是定向消息,发自^(00)^ 。请填写问卷,请回复: 是 "
if 'add' in msg.text: name = msg.text.split()[1] stack = '' for row in msg.text.split('\n')[1:]: stack = stack + '\n' + row info.stack[name] = stack msg.user.send(name + "的技术栈录入成功") if 'stack' == msg.text: stack = "" for cow in info.stack: stack = stack + cow stack = stack + info.stack[cow] stack += "\n\n" msg.user.send(stack) if 'action' == msg.text: message = "为了能启动我们这个班级项目,我们这边需要更加了解同学们的技术方向以及技术路线,以便于我们能够分配任务。" \ "所以请同学们发一下自己的技术栈(包括已学的与打算学的技术,可以参考下面这幅图,图中没有的也可以)。" \ "\n\n(直接发在群里就好, 让同学们更了解你,方便组队)" \ "\n\n格式如下(姓名后换行,技术之间用空格隔开)\n\n add 姓名 \n技术1 技术2 技术3 技术4" msg.user.send(message) msg.user.send('@[email protected]') itchat.auto_login(True, enableCmdQR=2) itchat.run(True)
# -*- coding=utf-8 -*- # t00ls每日扫码微信签到脚本 import itchat def sigin(): user = itchat.search_mps(name='T00ls') UserName = user[0]['UserName'] itchat.send(msg=u'3',toUserName=UserName) itchat.dump_login_status() exit() if __name__ == '__main__': itchat.auto_login(hotReload=True) itchat.dump_login_status() sigin()
# -*- coding: utf-8 -*- """ Created on Fri May 25 18:36:22 2018 @author: 834235185 """ import itchat, time, os, jieba import pandas as pd import numpy as np itchat.auto_login(enableCmdQR=False, hotReload=False) friends = itchat.get_friends() mps = itchat.get_mps() mpslist = [] all = [] for i, mp in zip(friends, mps): cur1, cur2 = {}, {} cur1['个签'] = i['Signature'] cur1['昵称'] = i['NickName'] cur1['此次地址'] = i['UserName'] cur2['个签'] = mp['Signature'] cur2['昵称'] = mp['NickName'] cur2['此次地址'] = mp['UserName'] all.append(cur1) mpslist.append(cur2) os.chdir('E:\迅雷下载') for j in all: if '平安保险' in j['昵称']: #'Al': w = 0 print('Find')
#!/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()
import itchat itchat.auto_login(enableCmdQR=2, hotReload=True) mpsList = itchat.get_chatrooms() for mp in mpsList: print(mp['NickName'], mp['UserName'])