Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand Python-Wechaty: a chat Robot Framework for IM Software

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "how to understand Python-Wechaty: a chatbot framework for IM software". The explanation in this article is simple and clear and easy to learn and understand. please follow the editor's train of thought to study and learn "how to understand Python-Wechaty: a chatbot framework for IM software".

Python-wechaty can use a small amount of code to complete a robot, it is very easy to use, OOP-based design ideas can well monitor and handle a large number of events within Wechat, such as: automatic reply messages, regularly send messages, pull people into the group, friends apply for consent and so on. In addition, there are many ready-to-use tools in the current plug-in system, such as pulling people into the group and so on. Of course, it is very easy to develop your own plug-in, you don't need a very advanced concept, you just need to be able to understand events and OOP.

The python-wechaty project originated from wechaty, and even said that the code was translated directly from it to a large extent, and then added some python features to make it more pythonic. As an entry tool for IM, we will add more Chatbot elements to it in the future so that it can become a real chat robot.

Before introducing python-wechaty, let's take a brief look at wechaty.

Wechaty

Maybe a lot of people will associate wechaty with wechat, after all, there is only a word difference in the name. This starts from the origin of wechaty. At first, this project was only used as a tool library for Wechat to carry out some simple automatic operations, such as sending messages regularly, sending group messages, accepting friend applications, and so on.

But with the gradual update of the project, wechaty has supported mainstream IM software, such as Wechat, nailing, Telegram.

This project started in 2016 and has acquired 8k star so far. It is a very stable project with a large number of users. The official introduction to it is:

A Conversational AI RPA SDK for Chatbot

So wechaty, as the entry tool of IM ChatBot, is the infrastructure component of many chat robots, and will gradually support the functions of mainstream chat robots.

The birth of python-wchaty

The bond with Wechaty was at a technology salon at the end of 2019. I was shocked to realize that a flexible robot could be developed in six lines of code. Wechat as one of our daily chat tools, if we can do some automated process to it, we can greatly reduce the workload of the tedious process, such as: pulling people into the group when holding activities, regularly reminding users to clock in, reminding my girlfriend and aunt to be here soon, and so on. And wechaty can well support all the above functions, only a few simple lines of code can be completed. After going back, we will immediately start to consult the relevant materials, and then gradually enter the wechaty community.

A very coincidental opportunity group said that it was possible to develop a go-wechaty development. At that time, I was thinking, why not have a python-wechaty, and then introduced myself to become one of the co-authors of python-wechaty. Due to not very familiar with open source software and DevOps, the initial stage encountered a lot of problems, but through the patient guidance of community leaders, has been able to complete the development and management of issue and feature. Personal experience, it is recommended that everyone have the opportunity to participate in open source projects, so that you can learn a lot of knowledge.

The simplest Bot

Using python-wechaty, you can easily develop a Bot, especially after using a plug-in system, as follows:

Two main functions are implemented in the above code:

When Bot receives a # ding signal, it immediately replies with a dong message, which is a basic ding-dong-bot.

When you receive a text statement that looks up the weather, the corresponding weather query result is returned, such as: what's the weather like today?

The above two plug-ins are built into the system, and more ready-to-use plug-ins will be added later. Of course, users can also create their own plug-ins in a very simple way.

How to develop plug-in system

