非网页版微信机器人-Wechaty
微信机器人有很多,比如之前的 itchat 是基于网页版实现的,然而现在微信网页版被封的厉害,许多账号都用不了了。找来找去发现 Wechaty 有基于 ipad 协议的实现,下面对其进行简单介绍。
本项目使用wechaty-puppet-padplus,点此查看官方文档。
使用方法
报时机器人,每逢整点在群里发送报时信息。具体报时内容可以由群友设置。
基本功能:
每逢整点自动报时
发送“报时”立刻报时
发送“修改模板 新模板”可以修改报时内容,其中
\h
表示当前小时,\m
表示当前分钟,\s
表示当前秒。类似于其他语言的转义字符,\\
表示字符\
。例如现在是11:45:14
,\\\h:\mm
会被解析为\11:45m
。
为了重点展示框架,本项目没有添加过多复杂的功能,后续可以在此基础上实现群友报时情况统计、排行榜等涉及文件操作的功能。
环境
CentOS 7
开始
照着官方文档初始化一些东西就可以。
首先检查 Node
版本
node --version
如果是 v10.16.0
以下,需要先更新 Node
。
创建文件夹,我的文件夹名字叫 wechatbot
:
mkdir wechatbot
cd wechatbot
npm init -y
npm install ts-node typescript -g
tsc --init --target ES6
touch bot.ts
上面我们新建了文件 bot.ts
,这个文件就是主程序了,我们把官方示例代码放到这个文件里,不要忘了把 token
和 name
改成你自己的:
// bot.ts
import { Contact, Message, Wechaty } from 'wechaty'
import { ScanStatus } from 'wechaty-puppet'
import { PuppetPadplus } from 'wechaty-puppet-padplus'
import QrcodeTerminal from 'qrcode-terminal'
import { FileBox } from 'wechaty'const token = your_tokenconst puppet = new PuppetPadplus({token,
})const name = your_nameconst bot = new Wechaty({name,puppet, // generate xxxx.memory-card.json and save login data for the next login
})var baoshi: RegExp = new RegExp('报时.*') // 正则表达式,群名以“报时”开头//报时器,整点触发
async function hourReport() {//当前时间var time = new Date();//小时var hours = time.getHours();//分钟var mins = time.getMinutes();//秒钟var secs = time.getSeconds();//下一次报时间隔var next = ((60 - mins) * 60 - secs) * 1000;//设置下次启动时间setTimeout(hourReport, next);//整点报时,因为第一次进来mins可能不为0所以要判断const room = await bot.Room.find({topic:baoshi})var request = require('request')request.get({url:'http://127.0.0.1:5000/clock'}, function (error, response, body) { if (error) {console.log('Error :', error)return}console.log(' Body :', body)if(body.length > 0){room?.say(body)}})
}bot.on('scan', (qrcode, status) => {if (status === ScanStatus.Waiting) {QrcodeTerminal.generate(qrcode, {small: true})}})
bot.on('login', async (user: Contact) => {console.log(`login success, user: ${user}`)//启动报时器hourReport();})
bot.on('message', async (msg: Message) => {console.log(`msg : ${msg}`)var room = msg.room()var topic = ''if(room){topic = await room.topic()}var contact = msg.from()//直接推给python处理,我们获得回复内容var request = require('request')var formData = {text: msg.text(),roomtopic: topic,date: JSON.stringify(msg.date()),contactid: contact?.id,}try{// 所有的东西都推到后端用python处理request.post({url:'http://127.0.0.1:5000/message', formData: formData}, function (error, response, body) { if (error) {console.log('Error :', error)return}console.log(' Body :', body)var response = JSON.parse(body)if(body.length > 0){const type: string = response['type']if(type=='image'){const path: string = response['content']const filebox: FileBox = FileBox.fromFile(path)if(room){console.log('准备发啦!')room.say(filebox)}else{contact?.say(filebox)}}else if(type=='text'){const text: string = response['content']if(room){room.say(text)}else{contact?.say(text)}}else{//什么也不做} }})}catch(e){console.log(e)}})
安装 wechaty
和 qrcode-terminal
npm install wechaty@latest
npm install wechaty-puppet-padplus@latest
npm install qrcode-terminal
这一步我遇到了点问题,装着装着就卡住不动了,因为某些不可描述的原因国外的网站连接质量不好,我们需要使用代理:
npm config set registry https://registry.npm.taobao.org
然后安装就好了。
后端代码
# backend.py
from flask import Flask
from flask import request
import json
import datetimeapp = Flask(__name__)# 全局变量
name = '报时'
model = r'淦!已经\h点\m分了!你今天学习了吗?'# 获取报时内容
def gettext():response_text = ''status = Falsefor c in model:if not status:if c == chr(92):status = Trueelse:response_text += c else:status = Falseif c == chr(92):response_text += celif c == 'h':response_text += str(datetime.datetime.now().hour)elif c == 'm':response_text += str(datetime.datetime.now().minute)elif c == 's':response_text += str(datetime.datetime.now().second)else:passreturn response_textdef handle(data):global modeltext = data['text']if len(text) >= 6 and text[:4] == '修改模板':model = text[5:]return json.dumps({'type': 'text', 'content': '修改大成功!现在的模板是:\n'+model})elif text == '报时':return json.dumps({'type': 'text', 'content': gettext()})else:return json.dumps({'type': 'null'})@app.route('/message', methods=['GET', 'POST'])
def message():if request.method == 'POST':data = request.formprint(data)roomtopic = data['roomtopic']if roomtopic: # 是群if len(roomtopic) >= 2 and roomtopic[0:2] == name:return handle(data) return json.dumps({'type':'null'})# 返回当前报时内容
@app.route('/clock', methods=['GET'])
def clock():return gettext()if __name__ == '__main__':app.run()
启动服务(可以使用 screen 同时运行两个程序):
ts-node bot.ts
python3 backend.py
大功告成!
非网页版微信机器人-Wechaty相关推荐
- Ubuntu16.04下安装类似于windows下微信软件,非网页版微信(内附安装包和详细安装指令)
一.下载安装包 安装包下载地址: 链接:https://pan.baidu.com/s/1M8i6mdC952exhyFoLp84rg 提取码:nt5q 然后解压压缩包,获得文件夹如下: 然后进入文件 ...
- 网页版微信聊天机器人源码调试遇到的几个问题
最近加了一个源码阅读的群,其中这周的源码是网页版微信机器人 github代码链接 https://github.com/Urinx/WeixinBot 在这个源码的调试过程中遇到以下问题,不过仍然还没 ...
- 用WeRoBot和Python编写一个不使用网页版微信且能够回复消息微信群聊机器人
要用 WeRoBot 和 Python 编写一个不使用网页版微信且能够回复消息的微信群聊机器人,您需要以下步骤: 安装 WeRoBot 和相关依赖: pipinstall werobot 创建一个 P ...
- 用WeRoBot和Python编写一个不使用网页版微信的微信群聊机器人
要使用 WeRoBot 和 Python 编写一个不使用网页版微信的微信群聊机器人,您需要执行以下步骤: 安装 WeRoBot 库: pipinstall WeRoBot 创建一个 Python 脚本 ...
- 微信机器人 wechaty 针对个人微信对接chatterbot +django+drf 实现 自动回复 接入自己api接口
之前发表过chatterbot 的自定义api本人的流程 但是有粉丝或游客私信我 怎样对接自己个人微信 现在统一回复下 自己的心得流程 实现等 在写代码之前我先表述下 之前个人微信接口 使用itcha ...
- ubuntu安装微信,解决网页版微信不能登陆问题
1.下载附件deb包wine-wechat_1.0-windows2.8.6_all.deb 2.sudo dpkg -i wine-wechat_1.0-windows2.8.6_all.deb 1 ...
- python爬虫+网页版微信实时获取消息程序
项目需求: 目的是24小时爬取各种软件的讯息并且以一种统一的方式集中发送给自己. 实现方法: 利用python的requests库以及wxpy库,前者用来爬取网页,后者用来将爬到的内容发送给自己. 程 ...
- 微信协议网页版微信协议解析
最近在做个微信机器人,所以研究了网页版的微信协议及相关接口,在这里简单总结一下. 从表面上看,对于网页版微信我们的使用流程是这样的: 很简单,只有四步,但如果细化到内里细节的话,上面这简单四步的背后其 ...
- jquery 背景特效实现_html5实现的仿网页版微信聊天界面效果源码
码农那点事儿 关注我们,一起学习进步 这是一款基于html5实现的仿网页版微信聊天界面效果源码,可实现微信网页版聊天界面效果,在编辑框编辑文字之后按Ctrl+Enter键即可提交文字到聊天对话框上.整 ...
最新文章
- echarts树图节点垂直间距_矿棉板吊顶标准工艺节点
- 作业九 ——报告及总结
- 微软出品 Kubernetes 最新学习指南 v3.0
- 比特币、以太坊、瑞波币、万融链和区块链
- 太惨了!卖一个月不如小米卖一天,手机一哥仍不甘心
- 一文看懂深度学习新王者「AutoML」:是什么、怎么用、未来如何发展?
- C语言基础专题 - 通过案例历学 - 共用体
- csv 逗号数量不一样_lexin_common系列之CSV
- [科技部与你共成长] 几道语言题
- zen brush 2 android,Zen Brush 2 才不仅仅是个练字 App 那么简单
- 如何在word中的图片上画圈标注_教你如何轻松在图片上画圈圈、画箭头、写注释...
- 新手入门吉他买什么好?十年吉他老司机教你如何远离烧火棍,附上靠谱吉他品牌推荐!
- 虚拟机批量克隆工具_如何使用老毛桃winpe进行克隆磁盘?
- AutoCAD 快捷键
- Android 闹钟app 课程设计
- 从B站审核变慢现象,聊聊谛听安全内容社区产品的内容风控
- JAVA基础个人总结,不喜勿喷
- 2021年压力容器作业R2移动式压力容器充装证考试题库
- html5仿蚂蚁森林效果代码,vue仿支付宝蚂蚁森林水滴
- cd /www/wwwroot/admin.aalajyh.cn/public php index.php api/user/loginTest