欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

微信公眾號(hào)腳本-獲取熱搜自動(dòng)新建草稿并發(fā)布文章

 更新時(shí)間:2025年04月04日 15:26:22   作者:春寒知冬冷  
本來想寫一個(gè)自動(dòng)化發(fā)布微信公眾號(hào)的小綠書的腳本,但是微信公眾號(hào)官網(wǎng)沒有小綠書的接口,那就寫一個(gè)獲取熱搜微信普通文章的腳本吧,這篇文章主要介紹了微信公眾號(hào)腳本-獲取熱搜自動(dòng)新建草稿并發(fā)布文章

介紹

本來想寫一個(gè)自動(dòng)化發(fā)布微信公眾號(hào)的小綠書的腳本。但是微信公眾號(hào)官網(wǎng)沒有小綠書的接口。

想著算了吧,寫都寫了,那就寫一個(gè)微信普通文章的腳本吧。

寫完了 就想著把腳本分享出來,給大家一起交流下。

水平有限,大佬輕噴。

2025-0226:

1,解決gitee不能開源問題,我把之前的庫刪除了,新建了個(gè)同名的庫

2,新增微信公眾號(hào)小綠書,自動(dòng)發(fā)布草稿

3,新增小綠書,利用ai編寫國(guó)家5A級(jí)景區(qū) 小綠書種草文章

4,小綠書跟普通文章的大致步驟一樣,歡迎大家交流

2025-0320:

1,優(yōu)化一些邏輯

2,新增保持56篇熱搜文章,刪除老的熱搜文章

思路

1,獲取百度熱搜列表

2,給熱搜圖片加上文字標(biāo)題

3,上傳圖片到微信公眾號(hào)素材庫

4,新建微信公眾號(hào)草稿

5,發(fā)布草稿

前期準(zhǔn)備

1,注冊(cè)微信公眾號(hào),獲取AppID和AppSecret

2,微信公眾號(hào)接口文檔( 文檔鏈接),參照文檔進(jìn)行接口調(diào)用

3,微信公眾號(hào)設(shè)置IP白名單

在服務(wù)器上面獲取出口外網(wǎng)ip

curl -s https://ipinfo.io/ip

環(huán)境要求

1,我使用的是python12

2,依賴就需要安裝PIL庫,其他庫都是默認(rèn)安裝的

(py12-ai-django5) [root@gtp-test01-cyt wxmp]# python -V
Python 3.12.4
# 

import requests
import os
import time
import yaml
import json
import string

from PIL import Image, ImageDraw, ImageFont
 
# 安裝PIL
pip install pillow==10.4.0
 
# 運(yùn)行腳本wxmp.py 就行
python wxmp.py

# 輸出

# 輸出
圖片已保存到 hotimg/orgimg/2.png
圖片已保存到 hotimg/orgimg/3.png
圖片已保存到 hotimg/orgimg/4.png
圖片已保存到 hotimg/orgimg/5.png
圖片已保存到 hotimg/orgimg/6.jpg
圖片已保存到 hotimg/orgimg/7.jpg
圖片已保存到 hotimg/orgimg/8.png
圖片已保存到 hotimg/orgimg/9.png
圖片已保存到 hotimg/orgimg/10.jpg
圖片已保存到 hotimg/orgimg/11.png
圖片已加文字 hotimg/nowimg/2.png
圖片已加文字 hotimg/nowimg/3.png
圖片已加文字 hotimg/nowimg/4.png
圖片已加文字 hotimg/nowimg/5.png
圖片已加文字 hotimg/nowimg/6.jpg
圖片已加文字 hotimg/nowimg/7.jpg
圖片已加文字 hotimg/nowimg/8.png
圖片已加文字 hotimg/nowimg/9.png
圖片已加文字 hotimg/nowimg/10.jpg
圖片已加文字 hotimg/nowimg/11.png
新建草稿成功--{'media_id': 'V4QdIouS1e-m5FaD0_0keQQMcEMKo0-3YjLoF_JqJohqywWC3Byyr81SXUi1TheO', 'item': []}
{'errcode': 0, 'errmsg': 'ok', 'publish_id': 2247483801, 'msg_data_id': 2247483801}

