Preface:

I heard that a lot of friends are suffocating at home because of the epidemic. How about yelling at the computer to vent? Yell loud enough so you can auto-tweet to celebrate? Without further ado, let’s begin happily

The development tools

Python version: 3.6.4

Related modules:

DecryptLogin module;

The argparse module;

Pyaudio module;

And some modules that come with Python.

Environment set up

Install Python and add it to the environment variables. PIP installs the required related modules.

Introduction of the principle

Since we want to realize automatic micro-blog, we must first realize micro-blog simulation login. Here we still use the public account open source simulated login package DecryptLogin to achieve:

Simulate login with DecryptLogin
@staticmethod
def login(username, password) :
    lg = login.Login()
    infos_return, session = lg.weibo(username, password, 'pc')
    return infos_return.get('nick'), infos_return.get('uid'), session
Copy the code

Then we will create a new folder (such as Weibo) and put the content of the microblog we need to post in this folder:

The contents of weibo folder are as follows:

The pictures of our microblog are placed in the pictures folder:

Write the text content of our microblog in Weibo. Md:

Write a function to automatically parse the above tweet:

Content analysis of microblogging to be sent
def __parseWeibo(self, weibopath) :
    text = open(os.path.join(weibopath, 'weibo.md'), 'r', encoding='utf-8').read()
    pictures = []
    for filename in sorted(os.listdir(os.path.join(weibopath, 'pictures'))) :if filename.split('. ')[-1].lower() in ['jpg'.'png']:
            pictures.append(open(os.path.join(weibopath, 'pictures', filename), 'rb').read())
    if len(pictures) > 9:
        print('[Warning]: A tweet can have a maximum of 9 images, the program will now automatically eliminate the extra images')
        pictures = pictures[:9]
    return text, pictures
Copy the code

This function can automatically parse the content of the tweets to be sent (text + image) according to the path of the weibo folder passed in (for example, we just created a folder named Weibo in the current directory, so we can pass./weibo).

After successfully parsing the content of the tweet, we enter the main part of the game, yelling at the computer to automatically tweet. When the volume is high enough (it needs to reach the minimum set volume within 30 seconds), it will automatically send the latest tweet:

# Roar confirm it's the tweet
print('Microblog content: %s\n Number of pictures: %s' % (text, len(pictures)))
print('If you are sure you want to send this tweet, please shout at your computer in 30 seconds')
stream = pyaudio.PyAudio().open(format=pyaudio.paInt16, 
                                channels=1, 
                                rate=int(pyaudio.PyAudio().get_device_info_by_index(0) ['defaultSampleRate']), 
                                input=True, 
                                frames_per_buffer=1024)
is_send_flag = False
start_t = time.time()
while True:
    time.sleep(0.1)
    audio_data = stream.read(1024)
    k = max(struct.unpack('1024h', audio_data))
    # -- Loud enough to send this tweet
    if k > 8000:
        is_send_flag = True
        break
    # -- Not loud enough to tweet when time is up
    if (time.time() - start_t) > 30:
        break
# Tweet
if is_send_flag:
    print('Shout success! Ready to send this tweet ~')
    if self.__sendWeibo(text, pictures):
        print('[INFO]: Sent successfully! ')
Copy the code

Some friends may ask, how do you automatically send micro blog? Do you register for the SDK as well as online tutorials? Of course, no, registering the SDK is cumbersome (and often fails to register the T_T). Just try tweeting and grabbing a bag:

We can easily see that the image upload uses this interface:

This interface is used for tweeting:

So we can easily write a function that automatically tweets:

Tweet.
def __sendWeibo(self, text, pictures) :
    # upload images
    pic_id = []
    url = 'https://picupload.weibo.com/interface/pic_upload.php'
    params = {
                'data': '1'.'p': '1'.'url': 'weibo.com/u/%s' % self.uid,
                'markpos': '1'.'logo': '1'.'nick': '@%s' % self.nickname,
                'marks': '1'.'app': 'miniblog'.'s': 'json'.'pri': 'null'.'file_source': '1'
            }
    for picture in pictures:
        res = self.session.post(url, headers=self.headers, params=params, data=picture)
        res_json = res.json()
        if res_json['code'] = ='A00006':
            pid = res_json['data'] ['pics'] ['pic_1'] ['pid']
            pic_id.append(pid)
        time.sleep(random.random()+0.5)
    # tweeting
    url = 'https://www.weibo.com/aj/mblog/add?ajwvr=6&__rnd=%d' % int(time.time() * 1000)
    data = {
                'title': ' '.'location': 'v6_content_home'.'text': text,
                'appkey': ' '.'style_type': '1'.'pic_id': '|'.join(pic_id),
                'tid': ' '.'pdetail': ' '.'mid': ' '.'isReEdit': 'false'.'gif_ids': ' '.'rank': '0'.'rankid': ' '.'pub_source': 'page_2'.'topic_id': ' '.'updata_img_num': str(len(pictures)),
                'pub_type': 'dialog'
            }
    headers = self.headers.copy()
    headers.update({'Referer': 'http://www.weibo.com/u/%s/home?wvr=5' % self.uid})
    res = self.session.post(url, headers=headers, data=data)
    is_success = False
    if res.status_code == 200:
        is_success = True
    return is_success
Copy the code

Results show

Operation mode:

Python weibosender. py --username username --password passwordCopy the code

That’s the end of this article. Thank you for watching.

To thank you readers, I’d like to share some of my recent programming favorites to give back to each and every one of you in the hope that they can help you.

Dry goods mainly include:

① Over 2000 Python ebooks (both mainstream and classic books should be available)

②Python Standard Library (Most Complete Chinese version)

③ project source code (forty or fifty interesting and classic practice projects and source code)

④Python basic introduction, crawler, Web development, big data analysis video (suitable for small white learning)

⑤ A Roadmap for Learning Python

All done~ Complete source code + dry + Python novice learning community: 594356095