For study and exchange only, do not use for commercial purposes, and comply with the relevant regulations of Sina Weibo.

The code directory

The functions of this microblog robot are as follows:

  • Simulated login on Sina Weibo to obtain cookies;
  • Automatically upload pictures to weibo map bed;
  • Automatically send different content of the text and text microblogging;
  • Through the scheduled task, the periodic microblog task is realized.

rendering

There are three steps to realize the sending of pictures and tweets

  1. Log on to Weibo.
  2. Upload the picture to weibo picture bed to obtain PID.
  3. Send tweets.

The login

You can use the Puppeteer node library to log in to the Puppeteer and obtain the Weibo cookie. You can search for Puppeteer by yourself.

Puppeteer is an official Google Node library that controls Headless Chrome through the DevTools protocol. You can directly control Chrome through the apis provided by Puppeteer to simulate most user actions to perform UI tests or to crawl pages to collect data.

async function login(username, password) {
    const browser = await puppeteer.launch({
        // headless: false,
        slowMo: 250,
        executablePath: ' '
    });
    const page = (await browser.pages())[0];
    await page.setViewport({
        width: 1280,
        height: 800
    });

    await page.goto("https://weibo.com/");
    await page.waitForNavigation();
    await page.type("#loginname", username);
    await page.type("#pl_login_form > div > div:nth-child(3) > div.info_list.password > div > input", password);
    await page.click("#pl_login_form > div > div:nth-child(3) > div:nth-child(6)");
    await page.waitForNavigation().then(result => {
        return new Promise((resolve) => {
            page.cookies().then(async cookie => {
                fs.createWriteStream("cookie.txt").write(JSON.stringify(cookie), "UTF8"); // Store cookie await browser.close(); // Close the open browser resolve(cookie); }); }) }).catch(e => { page.screenshot({ path:'code.png'.type: 'png',
            x: 800,
            y: 200,
            width: 100,
            height: 100
        });
        return new Promise((resolve, reject) => {
            readSyncByRl("Please enter the verification code.").then(async (code) => {
                await page.type("#pl_login_form > div > div:nth-child(3) > div.info_list.verify.clearfix > div > input", code);
                await page.click("#pl_login_form > div > div:nth-child(3) > div:nth-child(6)");
                await page.waitForNavigation();
                page.cookies().then(async cookie => {
                    fs.createWriteStream("cookie.txt").write(JSON.stringify(cookie), "UTF8"); await browser.close(); resolve(cookie); }); })})})}Copy the code

Upload pictures to weibo chart bed

Uploading to Weibo map can be seen here weibo.com/minipublish packet capture to see the interface process of uploading, you can see that the uploaded base64 picture information. So before uploading the image into base64 encoding, and local image encoding and Internet link image encoding is different, here is the use of Internet link image, Node local image into Base64 encoding is easier. Return the PID of the weibo picture bed after uploading successfully. Remember the PID, that’s what you tweet with.

Send weibo

With weibo cookies and pictures after pid can tweeting, separated with | between pid when multiple pictures.

async function weibopost(text, pic_ids = ' ', cookie) {// Send micro blog content (supported with pictures)return new Promise(async (resolve, reject) => {
        if (cookie === ' ') {
            reject('Error: Cookie not set! ');
        }
        let post_data = querystring.stringify({
            'location': 'v6_content_home'.'text': text,
            'appkey': ' '.'style_type': '1'.'pic_id': pic_ids,
            'tid': ' '.'pdetail': ' '.'mid': ' '.'isReEdit': 'false'.'rank': '0'.'rankid': ' '.'module': 'stissue'.'pub_source': 'main_'.'pub_type': 'dialog'.'isPri': '0'.'_t': '0'
        });

        let post_options = {
            'Accept': '* / *'.'Accept-Encoding': 'gzip, deflate, br'.'Accept-Language': 'zh-CN,zh; Q = 0.9, en. Q = 0.8, useful - TW; Q = 0.7 '.'Connection': 'keep-alive'.'Content-Length': Buffer.byteLength(post_data),
            'Content-Type': 'application/x-www-form-urlencoded'.'Cookie': cookie,
            'Host': 'weibo.com'.'Origin': 'https://weibo.com'.'Referer': 'https://weibo.com'.'User-Agent': 'the Mozilla / 5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.167 Safari/537.36'.'X-Requested-With': 'XMLHttpRequest'
        };


        let {
            data
        } = await axios.post('https://weibo.com/aj/mblog/add?ajwvr=6&__rnd=' + new Date().getTime(), post_data, {
            withCredentials: true,
            headers: post_options
        })
        if (data.code == 100000) {
            console.log('\n' + text + '-----Sent! ' + The '-' + new Date().toLocaleString());
            resolve(data);
        } else {
            console.log('post error');
            reject('post error'); }}); }Copy the code

You can use the Node-schedule node library to search and learn scheduled tasks. This is a 10-minute interval.

function loginTo() {
	login(config.username, config.password).then(async () => {
		let rule = null;
		rule = new schedule.RecurrenceRule();
		rule.minute = [01, 11, 21, 31, 41, 51];
		try {
			letcookie = await getCookie(); getContent(cookie); } catch (error) { console.log(error); } j = schedule.scheduleJob(rule, async () => {letcookie = await getCookie(); getContent(cookie); } catch (error) { console.log(error); }}); })}Copy the code

Code Address:Making the address

reference

Github.com/itibbers/we…

No server learning children can look at Tencent cloud 1 core 2G, 1M bandwidth, 50GB storage space cloud server, 1201 oh.