Why is the article so slow this time? It’s because last week he flew to Japan to celebrate his girlfriend’s 18th birthday without pikpa.

These days, obviously, the Beijing conference is over, air quality, hehe hehe.

So this time we’re going to talk about something extra. Those of you who own a Kindle know that if you want to read kindle books, there are generally several channels:

  1. Go to the Kindle website and buy genuine books, but books are expensive, and when there is an occasional sale, the sale is not cheap. Tuhao can choose this path.
  2. Go to the Internet and download your own ebook, then upload it to your Kindle. This way is generally for the students who do not love to use computers, quite technical, so the students who love to start can choose this.
  3. The last one is to go to some treasure or to find some public number, where they provide the download of books, paid free, and, is the way to push. This path works for almost everyone, and it’s convenient.

When I bought A Kindle, I also used the third method to find books. I remember that I found an official account, searched some books and pushed them to Kindle, thinking it was convenient to stir chicken. However, that official account was suspended later, and then I changed several official accounts, which were not stable, but they all had one common feature. I just need to manually bind the mailbox myself. Personally, this step seems to have no electronic intelligence for people, very unfriendly, so some public account opened an exclusive customer service, teach you how to bind. On the whole, everyone went through the same process, but as a coder, I was professionally curious to know what was going on with them. Therefore, I found on Google that the most promoted articles are made with KindleEar, but this thing is compatible with Google App Engine, which is very unfriendly to Chinese children. I remember that in the process of searching, I also found that there was a god who would crawl zhihu hot articles, articles on official accounts and other hot articles and integrate them by himself. He would push them to Kindle at 5 o ‘clock every day and read them by himself on the subway after work. This is actually a great way to use fragmented time to absorb knowledge, very strong. Too bad the article doesn’t say how. From these two points, shovel excrement officer decided to rely on heaven to rely on their own, their concentration of cultivation, trend to get through this pulse. Sure enough, through my continuous in-depth learning of Python, I gradually got through all the nodes and could easily complete this task. Haha haha.

So today, shovel excrement officer will come and you papering papering papering this third method said above, to provide you with ideas, and specific implementation methods. Do well, you can pay to help others find books ah, such as a dollar 10 books, not to make more money, just to balance the electricity bill, after all, you are only a porter.

Without further ado, let’s get to the details.

The overall train of thought

Get a problem, we first have to analyze, this problem is composed of which parts, these parts how to do better.

The Kindle push server can be roughly divided into two parts: find books and push.

【Python 】 use code to access the website 1024, send benefits 【Python 】 use code to achieve automatic post in the forum 1024

Let’s talk about server push in detail. The push process should look something like this:

  • First, bind the user’s push Kindle information through the wechat public account: Kindle account email, Kindle approved sender email, Kindle approved sender email STMP password.
  • You can find relevant books by sending the title of the book through the wechat official account.
  • The server realizes the e-book push of Kindle through the previously bound account.
  • In about 10 minutes, the ebook is pushed to the Kindle and you can read happily.

Probably is such a few points, in fact, see here, if you are a loyal reader of shovel-poo officer, then I say these points, in fact, in my previous series of articles, the key knowledge point has been said in detail, shovel-poo officer here combined with the code to help you to a.

I have deployed the whole set of server code to Ali Cloud. The shod officer has some coupons of Ali Cloud and Tencent Cloud, which are very affordable and cheap. If he plays server, he can take down less than 200 servers of more than 300 a year. Available via the link below, on a limited basis, on a first-come-first-served basis:

Ali Cloud (with a total value of 1000 yuan voucher) :

https://promotion.aliyun.com/ntms/yunparter/invite.html?userCode=nrkmbo9q



Tencent Cloud (total value up to 2,775 yuan voucher) :


https://cloud.tencent.com/redirect.php?redirect=1025&cps_key=b351b2fc50b15866ff9d19b58a5df0f5

First of all, let’s talk about the binding of user information through wechat public account.

WeRobot

For the development of wechat official account, I first recommend using WeRobot framework. This framework encapsulates the things mentioned in the official development document of wechat official account. It is very easy to use.

https://werobot.readthedocs.io/zh_CN/latest/

The scenario where we need the user to bind the account here uses the Session in WeRobot. The official documentation is below:

https://werobot.readthedocs.io/zh_CN/latest/session.html

By default, a werobot_session.sqlite3 file is created in the server’s local folder, which stores data in the form of key-value pairs. The following code is an example of a session used in the Kindle project:

 1from werobot import WeRoBot
 2from werobot.contrib.tornado import make_handler
 3import re
 4
 5robot = WeRoBot(token="Your token")
 6
 7urls = [
 8    (r'reply', make_handler(robot))
 9]
