Python 发送微信消息
安装
pip install itchat
1、基本使用
# 使用微信接口给微信好友发送消息,
import itchat
nickname = "迪丽热巴"
send_message = "测试消息"
try:
# 1. 自动登录方法, hotReload=True可以缓存, 不用每次都登录, 但是第一次执行时会出现一个二维码, 需要手机微信扫码登录
itchat.auto_login(hotReload=False)
# 2. 搜索好友,search_friends("xxx"),其中"xxx"为好友昵称,备注或微信号不行
userinfo = itchat.search_friends(nickname)
# 3. 获取用户id
userid = userinfo[0]["UserName"]
# 4. 调用微信接口发送消息
# 4.1 通过用户id发送信息
itchat.send(send_message, userid)
# 4.2 发送纯文本信息
itchat.send_msg(msg=send_message, toUserName=userid)
except Exception as e:
print("消息发送异常:", e)
finally:
# 退出微信
itchat.logout()
2、批量发送
import itchat
class SendWeChat():
def __init__(self):
# 自动登录
itchat.auto_login(hotReload=False)
self.UserNameList = []
def get_user_name(self, nickname_list):
for nickname in nickname_list:
try:
# 根据用户昵称搜索用户
userinfo = itchat.search_friends(nickname)
# 获取用户id 并添加至列表
self.UserNameList.append(userinfo[0]["UserName"])
except Exception:
print(f"抱歉无法找到昵称 {nickname} 为用户")
def send_message(self, message):
for UserName in self.UserNameList:
res = itchat.send(message, UserName)
if res["BaseResponse"]["Ret"] != 0:
print("消息发送失败: ", UserName)
else:
print("消息发送成功: ", UserName)
if __name__ == '__main__':
nickname_list = ['迪丽热巴', '景田']
message = "有些性情,崇高不可遏,高傲不可屈。"
send_wechat = SendWeChat()
send_wechat.get_user_name(nickname_list)
send_wechat.send_message(message)
3、异步发送消息
import asyncio
import itchat
class SendWeChat():
def __init__(self):
# 自动登录
itchat.auto_login(hotReload=False)
self.UserNameList = []
async def get_user_name(self, nickname_list):
for nickname in nickname_list:
try:
# 根据用户昵称搜索用户
userinfo = itchat.search_friends(nickname)
# 获取用户id 并添加至列表
self.UserNameList.append(userinfo[0]["UserName"])
except Exception:
print(f"抱歉无法找到昵称 {nickname} 为用户")
async def send_message(self, message):
for UserName in self.UserNameList:
res = itchat.send(message, UserName)
if res["BaseResponse"]["Ret"] != 0:
print("消息发送失败: ", UserName)
else:
print("消息发送成功: ", UserName)
async def main(self, nickname_list, message_list):
# 异步获取用户列表 并等待完成
await self.get_user_name(nickname_list)
tasks = [asyncio.create_task(self.send_message(message)) for message in message_list]
# 等待结束
await asyncio.wait(tasks)
if __name__ == '__main__':
nickname_list = ['迪丽热巴', '景田']
message_list = ["有些性情,崇高不可遏,高傲不可屈。", "There are some natures too noble to curb and too lofty to bend."]
send_wechat = SendWeChat()
asyncio.run(send_wechat.main(nickname_list, message_list))
标签:itchat,Python,微信,self,list,send,发送,message,nickname
From: https://www.cnblogs.com/xingxingnbsp/p/17446048.html