SoFunction
Updated on 2024-11-17

Python realize APP automation send WeChat group message sample code

1. Preamble

However, for many people, first of all, to write an app requires a certain amount of mobile development experience, and secondly, you need to additionally write an accessibility service application, so it seems to have a certain degree of difficulty.
This post will introduce another solution, namely: the use of the previous article introduced AutoJS to automatically send news to the microblogging group to send the morning news!

2. Crawlers and services

For the sake of demonstration convenience, here is Baidu Hot Search as the news morning news data source.

Using Requests + BeautifulSoup to Crawl the 15 Hottest Data by Hotness

import requests
from bs4 import BeautifulSoup

def baidu_top_tipic():
    """Baidu Hot Search"""
    requests_page = ('/buzz?b=1&c=513&fr=topbuzz_b42_c513')
    soup = BeautifulSoup(requests_page.text, "lxml")

    # Query
    soup_text = soup.find_all("div", class_='c-single-text-ellipsis', text=True)

    top_list = []
    for index, text in enumerate(soup_text):
        top_list.append((str(index + 1) + "、" + ()))

    # Take the 15 most popular data
    return '\n'.join(top_list[:15])

Then, using FastAPI, write the API for getting the morning news and deploy it to a cloud server (CentOS is used here as an example)

import uvicorn
from fastapi import FastAPI
from every_news import *

# pip3 install uvicorn
# pip3 install fastapi

# Instantiation
app = FastAPI()

# Daily News
@("/news")
async def rsc_api():
    msg = get_news()
    return {
        "code": 200,
        "msg": msg
    }

if __name__ == '__main__':
    (app='news_api:app', host="0.0.0.0",
                port=6789, reload=True, debug=True)

Finally, run the following command to make the service run in the background

# Command line running in the background
# Log directory: /news_api.log
nohup python3 /xag/news_api.py >  /news_api.log 2>&1 &

3. Automated delivery of group chats

Writing AutoJS Scripts in VS Code

First, define a method that sends a message to the group chat
PS: Performing clicks with the click() coordinate is only available for Android 7.0+.

//API calls to get news data
var url = "http://host:6789/news";

//Send group chat name
var group_name = "Group chat name";

//Send a message to WeChat
function send_wx_msg(group_name, send_msg) {
    //wake up the device if it is sleeping
    //Note: To ensure low power consumption, set sleep (10s no operation)
    ()

    // Open WeChat
    ("");
    text("WeChat.").waitFor()

    //Click to go to the chat screen
    var chat_element_bounds = text(group_name).findOne().bounds();
    //Support Android 7.0+
    click(chat_element_bounds.centerX(), chat_element_bounds.centerY());
    sleep(3000)
    id("auj").className("EditText").findOne().setText(send_msg)
    sleep(3000)
    //Send a message
    text("Send.").click()
    log("Sent successfully!")
    //Return to phone desktop
    back();
    home();

Then, start a new thread in the main thread, call the API interface, get the data and send it out

//Threads
(function () {
    //Access to news
    (url, {}, function (res, err) {
        //Error
        if (err) {
            log("Sorry! Failed to get news today...")
            return;
        }
        log("Today's News Acquisition Successful!")
        let html = ();
        let msg = (html).msg;
        send_wx_msg(group_name, msg)
    });
})

Next, use VS Code to import the source code to the mobile device
Finally, select the source file - Right click - More - Timed Tasks and set the timed task.

4. Finally

In this way, it is possible to realize the function of sending the morning news to the designated group every morning.
Of course, if you're sending to multiple chats, you just need to use AutoJS to query multiple target chats + slide the page, and iterate through them to send the message.
In addition, due to the instability of the accessibility service, you can prioritize the AutoJS application service in the settings to ensure the stable operation of the program

To this article on the Python APP automation to send microblogging group message sample code is introduced to this article, more related Python APP automation to send microblogging group content, please search for my previous articles or continue to browse the following related articles I hope you will support me in the future more!