PK creative Spring Festival, I am participating in the “Spring Festival creative submission contest”, please see: Spring Festival creative submission Contest
New Year is coming, do an intelligent Spring Festival couplet small program to help everyone! I wish you all the friends in advance, the 2022 New Year falls fast! Spring falls fast!
1. Effect display
Random Spring Festival couplets Specify the name Experience the address
Wechat scan the following TWO-DIMENSIONAL code or wechat search treasure program The source address
Gitee:Wechat small program multiple projects _ south
Second, preparation
Technical points: ① wechat small program cloud development ② Baidu AI intelligent creation platform – intelligent writing Spring Festival couplets
Iii. Game process and rules
Game flow: you can click on the random Spring Festival couplets and specify the surname to obtain the desired Spring Festival couplets ~ noun explanation: ① random Spring Festival couplets, randomly display a pair of Spring Festival couplets. ② Specify last name: Enter your last name to generate couplets.
Iv. Deployment steps
1️ wechat small program process, open cloud development 2️ discount baidu AI platform — “console –” creation of natural language processing application — “Baidu authentication and authorization, get token –” And then take token to intelligent Spring Festival API interface 3️ Modifications needed: APPID (APPID entered when opened with wechat developer tool), Baidu Token (index.js file in Couplet folder), cloud development environment Env (app.js file)
Logic explanation and core code
1. Logical explanation of random Spring Festival couplets
Since the intelligent Spring Festival couplet API provided by Baidu needs to be transmitted, we can prepare a small data set in advance, and then return the required couplet by clicking on it. Therefore, it is part of the collection of Spring Festival words, words.
var RANDOM_TEXT_LIST = ["Tiger"."The year of the tiger"."Chun"."Spring Festival"."New Year"."Nian"."Celebrating the Spring Festival"."New moon"."Early"."Red hot"."Red"."Happy"."Have fun."."Health"."Fit and healthy"."Long life"."Peace"."Safe and sound"."Family"."Family harmony."."Harmony"."Children and grandchildren"."Hard"."Blessing"."福"."Get rich"."The rich"."The rich"."Happy family."."Family"."Joy"."Festival"."Happy"."Various"."Business is booming"."Kung Hei Fat Choi"."Big rich big rich."."Rich"."The rich"."Harvest"."Full of offspring."."Happy heart"."Joy on earth."."Lights"."Lantern"."Fireworks"."Fireworks"]
Copy the code
2 Logical explanation of the specified surname
This and random Spring Festival couplets are similar logic, but the user input surname, but the API interface is a little pull, input only a surname of the word, the output content is a little unreasonable. So in this processing method is to splice and add a “home” in the word, such as the input of the surname: Liu, the value is Liu home; The input is Zhang, is the Zhangs…
ok: function () {
var text = this.data.textV
if(! text || text.length >4) {
wx.showToast({
title: 'Surnames cannot be more than 4 characters. '.icon: 'none'
})
return;
}
this.getCoupletByTxt(text + "Home") // Write couplets intelligently
this.setData({
showModal: false})},Copy the code
3 Core Code
As you probably know from the logic explained above, the core code is the method that is called publicly. (Bingo~ you guessed it) random Spring Festival couplets call method
// Random Spring Festival couplets call method
bindGetRandomCouplet() {
let that = this
var num = parseInt(Math.random() * (MAX_NUM - MIN_NUM + 1) + MIN_NUM, 10); // Generate a random integer [n,m]
that.getCoupletByTxt(RANDOM_TEXT_LIST[num]) // Write couplets intelligently
},
Copy the code
Specifies the method called by the last name
// Random Spring Festival couplets call method
ok: function () {
var text = this.data.textV
if(! text || text.length >4) {
wx.showToast({
title: 'Surnames cannot be more than 4 characters. '.icon: 'none'
})
return;
}
this.getCoupletByTxt(text + "Home") // Write couplets intelligently
this.setData({
showModal: false})},Copy the code
Call the public method of the smart Spring Festival couplet
// Intelligent writing couplets (API interface source, refer to Baidu - language processing technology - intelligent creation platform - intelligent writing couplets: https://ai.baidu.com/ai-doc/NLP/Ok53wb6dh)
getCoupletByTxt(text) {
let that = this
console.log(text) // The string (5 characters or less) is the subject of the poem
if(! text || text.length >5) {
wx.showToast({
title: 'Subject limit is 5 words! '.icon: 'none'
})
return;
}
wx.cloud.callFunction({
name: 'couplet'.data: {
action: 'getCoupletByTxt',
text
}
}).then(res= > {
console.log(res)
if (res.result.error_code) {
if ("17".indexOf(res.result.error_code) ! = -1) {
wx.showToast({
title: 'Call times used up, click on the lower right corner of the small phone, contact the developer charge times! '.icon: 'none'.duration: 3000})},else {
wx.showToast({
title: 'The current couplet is not very good, please try again! '.icon: 'none'})}return;
}
that.setData({
couplets: res.result.couplets
})
})
},
Copy the code
Public method for cloud function calls
// Note: read the readme.md file first
// the couplet generates the request
const cloud = require('wx-server-sdk')
var rp = require('request-promise')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
})
const DB = cloud.database()
// The KEY of the row data
var TIAN_XING_KEY = ' '
// Day data interface API
var TIAN_XING_API = 'http://api.tianapi.com/duilian/index'
/ / baidu Token
var BAI_DU_ACCESS_TOKEN = ' ' // You need to apply for it yourself
// Baidu interface API
var BAI_DU_API = [
"https://aip.baidubce.com/rpc/2.0/creation/v1/poem".// Write poems intelligently
"https://aip.baidubce.com/rpc/2.0/creation/v1/couplets" // Write couplets intelligently
]
// Cloud function entry function
exports.main = async (event, context) => {
var { action, text } = event
var data = {}
switch (action) {
case 'getPoemByTxt': {
data.text = text
if (text == "")
return {
message: 'Missing argument text'
}
// Intelligent poem writing (API interface source, reference Baidu - language processing technology - intelligent writing platform - intelligent poem writing: https://ai.baidu.com/ai-doc/NLP/ak53wc3o3)
return new Promise((resolve, reject) = > {
try {
rp({
method: 'POST'.headers: {
"content-type": "application/json",},body: JSON.stringify(data),
url: BAI_DU_API[0] + '? access_token=' + BAI_DU_ACCESS_TOKEN, // text Specifies the necessary parameters for writing poems
}, function (error, response, body) {
if (error) {
return reject(error);
}
return resolve(JSON.parse(body)); })}catch (e) {
return reject(e)
}
});
}
case 'getCoupletByTxt': {
data.text = text
if (text == "")
return {
message: 'Missing argument text'
}
// Intelligent writing couplets (API interface source, refer to Baidu - language processing technology - intelligent creation platform - intelligent writing couplets: https://ai.baidu.com/ai-doc/NLP/Ok53wb6dh)
return new Promise((resolve, reject) = > {
try {
rp({
method: 'POST'.headers: {
"content-type": "application/json",},body: JSON.stringify(data),
url: BAI_DU_API[1] + '? access_token=' + BAI_DU_ACCESS_TOKEN, // text Required parameters, the subject content of the couplet
}, function (error, response, body) {
if (error) {
return reject(error);
}
return resolve(JSON.parse(body)); })}catch (e) {
return reject(e)
}
});
}
case 'getRandomCouplet': {
/ / a pair of couplets random (no horizontal batch) (API interface source, day line data: https://www.tianapi.com/console/)
return new Promise((resolve, reject) = > {
rp({
url: TIAN_XING_API + '? key=' + TIAN_XING_KEY,
method: "POST".json: true,},function (error, response, body) {
console.log("Response" + body)
resolve(body)
if(! error && response.statusCode ==200) {
try{}catch (e) {
reject()
}
}
})
})
}
default: {
return {
message: 'action error! '}}}}Copy the code
(Some redundant code in the middle, not redundant, just unorganized, and continue to develop this small program…)
Full code address: gitee.com/nanfangzhe/…
Article tail
If you have different views, you are welcome to leave a message or comment below the article. If it is helpful to you, or you agree with it, welcome to give a small thumbs-up, support ~ I am a southerner, a love of computer and love the motherland. (The content of this article is only for learning reference, if there is infringement, I am very sorry, please contact the author immediately delete.)