10debug_list = []
11exception_list = []
12info_message = []
13
14
[email protected]('kindle')
16def replyKindle(message, session):
17    count = session.get("kindle_count", 0)
18    email = session.get("kindle_auth_email".""19)if email is "":
20        session["kindle_count"] = count + 1
21        return "Enter Kindle Email:"
22    else23:return "Please enter the title of the book you are looking for:"
24
[email protected]("Rebind")
26def printSeesino(message, session):
27    session['kindle_count'] = 1
28    session['kindle_email'] = ""
29    session['kindle_auth_email'] = ""
30    session['kindle_auth_pwd'] = ""
31    return "Untying successful! \n Please re-type Kindle email:"
32
33
[email protected]("session")
35def printSeesino(message, session):
36    return "session: " + str(session)
37
[email protected](re.compile('Looking for a book:'))
39def replayHuitie(message, session):
40    return findBook(message, session)
41
42
43def findBook(message, session):
44    if session['kindle_count']! = 4:45return "Please attach your Kindle account and come back for the book."
46    book_name = message.content[3:]
47    if book_name is ""48:return "Old iron you typed the title of the book wrong, please re-enter."
49    else:
50        ### The process of finding a book
51        # find_result = find_book()
52        find_result = True
53        if find_result is True:
54            ### Send the book function method
55            # send_result = send_book()
56            send_result = emailSender().sendEmailWithAttr(session['kindle_email'], session['kindle_auth_email'],
57                                                          session['kindle_auth_pwd'58])if send_result is True:
59                return "What are you looking for?" + book_name + "\n The background has been successfully sent to you, please pay attention to check within 10 minutes. Thanks for using it."
60            else:
61                return "Sorry, old iron to send the book failed, please try again."
62        else:
63            return "Sorry, I can't find the book Lao Tie wants. Please try some other books."
64
65
[email protected]
67def restReply(message, session):
68    count = session.get("kindle_count"69, 0)print(message.content + " count: " + str(count))
70    if count == 1:
71        session["kindle_count"] = count + 1
72        session["kindle_email"] = message.content
73        return "Please enter Kindle authentication email address:"
74    if count == 2:
75        session["kindle_count"] = count + 1
76        session["kindle_auth_email"] = message.content
77        return "Please enter the password of authentication email:"
78    if count == 3:
79        session["kindle_count"] = count + 1
80        session["kindle_auth_pwd"] = message.content
81        return "Binding successful! \n Your Kindle email address:" + session['kindle_email'] \
82               + "\nKindle certified email address:" + session['kindle_auth_email'] + "\n Authentication email password:" \
83               + session['kindle_auth_pwd'] + "\n If you need to rebind, reply "rebind". \n Now you can find a book, just reply "looking for a book: + title", for example: "Looking for a book: Gold scales are not in the pool"
84    if count == 4:
85        if "Looking for a book:" in message.content:
86            findBook(message, session)
87        else:
88            reply = """Pique pa shoveling excrement officer" so awesome public account, still don't pay attention to a wave ah?"""
89        return reply
Copy the code

As you can see, I’m using a count variable to control the processing of text information. Each user, when entering the specific keyword kinle, will enter the specified processing logic. Then, different processing logic is controlled through the change of count, and relevant text information entered by the user is saved to the session dictionary. WeRobot automatically updates the information to the database.

Here are a few things you can do:

  1. You can check whether the information entered by the user is valid. For example, when you need to enter an email address, the text structure entered is valid.
  2. When you Debug, you can add some special words to print the information you need, such as addsessionIs used to print its own session information as follows:

So here we are, our first step is complete, and the final result is roughly as follows:

OK, here we put the wechat public number this piece of code logic clear. So now we have to look at the code that sends the book.

Send.mobi files

You need to send mail in Python. First, we need to learn how to send mobi files to the Kindle by email. Here, the Kindle’s official documentation goes into great detail:


https://www.amazon.cn/gp/help/customer/display.html/ref=kinw_myk_wl_ln?ie=UTF8&nodeId=200767340#pdocarchive


https://www.amazon.cn/gp/help/customer/display.html?nodeId=201974220

Note that there are two requirements for successfully sending mobi files to the Kindle:

  1. The email address from which the document is sent must be on the Kindle approved email list.
  2. The subject of the email must be “Convert”

So, what we’re going to do here is, we’re going to take the books we found, and we’re going to attach the book file to the email, and the subject of the email is “Convert”, and we’re going to send it to our Kindle account. That completes the book push. Super simple?

