2025年3月29日 星期六 甲辰(龙)年 月廿八 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

自动化篇 - 为闲鱼制作一个客服机器人(上)

时间:10-12来源:作者:点击数:53

1、目 标 场 景

我们都知道「闲鱼」的流量很大,除了淘宝、拼多多,很多商家和个人卖家都会在闲鱼上卖商品和各类服务。

闲鱼 App 内置的「自动回复」仅仅包含了一些固定关键字,包含默认回复、价格、包邮、发货地 4 个功能,因此,没法做到完全自定义消息回复。

图片

另外,如果你有多个闲鱼号,经常会因为消息处理不及时,导致订单丢失了。因此,对闲鱼消息进行统一管理变得非常有必要。

本篇文章的目的是利用前面文章提到的无障碍方案带大家实现这些功能。

2、实 现 代 码

首先,新建一个 Android 项目,然后在app/src/main/res/xml/ 目录下新建配置文件。

利用 packageNames 属性指定仅监听闲鱼 App 的页面事件,accessibilityEventTypes 指定监听所有的事件,其他属性使用默认的即可。

  • <?xml version="1.0" encoding="utf-8"?>
  • <accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
  • android:accessibilityEventTypes="typeAllMask"
  • android:accessibilityFeedbackType="feedbackGeneric"
  • android:accessibilityFlags="flagDefault"
  • android:canRetrieveWindowContent="true"
  • android:description="@string/app_name"
  • android:notificationTimeout="100"
  • android:packageNames="com.taobao.idlefish" />

新建 AccessibilityService 的子类,在 AndroidManifest.xml 中配置服务后,然后来处理onAccessibilityEvent() 事件方法。

  • public void onAccessibilityEvent(AccessibilityEvent event){}

无障碍服务会接受到很多种类的事件,这里我们只要处理下面 3 个事件,包含:通知栏事件、页面变换事件、页面内容变化事件。

  • # 通知栏事件
  • AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED
  • # 页面切换变化
  • AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED
  • # 页面内容变化
  • AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED

所以,首先在 onAccessibilityEvent()内需要对事件进行一次过滤,筛选出上面的 3 种事件。

  • //事件类型
  • int eventType = event.getEventType();
  • //获取包名
  • String packageName = event.getPackageName().toString();
  • //类名
  • String className = event.getClassName().toString();
  • //只筛选下面三个事件,其他事件过滤掉
  • if (eventType != AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED && eventType != AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED && eventType != AccessibilityEvent.TYPE_WINDOW_CONTENT_CHANGED)
  • {
  • Log.e("xxx","eventType:"+eventType);
  • return;
  • }

如果闲鱼应用在后台运行,这时如果收到一条闲鱼消息,会直接在通知栏展示出来,这个过程会触发「通知栏消息」事件。

一旦触发了通知栏消息事件,可以拿到通知栏的内容。

由于闲鱼消息通知文本没有实际的意义,这里通过通知对象拿到 Intent 对象,直接跳转到聊天界面。

  • /***
  •  * 处理通知栏消息
  •  * @param event
  •  */
  • private void handleNotificationEventMet(AccessibilityEvent event)
  • {
  •     if (event.getParcelableData() != null && event.getParcelableData() instanceof Notification)
  •     {
  •         Notification notification = (Notification) event.getParcelableData();
  •         if (notification == null)
  •         {
  •             return;
  •         }
  •         PendingIntent pendingIntent = notification.contentIntent;
  •         if (pendingIntent == null)
  •         {
  •             return;
  •         }
  •         try
  •         {
  •             //注意:通知栏的文字消息没有参考意义
  •             //跳转到聊天信息界面
  •             Log.e("xag""准备跳转到聊天界面");
  •             pendingIntent.send();
  •         } catch (PendingIntent.CanceledException e)
  •         {
  •             e.printStackTrace();
  •         }
  •     }
  • }

跳转到聊天界面这一操作会立即触发「页面变更」事件,这里可以先将聊天界面滑到到底部。

  • /**
  •  * 模拟下滑操作
  •  */
  • public void performScrollBackward()
  • {
  •     try
  •     {
  •         Thread.sleep(500);
  •     } catch (InterruptedException e)
  •     {
  •         e.printStackTrace();
  •     }
  •     performGlobalAction(AccessibilityNodeInfo.ACTION_SCROLL_BACKWARD);
  • }

需要获取元素的 ID 可以利用 DDMS 或者 uiautomatorviewer 两个工具。

图片

