微信公众号接入天行机器人案例和方法

article/2025/10/1 18:37:35

首先使用的是天行机器人:

1、接入基本原理:

https://www.tianapi.com/apiview/47

申请完成后的结果如下

调用对应的接口的参数如下:
 

http://api.tianapi.com/txapi/robot/index?key=ae5e9a72c8d4cb1f5e096f7bb4daf1f3&question=robot

看懂这部分请参考微信公众号接入服务器开发第一部分的代码和逻辑:

链接: https://blog.csdn.net/liudaka/article/details/119640210

2、代码展示:

微信公众号的入口代码:

package com.special.weixin.weixindev.controller;import com.special.weixin.weixindev.WeixinService;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;/*** @author liuYC* @ClassName WeixinController* @Description TODO* @date 2021/8/12 9:58*/
@RestController
@RequestMapping
public class WeixinController {@ResourceWeixinService weixinService;private static final String TOKEN = "adfadfsda";@RequestMapping("wx")public void test() throws IOException {// 对于的controller方法里面,写以下代码/***   取出来对应的参数:* 参数	描述* signature	微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。* timestamp	时间戳* nonce	随机数* echostr	随机字符串*/RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;HttpServletRequest request = servletRequestAttributes.getRequest();HttpServletResponse response = servletRequestAttributes.getResponse();String signature = request.getParameter("signature");String timestamp = request.getParameter("timestamp");String nonce = request.getParameter("nonce");String echostr = request.getParameter("echostr");System.out.println(signature);System.out.println(timestamp);System.out.println(nonce);System.out.println(echostr);if (weixinService.checkSignature(signature, timestamp, nonce, TOKEN)) {System.out.println("success");request.setCharacterEncoding("utf8");response.setCharacterEncoding("utf8");
//		//处理消息和事件推送Map<String, String> requestMap = weixinService.parseRequest(request.getInputStream());System.out.println(requestMap);//准备回复的数据包通过 basemessage 等等情况String respXml = weixinService.getRespose(requestMap);System.out.println(respXml);PrintWriter out = response.getWriter();out.print(respXml);out.flush();out.close();
//            原样返回 :微信公众号服务器收到返回的数据,显示修改成功,相当于是
//            测试链接进行的代码:每次重新链接收需要这部分代码运行,链接完成后,进行注掉,开始正常的功能的测试!/* PrintWriter out = response.getWriter();out.println(echostr);out.flush();out.close();*/} else {System.out.println("fail");}System.out.println("=========== end ============");}/*@RequestMapping("wx")public void test() throws IOException {// 对于的controller方法里面,写以下代码*//***   取出来对应的参数:* 参数	描述* signature	微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。* timestamp	时间戳* nonce	随机数* echostr	随机字符串*//*RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) requestAttributes;HttpServletRequest request = servletRequestAttributes.getRequest();HttpServletResponse response = servletRequestAttributes.getResponse();String signature = request.getParameter("signature");String timestamp = request.getParameter("timestamp");String nonce = request.getParameter("nonce");String echostr = request.getParameter("echostr");System.out.println(signature);System.out.println(timestamp);System.out.println(nonce);System.out.println(echostr);if (weixinService.checkSignature(signature, timestamp, nonce, TOKEN)) {System.out.println("success");Map<String, String> requestMap = weixinService.parseRequest(request.getInputStream());System.out.println(requestMap);
//            原样返回 :微信公众号服务器受到返回的数据,显示修改成功PrintWriter out = response.getWriter();out.println(echostr);out.flush();out.close();} else {System.out.println("fail");}System.out.println("=========== end ============");}*/
/*** 拿到参数的接入的方法是:* 通过对应的参数的排序之后进行验证,把最后的一个数,赋值特定含义进行返回**/
}

我们配置的机器人聊天的方法调用部分:

  Map<String, String> requestMap = weixinService.parseRequest(request.getInputStream());

对应解析xml数据包的方法:

 /*** 解析xml数据包** @param is*/public static Map<String, String> parseRequest(InputStream is) {Map<String, String> map = new HashMap<>();SAXReader reader = new SAXReader();try {//读取输入流,获取文档对象Document document = reader.read(is);//根据文档对象获取根节点Element root = document.getRootElement();//获取根节点的所有的子节点List<Element> elements = root.elements();for (Element e : elements) {map.put(e.getName(), e.getStringValue());}} catch (DocumentException e) {e.printStackTrace();}return map;}

调用消息处理的方法(); 

/*** 用于处理所有的事件和消息的回复* @param requestMap* @return 返回的是xml数据包*/public static String getRespose(Map<String, String> requestMap) {BaseMessage msg = null;String msgType = requestMap.get("MsgType");switch (msgType) {//处理文本消息case "text":msg = dealTextMessage(requestMap);break;case "image":msg = dealImage(requestMap);break;case "voice":break;case "video":break;case "shortvideo":break;case "location":break;case "link":break;case "event":msg = dealEvent(requestMap);break;default:break;}//把消息对象处理为xml数据包if (msg != null) {return beanToXml(msg);}return null;}

 处理文本消息(注意没有的方法,注掉就可以)

因为笔者很多功能都在这个基础上完成的,没有的没有用到的注释一般不会影响结果,也可以私聊up主,获取完整的代码!

/*** 处理文本消息** @param requestMap*/private static BaseMessage dealTextMessage(Map<String, String> requestMap) {//用户发来的内容String msg = requestMap.get("Content");System.out.println("get content ----------- is " + msg);if (msg.equals("图文")) {List<Article> articles = new ArrayList<>();articles.add(new Article("这是图文消息的标题", "这是图文消息的详细介绍", "http://mmbiz.qpic.cn/mmbiz_jpg/dtRJz5K066YczqeHmWFZSPINM5evWoEvW21VZcLzAtkCjGQunCicDubN3v9JCgaibKaK0qGrZp3nXKMYgLQq3M6g/0", "http://www.baidu.com"));NewsMessage nm = new NewsMessage(requestMap, articles);return nm;}/*** 在网页授权部分需要使用:这个部分着重强调的是:* 当网页授权之后进行对应的登录,然后达到对应的目标:* 比如:进入登陆的状态页* 注意替换对应的 openid 和对应的 跳转路径:http://hzwg6t.natappfree.cc/GetUserInfo** 输入登录:* 会出现点击这里登录:* 但是结果问题::** 点击< a href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx4f32bc6b05e17a84* &redirect_uri=http://hzwg6t.natappfree.cc/GetUserInfo&response_type=code&scope=snsapi_userinfo#wechat_redirect">这里</ a>登录**/if (msg.equals("登录")) {String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx4f32bc6b05e17a84\n&redirect_uri=http://hzwg6t.natappfree.cc/GetUserInfo&response_type=code&scope=snsapi_userinfo#wechat_redirect";TextMessage tm = new TextMessage(requestMap, "点击<a href=\"" + url + "\">这里</a>登录");return tm;}//调用方法返回聊天的内容String resp = chat(msg);TextMessage tm = new TextMessage(requestMap, resp);/*** 直接文本的方法,通过微信小程序的机器人的方法* demo:公众号解锁:小薇,然后通过一些很多的方法,进行聊天获取得到对应的消息和结果!**/
//        写死回复文本消息的方法
//        TextMessage tm = new TextMessage(requestMap, "你要干哈");return tm;}

机器人调用的部分代码:

 /*** 调用天行机器人聊天* https://www.tianapi.com/apiview/47* 返回的数据:* {"code":200,"msg":"success",* "newslist":[{"reply":"亲爱的{appellation}你好,我叫{robotname},性别{robotsex},来自{hometown},正在从事{robotwork}工作。{constellation}的我,爱好{robothobby}也喜欢和人类做朋友!",* "datatype":"text"}]}** @param msg 发送的消息*/private static String chat(String msg) {String httpUrl = "http://api.tianapi.com/txapi/robot/index?key=ae5e9a72c8d4cb1f5e096f7bb4daf1f3&question=robot";System.out.println(request(httpUrl, msg));final String request = request(httpUrl, msg);
//        转为  jsonJSONObject jsonObject = JSONObject.fromObject(request);JSONObject newslist = (JSONObject) jsonObject.getJSONArray("newslist").get(0);
//       通过 key 获取对应的 value 值String reply = newslist.getString("reply");System.out.println(reply);
//        String resp = jsonObject.getJSONObject("newslist").getString("reply");return reply;}/*** @param :请求接口* @param httpArg :参数* @return 返回结果*/public static String request(String httpUrl, String httpArg) {BufferedReader reader = null;String result = null;StringBuffer sbf = new StringBuffer();httpUrl = httpUrl + "?" + httpArg;try {URL url = new URL(httpUrl);HttpURLConnection connection = (HttpURLConnection) url.openConnection();connection.setRequestMethod("GET");InputStream is = connection.getInputStream();reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));String strRead = null;while ((strRead = reader.readLine()) != null) {sbf.append(strRead);sbf.append("\r\n");}reader.close();result = sbf.toString();} catch (Exception e) {e.printStackTrace();}return result;}

全部maven的依赖文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.5.3</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.special</groupId><artifactId>weixin</artifactId><version>0.0.1-SNAPSHOT</version><name>weixin</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><!--   <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId></dependency>--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.mybatis.spring.boot</groupId><artifactId>mybatis-spring-boot-starter</artifactId><version>2.2.0</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><scope>runtime</scope></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>com.thoughtworks.xstream</groupId><artifactId>xstream</artifactId><version>1.4.10</version></dependency><!-- 百度的sdK 下载页面进入然后选择图像识别 maven包的管理--><!--     <dependency><groupId>com.baidu.aip</groupId><artifactId>java-sdk</artifactId><version>4.15.7</version></dependency>--><!--        baidu 2--><dependency><groupId>com.baidubce</groupId><artifactId>api-explorer-sdk</artifactId><version>1.0.0</version></dependency><dependency><groupId>org.dom4j</groupId><artifactId>dom4j</artifactId><version>2.0.0</version></dependency><dependency><groupId>net.sf.json-lib</groupId><artifactId>json-lib</artifactId><version>2.4</version><classifier>jdk15</classifier></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><excludes><exclude><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></exclude></excludes></configuration></plugin></plugins></build></project>

区别于文字写死回复部分,调用对应的chat()方法,这个方法其实就是接入的机器人的回复,反复的消息基本不变!

代码部分和测试结果:

 

 

自定义资料设置:

在天行机器人的接口的界面进行配置就可以了!

比如 

 

设置页:

 

 

 属性设置里面:

 

 

设置完成的结果演示:

 

 

 以及词库管理:

 

能力拓展使用等

 

 


http://chatgpt.dhexx.cn/article/vuO7POoc.shtml

相关文章

微信公众号的端口映射及服务开发

一. 开发准备 微信公众号申请---->实名认证---->服务器开发---->绑定服务器 PS: 这里有一点需要注意的就是, 微信开发必须是80端口或者443端口, 如果我们有云服务器主机一切都好办. 但是如果没有我们还有几个备选方案: 1. 花生壳 , net123 : 这两个都需要实名认证(…

[JAVA实现]微信公众号网页授权登录,java开发面试笔试题

我总结出了很多互联网公司的面试题及答案,并整理成了文档,以及各种学习的进阶学习资料,免费分享给大家。 扫描二维码或搜索下图红色VX号,加VX好友,拉你进【程序员面试学习交流群】免费领取。也欢迎各位一起在群里探讨技术。 推荐文章:Java 面试知识点解析;Mysql优化技巧…

后端操作微信公众号

一、功能说明 员工端使用微信公众号完成审批操作&#xff0c;涉及到的功能包含&#xff1a;自定义菜单、授权登录、消息 1、微信公众号一级菜单为&#xff1a;审批列表、审批中心、我的 2、员工关注公众号&#xff0c;员工第一次登录微信公众号&#xff0c;通过微信授权登录进行…

Java基于微信公众号接口实现授权登录源码及原理分析

微信公众号授权登录操作前提必须注册微信公众平台账号&#xff0c;注意的是订阅号不支持授权登录操作&#xff0c;因此对于个人开发者注册的订阅号是无法实现的&#xff0c;必须注册企业号的微信平台账号而具体注册流程就不详细介绍了&#xff0c;有什么疑问可去微信公众号平台…

微信公众号多域名回调系统1.0发布

这是一款基于ThinkPHP6.0框架的微信公众号多域名回调系统。 微信公众号后台默认只能授权2个网页域名&#xff0c;用本系统可突破这个限制&#xff0c;用同一个公众号对接无限多个网站。网站后台支持回调域名白名单的管理&#xff0c;以及登录记录的查看。 本系统还有微信access…

PHP微信扫码关注公众号并授权登录源码

PHP微信扫码登录看起来简单&#xff0c;但做起来有点麻烦&#xff0c;开发起来就会浪费很多的时间。 PHP判断是否首次关注公众号&#xff0c;扫码关注公众号获取微信用户头像、openid和省市等信息源码。 演示体验地址: https://www.skpan.cn/user/login.html 网盘下载地址:…

2023最新微信公众号无限回调系统源码/已修复BUG亲测可用

正文: 测试环境&#xff1a; Nginx 1.20.2 MySQL 5.6.50 PHP-7.2 1.创建站点 2.到根目录上传源码 3.创建数据库并导入 4.修改数据库信息 根目录/config.php 第5&#xff0c;6&#xff0c;7行 5.后台地址域名/admin 账号admin 密码123456 6.修改域名 根目录下 api.php 第…

Java微信公众号开发登录

MySQL基础开发篇 这部分的内容应该更合适那些刚入坑的朋友们或者是对于基础部分掌握不牢固的朋友,因此有一定经验的或者基础不错的可以自动跳至下一章内容阅读,这部分我仅把目录内容截图展示。 MySQL的优化以及管理维护 MySQL作为一款关系型数据库,SQL语句的优化是尤其重要的…

mysql 推送微信公众号_10分钟完成微信公众号第三方平台全网发布

背景&#xff1a;在微信公众平台配置服务器URL时&#xff0c;使用了新浪云SAE自带的二级域名&#xff0c;提交时出现一个安全风险的警告&#xff0c;网上查了下&#xff0c;许多服务平台和团队也遇到同样的问题。 经过一番研究 … 为什么会有安全风险的警告&#xff1f; 微信公…

springboot微信公众号管理系统vue内容文章文件上传jsp源码mysql

本项目为前几天收费帮学妹做的一个项目&#xff0c;Java EE JSP项目&#xff0c;在工作环境中基本使用不到&#xff0c;但是很多学校把这个当做编程入门的项目来做&#xff0c;故分享出本项目供初学者参考。 一、项目描述 这是一个基于springbootvue的微信公众号管理系统 二…

微信公众号迁移,需要做些什么

❤️ 个人主页&#xff1a;水滴技术 &#x1f680; 支持水滴&#xff1a;点赞&#x1f44d; 收藏⭐ 留言&#x1f4ac; &#x1f338; 订阅专栏&#xff1a;微信公众平台 文章目录 一、开通开发者二、设置IP白名单三、自定义菜单四、认证五、网页授权域名六、模板消息七、转换…

PHP微信公众号网页授权登录 扫码登录 获取用户基本信息

前言 现在微信登录是一个网站、APP的标配&#xff0c;所以微信授权登录是我们应该要掌握的。微信授权登录有4种方式&#xff1a; 1、通过微信开放平台2、通过认证的微信服务号3、通过认证的微信订阅号4、通过微信小程序曲线救国 今天我们就讲解的是微信服务号&#xff0c;通…

微信公众号多域名回调系统

介绍&#xff1a; 这是一款基于ThinkPHP6.0框架的微信公众号多域名回调系统。 微信公众号后台默认只能授权2个网页域名&#xff0c;用本系统可突破这个限制&#xff0c;用同一个公众号对接无限多个网站。网站后台支持回调域名白名单的管理&#xff0c;以及登录记录的查看。 本…

微信公众号授权获取用户信息及jwt登录

Java 微信公众号授权获取用户信息及jwt登录 &#xff01;&#xff01;&#xff01; 前言 前几篇文章小编分享过&#xff1a; 微信小程序授权获取用户手机号 jwt登录 (含源码)微信小程序支付 公众号支付 (含源码) 工作之余&#xff0c;分享下 “ 微信公众号授权 获取用户信…

手把手教程用Java实现微信公众号扫码登录功能

文章目录 前言一、环境准备二、使用步骤1. 使用微信工具包2. 创建数据表3. 登录页面代码逻辑4. 验证微信公众号登录 总结 前言 微信现今是我们必不可少的社交工具了&#xff0c;围绕微信这个生态实际上有很多东西可以做&#xff0c;我们经常会看到一些网站通过微信扫码进如公众…

[一维前缀和]leetcode303:区域和检索 - 数组不可变(easy)

题目&#xff1a; 题解&#xff1a; 一维前缀和&#xff0c;元素数组[0,j]的前缀和对应prefix[j1] 代码如下&#xff1a; class NumArray { private:vector<int> prefix; public://题解&#xff1a;一维前缀和NumArray(vector<int>& nums) {int nnums.size()…

前缀和矩阵前缀和

前缀和 前缀和是一种重要的预处理&#xff0c;能大大降低查询的时间复杂度。我们可以简单理解为“数列的前 n n n 项的和”。 例题 有 N N N 个的正整数放到数组 A A A 里&#xff0c;现在要求一个新的数组 B B B&#xff0c;新数组的第 i i i 个数 B [ i ] B[i] B[i]…

【算法基础】一维前缀和 + 二维前缀和

&#x1f466;个人主页&#xff1a;Weraphael ✍&#x1f3fb;作者简介&#xff1a;目前正在学习c和算法 ✈️专栏&#xff1a;【C/C】算法 &#x1f40b; 希望大家多多支持&#xff0c;咱一起进步&#xff01;&#x1f601; 如果文章有啥瑕疵 希望大佬指点一二 如果文章对你有…

前缀和与差分总结

目录 1.前缀和 2.前缀和算法的好处 3.二维前缀和 4.差分 5.一维差分 6.二维差分 1.前缀和 前缀和是指某序列的前n项和&#xff0c;可以把它理解为数学上的数列的前n项和&#xff0c;而差分可以看成前缀和的逆运算。合理的使用前缀和与差分&#xff0c;可以将某些复杂的…

一维前缀和

今天我们来讲讲一维前缀和 首先我们来介绍一下一维前缀和&#xff0c;emmm其实和数列的前n项和差不多&#xff0c;它能在 O ( 1 ) O(1) O(1) 的时间复杂度操作数组的任意子区间&#xff0c;比如我们要找出一段区间的和。 我们先预处理出一个前缀和数组&#xff0c;为了方便使…