Before learning how to develop a plug-in system, you can first move Plug- in`. The plug-in system supports the installation, uninstallation, custom configuration of plug-ins, and so on. As for the specific implementation form, I believe it also needs to face specific application scenarios. In the scenario of Wechaty, which is event-oriented and the interaction logic is very simple, the design and development of plug-ins is very simple.

Let's take a direct look at how the Ding Dong plug-in built into the system is implemented.

"" basic ding-dong bot for the wechaty plugin "from typing import Union from wechaty import Message, Contact, Room, FileBox from wechaty.plugin import WechatyPlugin class DingDongPlugin (WechatyPlugin):" basic ding-dong plugin "" @ property def name (self): "name of the plugin" return 'ding-dong' async def on_message (self) " Msg: Message): "" listen message event "" from_contact = msg.talker () text = msg.text () room = msg.room () if text ='# ding': conversation: Union [Room, Contact] = from_contact if room is None else room await conversation.ready () await conversation.say ('dong')

The code is simple, but it also needs to be introduced at several levels of atmosphere.

WechatyPlugin

On_ [event_name]

Init_plugin

WechatyPlugin

This class is an abstract class, and all plug-ins must inherit this base class and override the functions in it.

The name property function is abstract and must be overridden. The main purpose is to identify the name of the plug-in as the unique authentication of the plug-in.

The init_plugin initialization function can support the initialization process of the plug-in, such as initialization timer object, database delay connection object and so on.

On_ [event_name] this kind of function is mainly used to listen for different events in the system, such as on_message, on_login, on_friendship and other events. You only need to rewrite the function. Different plug-ins and different events are independent and can be well focused on development in different business scenarios.

Event_name

Python-wechaty is largely event-driven. After all, many operations are triggered based on message acceptance, and the listening of this event is its basic feature. Maybe the first feeling is to use the EventEmitter mode to listen to events, so that I can register different functions to listen for each event, and there will be different logic processing in each function. This is also a traditional event monitoring method, but it will at least bring some inconvenience to the development: the parameters of the function need to consult the documentation to know, standard functional programming.

I'm not saying that functional programming is bad, but it doesn't improve system performance much in this scenario, and python-wechaty doesn't pay too much attention to performance.

This extends the way of OOP, users can inherit Wechaty or WechatyPlugin to listen for different events, and when the function is rewritten in the regular code editor, the function parameters can be automatically filled, thus reducing the problem of looking up the parameters of the event function.

The types of listening events are: error, friendship, heartbeat, login, logout, message, ready, room_invite, room_join, room_leave, room_topic, scan.

The above has shown how to develop WechatyPlugin, and what you need to pay attention to, then I will show you in detail how to develop the most basic daily robot.

Talk about robots every day

Every day, as the name implies, send a blessing or reminder at a fixed time every day, and the specific content can be customized. There are several points to pay attention to:

There is a scheduler inside the robot, which is used to schedule the trigger of time events.

The robot can send the corresponding content to the designated people and groups.

The above functions are packaged into a plug-in and then injected into python-wechaty.

"" daily word plugin "" from datetime import datetime from apscheduler.schedulers.asyncio import AsyncIOScheduler from wechaty import Wechaty from wechaty.plugin import WechatyPlugin class DailyPlugin (WechatyPlugin): "say something everyday Like `Daily Words` "" @ property def name (self)-> str: "get the name of the plugin" return 'dayily' async def tick (self): "time tick for the plugin scheduler" room_id = get_room_id () room = self.bot.Room.load (room_id) await room.ready () Await room.say (f'i love you-> {datetime.now ()}') async def init_plugin (self Wechaty: Wechaty): "init plugin" await super () .init_plugin (wechaty) scheduler = AsyncIOScheduler () scheduler.add_job (self.tick, 'cron', hour=6, minute=16) scheduler.start ()

The plug-in is developed, and then injected into Wechaty can be run.

Async def main (): bot = Wechaty () .use (DailyPlugin () await bot.start () asyncio.run (main ())

Is it super simple? the plug-in system helps you isolate all business scenarios, making the code very easy to develop and maintain.

Python-wechaty can do more.

At present, python-wechaty has only completed the basic Chatbot entry tools, which is still a long way from the real chatbot, so there is still a lot of work to do in the future.

Thank you for your reading, the above is the content of "how to understand Python-Wechaty: chatbot framework for IM software". After the study of this article, I believe you have a deeper understanding of how to understand Python-Wechaty: chatbot framework for IM software. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report