Table of Contents
1. Effect display
1️⃣Register WeChat applet process and start cloud development
Home WeChat Applet Mini Program Development Let's take a look at how to create the 'Intelligent Spring Festival Couplet” applet for the Spring Festival in this article!

Let's take a look at how to create the 'Intelligent Spring Festival Couplet” applet for the Spring Festival in this article!

Jan 17, 2022 am 10:21 AM
Applets Spring Festival

2022 has officially arrived. There are only ten days left before the Chinese Lunar New Year. Spring Festival couplets are indispensable for the Spring Festival. The following article will look at how to implement the "Smart Spring Festival Couplets" applet for the Spring Festival. I hope it will be helpful to everyone. Helps!

Let's take a look at how to create the 'Intelligent Spring Festival Couplet” applet for the Spring Festival in this article!

The New Year is approaching, let’s make a smart Spring Festival couplet applet to cheer everyone up! I wish all digging friends a happy new year in 2022 in advance! New Year is coming soon!

1. Effect display

Random Spring Couplets

Lets take a look at how to create the Intelligent Spring Festival Couplet” applet for the Spring Festival in this article!

##Specified last name

Lets take a look at how to create the Intelligent Spring Festival Couplet” applet for the Spring Festival in this article!

Experience addressScan the QR code below on WeChat or WeChat search treasure program

Lets take a look at how to create the Intelligent Spring Festival Couplet” applet for the Spring Festival in this article!

##Source code address

Gitee: https://gitee.com/nanfangzhe/wechat_demo

2. Preparation work

Master the language

:WeChat Mini Program LanguageTechnical Points
: ①WeChat Mini Program Cloud DevelopmentBaidu AI Intelligent Creation Platform - Intelligent Writing of Spring Festival Couplets3. Game Process and Rules

Game Process

: You can click random Spring Festival Couplets and Specify the last name to get the desired Spring Festival couplets~Explanation of terms
: ①Random Spring Festival couplets, randomly display a pair of Spring Festival couplets. ②Specify surname: Enter your surname to generate a couplet. 4. Deployment steps

1️⃣Register WeChat applet process and start cloud development

2️⃣Register Baidu AI platform——》Console——》Create natural language processing application—— 》Baidu authentication and authorization, get the token——》 Then take the token to the Smart Spring Festival Couplets API interface

3️⃣What needs to be modified: APPID (the APPID entered when opening it with the WeChat developer tool), Baidu token (in the couplet folder index.js file), cloud development environment env (in app.js file)

5. Logic explanation and core code

1 Logic explanation of random Spring Festival coupletsSince the smart Spring Festival couplets API interface provided by Baidu requires parameters to be passed, we can prepare a small data collection in advance, pass the value when clicked, and then return the required couplets. Therefore, we have collected some words and phrases used to welcome the Spring Festival and celebrate the New Year.

var RANDOM_TEXT_LIST = ["虎", "虎年", "迎春", "春节", "过年", "年兽", "过春节", "初一", "年初", "红红火火", "红火", "开心", "开开心心", "健康", "健健康康", "长寿", "平安", "平平安安", "家庭", "家庭和睦", "和睦", "子子孙孙", "勤劳", "福气", "福", "致富", "富裕", "富", "合家欢喜", "合家", "欢喜", "喜庆", "喜", "囍", "生意兴隆", "恭喜发财", "大富大贵", "富贵", "富裕", "丰年", "子孙满堂", "心欢喜", "人间喜", "灯火", "灯笼", "烟花", "爆竹"]
Copy after login

Lets take a look at how to create the Intelligent Spring Festival Couplet” applet for the Spring Festival in this article!

2 Explanation of the logic of specifying the surnameThis is similar to the logic of random Spring Festival couplets, only However, the user is required to enter the last name, but the API interface used is a bit awkward. If only one character of the last name is entered, the output content is a bit unreasonable. So the solution here is to splice and add the word "家". For example, if you enter the surname: Liu, the passed value is the Liu family; if the input is Zhang, it is the Zhang family...

  ok: function () {
    var text = this.data.textV
    if (!text || text.length > 4) {
      wx.showToast({
        title: '姓氏暂不支持超过4个字哦!',
        icon: 'none'
      })
      return;
    }
    this.getCoupletByTxt(text + "家") // 智能写对联
    this.setData({
      showModal: false
    })
  },
Copy after login

3 Core CodeAfter the previous logical explanation, you may know that the core code is a publicly called method. (Bingo~ You guessed it)

Method called by random Spring Festival couplets

// 随机春联的调用方法
  bindGetRandomCouplet() {
    let that = this
    var num = parseInt(Math.random() * (MAX_NUM - MIN_NUM + 1) + MIN_NUM, 10); // 生成[n,m]的随机整数
    that.getCoupletByTxt(RANDOM_TEXT_LIST[num]) // 智能写对联
  },