通过观察,可以发现每一条聊天记录都在一个「列表元素」中。

  • /**
  •  * 查找对应ID的View  Level>=18
  •  *
  •  * @param id id
  •  * @return View
  •  */
  • @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
  • public AccessibilityNodeInfo findViewByID(String id)
  • {
  •     AccessibilityNodeInfo accessibilityNodeInfo = getRootInActiveWindow();
  •     if (accessibilityNodeInfo == null)
  •     {
  •         return null;
  •     }
  •     List<AccessibilityNodeInfo> nodeInfoList = accessibilityNodeInfo.findAccessibilityNodeInfosByViewId(id);
  •     if (nodeInfoList != null && !nodeInfoList.isEmpty())
  •     {
  •         for (AccessibilityNodeInfo nodeInfo : nodeInfoList)
  •         {
  •             if (nodeInfo != null)
  •             {
  •                 return nodeInfo;
  •             }
  •          }
  •      }
  •      return null;
  • }
  • //聊天列表
  • AccessibilityNodeInfo chat_lv = findViewByID(Ids.id_chat_listview);

通过列表元素,拿到所有子元素,然后遍历去查找「每一条聊天内容」元素。

聊天消息又包含发送消息、接受消息、公共消息(包含一直未回复?试试语音/视频通话) 3 种消息。

图片

判断左、右图片是否存在,判断是哪种消息。如果左图标存在,就是接收到的消息;如果右图标存在,便是发送的消息;否则,就是公共消息。

  • int chat_count = chat_lv.getChildCount();
  • //注意:包含自己发送的消息、收到的消息、公共提示消息,比如:一直未回复?试试语音/视频通话
  • Log.e(TAG, "一共有:" + chat_count + "条聊天记录");
  • /所有聊天记录
  • //系统聊天信息,可以忽略
  • List<String> chat_msgs_common = new ArrayList<>();
  • //收到的信息
  • List<String> chat_msgs_from = new ArrayList<>();
  • //发出去的信息
  • List<String> chat_msgs_to = new ArrayList<>();
  • for (int i = 0; i < chat_count; i++)
  • {
  •      AccessibilityNodeInfo tempChatAccessibilityNodeInfo = chat_lv.getChild(i);
  •      //注意:通过判断是否有头像元素、昵称元素来判断是哪种聊天记录
  •      //获取头像元素【左】【发送者】
  •      AccessibilityNodeInfo headPortraitAccessibilityNodeInfoLeft = findViewByID(tempChatAccessibilityNodeInfo, Ids.id_chat_head_portrait_left);
  •      //获取头像元素【右】【接受者】
  •      AccessibilityNodeInfo headPortraitAccessibilityNodeInfoRight = findViewByID(tempChatAccessibilityNodeInfo, Ids.id_chat_head_portrait_right);
  •      //获取文字内容
  •      AccessibilityNodeInfo tempTextAccessibilityNodeInfo = findViewByID(tempChatAccessibilityNodeInfo, Ids.id_chat_text);
  •      if (null == tempTextAccessibilityNodeInfo || null == tempTextAccessibilityNodeInfo.getText())
  •      {
  •           Log.e(TAG, "索引" + i + ",聊天内容为空");
  •           continue;
  •      }
  •      String chatText = tempTextAccessibilityNodeInfo.getText().toString();
  •      Log.e(TAG, "聊天内容为:" + chatText);
  •      if (null != headPortraitAccessibilityNodeInfoLeft)
  •      {
  •           chat_msgs_from.add(0, chatText);
  •      } else if (null != headPortraitAccessibilityNodeInfoRight)
  •      {
  •           chat_msgs_to.add(0, chatText);
  •      } else
  •      {
  •           chat_msgs_common.add(0, chatText);
  •      }
  • }

回复消息」可以拿到底部的输入框,把文本传入到输入框,模拟点击右侧发送按钮就能够实现。

  • /***
  •  * 回复消息
  •  * @param event
  •  */
  • private void reply_content(AccessibilityEvent event, String content)
  • {
  •     //元素:输入框
  •     AccessibilityNodeInfo chat_edit = findViewByID(Ids.id_edittext);
  •     //把文本输入进去
  •     inputText(chat_edit, content);
  •     //元素:发送按钮
  •     AccessibilityNodeInfo chat_send = findViewByID(Ids.id_sendtext);
  •     Log.e(TAG,"准备回复的内容是:"+content);
  •     try
  •     {
  •         Thread.sleep(5000);
  •     } catch (InterruptedException e)
  •     {
  •         e.printStackTrace();
  •     }
  •     //模拟点击发送按钮
  •     performViewClick(chat_send);
  • }

根据收到的消息数目判断是否是「第一次收到的消息」。

如果是第一次收到消息,就可以返回一些引导语,告诉客户可以通过回复固定的内容返回对应的消息;否则拿到最新的一条消息,回复自定义的内容。