獲取接口token

1,由于access_token的有效期只有2小時(shí),故需要定時(shí)刷新。

2,這里使用app_token.yaml來保存獲取到的token以及時(shí)間;token在時(shí)效內(nèi)返回保存的token,超過時(shí)效會(huì)獲取新的token

def get_token(
        app_id='',  # 微信公眾號(hào)AppID
        app_secret=''  # 微信公眾號(hào)AppSecret
):
    """
    獲取token
    :return:
    """
    url = f'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={app_id}&secret={app_secret}'
    res = requests.get(url=url)
    result = res.json()
    if result.get('access_token'):
        token = result['access_token']
        print(f"獲取token成功:{token[:14]}****")
        return token
    else:
        print(f"獲取token失敗--{result}")


def refresh_token():
    """
    token刷新機(jī)制
    :return:
    """
    app_token_path = os.path.dirname(os.path.abspath(__file__)) + os.sep + 'app_token.yaml'
    try:
        # 讀取時(shí)間和token
        if not os.path.exists(app_token_path):
            with open(app_token_path, 'w+') as f:
                f.write('')
        cfg_token = yaml_read(app_token_path)
        t = cfg_token['time']
        record_token = cfg_token['token']
        cur_time = time.time()
        # token時(shí)間在7200s之內(nèi),返回token
        if 0 < cur_time - t < 7200:
            # print(f"token時(shí)效內(nèi)")
            return record_token
        # token過期,刷新時(shí)間和token
        else:
            # print('token已過期')
            token = get_token()
            if token:
                data = {'time': time.time(), 'token': token}
                yaml_clear(app_token_path)
                yaml_write(data, app_token_path)
                return token
    except TypeError:
        # 獲取初始時(shí)間和token
        print('獲取初始token')
        token = get_token()
        data = {'time': time.time(), 'token': token}
        yaml_write(data, app_token_path)
        return token


def yaml_read(file):
    """
    yaml文件讀取
    :param file:
    :return:
    """
    with open(file=file, mode="r", encoding="utf-8") as f:
        data = yaml.safe_load(f.read())
    return data


def yaml_write(data, file):
    """
    yaml文件寫入
    :param data:
    :param file:
    :return:
    """
    with open(file, 'a', encoding='utf-8') as f:
        yaml.dump(
            data,
            stream=f,
            allow_unicode=True,  # 避免unicode編碼問題
            sort_keys=False  # 不自動(dòng)排序
        )


def yaml_clear(file):
    """
    yaml文件清空
    :param file:
    :return:
    """
    with open(file, 'w', encoding='utf-8') as f:
        f.truncate()

獲取熱搜

這里我是找的網(wǎng)上別人寫好的接口。簡(jiǎn)單快速方便

https://dabenshi.cn/other/api/hot.php?type=douyinhot // 抖音熱點(diǎn)
https://dabenshi.cn/other/api/hot.php?type=toutiaoHot // 頭條熱榜
https://dabenshi.cn/other/api/hot.php?type=baidu // 百度熱搜

我這里使用的是百度熱搜。

獲取熱搜數(shù)據(jù)

# 獲取熱搜數(shù)據(jù)
def get_hotdata():
    '''
    獲取百度熱搜的數(shù)據(jù)
    url網(wǎng)上找的: https://dabenshi.cn/other/api/hot.php?type=baidu
    '''
    url = f"https://dabenshi.cn/other/api/hot.php?type=baidu"
    hotdata = [] # 存儲(chǔ)所有的熱搜數(shù)據(jù)

    res = requests.get(url=url)
    result = res.json()
    hotdata = result['data'][1:11]    # 這里我只拿了10條數(shù)據(jù)


