def download_files(msg):
user_remark = itchat.search_friends(userName=msg['FromUserName'])['RemarkName'] or itchat.search_friends(
userName=msg['FromUserName'])['NickName']
if msg['FromUserName'] == itchat.originInstance.storageClass.userName:
user_remark = '?'
msg_time = t.asctime(t.localtime(t.time()))
if msg['ToUserName'] == 'filehelper':
print('\033[33m{time} \033[34m{user_from}\033[0m ????? \033[34m{user_to}\033[0m: <{file_name}>'.format(
time=msg_time, user_from=user_remark, user_to='?', file_name=msg['FileName'])) # ????
else:
user_to = itchat.search_friends(userName=msg['ToUserName'])['RemarkName'] or itchat.search_friends(
userName=msg['ToUserName'])['NickName']
print('\033[33m{time} \033[34m{user_from}\033[0m ????? \033[35m{user_to}\033[0m: <{file_name}>'.format(
time=msg_time, user_from=user_remark, user_to=user_to, file_name=msg['FileName'])) # ????
else:
msg_time = t.asctime(t.localtime(t.time()))
print('\033[33m{time} \033[35m{user_from}\033[0m ????? \033[34m?\033[0m: <{file_name}>'.format(
time=msg_time, user_from=user_remark, file_name=msg['FileName'])) # ????
try:
msg['Text']('./wechat_files/file/{file_name}'.format(file_name=msg['FileName']))
except (TimeoutError, ConnectionError, ConnectionAbortedError):
print('\033[31m???????\033[0m')
else:
print("Unexpected error:", sys.exc_info()[0])
pass
python类search_friends()的实例源码
def login_chat_init():
# ??Linux ? Windows ??
os_paltform = platform.system()
# ????? hotReload?????????????????, ???????
# for some linux system, width of block character is one instead of two, so enableCmdQR should be 2
if os_paltform == "Windows":
print("This is windows system\n")
itchat.auto_login(hotReload=True)
else:
itchat.auto_login(hotReload=True, enableCmdQR=2)
# ???????????????????name?????
# ????????????
#I = itchat.search_friends()
#I.send("hello")
# ???????????
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 start(location=LOCATION, report_time=REPORT_TIME):
if datetime.datetime.now().strftime('%H:%M') == report_time: #?? 03:25
weather = ''
count = 0
while not weather:
weather = get_weather(location)
count += 1
print('??????%d?' % count)
time.sleep(1)
if count >= 10:
break
if not weather:
print('????????')
else:
#???????
for USER_NAME in USER_NAME_LIST:
num = itchat.search_friends(name = USER_NAME)[0]["UserName"]
try:
itchat.send_msg(get_weather(location), num)
except Exception as e:
print(e)
#print(get_weather(location))
def receive(msg):
"""?????????
:param msg: ????
:return: ???
"""
type_dict = {'Text': 0, 'Map': 1, 'Card': 2, 'Note': 3, 'Sharing': 4}
msg_type = ['', '????', '????', '????', '????']
user_remark = itchat.search_friends(userName=msg['FromUserName'])['RemarkName'] or itchat.search_friends(
userName=msg['FromUserName'])['NickName'] or 'Unknown'
if user_remark == 'Unknown':
print('------- DEBUG output -------\n' + msg + '\n----------------------------')
if msg['FromUserName'] == itchat.originInstance.storageClass.userName:
user_remark = '?'
msg_time = t.asctime(t.localtime(t.time()))
if msg['ToUserName'] == 'filehelper':
print('\033[33m{time} \033[34m{user_from}\033[0m -> '
'\033[34m{user_to}\033[0m: \033[1;35m{type}\033[30m{msg}'
'\033[0m'.format(time=msg_time, user_from=user_remark, user_to='?',
type=msg_type[type_dict[msg['Type']]], msg=msg['Text'])) # ????
else:
user_to = itchat.search_friends(userName=msg['ToUserName'])['RemarkName'] or itchat.search_friends(
userName=msg['ToUserName'])['NickName']
print('\033[33m{time} \033[34m{user_from}\033[0m -> '
'\033[35m{user_to}\033[0m: \033[1;35m{type}\033[30m{msg}'
'\033[0m'.format(time=msg_time, user_from=user_remark, user_to=user_to,
type=msg_type[type_dict[msg['Type']]], msg=msg['Text'])) # ????
else:
msg_time = t.asctime(t.localtime(t.time()))
print('\033[33m{time} \033[35m{user_from}\033[0m: \033[1;35m{type}\033[30m{msg}\033[0m'.format(
time=msg_time, user_from=user_remark, type=msg_type[type_dict[msg['Type']]], msg=msg['Text'])) # ????
def download_files(msg):
user_remark = itchat.search_friends(userName=msg['FromUserName'])['RemarkName'] or itchat.search_friends(
userName=msg['FromUserName'])['NickName']
if msg['FromUserName'] == itchat.originInstance.storageClass.userName:
user_remark = '?'
msg_time = t.asctime(t.localtime(t.time()))
if msg['ToUserName'] == 'filehelper':
print('\033[33m{time} \033[34m{user_from}\033[0m ??? \033[34m{user_to}\033[0m: #{file_type}#'.format(
time=msg_time, user_from=user_remark, user_to='?', file_type=type_dict_we[msg['MsgType']])) # ????
else:
user_to = itchat.search_friends(userName=msg['ToUserName'])['RemarkName'] or itchat.search_friends(
userName=msg['ToUserName'])['NickName']
print('\033[33m{time} \033[34m{user_from}\033[0m ??? \033[35m{user_to}\033[0m: #{file_type}#'.format(
time=msg_time, user_from=user_remark, user_to=user_to, file_type=type_dict_we[msg['MsgType']])) # ????
else:
msg_time = t.asctime(t.localtime(t.time()))
print('\033[33m{time} \033[35m{user_from}\033[0m ??? \033[34m?\033[0m: #{file_type}#'.format(
time=msg_time, user_from=user_remark, file_type=type_dict_we[msg['MsgType']])) # ????
try:
if msg['Content']: # ?????????????????????(????'MsgType'?????png?3?gif?47?????gif)
msg['Text']('./wechat_files/picture_video_etc/{file_name}'.format(file_name=msg['FileName']))
except (TimeoutError, ConnectionError, ConnectionAbortedError):
print('\033[31m??????????\033[0m')
pass
else:
print("Unexpected error:", sys.exc_info()[0])
pass
def is_at_me(to_usr: str) -> bool:
return to_usr == itchat.search_friends(name=MASTER_NAME)[0].UserName
def search_friends(name=None, user_name=None, remark_name=None, nick_name=None, wechat_account=None):
return itchat.search_friends(name, user_name, remark_name, nick_name, wechat_account)
def after_login(self):
user = itchat.search_friends()
self.user_name = user['UserName']
self.nick_name = user['NickName']
logger.debug('Login username is: %s, nickname is: %s' % (self.user_name, self.nick_name))
for module in self.modules:
module.after_login()
def main():
#????
itchat.auto_login(hotReload=True)
user_content = itchat.search_friends(name=u'????')
userName = user_content[0]['UserName']
itchat.send(getWeather(101230201),toUserName = userName)#??
itchat.send(getWeather(101010100),toUserName = userName)#??
def get_task(taskList):
'''
????? ???MyChat??? ???????get_tasklist ?????????
:param taskList:
:return:
'''
contacts = []
chatrooms_list = []
contact_list = []
is_info_correct = True # ????????
for task in taskList:
contact_list = itchat.search_friends(name=task[1]) # ????????
# ??????????????????
if len(contact_list) == 0:
# ????????
chatrooms_list = itchat.search_chatrooms(name=task[1])
# ????????????????????
if len(chatrooms_list) == 0:
print("???????????.????????? -> ???{0}".format(task[1]))
# ??????
is_info_correct = False
break
else:
contacts.append(MyChat(chatrooms_list[0], task[0], task[1],task[2]))
# ????
else:
contacts.append(MyChat(contact_list[0], task[0], task[1], task[2]))
if is_info_correct is False:
return False
else:
return contacts
def text_reply(msg):
reply = talk(msg['Text'], md5(msg['FromUserName']))
User = itchat.search_friends(userName=msg['FromUserName'])
if User['RemarkName'] == '':
NickName = User['NickName']
else:
NickName = '%s(%s)' % (User['NickName'], User['RemarkName'])
print('------------------------------------------------------------------------------')
print('%s??????%s' % (NickName, msg['Text']))
print('AI????%s?%s' % (NickName, reply))
print('------------------------------------------------------------------------------')
return reply
def map_reply(msg):
reply = talk(msg['Text'], md5(msg['FromUserName']))
User = itchat.search_friends(userName=msg['FromUserName'])
if User['RemarkName'] == '':
NickName = User['NickName']
else:
NickName = '%s(%s)' % (User['NickName'], User['RemarkName'])
print('------------------------------------------------------------------------------')
print('%s????????%s' % (NickName, msg['Text']))
print('AI????%s?%s' % (NickName, reply))
print('------------------------------------------------------------------------------')
return reply
def card_reply(msg):
reply = '?????????????????'
User = itchat.search_friends(userName=msg['FromUserName'])
if User['RemarkName'] == '':
NickName = User['NickName']
else:
NickName = '%s(%s)' % (User['NickName'], User['RemarkName'])
print('------------------------------------------------------------------------------')
print('%s?????%s' % (NickName, msg['Text']['NickName']))
print('AI????%s?%s' % (NickName, reply))
print('------------------------------------------------------------------------------')
return reply
def sharing_reply(msg):
reply = talk(msg['Text'], md5(msg['FromUserName']))
User = itchat.search_friends(userName=msg['FromUserName'])
if User['RemarkName'] == '':
NickName = User['NickName']
else:
NickName = '%s(%s)' % (User['NickName'], User['RemarkName'])
print('------------------------------------------------------------------------------')
print('%s????????%s' % (NickName, msg['Text']))
print('AI????%s?%s' % (NickName, reply))
print('------------------------------------------------------------------------------')
return reply
def att_reply(msg):
msg['Text']('./attachments/' + msg['FileName'])
User = itchat.search_friends(userName=msg['FromUserName'])
if User['RemarkName'] == '':
NickName = User['NickName']
else:
NickName = '%s(%s)' % (User['NickName'], User['RemarkName'])
print('------------------------------------------------------------------------------')
print('%s??????????????attachments???????%s' % (NickName, msg['FileName']))
print('AI????% s?????????????' % NickName)
print('------------------------------------------------------------------------------')
return '????????????'
def task_remind():
for task in task_list:
task_time = task[0]
task_content = task[1]
if datetime.datetime.now().strftime("%H:%M") == task_time:
#name=????
receiver = itchat.search_friends(name=u"Hoder")[0]["UserName"]
itchat.send_msg(task_content, receiver)
def tick():
users = itchat.search_friends(name=u'xxx') # ?????????
userName = users[0]['UserName']
meetDate = dt.date(2015,9,29) # ?????????????
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) # ?????????
nextTickTime = now + dt.timedelta(days=1)
nextTickTime = nextTickTime.strftime("%Y-%m-%d 00:00:00")
my_scheduler(nextTickTime)
def text_reply(msg):
nickName = itchat.search_friends(userName=msg['FromUserName']).get('NickName', 'Unknown')
logging.info('{}-{} send: {}'.format(nickName, msg['FromUserName'], msg['Content']))
if msg["FromUserName"] == itchat.get_friends()[0]["UserName"]:
# dont replay self
return
# if invite
if faq.invite_key in msg['Text'].upper():
# TODO Modify add_member_into_chatroom
invite_friend = [{'UserName': msg['FromUserName']}]
grouproom = itchat.search_chatrooms(name=faq.group_name)
grouproom = grouproom and grouproom[0] or None
result = itchat.add_member_into_chatroom(grouproom.get('UserName'),
invite_friend, useInvitation=True)
# invite success
if result['BaseResponse']['Ret'] == 0:
logging.info('invite user {}-{} successful'.format(nickName, msg['FromUserName']))
else:
logging.error('invite user {}-{} failed'.format(nickName, msg['FromUserName']))
itchat.send(REPLAY_ERROR_TEXT, msg['FromUserName'])
else:
# else TuLing replay
replay_text = tuling.replay_text(msg['Text'],
msg['FromUserName']) or REPLAY_ERROR_TEXT
logging.info('tuling replay user {}-{}: {}'.format(nickName, msg['FromUserName'], replay_text))
itchat.send(replay_text, msg['FromUserName'])
# TODO can not return Bool
return
apiTestForWeChatWithItChat.py 文件源码
项目:LinuxBashShellScriptForOps
作者: DingGuodong
项目源码
文件源码
阅读 19
收藏 0
点赞 0
评论 0
def text_reply(msg):
if msg['Type'] == 'Text':
reply_content = msg['Text']
elif msg['Type'] == 'Picture':
reply_content = u"??: " + msg['FileName']
elif msg['Type'] == 'Card':
reply_content = u" " + msg['RecommendInfo']['NickName'] + u" ???"
elif msg['Type'] == 'Map':
x, y, location = re.search("<location x=\"(.*?)\" y=\"(.*?)\".*label=\"(.*?)\".*", msg['OriContent']).group(1,
2,
3)
if location is None:
reply_content = u"??: ??->" + x.__str__() + " ??->" + y.__str__()
else:
reply_content = u"??: " + location
elif msg['Type'] == 'Note':
reply_content = u"??"
elif msg['Type'] == 'Sharing':
reply_content = u"??"
elif msg['Type'] == 'Recording':
reply_content = u"??"
elif msg['Type'] == 'Attachment':
reply_content = u"??: " + msg['FileName']
elif msg['Type'] == 'Video':
reply_content = u"??: " + msg['FileName']
else:
reply_content = u"??"
friend = itchat.search_friends(userName=msg['FromUserName'])
itchat.send(u"Friend:%s -- %s "
u"Time:%s "
u" Message:%s" % (friend['NickName'], friend['RemarkName'], time.ctime(), reply_content),
toUserName='filehelper')
itchat.send(u"????????%s???????%s??????--????(Python?)" % (time.ctime(), reply_content),
toUserName=msg['FromUserName'])