ps:这部分内容可以完全自定义处理。

  • //定义一段固定的回复内容
  • public static String reply_first = "让我开心的是,可以在这里遇见有趣的事物,可以遇见您。\n有什么可以帮到您的呢?\n回复【11】获取商品信息\n回复【22】获取发货信息";
  • //11:商品信息
  • public static String reply_11 = "亲,商品还有货\n现在可以直接拍下\n等店主看到了会第一时间发货";
  • //22:发货信息
  • public static String reply_22 = "亲,我们是包邮的!\n需要邮寄快递可以给我们留言";
  • //other:其他
  • public static String reply_other = "亲,信息收到了!\n主人会第一时间给你答复,稍等哈~";
  • // 初次聊天就发送默认的信息
  • if (chat_msgs_from.size() == 1 && chat_msgs_to.size() == 0)
  • {
  •      //输入之后,返回,退出输入框
  •      Log.e(TAG, "第一次收到信息,回复默认准备的内容");
  •      reply_content(event, Constants.reply_first);
  • else if (chat_msgs_from.size() > 0)
  • {
  •      //第一条文本内容
  •      String first_msg = chat_msgs_from.get(0);
  •      if ("11".equals(first_msg))
  •      {
  •           reply_content(event, Constants.reply_11);
  •      } else if ("22".equals(first_msg))
  •      {
  •           reply_content(event, Constants.reply_22);
  •      } else
  •      {
  •           reply_content(event, Constants.reply_other);
  •      }
  • else
  • {
  •      Log.e(TAG, "对方没有应答,不处理");
  • }

消息回复完成后,需要模拟点击返回键,直到页面回到应用的主界面。

  • /**
  •  * 模拟返回操作
  •  */
  • public void performBackClick()
  • {
  •     try
  •     {
  •         Thread.sleep(500);
  •     } catch (InterruptedException e)
  •     {
  •         e.printStackTrace();
  •     }
  •     while (!AppUtils.judgeIsMainPage(getRootInActiveWindow()))
  •     {
  •         Log.e("xag","现在不是主页面,返回一次");
  •         performGlobalAction(GLOBAL_ACTION_BACK);
  •     }
  • }

当回到主界面,这时候如有收到新的消息,聊天主界面会触发「页面内容变化」事件。

图片

可以先判断消息列表是否存在「未读」的消息元素。

  • /***
  •  * 获取消息列表中有未读的消息Node
  •  * @param node
  •  * @return
  •  */
  • public static AccessibilityNodeInfo getUnreadMsgNode(AccessibilityNodeInfo node)
  • {
  •     AccessibilityNodeInfo unread_node = null;
  •     if (node == null || node.getChildCount() <= 1)
  •     {
  •         Log.e("xag""未读消息判断,node==null");
  •         return unread_node;
  •     }
  •     Log.e("xag""未读消息判断,子类个数:" + node.getChildCount());
  •     //过滤ListView的头部,包含:通知消息、互动消息、活动消息、鱼塘消息
  •     for (int i = 1; i < node.getChildCount(); i++)
  •     {
  •         AccessibilityNodeInfo temp_node = node.getChild(i);
  •         List<AccessibilityNodeInfo> unread_nodes = temp_node.findAccessibilityNodeInfosByViewId(Ids.id_main_unread_tag);
  •         if (null == unread_nodes || unread_nodes.size() == 0)
  •         {
  •             Log.e("xag""未读消息判断,索引:" + i + ",unread_nodes为空");
  •         } else
  •         {
  •             unread_node = unread_nodes.get(0);
  •             break;
  •         }
  •     }
  •     Log.e("xag""未读消息判断,unread_node==null:" + (unread_node == null));
  •     return unread_node;
  •  }

如果应用「主页面聊天列表界面」存在未读的消息,就点击进入到聊天界面,重复利用上面的逻辑就可以回复消息了。

  • //选中在消息Tab,处理聊天页面
  • if (Constants.HOME_TAB.TAB_XIAO_XI == currentTab)
  • {
  •     Log.e(TAG, "当前Tab:消息Tab");
  •     //判断新消息在哪个位置,然后点击进入
  •     AccessibilityNodeInfo main_listview_node = findViewByID(Ids.id_main_conversation_listview);
  •     //未读消息Node
  •     AccessibilityNodeInfo unread_tag_node = AppUtils.getUnreadMsgNode(main_listview_node);
  •     if (null != unread_tag_node)
  •     {
  •          Log.e(TAG, "点击进入会话");
  •          //点击进入消息列表
  •          performViewClick(unread_tag_node);
  •          //处理聊天信息
  •          handleChatMet(event);
  •      } else
  •      {
  •          Log.e(TAG, "列表中没有未读消息");
  •      }
  • }

3、结 果 结 论

经过上面的一系列操作,就能监听处理通知栏和闲鱼应用内的消息,并完全自定义处理消息。

当然,如果你有多个闲鱼需要进行消息管理,可以通过「一个主闲鱼账号 + 一个商品」作为消息中转站来接受和发送消息;对每条消息由闲鱼账号 + 聊天对象 + 商品来确定唯一性,就可以实现一个闲鱼账号管理多个闲鱼账号的聊天消息。

已经将全部源码上传:https://github.com/xingag/app_spider/tree/master/xianyu_auto

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