Copy after login

Method called by specified last name

// 随机春联的调用方法
  ok: function () {
    var text = this.data.textV
    if (!text || text.length > 4) {
      wx.showToast({
        title: '姓氏暂不支持超过4个字哦!',
        icon: 'none'
      })
      return;
    }
    this.getCoupletByTxt(text + "家") // 智能写对联
    this.setData({
      showModal: false
    })
  },
Copy after login

Public methods for calling smart Spring Festival couplets

  // 智能写对联(API接口来源,参考百度-语言处理技术-智能创作平台-智能写对联:https://ai.baidu.com/ai-doc/NLP/Ok53wb6dh)
  getCoupletByTxt(text) {
    let that = this
    console.log(text) // 字符串(限5字符数以内)即作诗的主题
    if (!text || text.length > 5) {
      wx.showToast({
        title: '主题限制5个字以内哦!',
        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: '调用次数用完啦,点击右下角小电话,联系开发者充次钱充次数啦!',
            icon: 'none',
            duration: 3000,
          })
        } else {
          wx.showToast({
            title: '当前对联不太行,请重试!',
            icon: 'none'
          })
        }
        return;
      }
      that.setData({
        couplets: res.result.couplets
      })
    })
  },
Copy after login

Public methods for calling cloud functions

// 注:先看readme.md文件
// 对联生成请求
const cloud = require('wx-server-sdk')
var rp = require('request-promise')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const DB = cloud.database()
// 天行数据的KEY
var TIAN_XING_KEY = ''
// 天行数据的接口API
var TIAN_XING_API = 'http://api.tianapi.com/duilian/index'
// 百度Token
var BAI_DU_ACCESS_TOKEN = '' // 这里需要自行去申请咯~
// 百度接口api
var BAI_DU_API = [
  "https://aip.baidubce.com/rpc/2.0/creation/v1/poem", // 智能写诗
  "https://aip.baidubce.com/rpc/2.0/creation/v1/couplets" // 智能写对联
]


// 云函数入口函数
exports.main = async (event, context) => {
  var { action, text } = event
  var data = {}
  switch (action) {
    case 'getPoemByTxt': {
      data.text = text
      if (text == "")
        return {
          message: '缺少参数text'
        }
      // 智能写诗(API接口来源,参考百度-语言处理技术-智能创作平台-智能写诗: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必要参数,写诗的主题内容
          }, 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: '缺少参数text'
        }
      // 智能写对联(API接口来源,参考百度-语言处理技术-智能创作平台-智能写对联: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必要参数,对联的主题内容
          }, function (error, response, body) {
            if (error) {
              return reject(error);
            }
            return resolve(JSON.parse(body));
          })
        } catch (e) {
          return reject(e)
        }
      });
    }
    case 'getRandomCouplet': {
      // 随机一对对联(无横批)(API接口来源,天行数据: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("响应" + body)
          resolve(body)
          if (!error && response.statusCode == 200) {
            try { } catch (e) {
              reject()
            }
          }
        })
      })
    }
    default: {
      return {
        message: 'action错误!'
      }
    }
  }

}
Copy after login
(There are some redundant codes in the middle, but they are not redundant. It’s just not sorted out, and this small program is still being developed...)

Full code address: https://gitee.com/nanfangzhe/wechat_demo

【 Related learning recommendations:
小program development tutorial

The above is the detailed content of Let's take a look at how to create the 'Intelligent Spring Festival Couplet” applet for the Spring Festival in this article!. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Develop WeChat applet using Python Develop WeChat applet using Python Jun 17, 2023 pm 06:34 PM

With the popularity of mobile Internet technology and smartphones, WeChat has become an indispensable application in people's lives. WeChat mini programs allow people to directly use mini programs to solve some simple needs without downloading and installing applications. This article will introduce how to use Python to develop WeChat applet. 1. Preparation Before using Python to develop WeChat applet, you need to install the relevant Python library. It is recommended to use the two libraries wxpy and itchat here. wxpy is a WeChat machine

'Onmyoji''s new Spring Festival version event 'Whale Eternal Song' is about to start. Participate in the 'Luck Delivery' to draw New Year koi! 'Onmyoji''s new Spring Festival version event 'Whale Eternal Song' is about to start. Participate in the 'Luck Delivery' to draw New Year koi! Feb 05, 2024 pm 05:50 PM