Therefore, we will skip the process of finding a book here, and refer to article 1 for relevant technical points. We send the books to the Kindle by email. Send_result = emailSender().sendeMailWithattr (session[‘kindle_email’], Session [‘ kindLE_auth_email ‘],session[‘ kindLE_auth_PWd ‘]) Yes, this is the method call that sends the mail. So the emailSender() code looks like this:

 1class emailSender(object):
 2    def __init__(self):
 3        self.smtp_host = "smtp.126.com"      # SMTP server for sending mail (obtained from QQ mailbox)
 4        self.smtp_port = 465                SMTP server SSL port number, default is 465
 5
 6    def sendEmailWithAttr(self, kindleEmail, kindleAuthEmail, kindleAuthPwd):
 7        ' ''8 Send mail 9'' '
10        logging("sendEmailWithAttr:::\nkindleEmail: " + kindleEmail + "\nkindleAuthEmail: " + kindleAuthEmail + "\nkindleAuthPwd: " + kindleAuthPwd)
11        message = MIMEMultipart()  # Email content, format, code
12        message['From'] = kindleAuthEmail             # the sender
13        message['To'] = kindleEmail             # Recipient list
14        message['Subject'] = "Convert"                # Email header
15        filename = './ TXT/Consolations of Philosophy - Alain de Botton. Mobi '    # Local books
16        with open(filename, 'rb') as f:
17            attachfile = MIMEApplication(f.read())
18        filename = "The Solace of Philosophy - Alain de Botton mobi."
19        attachfile.add_header('Content-Disposition'.'attachment', filename=filename)
20        encoders.encode_base64(attachfile)
21        message.attach(attachfile)
22        try:
23            smtpSSLClient = smtplib.SMTP_SSL(self.smtp_host, self.smtp_port)   Instantiate a SMTP_SSL object
24            loginRes = smtpSSLClient.login(kindleAuthEmail, kindleAuthPwd)      # Log in to the SMTP server
25            logging(f"LoginRes = {loginRes}")    # loginRes = (235, b'Authentication successful')
26            if loginRes and loginRes[0] == 235:
27                logging(f"Login successful, code = {loginRes[0]}")
28                smtpSSLClient.sendmail(kindleAuthEmail, kindleEmail, message.as_string())
29                logging(f"mail has been send successfully. message:{message.as_string()}")
30                return True
31            else:
32                logging(f"Login failed, code = {loginRes[0]}"33)return False
34        except Exception as e:
35            logging(f"Failed to send, Exception: e={e}"36)return False
Copy the code

As you can see, the above code simply fills the Subject with Convert and sends the MOBi book as an attachment. This is the same process as the 1024 Seed Devourer V2.0, which scrapes and scrapes your mail. Thousand dollar welfare waiting for you

Below shovel excrement officer to show you the whole process:

The first is the binding of the public account:

Then the binding succeeds, and the start and display of the book also succeeds:


So let’s take a look at our Kindle:

Oh yeah, we’re all set. The process worked perfectly. Actually, that’s only half the process, the other half, we’ll talk about it next time, but you can do some research on your own. These gadgets can actually bring small profits, not bragging force.

Simple summary

Here is a brief summary of the key points:

  1. In the binding process of sending mailboxes, only 126 mailboxes are bound here. In fact, STMP ports of different mailboxes are different, and the STMP server address is also different. We need to make a judgment here.
  2. This is just the process of sending the book, actually should be in the book search, return the book search results, and then let the user choose which book to download. At present, the way I think of downloading books is to download them to the server first, and then send them out in the format of attachment. Finally, the following deletion operations need to be performed.
  3. You can also subscribe to a 1024Daily page and send it to your Kindle every day. You can also send your favorite series of technical forum posts to your Kindle every day. There are a lot of directions to play, waiting for you to dig.

Thank you for being able to tolerate the speaker’s nagging about so many broken knowledge points, then I will not be bad for you. I wrote this server with Tornado, and I have uploaded the whole code. The way to obtain the source code only needs to pay attention to”

Pick’s pooper

“, reply”

code

“Can be obtained. The content of this reply is guaranteed to your satisfaction.

For the next step, I think the Daily project can be improved, so the next step may be to add a collection function, haha, it will be more and more convenient. Ah-ha-ha

Recommended reading

A, one article is enough to get through python network request, scrapy crawler, server, proxy, all kinds of operations, really one is enough two, hand in hand with ali cloud server to build sock tools, from now on no longer ask people, there are three, 【Python actual situation 】 through the “acid” of the operation, let the crawler become no national borders, True hardcore can climb whatever they want

Powder a wave of their own small program

So hardcore public number, still not concerned about a wave ah?