def testcase1():
id='@5493580a22c9ba5db849ba33d0911d3d'
content=datetime.datetime.now().strftime("%H:%M:%S")
itchat.auto_login(hotReload=True)
#itchat.auto_login()
itchat.send(content,toUserName='filehelper')
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'
python类send()的实例源码
def text_reply(msg):
#logger.info(json.dumps(msg).decode("unicode_escape"))
if msg['isAt'] and myRobot.groupOnline:
match = re.match("@\S+\s+?(.*)",msg['Content'],re.U)
temp = match.group(1) if match else msg['Content']
logger.info(temp)
reply = tuLing.reply(temp,msg["FromUserName"])
logger.info(u"%s group %s msg :[%s],reply:[%s]",msg["User"].get("NickName"),msg['ActualNickName'],msg["Text"],reply)
itchat.send(u'@%s\u2005 ??: %s' % (msg['ActualNickName'], reply), msg['FromUserName'])
def stock():
time = datetime.datetime.now() # ??????
now = time.strftime('%H:%M:%S')
data = ts.get_realtime_quotes(stock_symbol) # ??????
r1 = float(data['price'])
r2 = str(stock_symbol) + ' ?????? ' + str(r1)
content = now + '\n' + r2
itchat.send(content, toUserName='filehelper')
print(content)
# ?????????????
if r1 <= float(price_low):
itchat.send('????????', toUserName='filehelper')
print('????????')
elif r1 >= float(price_high):
itchat.send('????????', toUserName='filehelper')
print('????????')
else:
itchat.send('????', toUserName='filehelper')
print('????')
# ? 3 ?????
def stock():
time = datetime.datetime.now() # ??????
now = time.strftime('%H:%M:%S')
data = ts.get_realtime_quotes(stock_symbol) # ??????
r1 = float(data['price'])
r2 = str(stock_symbol) + ' ?????? ' + str(r1)
content = now + '\n' + r2
itchat.send(content, toUserName='filehelper')
print(content)
# ?????????????
if r1 <= float(price_low):
itchat.send('????????', toUserName='filehelper')
print('????????')
elif r1 >= float(price_high):
itchat.send('????????', toUserName='filehelper')
print('????????')
else:
itchat.send('????', toUserName='filehelper')
print('????')
# ?????????
def process(self, msg, type):
if type != TEXT:
return
groupName = msg['User']['NickName']
if any([ re.search(x, groupName) is not None for x in self.blacklist ]):
return
if re.search('^/', msg['Content']):
return
if self.isFromSelf(msg):
# Stop processing if the message is from myself
return
self.updateGroupContentCache(msg, groupName)
contentToPaiDui = list(self.WhatToPaiDui(groupName))
if len(contentToPaiDui) > 1:
logging.error('Multiple duis detected.')
if len(contentToPaiDui) != 0:
# Pai dui!
itchat.send(msg['Content'], msg['FromUserName'])
logging.info('Pai Dui! {0}.'.format(msg['Content']))
# Update data structure to avoid Pai dui for multiple times.
self.updateGroupContentCache({ 'Content': msg['Content'], 'FromSelf': True }, groupName)
def ch_reply(msg):
chcont=msg['Content']
if chcont.find('<revokemsg><')>0:
loc1=chcont.find('</oldmsgid><msgid>')+18
loc2=chcont.find('</msgid><replacemsg><![CDATA')
messageid=chcont[loc1:loc2]
print(messageid)
try:#friend chat only
oritun=IDandTUN[str(messageid)]
orifun=IDandFUN[str(messageid)]
fname=itchat.search_friends(userName=orifun)
##print(fname)
itchat.send("[Autoreply] The message revoked by '"+fname['NickName']+"' just now is :"+IDandMESSAGE[messageid],oritun)
itchat.send("[Autoreply] The message revoked by '"+fname['NickName']+"' just now is :"+IDandMESSAGE[messageid],orifun)
except:
print("-----Can't find original msg")
#############----->Group Chat<-----#############
def group_reply(msg):
if msg['isAt']:
reply = talk(msg['Content'], md5(msg['ActualUserName']))
print(
'------------------------------------------------------------------------------')
print('%s????????%s' % (msg['ActualNickName'], msg['Content'].replace('\u2005',' ')))
print('AI????%s?%s' % (msg['ActualNickName'], reply))
print(
'------------------------------------------------------------------------------')
itchat.send('@%s %s' % (msg['ActualNickName'], reply), msg['FromUserName'])
else:
print(
'------------------------------------------------------------------------------')
print('%s??????%s' % (msg['ActualNickName'], msg['Content']))
print(
'------------------------------------------------------------------------------')
def handle_music_msg(text):
menu = Music.get_menu(text)
if not menu:
itchat.send(u'??????', 'filehelper')
ids = [menu['id']]
url = Music.get_url(ids)
if not url:
itchat.send(u'????????', 'filehelper')
name = '%s-%s' % (menu['name'], menu['singer'])
msg = DownLoad.down(url, name)
itchat.send(msg, 'filehelper')
os.startfile('%s\music\%s' % (os.getcwd(), name + ".mp3"))
itchat.send(u'????', 'filehelper')
# ??????
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')
def text_reply(msg):
match = re.search(u'?', msg['Text']).span()
if match:
itchat.send((u'??????????'), msg['FromUserName'])
def other_reply(msg):
itchat.send((u'??????????'), msg['FromUserName'])
def send_messages_in_queue(self):
while(True):
(username, message) = self.send_msg_queue.get()
itchat.send(message, toUserName = username)
time.sleep(0.5)
def search_iphone():
# ???????????????????????
buyers_info = get_buyers_info()
availability = r.get(current_config['IPHONE_MODELS_URL']).json()
if availability['stores']:
# ?????????????????
for store, models in buyers_info.items():
# ????????????????
for model_number, buyers in models.items():
# ????????????
stock = availability['stores'][store][model_number]
if stock['availability']['unlocked'] is True:
for buyer in buyers:
if cache.get(buyer['idcard']) is None:
buyer['store'] = store
with rabbit as mq:
mq.send_message(exchange_name='iphone', queue_name='buyers', messages=buyer)
# ???????????
msg = '[??] ??????????????{0}? ???{1}????{2}'.format(get_store_name(store), get_model_name(model_number), datetime.now())
logging.info(msg)
logging.info('?????{}'.format(buyer))
logging.info('[??] ????????????????')
itchat.send(msg, toUserName=wechat_user_name)
# ????????????5???????
cache.set(key=buyer['idcard'], val='???', time=300)
else:
logging.info('[??] ????????')
def send_wechat(self,name,content,user):
w_content=name+' '+content
itchat.send(w_content,toUserName=user)
time.sleep(1)
itchat.send(w_content,toUserName='filehelper')
def warming(self, coin, up_price, down_price,user):
url = 'https://www.jubi.com/api/v1/ticker/'
while 1:
time.sleep(5)
try:
data = requests.post(url, data={'coin': coin}).json()
except Exception,e:
print e
print "time out. Retry"
time.sleep(15)
continue
current = float(data['last'])
if current >= up_price:
print "Up to ", up_price
print "current price ",current
if self.send=='msn':
self.send_text(coin,str(current))
if self.send=='wechat':
self.send_wechat(coin,str(current),user)
time.sleep(1200)
if current <= down_price:
print "Down to ", down_price
print "current price ",current
if self.send=='msn':
self.send_text(coin,str(current))
if self.send=='wechat':
self.send_wechat(coin,str(current),user)
time.sleep(1200)
#????????????
def push_wechat(name, real_price, real_percent, type):
name=u'wwwei'
itchat.auto_login(hotReload=True)
account=itchat.get_friends(name)
for i in account:
if i[u'PYQuanPin']==name:
toName=i['UserName']
content=name+' ' + str(real_price)+' '+ str(real_percent)+' percent '+ type
itchat.send(content,toUserName=toName)
def text_reply(msg):
# cont = alice.respond(msg['Text'])
cont = requests.get('http://www.tuling123.com/openapi/api?key=?????&info=%s' % msg['Content']).content
m = json.loads(cont)
itchat.send(m['text'], msg['FromUserName'])
if m['code'] == 200000:
itchat.send(m['url'], msg['FromUserName'])
if m['code'] == 302000:
itchat.send(m['list'], msg['FromUserName'])
if m['code'] == 308000:
itchat.send(m['list'], msg['FromUserName'])
def snap(msg, toUserName, delay=5):
res = itchat.send(msg=msg, toUserName=toUserName)
msgID = res['MsgID']
time.sleep(delay)
revoke_res = itchat.revoke(msgID, toUserName)
print(revoke_res)
def send_msg(msg='Test Message', to_user_name=None):
''' send plain text message
for options
- msg: should be unicode if there's non-ascii words in msg
- to_user_name: 'user_name' key of friend dict
it is defined in components/messages.py
'''
return itchat.send_msg(msg, to_user_name)
def send_file(file_dir, to_user_name=None, media_id=None):
''' send attachment
for options
- file_dir: dir for file ready for upload
- media_id: media_id for file.
- if set, file will not be uploaded twice
- to_user_name: 'user_name' key of friend dict
it is defined in components/messages.py
'''
return itchat.send_file(file_dir, to_user_name)
def send_image(file_dir, to_user_name=None, media_id=None):
''' send image
for options
- file_dir: dir for file ready for upload
- if it's a gif, name it like 'xx.gif'
- media_id: media_id for file.
- if set, file will not be uploaded twice
- to_user_name: 'user_name' key of friend dict
it is defined in components/messages.py
'''
return itchat.send_image(file_dir, to_user_name, media_id)
def send_video(file_dir=None, to_user_name=None, media_id=None):
''' send video
for options
- file_dir: dir for file ready for upload
- if media_id is set, it's unnecessary to set file_dir
- media_id: media_id for file.
- if set, file will not be uploaded twice
- to_user_name: 'user_name' key of friend dict
it is defined in components/messages.py
'''
return itchat.send_video(file_dir, to_user_name)
def send_text(text):
#send text msgs to 'filehelper'
#???????????
try:
itchat.send_msg(msg=text,toUserName='filehelper')
return
except (ConnectionError,NotImplementedError,KeyError):
traceback.print_exc()
print('\nConection error,failed to send the message!\n')
return
else:
return
def send_img(filename):
#send text imgs to 'filehelper'
#???????
try:
itchat.send_image(filename,toUserName='filehelper')
return
except (ConnectionError,NotImplementedError,KeyError):
traceback.print_exc()
print('\nConection error,failed to send the figure!\n')
return
else:
return
#==============================================================================
#
#==============================================================================
def t_send(self,msg,toUserName='filehelper'):
try:
itchat.send_msg(msg=msg,toUserName=toUserName)
return
except (ConnectionError,NotImplementedError,KeyError):
traceback.print_exc()
print('\nConection error,failed to send the message!\n')
return
else:
return
def t_send_img(self,filename,toUserName='filehelper'):
try:
itchat.send_image(filename,toUserName=toUserName)
return
except (ConnectionError,NotImplementedError,KeyError):
traceback.print_exc()
print('\nConection error,failed to send the figure!\n')
return
else:
return
def on_epoch_end(self, epoch, logs=None):
for k in self.params['metrics']:
if k in logs:
self.mesg+=(k+': '+str(logs[k])[:5]+' ')
self.logs_epochs.setdefault(k, []).append(logs[k])
#==============================================================================
# except:
# itchat.auto_login(hotReload=True,enableCmdQR=True)
# itchat.dump_login_status()
# self.t_send(self.mesg, toUserName='filehelper')
#==============================================================================
if epoch+1>=self.stopped_epoch:
self.model.stop_training = True
logs = logs or {}
self.epoch.append(epoch)
self.t_epochs.append(time.time()-self.t_s)
if self.savelog:
sio.savemat((self.fexten if self.fexten else self.validateTitle(self.localtime))+'_logs_batches'+'.mat',{'log':np.array(self.logs_batches)})
sio.savemat((self.fexten if self.fexten else self.validateTitle(self.localtime))+'_logs_epochs'+'.mat',{'log':np.array(self.logs_epochs)})
th.start_new_thread(self.get_fig,())
#==============================================================================
# try:
# itchat.send(self.mesg, toUserName='filehelper')
# except:
# traceback.print_exc()
# return
#==============================================================================
self.t_send(self.mesg, toUserName='filehelper')
return
#==============================================================================
#
#==============================================================================
def group_reply_text(msg):
source = msg['FromUserName']
if msg['Content'] == 'Hi':
groups[source] = source
else:
if source in groups:
for item in groups.keys():
if not item == source:
itchat.send(' %s say:\n%s' % (msg['ActualNickName'], msg['Content']), item)
def download_png(msg):
source = msg['FromUserName']
msg['Text'](msg['FileName'])
itchat.send(msg['FileName'], source)
def __init__(self, send='wechat'):
cfg = Toolkit.getUserData('data.cfg')
self.public_key = cfg['public_key']
self.private_key = cfg['private_key']
self.send=send
from_mail = cfg['from_mail']
password = cfg['password']
to_mail = cfg['to_mail']
smtp_server = 'smtp.qq.com'
self.server = smtp_server
self.username = from_mail.split("@")[0]
self.from_mail = from_mail
self.password = password
self.to_mail = to_mail
self.coin_list=['IFC','DOGE','EAC','DNC','MET','ZET','SKT','YTC','PLC','LKC',
'JBC','MRYC','GOOC','QEC','PEB','XRP','NXT','WDC','MAX','ZCC',
'HLB','RSS','PGC','RIO','XAS','TFC','BLK','FZ','ANS','XPM','VTC',
'KTC','VRC','XSGS','LSK','PPC','ETC','GAME','LTC','ETH','BTC']
# ???????????????
# ????????
if self.send == 'msn':
try:
self.smtp = smtplib.SMTP_SSL(port=465)
self.smtp.connect(self.server)
self.smtp.login(self.username, self.password)
except smtplib.SMTPException, e:
print e
return 0
if send=='wechat':
self.w_name=u'wwwei'
#self.w_name1=u'wwwei'
itchat.auto_login(hotReload=True)
account=itchat.get_friends(self.w_name)
for i in account:
if i[u'PYQuanPin']==self.w_name:
self.toName= i['UserName']
#print self.toName