[Spring Festival version of the event "Whale Song"] The tide stagnated and the whale's cry disappeared. Thousands of miles of ice cover the eternal sea, and the newly born Mermaid Queen sets out again with an unswerving heart of protection. [Event Time] Phase 1: After maintenance on February 7th - From 23:59 on February 16th, gameplay such as Sharman Song, Ice Sea Stranger, Haiyuan Camp, Haiyue House, Qianxi Gifts and other games will be launched. Phase 2: February 17 From 10:00 on Sunday to 23:59 on February 20th, the second stage of gameplay [Activity Gameplay] - Shark Song - will be opened. During the first stage, 3 exploration story chapters will be gradually unlocked as time progresses. Onmyoji will explore the Sea of ​​Eternal Life with Qian Ji, complete plots, battles, adventures and other events to advance the story and obtain rewards. Adventure gameplay includes: Aurora Whirlpool and Iron Rat Game. Available to

Implement card flipping effects in WeChat mini programs Implement card flipping effects in WeChat mini programs Nov 21, 2023 am 10:55 AM

Implementing card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: <!--index.wxml-->&l

Alipay launched the 'Chinese Character Picking-Rare Characters' mini program to collect and supplement the rare character library Alipay launched the 'Chinese Character Picking-Rare Characters' mini program to collect and supplement the rare character library Oct 31, 2023 pm 09:25 PM

According to news from this site on October 31, on May 27 this year, Ant Group announced the launch of the "Chinese Character Picking Project", and recently ushered in new progress: Alipay launched the "Chinese Character Picking-Uncommon Characters" mini program to collect collections from the society Rare characters supplement the rare character library and provide different input experiences for rare characters to help improve the rare character input method in Alipay. Currently, users can enter the "Uncommon Characters" applet by searching for keywords such as "Chinese character pick-up" and "rare characters". In the mini program, users can submit pictures of rare characters that have not been recognized and entered by the system. After confirmation, Alipay engineers will make additional entries into the font library. This website noticed that users can also experience the latest word-splitting input method in the mini program. This input method is designed for rare words with unclear pronunciation. User dismantling

Inventory of new Genshin Impact characters in 2023: Which of the 15 characters have you obtained? Which one is your favorite? Inventory of new Genshin Impact characters in 2023: Which of the 15 characters have you obtained? Which one is your favorite? Jan 30, 2024 pm 07:12 PM

I have to lament that time flies so fast. Today I will give you a summary of the new characters that will appear in Genshin Impact in 2023. Without further ado, let’s get straight to the point. 1. Yaoyao online date: January 18, 2023 Yaoyao is a four-star grass nanny, grandma Ping’s disciple, and junior sister Xiangling. She has a good amount of milk and a certain ability to get rid of the grass, so she has a place in the bloom team. 2. Elhaysen launch date: January 18, 2023, grass-type one-handed sword short-axis main C. After it went online, its strength was gradually recognized by the public. Zero Life is the complete body. In the Xumi version, it is the absolute T0 main C. It is still one of the most cost-effective main Cs at present. 3. Desiya’s launch date: March 1, 2023. Desiya is the second resident fire five-star sword.

How uniapp achieves rapid conversion between mini programs and H5 How uniapp achieves rapid conversion between mini programs and H5 Oct 20, 2023 pm 02:12 PM

How uniapp can achieve rapid conversion between mini programs and H5 requires specific code examples. In recent years, with the development of the mobile Internet and the popularity of smartphones, mini programs and H5 have become indispensable application forms. As a cross-platform development framework, uniapp can quickly realize the conversion between small programs and H5 based on a set of codes, greatly improving development efficiency. This article will introduce how uniapp can achieve rapid conversion between mini programs and H5, and give specific code examples. 1. Introduction to uniapp unia

Tutorial on writing a simple chat program in Python Tutorial on writing a simple chat program in Python May 08, 2023 pm 06:37 PM

Implementation idea: Establishing the server side of thread, so as to process the various functions of the chat room. The establishment of the x02 client is much simpler than the server. The function of the client is only to send and receive messages, and to enter specific characters according to specific rules. To achieve the use of different functions, therefore, on the client side, you only need to use two threads, one is dedicated to receiving messages, and the other is dedicated to sending messages. As for why not use one, that is because, only

How to get membership in WeChat mini program How to get membership in WeChat mini program May 07, 2024 am 10:24 AM

1. Open the WeChat mini program and enter the corresponding mini program page. 2. Find the member-related entrance on the mini program page. Usually the member entrance is in the bottom navigation bar or personal center. 3. Click the membership portal to enter the membership application page. 4. On the membership application page, fill in relevant information, such as mobile phone number, name, etc. After completing the information, submit the application. 5. The mini program will review the membership application. After passing the review, the user can become a member of the WeChat mini program. 6. As a member, users will enjoy more membership rights, such as points, coupons, member-exclusive activities, etc.

See all articles