Traditional Culture Encyclopedia - Weather inquiry - Timing message push based on WeChat (can coax girlfriend), smart chat, personal assistant.

Timing message push based on WeChat (can coax girlfriend), smart chat, personal assistant.

-

Topic: "Timing message push based on WeChat (can fool your girlfriend), smart chat, personal assistant"

Author: jasonlovesharon

E-mail: 54027901@163.com.

Label:

? - nodejs

? -wechat

? -wechat-puppet -padplus

-

# # Preface

-since 20 17 wechat web API was restricted, a large number of bots such as itchat have stopped eating and have been looking for suitable substitutes.

-At present, most windows WeChat clients use hook-based dll injection to control WeChat, which has certain title risk. It can only be used in a fixed version, and it is difficult to deploy it on a linux server, which means that we can only turn it on all the time-WeChat supports various protocols such as IPAD, MAC and so on. You don't need to call the WEB API, and it can be deployed on the server to meet all my needs. [Project Address] (/WeChat/WeChat)

-I read the official document ([official introduction of Token] (/juzibot/welcome/wiki/everything-about-wechat)), and found that I need to apply for Token. I need to pay for the python version of Token, but I haven't learned typescript, and I want to give up a little. I browsed the example of Ding Dong -bot, which seems understandable and can be explored while learning. (ps: Later, I came across another article, which can be used to convert token to realize python version of WeChat, but it has been basically written in TS. If you want to use other languages such as Python, you can refer to the Official Document (/wechaty/wechaty/issues/1985). )

# # has this function.

### 1. Keyword trigger function

1. 1 The keywords "self-introduction", "self-introduction" and "who are you" trigger self-introduction.

1.2 Weather query triggered by place name+weather

### 2. Intelligent chat function

2. 1 Direct chat outside the group

2.2 All members in the group have the chat permission "@bot" to chat.

2.3 Will not reply to messages from @ other group members.

# # Implementation process

Empty talk is cheap, show your code.

### 1. main program

`` Typed manuscript

Import {WeChat, message, UrlLink, log,} from "WeChat"

Import {PuppetPadplus} from "WeChat-Puppet -padplus"

Import {EventLogger, QRCodeTerminal} from "we chat-plugin-contrib"

Import {wechat WeixinOpenAI,} from "wechat-wechat -openai"

From' Import {setSchedule,}/plan/index'

Import {getDay, formatDate,} from'. /utils/index '

Import {getOne, getTXweather, getSweetWord,} from'. /superagent/index '

//Create WeChat Daily Speech Timing Task

Asynchronous function initDay() {

? Console.log (`Daily call task has been set');

? setSchedule('0 40 0 * * * ',async()= & gt; {

Console.log ('Your lovely little assistant has already started working!' )

Let the log message

Let contact =

? (waiting for bot. contact . find({ name:' Jason ' })| |

? (awaitbot.contact.find ({alias:' boss'})//Get the contact you want to send.

Let one = await getOne() // Get a sentence every day.

Let weather = Await gettxWeather ()//Get weather information.

Let today = await format date (newdate ())//Get today's date.

Let memorial day = getday ('2009/08/07')//Get the number of days of Memorial Day.

Let sweetWord = await getSweetWord ()

Let str = ` $ {today} \ The first $ {memorial day} that we love each other \ n \ nThe energetic day begins. Be happy. Oh _ \ n \ Today's weather \n${weather.weatherTips}\n${

? weather today's weather

} \ nOne sentence a day:

Try {

? logMsg = str

? Waiting delay (2000)

? Await contact.say(str) // Send a message

} catch (e) {

? Log message = email

}

Console.log (log message)

? })

}

Const padplusToken =' Your own token'

const puppet = new PuppetPadplus({

? token: padplusToken,

})

const bot = new Wechaty({

? Name: "Assistant Jason",

? Puppet,

})

Bot.use (event recorder ())

bot . use(QR code terminal({ small:true }))

//Reference and configure plug-ins in WeChat.

Const openAIToken =' Your own robot token'//You need to apply on the WeChat dialogue open platform, and you can see it at the bottom of the page by clicking on the robot settings binding application.

Const openaiencodingaskey =' Your own encoding askey'//Apply for an open platform for WeChat dialogue, click Robot Settings, bind the application, and you can see it at the bottom of the page.

const preAnswerHook = async(Message:Message)= & gt; {

? Const is common material = await process commonmaterial (message)

? if (isCommonMaterial) {

Returns false

? }

}

/**

* get the BOSS contact card. When the robot can't find the answer to the question, push the boss card.

*/