# 數(shù)據(jù)就是一個(gè)打列表,里面有字典
hotdata =[
        {
            "index": 2,
            "title": "外交部回應(yīng)是否邀請(qǐng)?zhí)乩势赵L華",
            "desc": "1月21日,外交部就“中方是否邀請(qǐng)?zhí)乩势赵L華”一事做出回應(yīng):愿同美國(guó)新政府保持溝通,加強(qiáng)合作。",
            "pic": "https:\/\/fyb-2.cdn.bcebos.com\/hotboard_image\/4d0700b48e6c791e29f1e231e24af061",
            "url": "https:\/\/www.baidu.com\/s?wd=%E5%A4%96%E4%BA%A4%E9%83%A8%E5%9B%9E%E5%BA%94%E6%98%AF%E5%90%A6%E9%82%80%E8%AF%B7%E7%89%B9%E6%9C%97%E6%99%AE%E8%AE%BF%E5%8D%8E&sa=fyb_news&rsv_dl=fyb_news",
            "hot": "797.6萬",
            "mobilUrl": "https:\/\/www.baidu.com\/s?wd=%E5%A4%96%E4%BA%A4%E9%83%A8%E5%9B%9E%E5%BA%94%E6%98%AF%E5%90%A6%E9%82%80%E8%AF%B7%E7%89%B9%E6%9C%97%E6%99%AE%E8%AE%BF%E5%8D%8E&sa=fyb_news&rsv_dl=fyb_news"
        }
]

下載熱搜圖片

其實(shí)就是把熱搜數(shù)據(jù)里面的pic圖片保存到了本地

這樣一會(huì)就好給圖片加上標(biāo)題文字了

def get_hotimg(hotdataall):
    """
    下載熱搜圖片
    hotdata: 所有數(shù)據(jù)
    """

    if hotdataall:
        for hotdata in hotdataall:
            try:
                # 發(fā)送HTTP GET請(qǐng)求獲取圖片數(shù)據(jù)
                response = requests.get(hotdata['pic'], timeout=10)
                # 檢查請(qǐng)求是否成功
                if response.status_code == 200:
                    # 獲取Content-Type頭信息
                    content_type = response.headers.get('Content-Type')

                    # 根據(jù)Content-Type判斷圖片類型
                    image_extension = None
                    if content_type == 'image/jpeg':
                        image_extension = '.jpg'
                    elif content_type == 'image/png':
                        image_extension = '.png'
                    elif content_type == 'image/gif':
                        image_extension = '.gif'
                    else:
                        raise Exception(f"Unsupported image type: {content_type}")

                    # 以二進(jìn)制寫模式打開文件,并將圖片數(shù)據(jù)寫入文件
                    img_name = "hotimg/orgimg/" + str(hotdata['index']) + image_extension
                    img_name_new = "hotimg/nowimg/" + str(hotdata['index']) + image_extension
                    with open(img_name, 'wb') as file:
                        file.write(response.content)
                    print(f'圖片已保存到 {img_name}')

                    hotdata['image_path'] = img_name
                    hotdata['image_path_new'] = img_name_new
                else:
                    print(f'下載圖片失敗,狀態(tài)碼: {response.status_code}')
            except requests.RequestException as e:
                print(f'請(qǐng)求出現(xiàn)異常: {e}')

給圖片加上標(biāo)題文字

# 給圖片加上文字
    if hotdata:
        for hotdata_in in hotdata:
            image_path = hotdata_in['image_path']
            image_path_new = hotdata_in['image_path_new']
            text = hotdata_in['title']
            max_width = 500

            add_text_to_image(image_path, image_path_new, text=text, max_width=max_width)

def add_text_to_image(image_path, image_path_new, text='', max_width=500):
    '''
    給圖片添加文字
    '''
    image = Image.open(image_path)
    draw = ImageDraw.Draw(image)
    width, height = image.size

    font_size = max(30, int(width * 0.03))

    font = ImageFont.truetype("ttf/feihuasongti.ttf", font_size)
    text_color = (255, 255, 255)  # 黑色字體
    shadow_color = (0, 0, 0)  # 黑色陰影
    # text_width, text_height = draw.textsize(text, font=font)
    # 獲取文本尺寸
    bbox = draw.textbbox((0, 0), text, font=font)
    text_width = bbox[2] - bbox[0]
    text_height = bbox[3] - bbox[1]

    while text_width > width - 30:
        font_size -= 1
        font = ImageFont.truetype("ttf/feihuasongti.ttf", font_size)
        # text_width, text_height = draw.textsize(text, font=font)
        # 獲取文本尺寸
        bbox = draw.textbbox((0, 0), text, font=font)
        text_width = bbox[2] - bbox[0]
        text_height = bbox[3] - bbox[1]

    # 計(jì)算文本位置
    x = width - text_width
    y = height - text_height - 30
    # 繪制文本陰影
    draw.text(((x/2) + 2, y + 2), text, font=font, fill=shadow_color)
    draw.text((x / 2, y), text, font=font, fill=text_color)

    image.save(image_path_new)
    print(f'圖片已加文字 {image_path_new}')

