Django + werobot realizes automatic reply
As everyone knows, I have a WeChat official account, and then provide a function, that is, you write the key words, I reply to your key word corresponding to the content, so today I would like to talk about how this function is achieved.
1、 Install and configure Django
Install Django
Suppose we have installed the python version. It’s not very important. I’m using it this time3.8.6This version is used on the server3.6.9Version, Django, is the latest version. This time, it mainly refers to the official documents of Django.
#Install Django
pip install django
Create Django project
#Create Django project
django-admin startproject mysite
#After the project is created, the directory structure is as follows
mysite/
manage.py
mysite/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py
#Create an app, which is not an app, but a specific and complete function
#Start app is followed by an app name. Here I mainly do wechat robot, using the werobot framework
#Therefore, the name of a wrob, we need to make sure that the app name here can not be the same as various keywords
python manage.py startapp wrob
#At this point, the directory structure is as follows
wrob/
__init__.py
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
urls.py
views.py
2、 Install werobot
WeRoBot is a WeChat official account development framework, issued by MIT protocol.
Open source address:https://github.com/offu/WeRoBot
Document address:https://werobot.readthedocs.io/zh_CN/latest/
Install werobot
pip install werobot
3、 Change the code
Finally, it’s time to change the code
1. Modification views.py
This file, in short, all functions are put here, so according to the werobot documentIntegration with other web frameworksTo change the view file.
#Import various related modules
#The first one is the database model. There will be another file to be changed later
from django.db.models import Model
# Create your views here.
#Import werobot module
from werobot import WeRoBot
#Import the database model. We'll talk about this later
from .models import share
The basic authentication information required by WeChat module can be obtained from the developer of official account.
COMPONENT_APP_ID = 'XXXXXXXXXXXXXXX'
COMPONENT_APP_SECRET = 'XXXXXXXXXXXXXXXXXXXXXX'
COMPONENT_APP_TOKEN = 'XXXXXXXXXXXX'
COMPONENT_ENCODINGAESKEY = 'XXXXXXXXXXXXXXXXXXX'
#Create a werobot object called myrobot
MyRobot = WeRoBot(token=COMPONENT_APP_TOKEN)
MyRobot.config["APP_ID"] = COMPONENT_APP_ID
MyRobot.config["APP_SECRET"] = COMPONENT_APP_SECRET
#Message decorator, if the user sends text content, the method here is executed automatically
@MyRobot.text
def echo(message):
#Get the message content. If you need to get the user's openid, you can also get it here
content = message.content
#If the text content is larger than 1 character and less than 20 characters, after all, there are too many keywords, so it should not be called a word
if 20 > len(content) >= 1:
#Convert uppercase to lowercase, that is, case insensitive
content = content.lower()
#According to the keywords to the database query data
res = share.objects.filter(key=content).values()
#Because a keyword may correspond to more than one content, the search results need to be processed
slist = []
for data in res:
temp = [
data["desc"],
data["link"],
data["secret"]
]
slist.extend(temp)
string = "\n".join(slist)
#Just return the result
return string
#This is a decorator for subscribing, that is, who subscribes will reply to such a message
@MyRobot.subscribe
def welcome(message):
Return '' thank you so much for your attention to my official account. I call the battery. I hope I can make some contribution to your progress. '
#This is a message sent by unsubscribe. What can we do...
#You can do some functions here, such as adding it to the blacklist. If someone cancels, it won't let him subscribe again
@MyRobot.unsubscribe
def goodbye(message):
return 'nothing'
2. Modification model.py Files, creating databases
Django provides a set of database processing framework, which can process database in an object-oriented wayORMSo, we just need to describe the database in the class.
from django.db import models
# Create your models here.
#Create class
#Here, the class name is related to the table name in the database
#Generally speaking, it's the app name_ The class name is the name of the class table
class share(models.Model):
#Four columns of data are created here, including keywords, descriptions, links, and keys corresponding to links
key = models.CharField(max_length=50)
desc = models.CharField(max_length=200)
link = models.CharField(max_length=100)
secret = models.CharField(max_length=100)
#This is the class description information
#When you use print to output objects, you just need to define them__ str__ (self) method, then the data returned from this method will be printed
#Here we return the description information in the database
def __str__(self):
return self.desc
Create database
The Django framework uses SQLite database by default. The database name and location can be in themysiteOfsettingsI changed it into“werobot.db”。
To be fair, we just created a class and didn’t create a real database table. We need a series of operations to create a database. Here, we create an administrator account. Django brings an administrator awesome.
First, you need to modify the settings file
#Modify MySite/ settings.py
#In installed_ Add 'in apps' wrob.apps.WrobConfig ',
#This wrob.apps.WrobConfig You can't write it blindly. Wrob is
INSTALLED_APPS = [
'wrob.apps.WrobConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
Execute some orders
#Execute this command to have Django generate some databases and create related files
#After execution, a file 0001 is generated in the wrob / migrations / folder_ initial.py
python manage.py makemigrations wrob
#Execute the 0001 of wrob app_ Initial file to generate some SQL statements
#There is still no database created here
python manage.py sqlmigrate wrob 0001
#Create a data table. After this command is executed, the corresponding data table is actually created
python manage.py migrate
Create administrator user
#Execute the command, follow the prompt, add the transfer name next to the password
python manage.py createsuperuser
3. Modification admin.py file
This file is relatively simple to modify. It is just one line. After the above work is finished, the database information we added can not be displayed in the administrator interface. We need to register the table in the administrator interface and display it.
from django.contrib import admin
# Register your models here.
from .models import share
admin.site.register(share)
4. Modification urls.py
This file is in charge of the URL parsing task, that is, how does each URL correspond to a different view? Depending on it, in principle, there should be one in each app urls.py File, then in the general one urls.py It’s OK to refer to include in the file, but here, because there is only one routing relationship, so don’t be so complicated. Modify mys directly ite/ urls.py
from django.contrib import admin
from django.urls import path
#Import make in werobot_ View this thing
from werobot.contrib.django import make_view
#Import the myrobot created in the view of the app we created
from wrob.views import MyRobot
urlpatterns = [
path('admin/', admin.site.urls),
#Robot: if the second half of the URL is a URL, it will be parsed by myrobot, which cannot be accessed through the browser
#You need to fill in the settings in the wechat developer's background
path('robot/', make_view(MyRobot))
]