const get boss = async()= & gt; {

Const contact = bot.contact.load ('Boss WeChat ID')

Wait for contact.sync ()

Return contact

? }

const noAnswerHook = async(Message:Message)= & gt; {

const room = message.room()

const from = message.from()

If (! Room) {

? const boss = await getBoss()

? Waiting for news. Say ("I won't answer your question, you can contact my boss")

? Waiting for news. Say (boss)

? Return;

}

const members = await room . member all()

const bossInRoom = members . find(m = & gt; M.id ===' Boss WeChat id')

if (bossInRoom) {

? Await room.say`${bossInRoom}, ${from} I don't know the question, please help me answer it. `

} Otherwise {

? const boss = await getBoss()

? Await room.say`${from}, I won't answer your question, you can contact my boss `.

? Waiting room. Say (boss)

}

? }

/**

* Through WeChat -weixin-openai, you can quickly enter the WeChat dialogue platform.

*/

Bot.use (WeChat weixinopainai ({

token: openAIToken,

encodingAESKey:openAIEncodingAESKey,

NoAnswerHook,//Push the set answer when the robot can't answer.

PreAnswerHook,//Judge whether it is a keyword. If it is a keyword, do not access the WeChat open platform to trigger a keyword answer.

? }))

const processCommonMaterial = async(Message:Message)= & gt; {

const room = message.room()

// const from = message.from()

const mention self = await message . mention self()

const text = message.text()

Let's introduce Jason. He has many hobbies and makes friends with heroes all over the world. He won the world for nine days and caught a turtle of five oceans. As the saying goes, pilots who can't bake are not good outdoor people, aquarium lovers who can't play music are not good cooks, and extreme lovers who can't draw are not good programmers. This is my boss Jason, hehehe ~'

If (room! = = null & amp& amp remind yourself) {

? If (/jason| your boss | your boss/ Test (Text) (

Waiting room. Say (Introduction)

Await room.say (new UrlLink({

Caption:' Outdoor underclass &; Fight, fight, fight, read thousands of books, take Wan Li Road, and learn to eat, drink and be merry',

thumbnailUrl:“”,

Title: "Jason"

URL:“/s? _ _ biz = MzkxODE3MjAyNQ = = & ampmid = 100000 1 & amp; idx= 1。 sn = d05de 320 c 6 FBE 6 c 9 f 9 149 a 09 a 4 da 8 1ec & amp; chksm = 4 1b 439 1776 C3 b 00 1c 143 AC 284 c 58 AC 8 b 08 de 4 1d 95 cab 682 aa 07022 e 32096567 f 5780 D5 be # rd ',

? }))

Return true

? } else if (/ outdoor lowlife/. Test (Text) (

Await room.say (new UrlLink({

Caption:' Outdoor underclass &; Fight, fight, fight, read thousands of books, take Wan Li Road, and learn to eat, drink and be merry',

thumbnailUrl:“”,

Title: "Jason"

URL:“/s? _ _ biz = MzkxODE3MjAyNQ = = & ampmid = 100000 1 & amp; idx= 1。 sn = d05de 320 c 6 FBE 6 c 9 f 9 149 a 09 a 4 da 8 1ec & amp; chksm = 4 1b 439 1776 C3 b 00 1c 143 AC 284 c 58 AC 8 b 08 de 4 1d 95 cab 682 aa 07022 e 32096567 f 5780 D5 be # rd ',

? }))

Return true

? }

}

Returns false

}

//Login

Asynchronous function onLogin (user)

? Console.log (` cute little assistant ${user} has logged in `)

? //Create a scheduled task after logging in

? Wait for initDay ()

}

Bot.on ('login', onLogin)

bot.start()

? . Then (() = & gtlog.info('StarterBot',' StarterBot has started'))

? . catch(e = & gt; log.error('StarterBot ',e))

```

### 2. Create the planned timing function

`` Typed manuscript

Import {Plan} from Node Plan

//Date parameter

//See /package/node-schedule for other rules.

//Rule parameter interpretation * stands for wildcard.

//

// *? *? *? *? *? *

// ┬ ┬ ┬ ┬ ┬ ┬

// │ │ │ │ │? |

//│ │ │ What day is it (0-7) (0 or 7 is a grandson)

//│ │ └--month (1-12)

//│ │ └ ————————————————————— (1-3 1)

//│ └--------hours (0-23)

//│ └---------one minute (0-59)

//└---------Second (0-59, optional)

//Triggered every 30 seconds: "30 * * * *"

//

//every hour 1 min 30 seconds trigger: "301* *"

//

//Triggered at1:00am1:30+01* *'

//

//Every month 1 day, 1 point, 1 minute 30 seconds trigger:' 30 1 1 * *'

//

//Every week 1 1 min for 30 seconds, triggering:' 30 1 1 * * 1'

Function set Schedule (date, callback)

? Schedule.scheduleJob (date, callback)

}

Export function setSchedule ()

```

### 3. Create several functions, grab the daily statements of a website, and extract the messages obtained through the API.

`` Typed manuscript

Import * as cheerio from "cheerio"

Import * as superagent from "superagent"

Const ONE = '/' // ONE's website.

Const TXHOST = '/txapi/' // skyhost

Function request (url, method, parameter, data, cookies

? Return a new commitment (Function (Resolve, Reject) (

Superagent (method, url)

? . Query (Parameter)

? . To send (data)

? . set('Content-Type ',' application/x-www-form-urlencoded ')

? . End (function (err, response) {

If (error) {

Rejection (error)

}

Solve (respond)

? })

})

}

Asynchronous function getOne() {

? //Get a sentence every day

? Try {

Let res = await req (I, "GET")

let $ = cheerio.load(res.text)

let todayOneList = $(' # carousel-one。 Carousel-inside. Project')

let todayOne = $(todayOneList[0])

? . Find ('. FP-one-cita’)

? . Text ()

? . replace(/(^\s*)|(\s*$)/g,”)

Return today

? } catch (err) {

Console.log ('error ',err)

Return error

? }

}

Asynchronous function getTXweather() {

? //Get the weather in the sky

? Let url = TXHOST+'Apocalypse/'

? Try {

let res = await req(url,' GET ',{

? Key:' your own KEY',//You need to apply in Tianxing by yourself, address /signup.html? source=47428428 1

? City: "Arlington"

})

let content = JSON.parse(res.text)

if (content.code === 200) {

? let today info = content . news list[0]

? Let obj = {

Weather tip: todayInfo.tips,

Today's weather: `Today in Arlington is $ {todayinfo.weather} \ nTemperature: $ {todayinfo.lower}/$ {todayinfo.higher}

\n${todayInfo.wind} Wind: $ {todayinfo.windspeed} \ nUltraviolet Index: $ {todayinfo.uv _ index} \ nHumidity.

$ { today info . weather } `

? };

? Console.log ('weather obtained successfully', obj)

? Return object

} Otherwise {

? Console.log ('Unable to get interface', content.code)

}

? } catch (err) {

Console.log ('Unable to get interface', error)

? }

}

Asynchronous function getSweetWord() {

? //Get a simple love story

? Let url = TXHOST+'saylove/'

? Try {

let res = await req(url,' GET ',{ key: '' })

let content = JSON.parse(res.text)

if (content.code === 200) {

? let sweet = content.newslist[0]。 content

? let str = sweet.replace('\r\n ',' & lt' br & gt')

? Returns a string

} Otherwise {

? Console.log ('Unable to get interface', content.msg)

}

? } catch (err) {

Console.log ('Unable to get interface', error)

? }

}

Export {getOne, getTXweather, getSweetWord,}

```

# # # Calculate how many days are left before a certain day (birthday, wedding anniversary, etc.). )

`` Typed manuscript

Function getDay(date) {

? Var date2 = new date ()

? Var date 1 = new date (date)

? var iDays = parseInt(

math . ABS(date 2 . gettime()-date 1 . gettime())/ 1000/60/60/24

? )

? Return to working day

}

Function format Date (

? Var tempDate = new date (date)

? var year = tempDate.getFullYear()

? var month = tempdate . getmonth()+ 1

? var day = tempDate.getDate()

? var hour = tempDate.getHours()

? var min = tempDate.getMinutes()

? var second = tempDate.getSeconds()

? var week = tempDate.getDay()

? var str = ' '

? if (week === 0) {

Sunday

? } else if (week === 1) {

"Monday"

? } else if (week === 2) {

Tuesday

? } else if (week === 3) {

Wednesday

? } else if (week === 4) {

"Thursday"

? } else if (week === 5) {

Friday

? } else if (week === 6) {

Saturday

? }

? If (hour <10) {

Hours = '0'+hours

? }

? if(min & lt; 10) {

min = '0' + min

? }

? If (second & lt 10) {

Seconds = '0'+seconds

? }

? Returns the year+'-'+month+'-'+day+'hour+':'+minute+'+string.

}

Export {getDay, formatDate}

```

! [Keyword Trigger Message] (/jasonlovesharon/my_bot)), because I am not familiar with Typescript, many functions are realized by drawing on the wheels of many great gods, but I am familiar with Python. I'm going to use Python to realize the above functions and further expand more interesting functions.