首页 > 编程语言 >Python 发送微信消息

Python 发送微信消息

时间:2023-05-31 14:57:33浏览次数:43  
标签:itchat Python 微信 self list send 发送 message nickname

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

相关文章

  • Python 发送邮件
    Python发送邮件1、案例一(发送普通邮件)importsmtplibfromemail.mime.textimportMIMEText#发送普通邮件#POP3服务器地址:pop.qq.com#SMTP服务器地址:smtp.qq.comclassSendEmail:def__init__(self):#发送邮件的用户self.send_user=......
  • 《最新出炉》系列初窥篇-Python+Playwright自动化测试-2-playwright的API及其他知识
    1.简介上一篇宏哥已经将Python+Playwright的环境搭建好了,而且也简单的演示了一下三款浏览器的启动和关闭,是不是很简单啊。今天主要是把一篇的中的代码进行一次详细的注释,然后说一下playwright的API和其他相关知识点。那么首先将上一篇中的代码进行一下详细的解释。2.代码解释2.......
  • Python 函数
    函数返回多个返回值defmultiple_return_value():importdatetimed=datetime.date.today()val_1='年份为:{}'.format(d.year)val_2='月份为:{}'.format(d.month)returnval_1,val_2#只需在return关键字后跟多个值(依次用逗号分隔)val=mult......
  • python 中 re.match和re.search()函数
     两者都返回首次匹配字符串的索引,re.match函数只从头开始匹配,re.search函数不限制只从头开始匹配。001、re.match函数[root@PC1test2]#python3Python3.10.9(main,Mar12023,18:23:06)[GCC11.2.0]onlinuxType"help","copyright","credits"or"license"......
  • 无需发件箱的邮件发送软件
    奇石软件对于邮件营销工具一直非常关注,因为在获客成本不断飙升的今天,邮件引流获客成本低廉的优势凸显。最近奇石软件研发了一款邮件自动发送软件,本软件不同于常见的邮件软件,最主要的特点是【自动注册发件箱】,使用者无需准备大量发件箱,仅准备目标收件人列表即可。下面详细介绍一下:相......
  • python 视频拆分成帧,帧合成视频
    参考python将视频切分成帧&&帧合成视频,下面的代码来自这篇博客。#====================视频拆分成帧===================================importcv2defvideo2frame(videos_path,frames_save_path,time_interval):''':paramvideos_path:视频的存放路径:par......
  • 果然python是直接可以使用requests去请求https站点的,意味着一般的扫描工具可以直接扫
    #coding:utf-8importrequests#请求地址#url="https://www.qlchat.com"url="https://www.baidu.com"headers={'user-agent':'Mozilla/5.0(WindowsNT10.0;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chro......
  • python 从bulkblacklist信誉查询网站提交查询
    importurllibimporturllib2#importwebbrowserimportreimportsocketdefis_domain_in_black_list(domain,ip):try_time=3url="http://www.bulkblacklist.com/"foriinrange(try_time):try:data=......
  • python avro 数据格式使用demo
    {"name":"UEProcedures","type":"record","fields":[{"name":"imsi","type":"string"},{"name":"time_at","type":&quo......
  • 【Python-Scripts】自动删除Jenkins任务构建历史记录
    任务背景: Jenkins构建历史记录很多,占用服务器磁盘空间较大,根据开发需求定期删除历史记录。 1#!/usr/bin/envpython2#-*-coding:utf-8-*-345importdatetime6importjenkins7importtime8fromjenkinsapi.jenkinsimportJenkins91011def......