類似這樣,在圖片底部加上文字

上傳圖片素材

這塊會(huì)返回上傳到素材url。這個(gè)url地址,可以在文章里面使用

def add_media(hotdataall):
    """
    新增臨時(shí)素材: https://api.weixin.qq.com/cgi-bin/media/upload?access_token=ACCESS_TOKEN&amp;type=TYPE
    上傳圖文消息內(nèi)的圖片獲取URL, 新增永久素材: https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=ACCESS_TOKEN
    新增其他類型永久素材, 新增永久素材: https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=ACCESS_TOKEN&amp;type=TYPE
    """
    # url = f"https://api.weixin.qq.com/cgi-bin/media/upload?access_token={refresh_token()}&amp;type=image"
    url = f"https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token={refresh_token()}"

    if hotdataall:
        for hotdata in hotdataall:
            with open(hotdata['image_path_new'], 'rb') as fp:
                files = {'media': fp}
                res = requests.post(url, files=files)
                res = json.loads(str(res.content, 'utf8'))
                hotdata["wx_img_url"] = res['url']

新建草稿

這里會(huì)返回草稿的ID

def add_draft(hotdataall):
    '''
    新建草稿
    '''
    url = f'https://api.weixin.qq.com/cgi-bin/draft/add?access_token={refresh_token()}'

    # content = "<img src='https://mmbiz.qpic.cn/sz_mmbiz_jpg/hY63os7Ee2Ro6WVkfj9nvfDdpONqLwr48J2eQEYXygs3cWibLvQTHAveYWNnXOOWHO3jZldO3fr7quVj6V0X5uA/0?wx_fmt=jpeg'/>"
    # 讀取文件html
    # 打開HTML文件并讀取內(nèi)容
    with open('content.html', 'r', encoding='utf-8') as file:
        html_content_template = file.read()

    # 動(dòng)態(tài)生成草稿content內(nèi)容全部,先定義一個(gè)變量
    html_content = ""

    # 動(dòng)態(tài)生成草稿content內(nèi)容片段
    for hotdata in hotdataall:
        # 判斷熱搜第一
        if hotdata['index'] == 2:
            title_color = "red"
        else:
            title_color = "black"

        # 定義變量
        hot_context = {
            'num': hotdata['index'] - 1,
            'url_img': hotdata['wx_img_url'],
            'title_color': title_color,
            'title_title': hotdata['title'],
            'describe': hotdata['desc'],
        }

        # 替換變量
        substitute_data = string.Template(html_content_template)
        result = substitute_data.safe_substitute(hot_context)
        html_content += result

    data = {
        "articles": [
            {
                "title":"標(biāo)題",
                "author":"作者",
                "digest":"描述",
                "content":html_content,
                "thumb_media_id":"封面素材ID",
                "need_open_comment":1,
                "only_fans_can_comment":1
            }
        ]
    }

    res = requests.post(url=url, data=json.dumps(data, ensure_ascii=False).encode('utf-8'))

    if res.status_code == 200:
        result = json.loads(res.content)
        if result.get('media_id'):
            print(f'新建草稿成功--{result}')
            return result['media_id']
        else:
            print(f'新建草稿失敗--{result}')
    else:
        print(f'新建草稿失敗--{res.text}')

發(fā)布草稿

def free_publish(media_id):
    '''
    發(fā)布草稿
    '''
    url = f'https://api.weixin.qq.com/cgi-bin/freepublish/submit?access_token={refresh_token()}'

    data = {
        "media_id": media_id
    }

    res = requests.post(url=url, json=data)
    res = json.loads(str(res.content, 'utf8'))
    print(res)

