【python】使用 Python 自动发布微信公众号文章

一、准备工作

1. 注册微信公众号并获取接口权限

• 登录微信公众平台,进入 开发 > 基本配置
• 获取 AppIDAppSecret
• 开启 IP白名单(需配置服务器IP)。

2. 安装依赖库

使用 requests 发送 HTTP 请求:

pip install requests

二、核心流程

1. 获取 Access Token
import requests

def get_access_token(appid, appsecret):
    url = "https://api.weixin.qq.com/cgi-bin/token"
    params = {
        "grant_type": "client_credential",
        "appid": appid,
        "secret": appsecret
    }
    response = requests.get(url, params=params).json()
    return response.get("access_token")
2. 上传素材(如图片/缩略图)

图文消息需先上传图片获取 media_id

def upload_image(access_token, image_path):
    url = "https://api.weixin.qq.com/cgi-bin/media/upload"
    params = {"access_token": access_token, "type": "image"}
    with open(image_path, "rb") as file:
        files = {"media": file}
        response = requests.post(url, params=params, files=files).json()
    return response.get("media_id")
3. 构造图文消息内容
def create_article(title, content, thumb_media_id):
    return {
        "title": title,
        "thumb_media_id": thumb_media_id,  # 封面图片 media_id
        "author": "作者名称",
        "content": content,
        "content_source_url": "https://example.com",  # 原文链接
        "digest": "文章摘要",
        "show_cover_pic": 1  # 是否显示封面图(0/1)
    }
4. 发布图文消息
def publish_article(access_token, articles):
    url = "https://api.weixin.qq.com/cgi-bin/draft/add"
    headers = {"Content-Type": "application/json"}
    data = {
        "articles": articles  # 支持多图文(列表格式)
    }
    response = requests.post(
        url,
        params={"access_token": access_token},
        headers=headers,
        json=data
    )
    return response.json()

三、完整代码示例

import requests

# 配置信息
APPID = "YOUR_APPID"
APPSECRET = "YOUR_APPSECRET"
IMAGE_PATH = "cover.jpg"  # 封面图片路径

def main():
    # 1. 获取 Access Token
    access_token = get_access_token(APPID, APPSECRET)
    if not access_token:
        print("获取 Access Token 失败!")
        return

    # 2. 上传封面图片
    thumb_media_id = upload_image(access_token, IMAGE_PATH)
    if not thumb_media_id:
        print("上传封面图片失败!")
        return

    # 3. 构造文章内容
    article_content = """
    <p>这里是文章正文,支持HTML格式。</p>
    <p><img src="https://example.com/image.jpg" /></p>
    """
    article = create_article(
        title="测试文章标题",
        content=article_content,
        thumb_media_id=thumb_media_id
    )

    # 4. 发布草稿(需转为正式文章后发布)
    result = publish_article(access_token, [article])
    if result.get("errcode") == 0:
        print("草稿创建成功!媒体ID:", result.get("media_id"))
    else:
        print("发布失败:", result.get("errmsg"))

if __name__ == "__main__":
    main()

四、注意事项

  1. 从草稿到正式发布
    • 上述代码仅创建草稿,需通过微信公众平台手动 群发 或调用 submit 接口 完成发布。

  2. 内容安全审核
    • 微信会自动审核内容,涉及敏感词可能导致发布失败。

  3. 频率限制
    • 图文消息每日最多发布 1 次,草稿无限制但需谨慎操作。

  4. 错误处理
    • 检查返回的 errcode,常见错误:
    40001: Access Token 失效(需重新获取)
    45009: API 调用频率超限


五、扩展功能

1. 自动发布定时任务

结合 APScheduler 定时触发:

from apscheduler.schedulers.blocking import BlockingScheduler

scheduler = BlockingScheduler()
@scheduler.scheduled_job('cron', hour=8)
def auto_publish():
    main()
scheduler.start()
2. Markdown 转微信 HTML

使用 markdown 库生成内容:

import markdown
content_md = "# 标题\n正文内容"
article_content = markdown.markdown(content_md)

六、官方文档

微信公众号开发文档
图文消息接口文档

### 实现Python脚本送告警信息到微信公众号 为了实现这一目标,需要利用微信公众平台提供的API接口来完成消息推送。具体来说,先要获取`access_token`,这是调用微信开放平台上各个接口的全局唯一票据[^2]。 #### 获取Access Token 由于`access_token`的有效期为7200秒(即两小时),因此建议每次送消息前都重新获取一次以确保其有效性。可以通过GET请求至指定URL并携带必要的认证参数(如AppID和AppSecret)来获得该令牌: ```python import requests def get_access_token(appid, appsecret): url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={appid}&secret={appsecret}" response = requests.get(url).json() access_token = response['access_token'] return access_token ``` #### 送文本消息给特定用户或部门成员 一旦拥有了有效的`access_token`,就可以构建POST请求体并向相应的消息送接口起HTTP POST请求。对于企业内部应用而言,通常会选择向某个具体的用户账号或是某一群组内的所有人员送通知;而对于服务号,则可能更倾向于针对订阅者群体广播信息。下面是一个用于送简单文本形式警告信息的例子: ```python def send_message(access_token, touser, content): url = f"https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={access_token}" payload = { "touser": touser, "msgtype": "text", "agentid": 1, # 应用的 agentid "text": {"content": content}, "safe": 0 } headers = {'Content-Type': 'application/json'} response = requests.post(url, json=payload, headers=headers).json() return response["errmsg"] == "ok" ``` 此函数接收三个参数:一是前面提到过的`access_token`字符串;二是目标用户的OpenID列表(如果是单个收件人则传入单一值即可);三是实际想要传达的消息正文部分。注意这里的`agentid`应当替换为企业自有应用程序对应的合法标识符[^1]。 #### 完整流程示例 结合以上两个辅助方法,完整的告警信息发布逻辑如下所示: ```python if __name__ == "__main__": APP_ID = "your_app_id_here" APP_SECRET = "your_app_secret_here" TO_USER = "@all" # 或者是指定的具体用户ID alert_content = "服务器检测到异常情况,请立即查看!" try: token = get_access_token(APP_ID, APP_SECRET) success = send_message(token, TO_USER, alert_content) if not success: print("Failed to deliver the message.") except Exception as e: print(f"An error occurred during processing: {e}") ``` 这段程序首先尝试取得最新的访问凭证,接着调用消息传递功能并将结果反馈给控制台。如果过程中遇到任何问题也会被捕获并记录下来以便后续排查原因[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值