到此這篇關(guān)于微信公眾號(hào)腳本-獲取熱搜自動(dòng)新建草稿并發(fā)布文章的文章就介紹到這了,更多相關(guān)微信公眾號(hào)熱搜自動(dòng)發(fā)文腳本內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • python opencv 圖像拼接的實(shí)現(xiàn)方法

    python opencv 圖像拼接的實(shí)現(xiàn)方法

    高級(jí)圖像拼接也叫作基于特征匹配的圖像拼接,拼接時(shí)消去兩幅圖像相同的部分,實(shí)現(xiàn)拼接合成全景圖。這篇文章主要介紹了python opencv 圖像拼接,需要的朋友可以參考下
    2019-06-06
  • python中urllib.request和requests的使用及區(qū)別詳解

    python中urllib.request和requests的使用及區(qū)別詳解

    這篇文章主要介紹了python中urllib.request和requests的使用及區(qū)別詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-05-05
  • Django shell調(diào)試models輸出的SQL語句方法

    Django shell調(diào)試models輸出的SQL語句方法

    今天小編就為大家分享一篇Django shell調(diào)試models輸出的SQL語句方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-08-08
  • python使用opencv對(duì)圖像添加噪聲(高斯/椒鹽/泊松/斑點(diǎn))

    python使用opencv對(duì)圖像添加噪聲(高斯/椒鹽/泊松/斑點(diǎn))

    這篇文章主要介紹了python使用opencv對(duì)圖像添加噪聲(高斯/椒鹽/泊松/斑點(diǎn)),具有一定的學(xué)習(xí)價(jià)值,需要的小伙伴可以參考一下,希望對(duì)你有所幫助
    2022-04-04
  • Python光學(xué)仿真之對(duì)光的干涉理解學(xué)習(xí)

    Python光學(xué)仿真之對(duì)光的干涉理解學(xué)習(xí)

    這篇文章主要為大家介紹了Python光學(xué)仿真之對(duì)光的干涉理解學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步早日升職加薪
    2021-10-10
  • pytorch visdom安裝開啟及使用方法

    pytorch visdom安裝開啟及使用方法

    這篇文章主要介紹了pytorch visdom安裝開啟及使用方法,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-04-04
  • python矩陣列的實(shí)現(xiàn)示例

    python矩陣列的實(shí)現(xiàn)示例

    在Python和NumPy庫的幫助下,矩陣列可以很容易地進(jìn)行各種操作,本文主要介紹了python矩陣列的實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下
    2024-02-02
  • Python項(xiàng)目打包部署到服務(wù)器的實(shí)現(xiàn)

    Python項(xiàng)目打包部署到服務(wù)器的實(shí)現(xiàn)

    本文主要介紹了PyCharm和Ubuntu服務(wù)器部署Python項(xiàng)目,包括打包、上傳、安裝和設(shè)置自啟動(dòng)服務(wù)的步驟,具有一定的參考價(jià)值,感興趣的可以了解一下
    2025-01-01
  • django實(shí)現(xiàn)類似觸發(fā)器的功能

    django實(shí)現(xiàn)類似觸發(fā)器的功能

    今天小編就為大家分享一篇django實(shí)現(xiàn)類似觸發(fā)器的功能,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-11-11
  • 使用?PyQt5?設(shè)計(jì)下載遠(yuǎn)程服務(wù)器日志文件程序的思路

    使用?PyQt5?設(shè)計(jì)下載遠(yuǎn)程服務(wù)器日志文件程序的思路

    這篇文章主要介紹了使用?PyQt5?設(shè)計(jì)下載遠(yuǎn)程服務(wù)器日志文件程序,借助 PyQt5 強(qiáng)大的能力,我們可以通過“拖拉拽”的形式很容易地實(shí)現(xiàn)桌面端程序,只需要將原來的 Python 腳本綁定到 UI 程序的事件中,就實(shí)現(xiàn)了命令行程序到桌面程序的演進(jìn),需要的朋友可以參考下
    2022-11-11

最新評(píng)論