diff --git a/docs/introduction/use-padlocal-protocol.md b/docs/introduction/use-padlocal-protocol.md index f4aa35d2..3eec86e7 100644 --- a/docs/introduction/use-padlocal-protocol.md +++ b/docs/introduction/use-padlocal-protocol.md @@ -14,7 +14,7 @@ ### 2.2 PadLocal -当然也有一定的解决方案:商家可以换对应的IP池,通过不定期的购买新的IP来减少消息扎堆的问题。这种方法虽然是缓解了这个问题,可是羊毛出在羊身上,维护成本打了,`TOKEN`肯定就贵了,对于双方来说都不太好。于是社区就基于Pad协议提出了`Local`的概念:[wechaty-puppet-padlocal](https://github.com/wechaty/wechaty-puppet-padlocal). +当然也有一定的解决方案:商家可以换对应的IP池,通过不定期的购买新的IP来减少消息扎堆的问题。这种方法虽然是缓解了这个问题,可是羊毛出在羊身上,维护成本大了,`TOKEN`肯定就贵了,对于双方来说都不太好。于是社区就基于Pad协议提出了`Local`的概念:[wechaty-puppet-padlocal](https://github.com/wechaty/wechaty-puppet-padlocal). 要使用此协议,必须在本地开启一个Gateway来发送和接受官方服务器发送过来的消息,这样消息的来源和发送目的地都是由开发者自己决定,就类似于电脑的客户端接受和发送消息,这样就极大程度上减小了账号风险系数,这也是协议中`Local`的原因。 diff --git a/docs/references/contact-self.md b/docs/references/contact-self.md index 59827315..a630c065 100644 --- a/docs/references/contact-self.md +++ b/docs/references/contact-self.md @@ -2,120 +2,176 @@ title: ContactSelf --- -Bot itself will be encapsulated as a ContactSelf. This class is extends Contact. +机器人本身被封装为一个`ContactSelf`类。 这个类继承自联系人`Contact`类。 ## ContactSelf -Bot itself will be encapsulated as a ContactSelf. +机器人本身被封装为一个`ContactSelf`类。 -> Tips: this class is extends Contact +> 提示: 这个类继承自联系人`Contact`类。 -**Kind**: global class +**类型**: 公共类 -* [ContactSelf](contact-self.md#contactself) - * [intance](contact-self.md#contactself) - * [contactSelf.avatar\(\[file\]\) ⇒ `Promise `](contact-self.md#contactselfavatarfile-⇒-promise) - * [contactSelf.qrcode\(\) ⇒ `Promise `](contact-self.md#contactselfqrcode-⇒-promise) - * [contactSelf.signature\(signature\) ⇒ `Promise `](contact-self.md#contactselfsignaturesignature) - * [contactSelf.name\(\[name\]\) ⇒ `Promise | string`](contact-self.md#contactselfname-⇒-promisestring) +* [contact_self](contact-self.md#contactself) + * [实例方法](contact-self.md#contactself) + * [contact_self.avatar\(\[file\]\) ⇒ `Optinal[FileBox]`](contact-self.md#contactselfavatarfile-⇒-promise) + * [contact_self.qrcode\(\) ⇒ `str`](contact-self.md#contactselfqrcode-⇒-str) + * [contact_self.signature\(signature\) ⇒ `None`](contact-self.md#contactselfsignaturesignature) + * [contact_self.name\(\) ⇒ `str`](contact-self.md#contactselfname-⇒-str) + * [contact_self.set_name\(\[name\]\) ⇒ `None`](contact-self.md#contactselfset_name-⇒-str) -### contactSelf.avatar\(\[file\]\) ⇒ `Promise ` +### async def avatar(self, file: `Optional[FileBox]` = None) ⇒ `Optinal[FileBox]` -GET / SET bot avatar +获取/设置 机器人所使用账号的头像 -**Kind**: instance method of [`ContactSelf`](contact-self.md#ContactSelf) +**类型**: [`ContactSelf`](contact-self.md#ContactSelf)类的实例方法 -| Param | Type | +| 参数 | 类型 | | :--- | :--- | | \[file\] | `FileBox` | -**Example** _\( GET the avatar for bot, return {Promise<FileBox>}\)_ +**示例** -```javascript -// Save avatar to local file like `1-name.jpg` +_\( 获取机器人账号的头像, 返回`FileBox`类型的对象\)_ -bot.on('login', async user => { - console.log(`user ${user} login`) - const file = await user.avatar() - const name = file.name - await file.toFile(name, true) - console.log(`Save bot avatar: ${user.name()} with avatar file: ${name}`) -}) +```python +# 保存头像到本地文件, 类似 `1-name.jpg`的格式 +import asyncio +from wechaty import Wechaty, FileBox, Contact + +class MyBot(Wechaty): + + async def on_login(self, contact: Contact) -> None: + print(f"用户{contact}登入") + file: FileBox = await contact.avatar() + name = file.name + await file.to_file(name, True) + print(f"保存头像: {contact.name} 和头像文件: {name}") + + +asyncio.run(MyBot().start()) ``` -**Example** _\(SET the avatar for a bot\)_ +**示例** + +_\(设置机器人账号的头像\)_ + +```python +import asyncio +from wechaty import Wechaty, FileBox, Contact + +class MyBot(Wechaty): + + async def on_login(self, contact: Contact) -> None: + print(f"用户{contact}登入") + file_box: FileBox = FileBox.from_url('https://wechaty.github.io/wechaty/images/bot-qr-code.png') + await contact.avatar(file_box) + print(f"更改账号头像成功") + -```javascript -import { FileBox } from 'file-box' -bot.on('login', user => { - console.log(`user ${user} login`) - const fileBox = FileBox.fromUrl('https://wechaty.github.io/wechaty/images/bot-qr-code.png') - await user.avatar(fileBox) - console.log(`Change bot avatar successfully!`) -}) +asyncio.run(MyBot().start()) ``` -### contactSelf.qrcode\(\) ⇒ `Promise ` +### async def qr_code(self) ⇒ `str` -Get bot qrcode +获取机器人账号的二维码链接 -**Kind**: instance method of [`ContactSelf`](contact-self.md#ContactSelf) +**类型**: [`ContactSelf`](contact-self.md#ContactSelf)的实例方法 -#### Example +#### 示例 -```javascript -import { generate } from 'qrcode-terminal' -bot.on('login', async user => { - console.log(`user ${user} login`) - const qrcode = await user.qrcode() - console.log(`Following is the bot qrcode!`) - generate(qrcode, { small: true }) -}) +```python +import asyncio +from wechaty import Wechaty +from wechaty.user import ContactSelf +from wechaty.utils.qrcode_terminal import qr_terminal_str + +class MyBot(Wechaty): + + async def on_login(self, contact: ContactSelf) -> None: + print(f"用户{contact}登入") + qr_code = await contact.qr_code() # 获取二维码信息 + print(qr_terminal_str(qr_code)) # 在控制台打印二维码 + +asyncio.run(MyBot().start()) ``` -### contactSelf.signature\(signature\) ⇒ `Promise ` +### async def signature(self, signature: `str`) ⇒ `None` -Change bot signature +更改机器人账号的签名 -**Kind**: instance method of [`ContactSelf`](contact-self.md#ContactSelf) +**类型**: [`ContactSelf`](contact-self.md#ContactSelf)的实例方法 -| Param | Description | -| :--- | :--- | -| signature | The new signature that the bot will change to | - -#### Example - -```javascript -bot.on('login', async user => { - console.log(`user ${user} login`) - try { - await user.signature(`Signature changed by wechaty on ${new Date()}`) - } catch (e) { - console.error('change signature failed', e) - } -}) +| 参数 | 类型 | 描述 | +| :--- | :--- | :--- | +| signature | `str` | 您想要改变的新的签名 | + +#### 示例 + +```python +import sys +import asyncio +from datetime import datetime +from wechaty import Wechaty +from wechaty.user import ContactSelf + +class MyBot(Wechaty): + + async def on_login(self, contact: ContactSelf) -> None: + print(f"用户{contact}登入") + try: + await contact.signature(f"签名被Wechaty更改于{datetime.now()}") + except Exception as e: + print("更改签名失败", e, file=sys.stderr) + +asyncio.run(MyBot().start()) ``` -### contactSelf.name\(\[name\]\) ⇒ `Promise | string` +### `@property` def name(self) ⇒ `str` -Get or change bot name. +获取机器人的名字 -**Kind**: instance method of [`ContactSelf`](contact-self.md#contactself) +**类型**: [`ContactSelf`](contact-self.md#contactself)的实例方法 -| Param | Description | -| :--- | :--- | -| \[name\] | The new alias that the bot will change to | - -#### Example - -```javascript -bot.on('login', async user => { - console.log(`user ${user} login`) - const oldName = user.name() // get bot name - try { - await user.name(`${oldName}-${new Date().getTime()}`) // change bot name - } catch (e) { - console.error('change name failed', e) - } -}) + +#### 示例 \(更改名字与获取名字\) + +```python +import sys +import asyncio +from datetime import datetime +from wechaty import Wechaty +from wechaty.user import ContactSelf + + +class MyBot(Wechaty): + + async def on_login(self, contact: ContactSelf) -> None: + old_name = contact.name # 获取Bot账号的名字 + print(old_name) + +asyncio.run(MyBot().start()) +``` + +### async def set_name(self, name: `str`) -> `None`: + +获取机器人的名字 + +**类型**: [`ContactSelf`](contact-self.md#contactself)的实例方法 + +```python +import sys +import asyncio +from datetime import datetime +from wechaty import Wechaty +from wechaty.user import ContactSelf + + +class MyBot(Wechaty): + + async def on_login(self, contact: ContactSelf) -> None: + old_name = contact.name # 获取Bot账号的名字 + contact.set_name(f"{old_name}{datetime.now()}") # 更改Bot账号的名字 + +asyncio.run(MyBot().start()) ``` diff --git a/docs/references/contact.md b/docs/references/contact.md index 45591570..0c1f297a 100644 --- a/docs/references/contact.md +++ b/docs/references/contact.md @@ -2,316 +2,410 @@ title: Contact --- -All wechat contacts(friend) will be encapsulated as a Contact. - ## Classes -[Contact](contact.md#Contact) - -All wechat contacts\(friend\) will be encapsulated as a Contact. [Examples/Contact-Bot](https://github.com/wechaty/wechaty/blob/1523c5e02be46ebe2cc172a744b2fbe53351540e/examples/contact-bot.ts) - -## Typedefs - -[ContactQueryFilter](contact.md#ContactQueryFilter) +所有的微信联系人(朋友)都会被封装成一个`Contact`联系人对象。 -The way to search Contact ## Contact -All wechat contacts\(friend\) will be encapsulated as a Contact. [Examples/Contact-Bot](https://github.com/wechaty/wechaty/blob/1523c5e02be46ebe2cc172a744b2fbe53351540e/examples/contact-bot.ts) +所有的微信联系人(朋友)都会被封装成一个`Contact`联系人对象。示例: +[示例/Contact-Bot](https://github.com/wechaty/python-wechaty-getting-started/blob/master/examples/basic/contact-bot.py) -**Kind**: global class **Properties** +**类型**: 全局**属性** -| Name | Type | Description | +| **属性名** | 类型 | **描述** | | :--- | :--- | :--- | -| id | `string` | Get Contact id. This function is depending on the Puppet Implementation, see [puppet-compatible-table](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) | +| id | `str` | 获取联系人对象的id. 此函数取决于Puppet的实现, 详见 [Puppet兼容表](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) | * [Contact](contact.md#Contact) - * _instance_ - * [.say\(textOrContactOrFileOrUrl\)](contact.md#Contact+say) ⇒ `Promise ` - * [.name\(\)](contact.md#Contact+name) ⇒ `string` - * [.alias\(newAlias\)](contact.md#Contact+alias) ⇒ `Promise ` - * [.friend\(\)](contact.md#Contact+friend) ⇒ `boolean` \| `null` - * [.type\(\)](contact.md#Contact+type) ⇒ `ContactType.Unknown` \| `ContactType.Personal` \| `ContactType.Official` - * [.gender\(\)](contact.md#Contact+gender) ⇒ `ContactGender.Unknown` \| `ContactGender.Male` \| `ContactGender.Female` - * [.province\(\)](contact.md#Contact+province) ⇒ `string` \| `null` - * [.city\(\)](contact.md#Contact+city) ⇒ `string` \| `null` - * [.avatar\(\)](contact.md#Contact+avatar) ⇒ `Promise ` - * [.sync\(\)](contact.md#Contact+sync) ⇒ `Promise ` - * [.self\(\)](contact.md#Contact+self) ⇒ `boolean` - * _static_ - * [.find\(query\)](contact.md#Contact.find) ⇒ `Promise ` - * [.findAll\(\[queryArg\]\)](contact.md#Contact.findAll) ⇒ `Promise ` - -### contact.say\(textOrContactOrFileOrUrlLinkOrMiniProgram\) ⇒ `Promise ` - -> Tips: This function is depending on the Puppet Implementation, see [puppet-compatible-table](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) - -**Kind**: instance method of [`Contact`](contact.md#Contact) - -| Param | Type | Description | + * _实例方法_ + * [.say\(textOrContactOrFileOrUrl\)](contact.md#Contact+say) ⇒ `Optional[Message]` + * [.name](contact.md#Contact+name)⇒ `str` + * [.alias\(new\_alias\)](contact.md#Contact+alias) ⇒ `Union[None, str]` + * [.is_friend\(\)](contact.md#Contact+friend) ⇒ `bool` + * [.is_offical\(\)](contact.md#Contact+offical) ⇒ `bool` + * [.is_personal\(\)](contact.md#Contact+personal) ⇒ `bool` + * [.type\(\)](contact.md#Contact+type) ⇒ `ContactType.CONTACT_TYPE_UNSPECIFIED` \| `ContactType.CONTACT_TYPE_PERSONAL` \| `ContactType.CONTACT_TYPE_OFFICIAL` \| `ContactType.CONTACT_TYPE_CORPORATION` + * [.gender\(\)](contact.md#Contact+gender) ⇒ `ContactGender.CONTACT_GENDER_UNSPECIFIED` \| `ContactGender.CONTACT_GENDER_MALE` \| `ContactGender.CONTACT_GENDER_FEMALE` + * [.province\(\)](contact.md#Contact+province) ⇒ `Optional[str]` + * [.city\(\)](contact.md#Contact+city) ⇒ `Optional[str]` + * [.avatar\(\)](contact.md#Contact+avatar) ⇒ `FileBox` + * [.sync\(\)](contact.md#Contact+sync) ⇒ `None` + * [.is_self\(\)](contact.md#Contact+self) ⇒ `bool` + * _静态方法_ + * [.find\(query\)](contact.md#Contact.find) ⇒ `Optional[Contact]` + * [.find_all\(\[queryArg\]\)](contact.md#Contact.findAll) ⇒ `List[Contact]` + +### async def say\(self, message: `Union[str, Message, FileBox, Contact, UrlLink]`\) ⇒ `Optional[Message]` + +> 提示: 此功能取决于Puppet的实现, 详见 [Puppet兼容表](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) + +**类型**: [`Contact`](contact.md#Contact)的实例方法 + +| 参数 | 类型 | 描述 | | :--- | :--- | :--- | -| textOrContactOrFileOrUrlLinkOrMiniProgram | `string` \| [`Contact`](contact.md#Contact) \| `FileBox` \| `UrlLink` \| `MiniProgram` | send text, Contact, file or UrlLink to contact. You can use [FileBox](https://www.npmjs.com/package/file-box) to send file | +| 文本, 联系人对象, 文件对象, 链接或者小程序对象 | `str` \| [`Contact`](contact.md#Contact) \| `FileBox` \| `UrlLink` \| `MiniProgram` | 发送文本、联系人名片、文件或链接到目标联系人。 您可以使用 [FileBox](https://github.com/wechaty/python-wechaty-puppet/tree/master/src/wechaty_puppet/file_box) 类来发送文件。 | -#### Example +#### 示例 -```javascript -import { FileBox } from 'file-box' -import { - Wechaty, - UrlLink, - MiniProgram, -} from 'wechaty' +```python +import asyncio +from wechaty import Wechaty, Contact, FileBox, UrlLink +from wechaty_puppet import ContactQueryFilter -const bot = new Wechaty() -await bot.start() -const contact = await bot.Contact.find({name: 'lijiarui'}) // change 'lijiarui' to any of your contact name in wechat -// 1. send text to contact +class MyBot(Wechaty): -await contact.say('welcome to wechaty!') + async def on_login(self, contact: Contact) -> None: + contact = await self.Contact.find( + ContactQueryFilter(name="lijiarui")) # 把`lijiarui`更改为您在微信中的任意联系人的姓名 -// 2. send media file to contact + # 1. 发送文字到联系人 + await contact.say('welcome to wechaty!') -import { FileBox } from 'file-box' -const fileBox1 = FileBox.fromUrl('https://wechaty.github.io/wechaty/images/bot-qr-code.png') -const fileBox2 = FileBox.fromFile('/tmp/text.txt') -await contact.say(fileBox1) -await contact.say(fileBox2) + # 2. 发送媒体文件到联系人 + fileBox1 = FileBox.from_url('https://wechaty.github.io/wechaty/images/bot-qr-code.png', "bot-qr-code.png") + fileBox2 = FileBox.from_file('text.txt', "text.txt") + await contact.say(fileBox1) + await contact.say(fileBox2) -// 3. send contact card to contact + # 3. 发送名片到联系人 + contactCard = self.Contact.load('lijiarui') # 把`lijiarui`更改为您在微信中的任意联系人的姓名 + await contact.say(contactCard) -const contactCard = bot.Contact.load('contactId') -await contact.say(contactCard) + # 4. 发送链接到联系人 -// 4. send url link to contact + urlLink = UrlLink.create( + description='WeChat Bot SDK for Individual Account, Powered by TypeScript, Docker, and Love', + thumbnail_url='https://avatars0.githubusercontent.com/u/25162437?s=200&v=4', + title='Welcome to Wechaty', + url='https://github.com/wechaty/wechaty', + ) + await contact.say(urlLink) -const urlLink = new UrlLink({ - description : 'WeChat Bot SDK for Individual Account, Powered by TypeScript, Docker, and Love', - thumbnailUrl: 'https://avatars0.githubusercontent.com/u/25162437?s=200&v=4', - title : 'Welcome to Wechaty', - url : 'https://github.com/wechaty/wechaty', -}) -await contact.say(urlLink) + # 5. 发送小程序 (暂时只有`wechaty-puppet-macpro`支持该服务) -// 5. send MiniProgram (only supported by `wechaty-puppet-macpro`) + miniProgram = self.MiniProgram.create_from_json({ + "appid": 'gh_0aa444a25adc', + "title": '我正在使用Authing认证身份,你也来试试吧', + "pagePath": 'routes/explore.html', + "description": '身份管家', + "thumbUrl": '30590201000452305002010002041092541302033d0af802040b30feb602045df0c2c5042b777875706c6f61645f31373533353339353230344063686174726f6f6d3131355f313537363035393538390204010400030201000400', + "thumbKey": '42f8609e62817ae45cf7d8fefb532e83', + }) -const miniProgram = new MiniProgram ({ - appid : 'gh_0aa444a25adc', - title : '我正在使用Authing认证身份,你也来试试吧', - pagePath : 'routes/explore.html', - description : '身份管家', - thumbUrl : '30590201000452305002010002041092541302033d0af802040b30feb602045df0c2c5042b777875706c6f61645f31373533353339353230344063686174726f6f6d3131355f313537363035393538390204010400030201000400', - thumbKey : '42f8609e62817ae45cf7d8fefb532e83', -}); + await contact.say(miniProgram) -await contact.say(miniProgram); +asyncio.run(MyBot().start()) ``` -### contact.name\(\) ⇒ `string` +### `@property` def name\(self\) ⇒ `str` -Get the name from a contact +获取联系人对象的名字 -**Kind**: instance method of [`Contact`](contact.md#Contact) **Example** +**类型**: [`Contact`](contact.md#Contact) 的实例方法 -```javascript -const name = contact.name() +**示例:** + +```python +name: str = contact.name ``` -### contact.alias\(newAlias\) ⇒ `Promise ` +### async def alias\(self, `new_alias: Optional[str]` = None\) ⇒ `Union[None, str]` + +为一个联系人获取 / 设置 / 删除别名 -GET / SET / DELETE the alias for a contact +> 测试表明如果过于频繁地设置别名会导致失败\(每分钟60次\). -Tests show it will failed if set alias too frequently\(60 times in one minute\). +**类型**: [`Contact`](contact.md#Contact)对象的实例方法 -**Kind**: instance method of [`Contact`](contact.md#Contact) +**返回值**: Union\[None, str\] -| Param | Type | +| 参数 | 类型 | | :--- | :--- | -| newAlias | `none` \| `string` \| `null` | +| newAlias | Optional\[str\] | -**Example** _\( GET the alias for a contact, return {\(Promise<string \| null>\)}\)_ +**示例:** +_\(**获取**联系人对象的别名\(备注\)_ -```javascript -const alias = await contact.alias() -if (alias === null) { - console.log('You have not yet set any alias for contact ' + contact.name()) -} else { - console.log('You have already set an alias for contact ' + contact.name() + ':' + alias) -} +```python +alias = await contact.alias() +if alias is None or alias == "": + print('您还没有为联系人设置任何别名' + contact.name) +else: + print('您已经为联系人设置了别名 ' + contact.name + ':' + alias) ``` -**Example** _\(SET the alias for a contact\)_ +**示例** + +_\(为一个联系人**设置**别名\(备注\)\)_ -```javascript -try { - await contact.alias('lijiarui') - console.log(`change ${contact.name()}'s alias successfully!`) -} catch (e) { - console.log(`failed to change ${contact.name()} alias!`) -} +```python +try: + await contact.alias('lijiarui') + print(f"改变{contact.name}的备注成功!") +except Exception: + print(f"改变{contact.name}的备注失败~") ``` -**Example** _\(DELETE the alias for a contact\)_ +**示例** -```javascript -try { - const oldAlias = await contact.alias(null) - console.log(`delete ${contact.name()}'s alias successfully!`) - console.log(`old alias is ${oldAlias}`) -} catch (e) { - console.log(`failed to delete ${contact.name()}'s alias!`) -} +_\(**删除**给联系人设置的别名\(备注\)\)_ + +```python +try: + oldAlias = await contact.alias(None) + print(f"成功删除{contact.name}的备注!") + print(f"旧的备注名为{oldAlias}") +except Exception: + print(f"删除{contact.name}的备注失败!") ``` -### contact.friend\(\) ⇒ `boolean` \| `null` +### def is_friend\(self\) ⇒ `Optional[bool]` + +检查这个联系人对象是否是自己的朋友 + +> 注意: 此功能取决于Puppet的实现, 详见 [Puppet兼容表](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) -Check if contact is friend +**类型**: [`Contact`](contact.md#Contact) 的实例方法 -> Tips: This function is depending on the Puppet Implementation, see [puppet-compatible-table](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) +**返回值**: `Optional[bool]` - 如果是自己的朋友则返回True, 不是则返回False, Unknown(未知)则返回None. -**Kind**: instance method of [`Contact`](contact.md#Contact) **Returns**: `boolean` \| `null` - True for friend of the bot False for not friend of the bot, null for unknown. **Example** +**示例** -```javascript -const isFriend = contact.friend() +```python +isFriend = contact.is_friend() +print(isFriend) ``` -### contact.type\(\) ⇒ `ContactType.Unknown` \| `ContactType.Personal` \| `ContactType.Official` +### def is_offical\(self\) ⇒ `bool` -Return the type of the Contact +检查这个联系人对象是否是公众号 -> Tips: ContactType is enum here. +> 注意: 此功能取决于Puppet的实现, 详见 [Puppet兼容表](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) -**Kind**: instance method of [`Contact`](contact.md#Contact) **Example** +**类型**: [`Contact`](contact.md#Contact) 的实例方法 -```javascript -const bot = new Wechaty() -await bot.start() -const isOfficial = contact.type() === bot.Contact.Type.Official +**返回值**: `Optional[bool]` - 如果是公众号则返回True, 不是则返回False, Unknown(未知)则返回None. + +**示例** + +```python +isFriend = contact.is_offical() +print(isFriend) ``` -### contact.gender\(\) ⇒ `ContactGender.Unknown` \| `ContactGender.Male` \| `ContactGender.Female` +### def is_personal\(self) ⇒ `bool` + +检查这个联系人对象是否是个人账号 -Contact gender +> 注意: 此功能取决于Puppet的实现, 详见 [Puppet兼容表](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) -> Tips: ContactGender is enum here. +**类型**: [`Contact`](contact.md#Contact) 的实例方法 -**Kind**: instance method of [`Contact`](contact.md#Contact) **Example** +**返回值**: `Optional[bool]` - 如果是个人账号则返回True, 不是则返回False, Unknown(未知)则返回None. -```javascript -const gender = contact.gender() === bot.Contact.Gender.Male +**示例** + +```python +isFriend = contact.is_personal() +print(isFriend) ``` -### contact.province\(\) ⇒ `string` \| `null` +### def type\(self\) ⇒ `ContactType.CONTACT_TYPE_UNSPECIFIED` \| `ContactType.CONTACT_TYPE_PERSONAL` \| `ContactType.CONTACT_TYPE_OFFICIAL` \| `CONTACT_TYPE_CORPORATION` + +返回联系人的类型 + +> 注意: ContactType是个枚举类型. + +**类型**: [`Contact`](contact.md#Contact)的实例方法 -Get the region 'province' from a contact +**示例** -**Kind**: instance method of [`Contact`](contact.md#Contact) **Example** +```python +import asyncio +from wechaty import Wechaty, Message, ContactType -```javascript -const province = contact.province() +class MyBot(Wechaty): + + async def on_message(self, msg: Message) -> None: + contact = msg.talker() + print(contact.type() == ContactType.CONTACT_TYPE_OFFICIAL) + +asyncio.run(MyBot().start()) ``` -### contact.city\(\) ⇒ `string` \| `null` +### def gender(self)\(\) ⇒ `ContactGender.CONTACT_GENDER_UNSPECIFIED` \| `ContactGender.CONTACT_GENDER_MALE` \| `ContactGender.CONTACT_GENDER_FEMALE` + +获取联系人的性别 -Get the region 'city' from a contact +> 注意: ContactGender是个枚举类型. -**Kind**: instance method of [`Contact`](contact.md#Contact) **Example** +**类型**: [`Contact`](contact.md#Contact)的实例方法 -```javascript -const city = contact.city() +**示例** + +```python +import asyncio +from wechaty import Wechaty, Message, ContactGender + + +class MyBot(Wechaty): + + async def on_message(self, msg: Message) -> None: + contact = msg.talker() + # 判断联系人是否为男性 + print(contact.gender() == ContactGender.CONTACT_GENDER_MALE) + +asyncio.run(MyBot().start()) ``` -### contact.avatar\(\) ⇒ `Promise ` +### def province\(self\) ⇒ `Optional[str]` -Get avatar picture file stream +获取一个联系人-的省份信息 -**Kind**: instance method of [`Contact`](contact.md#Contact) **Example** +**类型**: [`Contact`](contact.md#Contact)的实例方法 -```javascript -// Save avatar to local file like `1-name.jpg` +**示例** -const file = await contact.avatar() -const name = file.name -await file.toFile(name, true) -console.log(`Contact: ${contact.name()} with avatar file: ${name}`) +```python +province: str = contact.province() ``` -### contact.sync\(\) ⇒ `Promise ` +### def city(self) ⇒ `Optional[str]` + +获取联系人所设置的城市 -Force reload data for Contact, Sync data from lowlevel API again. +**类型**: [`Contact`](contact.md#Contact)的实例方法 -**Kind**: instance method of [`Contact`](contact.md#Contact) **Example** +**示例** -```javascript +```python +city: str = contact.city() +``` + +### sync def avatar\(self, file_box: `Optional[FileBox]` = None\) ⇒ `FileBox` + +获取联系人头像图片的文件流 + +**类型**: [`Contact`](contact.md#Contact)的实例方法 + +**示例** + +```python +# 以类似 `1-name.jpg`的格式保存头像图片到本地 +import asyncio +from wechaty import Wechaty, Message, FileBox + +class MyBot(Wechaty): + + async def on_message(self, msg: Message) -> None: + contact = msg.talker() + avatar: "FileBox" = await contact.avatar() + name = avatar.name + await avatar.to_file(name, True) + print(f"联系人: {contact.name} 和头像: {name}") + +asyncio.run(MyBot().start()) +``` + +### async def sync\(self\) ⇒ `None` + +强制重新加载联系人的数据,再次从低级 API 同步数据。 + +**类型**: [`Contact`](contact.md#Contact)的实例方法 + +**示例** + +```python await contact.sync() ``` -### contact.self\(\) ⇒ `boolean` +### def is_self\(self\) ⇒ `bool` + +检查该联系人对象是不是Bot自身 -Check if contact is self +**类型**: [`Contact`](contact.md#Contact)的实例方法 -**Kind**: instance method of [`Contact`](contact.md#Contact) **Returns**: `boolean` - True for contact is self, False for contact is others **Example** +**返回值**: `bool` - 如果该联系人对象是Bot自身则返回True, 若不是则返回False -```javascript -const isSelf = contact.self() +**示例** + +```python +is_self: bool = contact.self() ``` -### Contact.find\(query\) ⇒ `Promise ` +### `@classmethod` async def find\(cls, query: `Union[str, ContactQueryFilter, Callable[[Contact], bool]]`\) ⇒ `Optional[Contact]` + +尝试通过过滤器查找联系人: {name: string \| RegExp} / {alias: string \| RegExp} -Try to find a contact by filter: {name: string \| RegExp} / {alias: string \| RegExp} +通过联系人的名字(name)或者别名(alias)来获取联系人对象, 如果查找的结果大于一个, 则返回第一个. -Find contact by name or alias, if the result more than one, return the first one. +**类型**: [`Contact`](contact.md#Contact)的**静态方法** -**Kind**: static method of [`Contact`](contact.md#Contact) **Returns**: `Promise.` - If can find the contact, return Contact, or return null +**返回值**: `Optional[Contact]` - 如果能找到联系人,则返回找到的联系人对象,否则返回`None` -| Param | Type | +| 参数 | 类型 | | :--- | :--- | | query | [`ContactQueryFilter`](contact.md#ContactQueryFilter) | -#### Example +#### 示例 + +```python +import asyncio +from wechaty import Wechaty, Contact +from wechaty_puppet import ContactQueryFilter -```javascript -const bot = new Wechaty() -await bot.start() -const contactFindByName = await bot.Contact.find({ name:"ruirui"} ) -const contactFindByAlias = await bot.Contact.find({ alias:"lijiarui"} ) +class MyBot(Wechaty): + + async def on_login(self, contact: Contact) -> None: + contact = await self.Contact.find(ContactQueryFilter(name="lijiarui")) + contact = await self.Contact.find(ContactQueryFilter(alias="ruirui")) + +asyncio.run(MyBot().start()) ``` -### Contact.findAll\(\[queryArg\]\) ⇒ `Promise ` +### `@classmethod` async def find_all\(cls, query: `Optional[Union[str, ContactQueryFilter, Callable[[Contact], bool]]]` = None\) -> `List[Contact]` -Find contact by `name` or `alias` +通过 `name` 或者 `alias` 查找并获取联系人对象 -If use Contact.findAll\(\) get the contact list of the bot. Include the contacts from bot's rooms. +使用 Contact.find_all\(\) 获取机器人的联系人列表。 包括来自机器人加入的房间内的联系人。 -#### definition +#### 定义 -* `name` the name-string set by user-self, should be called name -* `alias` the name-string set by bot for others, should be called alias +* `name` 由用户自己设置的名字, 叫做name +* `alias` 由Bot为联系人设置的名字\(备注/别名\). 该值可以传入正则表达式用于搜索用户 -**Kind**: static method of [`Contact`](contact.md#Contact) +**类型**: [`Contact`](contact.md#Contact)的**静态方法** -| Param | Type | +| 参数 | 类型 | | :--- | :--- | | queryArg | [`ContactQueryFilter`](contact.md#ContactQueryFilter) | -#### Example +#### 示例 -```javascript -const bot = new Wechaty() -await bot.start() -const contactList = await bot.Contact.findAll() // get the contact list of the bot -const contactList = await bot.Contact.findAll({ name: 'ruirui' }) // find all of the contacts whose name is 'ruirui' -const contactList = await bot.Contact.findAll({ alias: 'lijiarui' }) // find all of the contacts whose alias is 'lijiarui' -``` +```python +import asyncio +from wechaty import Wechaty, Contact +from wechaty_puppet import ContactQueryFilter + +class MyBot(Wechaty): -## ContactQueryFilter + async def on_login(self, contact: Contact) -> None: + contact = await self.Contact.find_all() # 获取一个列表, 里面包含了Bot所有的联系人 + contact = await self.Contact.find_all(ContactQueryFilter(name="lijiarui")) # 获取一个包含所有名字为lijiarui的联系人的列表 + contact = await self.Contact.find_all(ContactQueryFilter(alias="ruirui")) # 获取一个包含所有别名(备注)为ruirui的联系人的列表 -The way to search Contact +asyncio.run(MyBot().start()) +``` +## Typedefs 类型定义 -**Kind**: global typedef **Properties** +### [ContactQueryFilter](contact.md#ContactQueryFilter) -| Name | Type | Description | -| :--- | :--- | :--- | -| name | `string` | The name-string set by user-self, should be called name | -| alias | `string` | The name-string set by bot for others, should be called alias [More Detail](https://github.com/wechaty/wechaty/issues/365) | +用于搜索联系人对象的一个封装结构 + +| **属性名** | 类型 | **描述** | +| ---------- | -------- | ------------------------------------------------------------ | +| name | `str` | 由用户本身(user-self)设置的名字, 叫做name | +| alias | `str` | 由Bot为联系人设置的名字(备注/别名). 该值可以传入正则表达式用于搜索用户, 更多细节详见[issues#365](https://github.com/wechaty/wechaty/issues/365)和[源码](https://github.com/wechaty/python-wechaty-puppet/blob/master/src/wechaty_puppet/schemas/contact.py) | diff --git a/docs/references/friendship.md b/docs/references/friendship.md index 3a35f32f..ece520a5 100644 --- a/docs/references/friendship.md +++ b/docs/references/friendship.md @@ -2,37 +2,37 @@ title: Friendship --- -Send, receive friend request, and friend confirmation events. +发送、接收好友请求和好友确认事件。 ## Friendship -Send, receive friend request, and friend confirmation events. +发送、接收好友请求和好友确认事件。 -1. send request -2. receive request\(in friend event\) -3. confirmation friendship\(friend event\) +1. 发送请求 +2. 接收请求\(in friend event\) +3. 接受请求\(friend event\) -[Examples/Friend-Bot](https://github.com/wechaty/wechaty/blob/1523c5e02be46ebe2cc172a744b2fbe53351540e/examples/friend-bot.ts) +[示例/Friend-Bot](https://github.com/wechaty/python-wechaty-getting-started/blob/master/examples/advanced/friendship-bot.py) -**Kind**: global class +**类型**: 全局类 * [Friendship](friendship.md#Friendship) - * _instance_ - * [.accept\(\)](friendship.md#Friendship+accept) ⇒ `Promise ` - * [.hello\(\)](friendship.md#Friendship+hello) ⇒ `string` + * _实例方法_ + * [.accept\(\)](friendship.md#Friendship+accept) ⇒ `None` + * [.hello\(\)](friendship.md#Friendship+hello) ⇒ `str` * [.contact\(\)](friendship.md#Friendship+contact) ⇒ `Contact` * [.type\(\)](friendship.md#Friendship+type) ⇒ `FriendshipType` - * _static_ + * _静态方法_ * [~~.send\(\)~~](friendship.md#Friendship.send) - * [.add\(contact, hello\)](friendship.md#Friendship.add) ⇒ `Promise ` + * [.add\(contact, hello\)](friendship.md#Friendship.add) ⇒ `None` -### friendship.accept\(\) ⇒ `Promise ` +### friendship.accept\(\) ⇒ `None` -Accept Friend Request +接受朋友请求 -**Kind**: instance method of [`Friendship`](friendship.md#Friendship) +**类型**: [`Friendship`](friendship.md#Friendship)的实例方法 -#### Example +#### 示例 ```javascript const bot = new Wechaty() @@ -60,12 +60,15 @@ bot.on('friendship', async friendship => { .start() ``` -### friendship.hello\(\) ⇒ `string` +### friendship.hello\(\) ⇒ `str` Get verify message from -**Kind**: instance method of [`Friendship`](friendship.md#Friendship) -**Example** _\(If request content is \`ding\`, then accept the friendship\)_ +**类型**: [`Friendship`](friendship.md#Friendship)的实例方法 + +**示例** + +_\(If request content is \`ding\`, then accept the friendship\)_ ```javascript const bot = new Wechaty() @@ -84,11 +87,11 @@ bot.on('friendship', async friendship => { ### friendship.contact\(\) ⇒ `Contact` -Get the contact from friendship +获取邀请的联系人对象 -**Kind**: instance method of [`Friendship`](friendship.md#Friendship) +**类型**: [`Friendship`](friendship.md#Friendship)的实例方法 -#### Example +#### 示例 ```javascript const bot = new Wechaty() @@ -102,17 +105,18 @@ bot.on('friendship', friendship => { ### friendship.type\(\) ⇒ `FriendshipType` -Return the Friendship Type +返回Friendship请求的类型 -> Tips: FriendshipType is enum here. </br> +> 提示: FriendshipType在这里是枚举类型. </br> > -> * FriendshipType.Unknown -> * FriendshipType.Confirm -> * FriendshipType.Receive -> * FriendshipType.Verify +> * FriendshipType.FriendshipTypeFRIENDSHIP_TYPE_UNSPECIFIED +> * FriendshipType.FRIENDSHIP_TYPE_CONFIRM +> * FriendshipType.FRIENDSHIP_TYPE_RECEIVE +> * FriendshipType.FRIENDSHIP_TYPE_VERIFY + +**类型**: [`Friendship`](friendship.md#Friendship)的实例方法 -**Kind**: instance method of [`Friendship`](friendship.md#Friendship) -**Example** _\(If request content is \`ding\`, then accept the friendship\)_ +**示例** _\(If request content is \`ding\`, then accept the friendship\)_ ```javascript const bot = new Wechaty() @@ -130,11 +134,11 @@ bot.on('friendship', async friendship => { ### ~~Friendship.send\(\)~~ -_**Deprecated**_ +_**已弃用**_ -use [Friendship\#add](friendship.md#friendship-add-contact-hello-promise) instead +请使用[Friendship\#add](friendship.md#friendship-add-contact-hello-promise) -**Kind**: static method of [`Friendship`](friendship.md#Friendship) +**类型**: [`Friendship`](friendship.md#Friendship)的静态方法 ### Friendship.add\(contact, hello\) ⇒ `Promise ` @@ -142,9 +146,9 @@ Send a Friend Request to a `contact` with message `hello`. The best practice is to send friend request once per minute. Remeber not to do this too frequently, or your account may be blocked. -**Kind**: static method of [`Friendship`](friendship.md#Friendship) +**类型**: [`Friendship`](friendship.md#Friendship)的静态方法 -| Param | Type | Description | +| 参数 | 类型 | 描述 | | :--- | :--- | :--- | | contact | `Contact` | Send friend request to contact | | hello | `string` | The friend request content | diff --git a/docs/references/message.md b/docs/references/message.md index 7a0ac6c6..f7c3e0e8 100644 --- a/docs/references/message.md +++ b/docs/references/message.md @@ -8,382 +8,519 @@ title: Message 接受和发送的消息都封装成`Message`对象。 -[Examples/Ding-Dong-Bot](https://github.com/wechaty/wechaty/blob/1523c5e02be46ebe2cc172a744b2fbe53351540e/examples/ding-dong-bot.ts) +[示例/Ding-Dong-Bot](https://github.com/wechaty/python-wechaty-getting-started/blob/master/examples/ding-dong-bot.py) -**Kind**: 全局对象 +**类型**: 全局对象 * [Message](message.md#Message) - * _instance_ - * [.from\(\)](message.md#Message+from) ⇒ `Contact` \| `None` - * [.to\(\)](message.md#Message+to) ⇒ `Contact` \| `None` - * [.room\(\)](message.md#Message+room) ⇒ `Room` \| `None` + * _实例方法_ + * [~~.from\(\)~~](message.md#Message+from) ⇒ `Contact` + * [.talker\(\)](message.md#Message+talker) ⇒ `Contact` + * [.to\(\)](message.md#Message+to) ⇒ `Optional[Contact]` + * [.room\(\)](message.md#Message+room) ⇒ `Optional[Room]` * [.text\(\)](message.md#Message+text) ⇒ `str` * [.say\(textOrContactOrFile\)](message.md#Message+say) ⇒ `None` * [.type\(\)](message.md#Message+type) ⇒ `MessageType` - * [.self\(\)](message.md#Message+self) ⇒ `bool` - * [.mention\(\)](message.md#Message+mention) ⇒ `List[Contact]` - * [.mention_self\(\)](message.md#Message+mentionSelf) ⇒ `` - * [.forward\(to\)](message.md#Message+forward) ⇒ `` + * [.is_self\(\)](message.md#Message+isSelf) ⇒ `bool` + * [~~.mention\(\)~~](message.md#Message+mention) ⇒ `List[Contact]` + * [.mention_self\(\)](message.md#Message+mentionSelf) ⇒ `bool` + * [.mention_text\(\)](message.md#Message+mentionText) ⇒ `str` + * [.mention_list\(\)](message.md#Message+mentionList) ⇒ `List[Contact]` + * [.forward\(to\)](message.md#Message+forward) ⇒ `None` * [.date\(\)](message.md#Message+date) ⇒ `datetime` - * [.age\(\)](message.md#Message+age) ⇒ `number` + * [.age\(\)](message.md#Message+age) ⇒ `int` * [.to_file_box\(\)](message.md#Message+toFileBox) ⇒ `FileBox` + * [.to_image\(\)](message.md#Message+toImage) ⇒ `Image` * [.to_contact\(\)](message.md#Message+toContact) ⇒ `Contact` * [.to_url_link\(\)](message.md#Message+toUrlLink) ⇒ `UrlLink` - * _static_ - * [.find\(\)](message.md#Message.find) ⇒ `Message` - * [.find_all\(\)](message.md#Message.findAll) ⇒ `Message` + * [.to_url_linkto_mini_program\(\)](message.md#Message+toMiniProgram) ⇒ `UrlLink` + * [.say\(textOrContactOrFileOrUrl, mention_ids\)](contact.md#Message+say) ⇒ `Optional[Message]` + * [.to_recalled\(\)](contact.md#Message+toRecalled) ⇒ `Message` + * [.recall\(\)](contact.md#Message+recall) ⇒ `bool` + * _静态方法_ + * [.find\(\)](message.md#Message.find) ⇒ `Optional[Message]` + * [.find_all\(\)](message.md#Message.findAll) ⇒ `List[Message]` + -### message.from\(\) ⇒ `Contact | None` +### ~~def from\(self\)~~ ⇒ `Contact` + +已弃用, 详见[message.talker\(\)](message.md#Message+talker) + +### def talker\(self\) ⇒ `Contact` 获取消息的发送者。 -**数据类型**: instance method of [`Message`](message.md#Message) **Example** - -```javascript -const bot = new Wechaty() -bot -.on('message', async m => { - const contact = msg.from() - const text = msg.text() - const room = msg.room() - if (room) { - const topic = await room.topic() - console.log(`Room: ${topic} Contact: ${contact.name()} Text: ${text}`) - } else { - console.log(`Contact: ${contact.name()} Text: ${text}`) - } -}) -.start() +**类型**: [`Message`](message.md#Message)的实例方法 + +**示例** + +```python +import asyncio +from wechaty import Wechaty, Message + +class MyBot(Wechaty): + + async def on_message(self, msg: Message) -> None: + print(msg.talker()) + +asyncio.run(MyBot().start()) ``` -### message.to\(\) ⇒ `Contact` \| `None` - -Get the destination of the message Message.to\(\) will return None if a message is in a room, use Message.room\(\) to get the room. - -**Kind**: instance method of [`Message`](message.md#Message) - -#### Example - -```javascript -const bot = new Wechaty() -bot -.on('message', async m => { - const contact = message.from() - const text = message.text() - const toContact = message.to() - if (toContact) { - const name = toContact.name() - console.log(`toContact: ${name} Contact: ${contact.name()} Text: ${text}`) - } else { - console.log(`Contact: ${contact.name()} Text: ${text}`) - } -}) -.start() +### def to\(self\) ⇒ `Optional[Contact]` + +获取消息的接收者, 如果消息是在群聊发出的`Message.to()`会返回None, 请使用 `Message.room()` 获取群聊对象. + +**类型**: [`Message`](message.md#Message)的实例方法 + +#### 示例 + +```python +import asyncio +from wechaty import Wechaty, Message, Contact + +class MyBot(Wechaty): + + async def on_message(self, msg: Message) -> None: + talker: Contact = msg.talker() + text: str = msg.text() + to_contact = msg.to() + if to_contact: + name = to_contact.name + print(f"接收者: {name} 联系人: {talker.name} 内容: {text}") + else: + print(f"联系人: {talker.name} 内容: {text}") + + +asyncio.run(MyBot().start()) ``` -### message.room\(\) ⇒ `Room` \| `None` - -Get the room from the message. If the message is not in a room, then will return `None` - -**Kind**: instance method of [`Message`](message.md#Message) - -#### Example - -```javascript -const bot = new Wechaty() -bot -.on('message', async m => { - const contact = msg.from() - const text = msg.text() - const room = msg.room() - if (room) { - const topic = await room.topic() - console.log(`Room: ${topic} Contact: ${contact.name()} Text: ${text}`) - } else { - console.log(`Contact: ${contact.name()} Text: ${text}`) - } -}) -.start() +### def room\(self\) ⇒ `Optional[Room]` + +获取消息来自的群聊. 如果消息不是来自群聊, 则返回None + +**类型**: [`Message`](message.md#Message)的实例方法 + +#### 示例 + +```python +import asyncio +from wechaty import Wechaty, Message, Contact + +class MyBot(Wechaty): + + async def on_message(self, msg: Message) -> None: + talker: Contact = msg.talker() + text: str = msg.text() + room = msg.room() + if room: + room_name = await room.topic() + print(f"群聊名: {room_name} 联系人(消息发送者): {talker.name} 内容: {text}") + else: + print(f"联系人: {talker.name} 内容: {text}") + + +asyncio.run(MyBot().start()) ``` -### ~~message.content\(\)~~ +### ~~def content\(\)~~ -_**Deprecated**_ +_**已弃用**_ -use [text](message.md#Message+text) instead +请使用[text](message.md#Message+text) -**Kind**: instance method of [`Message`](message.md#Message) +**类型**: [`Message`](message.md#Message)的实例方法 -### message.text\(\) ⇒ `string` +### def text\(self\) ⇒ `str` -Get the text content of the message +获取对话的消息文本 -**Kind**: instance method of [`Message`](message.md#Message) **Example** +**类型**: [`Message`](message.md#Message)的实例方法 -```javascript -const bot = new Wechaty() -bot -.on('message', async m => { - const contact = msg.from() - const text = msg.text() - const room = msg.room() - if (room) { - const topic = await room.topic() - console.log(`Room: ${topic} Contact: ${contact.name()} Text: ${text}`) - } else { - console.log(`Contact: ${contact.name()} Text: ${text}`) - } -}) -.start() +**示例** + +```python +import asyncio +from wechaty import Wechaty, Message, Contact + +class MyBot(Wechaty): + + async def on_message(self, msg: Message) -> None: + talker: Contact = msg.talker() + text: str = msg.text() + room = msg.room() + if room: + room_name = await room.topic() + print(f"群聊名: {room_name} 联系人(消息发送者): {talker.name} 内容: {text}") + else: + print(f"联系人: {talker.name} 内容: {text}") + + +asyncio.run(MyBot().start()) ``` -### message.toRecalled\(\) ⇒ `Promise ` +### async def recall\(self\) ⇒ `bool` + +撤回这条信息 + +**类型**: [`Message`](message.md#Message)的实例方法 + +**返回值**: 返回撤回消息是否成功, 成功为`True`, 失败则为`False` + + +### async def to_recalled\(self\) ⇒ `Message` + +获取撤回的信息的文本 + +**类型**: [`Message`](message.md#Message)的实例方法 -Get the text content of the recalled message +**示例** -**Kind**: instance method of [`Message`](message.md#message) **Example** +```python +import asyncio +from wechaty import Wechaty, Message +from wechaty_puppet import MessageType -```javascript -const bot = new Wechaty() -bot -.on('message', async m => { - if (m.type() === bot.Message.Type.Recalled) { - const recalledMessage = await m.toRecalled() - console.log(`Message: ${recalledMessage} has been recalled.`) - } -}) -.start() +class MyBot(Wechaty): + + async def on_message(self, msg: Message) -> None: + if msg.type() == MessageType.MESSAGE_TYPE_RECALLED: + recalled_message = await msg.to_recalled() + print(f"{recalled_message}被撤回") + +asyncio.run(MyBot().start()) ``` -### message.say\(textOrContactOrFileOrUrlLinkOrMiniProgram\) ⇒ `Promise ` +### async def say(self, msg: `Union[str, Contact, FileBox, UrlLink, MiniProgram]`, mention_ids: `Optional[List[str]]` = None) ⇒ `Optional[Message]` + +向联系人或群聊发送一段文字, 名片, 媒体文件或者链接 -Reply a Text, Contact Card, Media File or Link message to the sender. +> 注意: 此功能取决于Puppet的实现, 详见 [Puppet兼容表](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) -> Tips: This function is depending on the Puppet Implementation, see [puppet-compatible-table](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) +**类型**: [`Message`](message.md#Message)的实例方法 -**Kind**: instance method of [`Message`](message.md#Message) **See**: [Examples/ding-dong-bot](https://github.com/wechaty/wechaty/blob/1523c5e02be46ebe2cc172a744b2fbe53351540e/examples/ding-dong-bot.ts) +**参阅**: [Examples/ding-dong-bot](https://github.com/wechaty/python-wechaty-getting-started/blob/master/examples/ding-dong-bot.py) -| Param | Type | Description | +| 参数 | 类型 | 描述 | | :--- | :--- | :--- | -| textOrContactOrFileOrUrlLinkOrMiniProgram | `string` \| `Contact` \| `FileBox` \| `UrlLink` \| `MiniProgram` | send text, Contact, UrlLink, MiniProgram or file to bot. You can use [FileBox](https://www.npmjs.com/package/file-box) to send file | - -#### Example - -```javascript -import { FileBox } from 'file-box' -import { - Wechaty, - UrlLink, - MiniProgram, -} from 'wechaty' - -const bot = new Wechaty() -bot -.on('message', async m => { - -// 1. send Image - - if (/^ding$/i.test(m.text())) { - const fileBox = FileBox.fromUrl('https://wechaty.github.io/wechaty/images/bot-qr-code.png') - await msg.say(fileBox) - } - -// 2. send Text - - if (/^dong$/i.test(m.text())) { - await msg.say('dingdingding') - } - -// 3. send Contact - - if (/^lijiarui$/i.test(m.text())) { - const contactCard = await bot.Contact.find({name: 'lijiarui'}) - if (!contactCard) { - console.log('not found') - return - } - await msg.say(contactCard) - } - -// 4. send UrlLink - - if (/^link$/i.test(m.text())) { - const urlLink = new UrlLink({ - description: 'Wechaty is a Bot SDK for Wechat Individual Account which can help you create a bot in 6 lines of javascript, with cross-platform support including Linux, Windows, Darwin(OSX/Mac) and Docker.', - thumbnailUrl: 'https://camo.githubusercontent.com/f310a2097d4aa79d6db2962fa42bb3bb2f6d43df/68747470733a2f2f6368617469652e696f2f776563686174792f696d616765732f776563686174792d6c6f676f2d656e2e706e67', - title: 'Wechaty', - url: 'https://github.com/wechaty/wechaty', - }); - - await msg.say(urlLink); - } - -// 5. send MiniProgram (only supported by `wechaty-puppet-macpro`) - - if (/^mini-program$/i.test(m.text())) { - const miniProgram = new MiniProgram ({ - appid : 'gh_0aa444a25adc', - title : '我正在使用Authing认证身份,你也来试试吧', - pagePath : 'routes/explore.html', - description : '身份管家', - thumbUrl : '30590201000452305002010002041092541302033d0af802040b30feb602045df0c2c5042b777875706c6f61645f31373533353339353230344063686174726f6f6d3131355f313537363035393538390204010400030201000400', - thumbKey : '42f8609e62817ae45cf7d8fefb532e83', - }); - - await msg.say(miniProgram); - } -}) -.start() +| textOrContactOrFileOrUrlLinkOrMiniProgram | `string` \| `Contact` \| `FileBox` \| `UrlLink` \| `MiniProgram` | 发送 `文本`, `媒体文件` 或者 `链接`. 您可以使用 [FileBox](https://github.com/wechaty/python-wechaty-puppet/tree/master/src/wechaty_puppet/file_box) 类来发送文件。 | + +#### 示例 + +```python +import asyncio +from wechaty import Wechaty, Message +from wechaty import Wechaty, Contact, FileBox, UrlLink + + +class MyBot(Wechaty): + + async def on_message(self, msg: Message) -> None: + text = msg.text() + + # 1. 发送文字到联系人 + if text == "叮": + await msg.say('咚') + return + + # 2. 发送媒体文件到联系人 + if text == "媒体": + file_box1 = FileBox.from_url('https://wechaty.github.io/wechaty/images/bot-qr-code.png', "bot-qr-code.png") + file_box2 = FileBox.from_file('text.txt', "text.txt") + await msg.say(file_box1) + await msg.say(file_box2) + return + + # 3. 发送名片到联系人 + if text == "名片": + contact_card = self.Contact.load('lijiarui') # 把`lijiarui`更改为您在微信中的任意联系人的姓名 + await msg.say(contact_card) + return + + # 4. 发送链接到联系人 + if text == "链接": + url_link = UrlLink.create( + description='WeChat Bot SDK for Individual Account, Powered by TypeScript, Docker, and Love', + thumbnail_url='https://avatars0.githubusercontent.com/u/25162437?s=200&v=4', + title='Welcome to Wechaty', + url='https://github.com/wechaty/wechaty', + ) + await msg.say(url_link) + return + + # 5. 发送小程序 (暂时只有`wechaty-puppet-macpro`支持该服务) + + if text == "小程序": + miniProgram = self.MiniProgram.create_from_json({ + "appid": 'gh_0aa444a25adc', + "title": '我正在使用Authing认证身份,你也来试试吧', + "pagePath": 'routes/explore.html', + "description": '身份管家', + "thumbUrl": '30590201000452305002010002041092541302033d0af802040b30feb602045df0c2c5042b777875706c6f61645f31373533353339353230344063686174726f6f6d3131355f313537363035393538390204010400030201000400', + "thumbKey": '42f8609e62817ae45cf7d8fefb532e83', + }) + await msg.say(miniProgram) + return + +asyncio.run(MyBot().start()) ``` -### message.type\(\) ⇒ `MessageType` - -Get the type from the message. - -> Tips: MessageType is Enum here. </br> -> -> * MessageType.Unknown -> * MessageType.Attachment -> * MessageType.Audio -> * MessageType.Contact -> * MessageType.Emoticon -> * MessageType.Image -> * MessageType.Text -> * MessageType.Video -> * MessageType.Url - -**Kind**: instance method of [`Message`](message.md#Message) **Example** - -```javascript -const bot = new Wechaty() -if (message.type() === bot.Message.Type.Text) { - console.log('This is a text message') -} +### def type\(self\) ⇒ `MessageType` + +获取消息的类型 + +> 注意: `MessageType`是枚举类型;
+> `from wechaty_puppet import MessageType` +>* MessageType.MESSAGE_TYPE_UNSPECIFIED +>* MessageType.MESSAGE_TYPE_ATTACHMENT +>* MessageType.MESSAGE_TYPE_AUDIO +>* MessageType.MESSAGE_TYPE_CONTACT +>* MessageType.MESSAGE_TYPE_EMOTICON +>* MessageType.MESSAGE_TYPE_IMAGE +>* MessageType.MESSAGE_TYPE_TEXT +>* MessageType.MESSAGE_TYPE_VIDEO +>* MessageType.MESSAGE_TYPE_CHAT_HISTORY +>* MessageType.MESSAGE_TYPE_LOCATION +>* MessageType.MESSAGE_TYPE_MINI_PROGRAM +>* MessageType.MESSAGE_TYPE_TRANSFER +>* MessageType.MESSAGE_TYPE_RED_ENVELOPE +>* MessageType.MESSAGE_TYPE_RECALLED +>* MessageType.MESSAGE_TYPE_URL + +**类型**: [`Message`](message.md#Message)的实例方法 + +**示例** + +```python +import asyncio +from wechaty import Wechaty, Message +from wechaty_puppet import MessageType + +class MyBot(Wechaty): + + async def on_message(self, msg: Message) -> None: + if msg.type() == MessageType.MESSAGE_TYPE_TEXT: + print(f"这是个文本消息") + +asyncio.run(MyBot().start()) + ``` -### message.self\(\) ⇒ `boolean` +### def is_self\(self\) ⇒ `bool` + +检查这个消息是否是由自己发出的 + +**类型**: [`Message`](message.md#Message)的实例方法 + +**返回值**: `bool` - - 返回 `True` 如果是Bot发出的消息, 如果是他人发出的则返回`False`. + +**示例** + +```python +import asyncio +from wechaty import Wechaty, Message +from wechaty_puppet import MessageType -Check if a message is sent by self. +class MyBot(Wechaty): -**Kind**: instance method of [`Message`](message.md#Message) **Returns**: `boolean` - - Return `true` for send from self, `false` for send from others. **Example** + async def on_message(self, msg: Message) -> None: + if msg.is_self(): + print("这个是Bot自己发出的消息") + else: + print("这是由别人发出的消息") -```javascript -if (message.self()) { - console.log('this message is sent by myself!') -} +asyncio.run(MyBot().start()) ``` -### message.mention\(\) ⇒ `Promise ` +### ~~def mention\(\)~~ ⇒ `List[Contact]` -Get message mentioned contactList. +已弃用, 请使用[.mention_list\(\)](message.md#Message+mentionList) -Message event table as follows +### async def mention_list\(self\) ⇒ `List[Contact]` -| | Web | Mac PC Client | iOS Mobile | android Mobile | +以列表的形式获取消息所提及\(@\)的人. + +消息事件表如下 + +| | Web\(网页版\) | Mac PC Client\(苹果电脑端\) | iOS Mobile\(IOS系统移动端\) | android Mobile\(安卓移动端\) | | :--- | :---: | :---: | :---: | :---: | | \[You were mentioned\] tip \(\[有人@我\]的提示\) | ✘ | √ | √ | √ | | Identify magic code \(8197\) by copy & paste in mobile | ✘ | √ | √ | ✘ | | Identify magic code \(8197\) by programming | ✘ | ✘ | ✘ | ✘ | | Identify two contacts with the same roomAlias by \[You were mentioned\] tip | ✘ | ✘ | √ | √ | -**Kind**: instance method of [`Message`](message.md#Message) **Returns**: `Promise ` - - Return message mentioned contactList **Example** +以下是表格的中文粗译 + +| | Web\(网页版\) | Mac PC Client\(苹果电脑端\) | iOS Mobile\(IOS系统移动端\) | android Mobile\(安卓移动端\) | +| :--- | :---: | :---: | :---: | :---: | +| \[有人@我\]的提示 | ✘ | √ | √ | √ | +| 区分移动端复制粘贴的魔法代码 `0d8197 \u0x2005` | ✘ | √ | √ | ✘ | +| 通过编程区分魔法代码`0d8197 \u0x2005`| ✘ | ✘ | ✘ | ✘ | +| 区分两个拥有相同群聊昵称的人的\[有人@我\]的提示 | ✘ | ✘ | √ | √ | + +注: `\u0x2005` 为不可见字符, 提及\(@\)的消息的格式一般为 `@Gary\u0x2005` + +**类型**: [`Message`](message.md#Message)的实例方法 -```javascript -const contactList = await message.mention() -console.log(contactList) +**返回值**: `List[Contact]` - - 以列表的形式获取消息所提及\(@\)的人. + +**示例** + +```python +import asyncio +from wechaty import Wechaty, Message + +class MyBot(Wechaty): + + async def on_message(self, msg: Message) -> None: + contact_mention_list = await msg.mention_list() + print(contact_mention_list) + +asyncio.run(MyBot().start()) ``` -### message.mentionSelf\(\) ⇒ `Promise ` +### async def mention_self\(self\) ⇒ `bool` + +**类型**: [`Message`](message.md#Message)的实例方法 -Check if a message is mention self. +**返回值**: `bool` - - 如果这个消息提及(@)了Bot, 则返回True -**Kind**: instance method of [`Message`](message.md#Message) **Returns**: `Promise ` - - Return `true` for mention me. **Example** +**示例** -```javascript -if (await message.mentionSelf()) { - console.log('this message were mentioned me! [You were mentioned] tip ([有人@我]的提示)') -} +```python +import asyncio +from wechaty import Wechaty, Message + +class MyBot(Wechaty): + + async def on_message(self, msg: Message) -> None: + print(await msg.mention_self()) + +asyncio.run(MyBot().start()) ``` -### message.forward\(to\) ⇒ `Promise ` +### async def mention_text\(self\)⇒ `str` + +返回过滤掉`@name`后的消息 + +**类型**: [`Message`](message.md#Message)的实例方法 -Forward the received message. This action doesn't trigger the on-message events. +**返回值**: `str` - - 返回过滤掉`@name`后的消息 -**Kind**: instance method of [`Message`](message.md#Message) +**示例** -| Param | Type | Description | +```python +import asyncio +from wechaty import Wechaty, Message + +class MyBot(Wechaty): + # 原消息为 `@Gary Helloworld` + async def on_message(self, msg: Message) -> None: + print(await msg.mention_text()) # 打印`Helloworld` + +asyncio.run(MyBot().start()) +``` + +### async def forward\(self, to: `Union[Room, Contact]`\) ⇒ `None` + +转发接收到的信息. 此操作不会触发on-message事件. + +**类型**: [`Message`](message.md#Message)的实例方法 + +| 参数 | 类型 | 描述 | | :--- | :--- | :--- | -| to | `Sayable` \| `Array` | Room or Contact The recipient of the message, the room, or the contact | - -#### Example - -```javascript -const bot = new Wechaty() -bot -.on('message', async m => { - const room = await bot.Room.find({topic: 'wechaty'}) - if (room) { - await m.forward(room) - console.log('forward this message to wechaty room!') - } -}) -.start() +| to | `Union[Room, Contact]` \| 群聊或者联系人, 消息的收件人、群聊房间或联系人 | + +#### 示例 + +```python +import asyncio +from wechaty import Wechaty, Message + +class MyBot(Wechaty): + + async def on_message(self, msg: Message) -> None: + room = await self.Room.find("wechaty") + if room: + await msg.forward(room) + print("成功转发消息到wechaty群聊") + +asyncio.run(MyBot().start()) ``` -### message.date\(\) ⇒ `Date` +### def date\(self\) ⇒ `datetime` + +获取消息发送的时间 + +**类型**: [`Message`](message.md#Message)的实例方法 + +### def age\(self\) ⇒ `int` + +获取当前距离已接收到的这条消息的时间的间隔 + +举个例子, 有条消息是`8:43:01`发送的, 而当我们在Wechaty中接收到它的时候时间已经为 `8:43:15`, 那么这时 `age()`返回的值为 `8:43:15 - 8:43:01 = 14 (秒)` + +**类型**: [`Message`](message.md#Message)的实例方法 + +### ~~def file\(\)~~ + +_**已弃用**_ + +请使用 [to_file_box](message.md#Message+toFileBox) + +**类型**: [`Message`](message.md#Message)的实例方法 + +### async def to_file_box\(self\) ⇒ `FileBox` -Message sent date +从消息中提取媒体文件,并将其封装为FileBox类返回。 -**Kind**: instance method of [`Message`](message.md#Message) +> 提示: 此功能取决于Puppet的实现, 详见 [Puppet兼容表](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) -### message.age\(\) ⇒ `number` +**类型**: [`Message`](message.md#Message)的实例方法 -Returns the message age in seconds. + .to_image -For example, the message is sent at time `8:43:01`, and when we received it in Wechaty, the time is `8:43:15`, then the age\(\) will return `8:43:15 - 8:43:01 = 14 (seconds)` +### async def to_mini_program\(self\) ⇒ `MiniProgram` -**Kind**: instance method of [`Message`](message.md#Message) +从消息中提取小程序卡片,并将其封装为MiniProgramM类返回。 -### ~~message.file\(\)~~ +> 提示: 此功能取决于Puppet的实现, 详见 [Puppet兼容表](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) -_**Deprecated**_ +**类型**: [`Message`](message.md#Message)的实例方法 -use [toFileBox](message.md#Message+toFileBox) instead -**Kind**: instance method of [`Message`](message.md#Message) +### def to_image\(self\) ⇒ `Image` -### message.toFileBox\(\) ⇒ `Promise ` +从消息中提取图像文件,以便我们可以使用不同的图像大小。 -Extract the Media File from the Message, and put it into the FileBox. +> 提示: 此功能取决于Puppet的实现, 详见 [Puppet兼容表](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) -> Tips: This function is depending on the Puppet Implementation, see [puppet-compatible-table](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) +**类型**: [`Message`](message.md#Message)的实例方法 -**Kind**: instance method of [`Message`](message.md#Message) -### message.toContact\(\) ⇒ `Promise ` +### async def to_contact\(self\) ⇒ `Contact` -Get Share Card of the Message Extract the Contact Card from the Message, and encapsulate it into Contact class +获取消息中的联系人卡片, 并从卡片中提取联系人将其封装到联系人类中返回 -> Tips: This function is depending on the Puppet Implementation, see [puppet-compatible-table](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) +> 提示: 此功能取决于Puppet的实现, 详见 [Puppet兼容表](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) -**Kind**: instance method of [`Message`](message.md#Message) +**类型**: [`Message`](message.md#Message)的实例方法 -### message.toUrlLink\(\) ⇒ `Promise ` +### async def to_url_link\(self\) ⇒ `UrlLink` -Get Url Link of the Message Extract the Url Link from the Message, and encapsulate it into UrlLink class +获取消息的UrlLink, 从消息中提取UrlLink,并封装到UrlLink类中返回 -> Tips: This function is depending on the Puppet Implementation, see [puppet-compatible-table](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) +> 提示: 此功能取决于Puppet的实现, 详见 [Puppet兼容表](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) -**Kind**: instance method of [`Message`](message.md#Message) +**类型**: [`Message`](message.md#Message)的实例方法 -### Message.find\(\) ⇒ `Promise ` +### `@classmethod` async def find(cls, talker_id: `Optional[str]` = None, message_id: `Optional[str]` = None, room_id: `Optional[str]` = None, text: `Optional[str]` = None, to_id: `Optional[str]` = None, message_type: `Optional[MessageType]` = None) ⇒ `Optional[Message]` -Find message in cache +在缓存中查找消息 -**Kind**: static method of [`Message`](message.md#Message) +**Kind**: [`Message`](message.md#Message)的静态方法 -### Message.findAll\(\) ⇒ `Promise ` +### `@classmethod` async def find_all(cls, talker_id: `Optional[str]` = None, message_id: `Optional[str]` = None, room_id: `Optional[str]` = None, text: `Optional[str]` = None, to_id: `Optional[str]` = None, message_type: `Optional[MessageType]` = None) ⇒ `List[Message]` -Find messages in cache +在缓存中查找消息 -**Kind**: static method of [`Message`](message.md#Message) +**类型**: [`Message`](message.md#Message)的静态方法 diff --git a/docs/references/room-invitation.md b/docs/references/room-invitation.md index a63f659b..b2d4456e 100644 --- a/docs/references/room-invitation.md +++ b/docs/references/room-invitation.md @@ -2,93 +2,115 @@ title: RoomInvitation --- -Accept room invitation +对群聊邀请事件的封装 ## RoomInvitation -accept room invitation +接受群聊的邀请 -**Kind**: global class +**类型**: 全局类 * [RoomInvitation](room-invitation.md#RoomInvitation) - * [.accept\(\)](room-invitation.md#RoomInvitation+accept) ⇒ `Promise ` - * [.inviter\(\)](room-invitation.md#RoomInvitation+inviter) ⇒ `Promise ` - * [.topic\(\)](room-invitation.md#RoomInvitation+topic) ⇒ `Promise ` - * [~~.roomTopic\(\)~~](room-invitation.md#RoomInvitation+roomTopic) ⇒ `Promise ` - * [.date\(\)](room-invitation.md#RoomInvitation+date) ⇒ `Promise ` - * [.age\(\)](room-invitation.md#RoomInvitation+age) ⇒ `Promise ` - -### roomInvitation.accept\(\) ⇒ `Promise ` - -Accept Room Invitation - -**Kind**: instance method of [`RoomInvitation`](room-invitation.md#RoomInvitation) - -#### Example - -```javascript -const bot = new Wechaty() -bot.on('room-invite', async roomInvitation => { - try { - console.log(`received room-invite event.`) - await roomInvitation.accept() - } catch (e) { - console.error(e) - } -} -.start() + * [.accept\(\)](room-invitation.md#RoomInvitation+accept) ⇒ `None` + * [.inviter\(\)](room-invitation.md#RoomInvitation+inviter) ⇒ `Contact` + * [.topic\(\)](room-invitation.md#RoomInvitation+topic) ⇒ `str` + * [~~.roomTopic\(\)~~](room-invitation.md#RoomInvitation+roomTopic) ⇒ `str` + * [.date\(\)](room-invitation.md#RoomInvitation+date) ⇒ `datetime` + * [.age\(\)](room-invitation.md#RoomInvitation+age) ⇒ `int` + +### async def accept\(self\) ⇒ `None` + +接受群聊邀请 + +**类型**: [`RoomInvitation`](room-invitation.md#RoomInvitation)的实例方法 + +#### 示例 + +```python +import asyncio +from wechaty import Wechaty, RoomInvitation + + +class MyBot(Wechaty): + + async def on_room_invite(self, room_invitation: RoomInvitation) -> None: + try: + print("收到群聊邀请事件") + await room_invitation.accept() + print("已经自动接受") + except Exception as e: + print(e) + +asyncio.run(MyBot().start()) ``` -### roomInvitation.inviter\(\) ⇒ `Promise ` +### async def inviter\(self\) ⇒ `Contact` -Get the inviter from room invitation +获取群聊邀请的邀请人 -**Kind**: instance method of [`RoomInvitation`](room-invitation.md#RoomInvitation) +**类型**: [`RoomInvitation`](room-invitation.md#RoomInvitation)的实例方法 -#### Example +#### 示例 -```javascript -const bot = new Wechaty() -bot.on('room-invite', async roomInvitation => { - const inviter = await roomInvitation.inviter() - const name = inviter.name() - console.log(`received room invitation event from ${name}`) -} -.start() +```python +import asyncio +from wechaty import Wechaty, RoomInvitation + + +class MyBot(Wechaty): + + async def on_room_invite(self, room_invitation: RoomInvitation) -> None: + try: + print("收到群聊邀请事件") + inviter = await room_invitation.inviter() + inviter_name = inviter.name + print(f"收到来自{inviter_name}的群聊邀请") + except Exception as e: + print(e) + +asyncio.run(MyBot().start()) ``` -### roomInvitation.topic\(\) ⇒ `Promise ` +### async def topic\(self\) ⇒ `str` + +获取群聊邀请的群聊名 + +**类型**: [`RoomInvitation`](room-invitation.md#RoomInvitation)的实例方法 + +#### 示例 + +```python +import asyncio +from wechaty import Wechaty, RoomInvitation -Get the room topic from room invitation -**Kind**: instance method of [`RoomInvitation`](room-invitation.md#RoomInvitation) +class MyBot(Wechaty): -#### Example + async def on_room_invite(self, room_invitation: RoomInvitation) -> None: + try: + room_name = await room_invitation.topic() + print(f"收到来自{room_name}的群聊邀请") + except Exception as e: + print(e) -```javascript -const bot = new Wechaty() -bot.on('room-invite', async roomInvitation => { - const topic = await roomInvitation.topic() - console.log(`received room invitation event from room ${topic}`) -} -.start() +asyncio.run(MyBot().start()) ``` -### ~~roomInvitation.roomTopic\(\)~~ +### ~~async def roomTopic\(\)~~ -**Kind**: instance method of [`RoomInvitation`](room-invitation.md#RoomInvitation) -**Deprecated:**: use topic\(\) instead +**类型**: [`RoomInvitation`](room-invitation.md#RoomInvitation)的实例方法 +**已弃用:**: 请使用 topic\(\) -### roomInvitation.date\(\) ⇒ `Promise ` +### async def date\(self\) ⇒ `datetime` -Get the invitation time +获取群聊邀请的日期 -**Kind**: instance method of [`RoomInvitation`](room-invitation.md#RoomInvitation) +**类型**: [`RoomInvitation`](room-invitation.md#RoomInvitation)的实例方法 -### roomInvitation.age\(\) ⇒ `Promise ` +### async def age\(self\) ⇒ `int` -Returns the roopm invitation age in seconds. +获取当前距离已接收到的这条群聊邀请的时间的间隔, 单位为秒 -For example, the invitation is sent at time `8:43:01`, and when we received it in Wechaty, the time is `8:43:15`, then the age\(\) will return `8:43:15 - 8:43:01 = 14 (seconds)` +举个例子, 有条群聊邀请是`8:43:01`发送的, 而当我们在Wechaty中接收到它的时候时间已经为 `8:43:15`, 那么这时 `age()`返回的值为 `8:43:15 - 8:43:01 = 14 (秒)` -**Kind**: instance method of [`RoomInvitation`](room-invitation.md#RoomInvitation) +**类型**: [`RoomInvitation`](room-invitation.md#RoomInvitation)的实例方法 diff --git a/docs/references/room.md b/docs/references/room.md index 53fdc721..1fa7a024 100644 --- a/docs/references/room.md +++ b/docs/references/room.md @@ -8,9 +8,9 @@ title: Room [Room](room.md#Room) -All wechat rooms\(groups\) will be encapsulated as a Room. +微信群聊(组)的相关功能被封装在 `Room` 类中。 -[Examples/Room-Bot](https://github.com/wechaty/wechaty/blob/1523c5e02be46ebe2cc172a744b2fbe53351540e/examples/room-bot.ts) +[示例/Room-Bot](https://github.com/wechaty/python-wechaty-getting-started/blob/master/examples/advanced/room_bot.py) ## Typedefs @@ -26,62 +26,66 @@ All wechat rooms\(groups\) will be encapsulated as a Room. ## Room -All wechat rooms\(groups\) will be encapsulated as a Room. +微信群聊(组)的相关功能被封装在 `Room` 类中。 + +[示例/Room-Bot](https://github.com/wechaty/python-wechaty-getting-started/blob/master/examples/advanced/room_bot.py) -[Examples/Room-Bot](https://github.com/wechaty/wechaty/blob/1523c5e02be46ebe2cc172a744b2fbe53351540e/examples/room-bot.ts) +**类型**: 全局类 -**Kind**: global class **Properties** +**属性** -| Name | Type | Description | +| 名称 | 类型 | 描述 | | :--- | :--- | :--- | -| id | `string` | Get Room id. This function is depending on the Puppet Implementation, see [puppet-compatible-table](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) | +| id | `str` | 获取群聊(组)对象的id. 此函数取决于Puppet的实现, 详见 [Puppet兼容表](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) | * [Room](room.md#Room) - * _instance_ + * _实例方法_ * [.ready\(force_sync=False\)](room.md#Room+ready) ⇒ `None` - * [.say\(textOrContactOrFileOrUrl, mention_ids\)](room.md#Room+say) ⇒ `None` - * [.on\(event, listener\)](room.md#Room+on) ⇒ `Room` + * [.say\(textOrContactOrFileOrUrl, mention_ids\)](room.md#Room+say) ⇒ `Union[None, Message]` + * [.on\(event, listener\)](room.md#Room+on) ⇒ `None` * [.add\(contact\)](room.md#Room+add) ⇒ `None` * [.delete\(contact\)](room.md#Room+delete) ⇒ `None` * [.quit\(\)](room.md#Room+quit) ⇒ `None` - * [.topic\(\[newTopic\]\)](room.md#Room+topic) ⇒ `None | str` - * [.announce\(\[text\]\)](room.md#Room+announce) ⇒ `None | str` + * [.topic\(\[newTopic\]\)](room.md#Room+topic) ⇒ `Optional[str]` + * [.announce\(\[text\]\)](room.md#Room+announce) ⇒ `Optional[str]` * [.qr_code\(\)](room.md#Room+qr_code) ⇒ `str` - * [.alias\(contact\)](room.md#Room+alias) ⇒ `None | str` + * [.alias\(contact\)](room.md#Room+alias) ⇒ `Optional[str]` * [.has\(contact\)](room.md#Room+has) ⇒ `bool` * [.member_list\(\[query\]\)](room.md#Room+member_list) ⇒ `List[Contact]>` - * [.member\(queryArg\)](room.md#Room+member) ⇒ `Contact | None` - * [.owner\(\)](room.md#Room+owner) ⇒ `Contact | None` + * [.member\(queryArg\)](room.md#Room+member) ⇒ `Optional[Contact]` + * [.owner\(\)](room.md#Room+owner) ⇒ `Optional[Contact]` * [.avatar\(\)](room.md#room-owner-contact-or-null) ⇒ `FileBox` - * _static_ + * _静态方法_ * [.create\(contactList, \[topic\]\)](room.md#Room.create) ⇒ `Room` + * [.find\(query\)](room.md#Room.find) ⇒ `Optional[Room]` * [.find_all\(\[query\]\)](room.md#Room.findAll) ⇒ `List[Room]` - * [.find\(query\)](room.md#Room.find) ⇒ `Room | None` -### room.ready\(force_sync=False\) ⇒ `None` +### async def ready\(self, force_sync: `bool` = None\) ⇒ `None` 同步 `Room` 的数据。 -**Kind**: instance method of [`Room`](room.md#Room) **Example** +**类型**: [`Room`](room.md#Room)的实例方法 + +**示例** ```python await room.ready() ``` -### room.say\(textOrContactOrFileOrUrlLinkOrMiniProgram, ...mentionList\) ⇒ `None` +### async def say\(self, some_thing: `Union[str, Contact, FileBox, MiniProgram, UrlLink]`, mention_ids: `Optional[List[str]]` = None\)⇒ `Union[None, Message]` 向群(组)中发送消息,如果携带了联系人列表 `mention_list` 参数,将会在群里同时 @ 这些联系人。 -> Tips: This function is depending on the Puppet Implementation, see [puppet-compatible-table](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) +> 注意: 此功能取决于Puppet的实现, 详见 [Puppet兼容表](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) -**Kind**: instance method of [`Room`](room.md#Room) +**类型**: [`Room`](room.md#Room)的实例方法 -| Param | Type | Description | +| 参数 | 类型 | 描述 | | :--- | :--- | :--- | -| textOrContactOrFileOrUrlLinkOrMiniProgram | `string` \| `Contact` \| `FileBox` \| `UrlLink` \| `MiniProgram` | Send `text`, `media file` or `link` inside Room. You can use [FileBox](https://www.npmjs.com/package/file-box) to send file | -| ...mentionList | `List[contact_id]` | Send content inside Room, and mention @contact list. | +| textOrContactOrFileOrUrlLinkOrMiniProgram | `str` \| `Contact` \| `FileBox` \| `UrlLink` \| `MiniProgram` | 在房间内发送 `文本`, `媒体文件` 或者 `链接`. 您可以使用 [FileBox](https://github.com/wechaty/python-wechaty-puppet/tree/master/src/wechaty_puppet/file_box) 类来发送文件。 | +| ...mentionList | `List[contact_id]` | 在群聊内发送内容,如果提供了联系人的id列表, 将会一并提及\(@\)他\(她\)们| -#### Example +#### 示例 ```python from wechaty import Wechaty, FileBox, UrlLink, MiniProgram import asyncio @@ -89,103 +93,98 @@ import asyncio class MyBot(Wechaty): async def on_login(self, contact: Contact): - # after logged in... + # 等待登入 room = await bot.Room.find('wechaty') # 可以根据 room 的 topic 和 id 进行查找 - # 1. Send text inside Room + # 1. 向房间发送文本 await room.say('Hello world!') - # 2. Send media file inside Room + # 2.发送语音文件到群聊 file_box1 = FileBox.from_url( url='https://wechaty.github.io/wechaty/images/bot-qr-code.png', name='QRCode') file_box2 = FileBox.from_file("./test.txt") # 注意路径,以及文件不能为空 await room.say(file_box1) await room.say(file_box2) - # 3. Send Contact Card in a room + # 3. 发送名片到群聊 contact_card = await self.Contact.find('master') await room.say(contact_card) - # 4. Send text inside room and mention @mention contact - members = await special_room.member_list() # all members in this room + # 4. 在群聊内发送文本, 并提及(@) `some_members_id`列表里面提供的人 + members = await special_room.member_list() # 房间内的所有联系人对象 some_members_id = [m.contact_id for m in members[:3]] await room.say('Hello world!', some_members_id) - # 5. send Link inside room - from wechaty_puppet.schemas.url_link import UrlLinkPayload - url_payload = UrlLinkPayload( - description="WeChat Bot SDK for Individual Account, Powered by TypeScript, Docker, and Love", - thumbnailUrl="https://avatars0.githubusercontent.com/u/25162437?s=200&v=4", - title="Welcome to Wechaty", + # 5. 在群聊内发送连接 + urlLink = UrlLink.create( + description='WeChat Bot SDK for Individual Account, Powered by TypeScript, Docker, and Love', + thumbnail_url='https://avatars0.githubusercontent.com/u/25162437?s=200&v=4', + title='Welcome to Wechaty', url='https://github.com/wechaty/wechaty', ) - link_payload = UrlLink(url_payload) - await room.say(link_payload) - - # 6. send MiniProgram (only supported by `wechaty-puppet-macpro`) - from wechaty_puppet.schemas.mini_program import MiniProgramPayload - mini_program_payload = MiniProgramPayload( - appid="gh_0xxxxxxxxx4a25adc", - title="我正在使用Authing认证身份,你也来试试吧", - pagePath="routes/explore.html", - description="身份管家", - thumbUrl="xxxxxxxxxxxxxxxxxx", - thumbKey="42f860xxxxxxxfefb532e83" - ) - mini_program = MiniProgram(mini_program_payload) + await room.say(urlLink) + + # 6. 发送小程序 (暂时只有`wechaty-puppet-macpro`支持该功能) + miniProgram = self.MiniProgram.create_from_json({ + "appid": 'gh_0aa444a25adc', + "title": '我正在使用Authing认证身份,你也来试试吧', + "pagePath": 'routes/explore.html', + "description": '身份管家', + "thumbUrl": '30590201000452305002010002041092541302033d0af802040b30feb602045df0c2c5042b777875706c6f61645f31373533353339353230344063686174726f6f6d3131355f313537363035393538390204010400030201000400', + "thumbKey": '42f8609e62817ae45cf7d8fefb532e83', + }) await room.say(mini_program) asyncio.run(MyBot().start()) ``` -### room.on\(event, listener\) ⇒ `this` +### def on\(self, event_name: `str`, func: `Callable`\) ⇒ `None` -**Kind**: instance method of [`Room`](room.md#Room) **Returns**: `this` - - Room for chain +**类型**: [`Room`](room.md#Room)的实例方法 -| Param | Type | Description | + +| 参数 | 类型 | 描述 | | :--- | :--- | :--- | -| event | [`RoomEventName`](room.md#RoomEventName) | Emit WechatyEvent | -| listener | [`RoomEventFunction`](room.md#RoomEventFunction) | Depends on the WechatyEvent | +| event | [`RoomEventName`](room.md#RoomEventName) | 发出的微信事件 | +| listener | [`RoomEventFunction`](room.md#RoomEventFunction) | 收到事件所触发的函数 | -#### Example _\(Event:join \)_ +#### 示例 _\(Event:join \)_ ```python bot = Wechaty() await bot.start() -# after logged in... -# change `event-room` to any room topic in your wechat -room = await bot.Room.find("wechaty") +# 等待机器人登入 +room = await bot.Room.find("event-room") # 把`event-room`改为您在微信中加入的任意群聊的群聊名称 -async def on_join(invitee_list, inviter): - log.info('room.on(join) id:', room.room_id) - check_room_join(bot, room, invitee_list, inviter) +async def on_leave(leaver_list, remover): + log.info('Bot' + 'Room EVENT: leave - "%s" leave(remover "%s"), bye bye' % (','.join(leaver_list), remover or 'unknown')) if room: - room.on('join', on_join) + room.on('leave', on_leave) ``` -#### Example _\(Event:leave \)_ +#### 示例 _\(Event:leave \)_ ```python bot = Wechaty() await bot.start() -# after logged in... -room = await bot.Room.find("wechaty") # change `event-room` to any room topic in your wechat +# 等待机器人登入 +room = await bot.Room.find("event-room") # 把`event-room`改为您在微信中加入的任意群聊的群聊名称 async def on_leave(leaver_list, remover): - log.info('Bot' + 'Room EVENT: leave - "%s" leave(remover "%s"), bye bye' % (','.join(leaver_list), remover or 'unknown')) + log.info('Bot' + '群聊事件: 离开 - "%s" leave(remover "%s"), bye bye' % (','.join(leaver_list), remover or 'unknown')) if room: room.on('leave', on_leave) ``` -#### Example _\(Event:topic \)_ +#### 示例 _\(Event:topic \)_ ```python bot = Wechaty() await bot.start() -# after logged in... -room = await bot.Room.find("wechaty") # change `event-room` to any room topic in your wechat +# 等待机器人登入 +room = await bot.Room.find("wechaty") # 把`wechaty`改为您在微信中加入的任意群聊的群聊名称 async def on_topic(topic, old_topic, changer): log.info('Bot' + 'Room EVENT: topic - changed from "%s" to "%s" by member "%s"' % (old_topic, topic, changer.name())) @@ -194,13 +193,13 @@ if room: room.on('topic', on_topic) ``` -#### Example _\(Event:invite \)_ +#### 示例 _\(Event:invite \)_ ```python bot = Wechaty() await bot.start() -# after logged in... -room = await bot.Room.find("wechaty") # change `event-room` to any room topic in your wechat +# 等待机器人登入 +room = await bot.Room.find("wechaty") # 把`wechaty`改为您在微信中加入的任意群聊的群聊名称 async def on_invite(room_invitation): room_invitation.accept() @@ -209,28 +208,28 @@ if room: room.on('invite', on_invite) ``` -### room.add\(contact\) ⇒ `None` +### async def add\(self, contact: `Contact`\) ⇒ `None` -Add contact in a room +将一个联系人添加到群聊 -> Tips: This function is depending on the Puppet Implementation, see [puppet-compatible-table](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) +> 提示: 此功能取决于Puppet的实现, 详见 [Puppet兼容表](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) > -> see [Web version of WeChat closed group interface](https://github.com/wechaty/wechaty/issues/1441) +> 请参阅[网页版微信封闭了群聊接口](https://github.com/wechaty/wechaty/issues/1441) -**Kind**: instance method of [`Room`](room.md#Room) +**类型**: [`Room`](room.md#Room)类的实例方法 -| Param | Type | +| 参数 | 类型 | | :--- | :--- | | contact | `Contact` | -#### Exampl +#### 示例 ```python bot = Wechaty() await bot.start() # after logged in... -contact = await bot.Contact.find('lijiarui') # change 'lijiarui' to any contact in your wechat -room = await bot.Room.find('wechat') # change 'wechat' to any room topic in your wechat +contact = await bot.Contact.find('lijiarui') # 把'lijiarui'改为您通讯录中的任意联系人 +room = await bot.Room.find('wechaty') # 把`wechaty`改为您在微信中加入的任意群聊的群聊名称 if room: try: await room.add(contact) @@ -238,21 +237,21 @@ if room: log.error(e) ``` -### room.delete\(contact\) ⇒ `None` +### async def delete\(self, contact: `Contact`\) ⇒ `None` -Delete a contact from the room It works only when the bot is the owner of the room +从房间中删除联系人, 该功能仅当机器人是房间的所有者\(群主\)时才有效 -> Tips: This function is depending on the Puppet Implementation, see [puppet-compatible-table](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) +> 提示: 此功能取决于Puppet的实现, 详见 [Puppet兼容表](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) > -> see [Web version of WeChat closed group interface](https://github.com/wechaty/wechaty/issues/1441) +> 请参阅[网页版微信封闭了群聊接口](https://github.com/wechaty/wechaty/issues/1441) -**Kind**: instance method of [`Room`](room.md#Room) +**类型**: [`Room`](room.md#Room)类的实例方法 -| Param | Type | +| 参数 | 类型 | | :--- | :--- | | contact | `Contact` | -#### Example +#### 示例 ```python bot = Wechaty() @@ -267,140 +266,184 @@ if room: log.error(e) ``` -### room.quit\(\) ⇒ `None` +### async def quit\(self\) ⇒ `None` -Bot quit the room itself +机器人自行离开该群聊 -> Tips: This function is depending on the Puppet Implementation, see [puppet-compatible-table](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) +> 提示: 此功能取决于Puppet的实现, 详见 [Puppet兼容表](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) -**Kind**: instance method of [`Room`](room.md#Room) **Example** +**类型**: [`Room`](room.md#Room)类的实例方法 + +**示例** ```python await room.quit() ``` -### room.topic\(\[newTopic\]\) ⇒ `None | str` +### async def topic\(self, new_topic: `str` = None\) ⇒ `Optional[str]` -SET/GET topic from the room +设置/获取 群聊的名称 -**Kind**: instance method of [`Room`](room.md#Room) +**类型**: [`Room`](room.md#Room)类的实例方法 -| Param | Type | Description | +| 参数 | 类型 | 描述 | | :--- | :--- | :--- | -| \[newTopic\] | `string` | If set this para, it will change room topic. | +| \[newTopic\] | `str` | 如果设置了该参数, 则会修改群聊名 | -#### Example _\(When you say anything in a room, it will get room topic. \)_ +#### 示例 _\(当任意联系人在群聊内发送消息, 您都会得到该群聊的名称 \)_ ```python -topic = await room.topic() -print(f'topic: {topic}') +import asyncio +from wechaty import Wechaty, Room, Contact, Message + + +class MyBot(Wechaty): + + async def on_message(self, msg: Message) -> None: + room: "Room" = msg.room() + topic = await room.topic() + print(f'群聊名: {topic}') + +asyncio.run(MyBot().start()) ``` -#### Example _\(When you say anything in a room, it will change room topic. \)_ +#### 示例 _\(每当机器人登陆账号时, 机器人都会改变群聊的名字. \)_ ```python -old_topic = await room.topic() -new_topic = await room.topic('change topic to wechaty!') -print(f'room topic change from {old_topic} to {new_topic}') +import asyncio +from wechaty import Wechaty, Room, Contact, Message + +class MyBot(Wechaty): + + async def on_login(self, contact: Contact) -> None: + room = await bot.Room.find('your room') # 替换为您所加入的任意群聊 + old_topic = await room.topic() + new_topic = await room.topic('Wechaty!') + print(f'群聊名从{old_topic}改为{new_topic}') + +asyncio.run(MyBot().start()) + ``` -### room.announce\(\[text\]\) ⇒ `None | str` +### async def announce\(self, announce_text: `str` = None\) ⇒ `Optional[str]` -SET/GET announce from the room +`设置/获取` 群聊的公告 -> Tips: It only works when bot is the owner of the room. +> 注意: 这个功能只有机器人是群主时才可以使用 > -> This function is depending on the Puppet Implementation, see [puppet-compatible-table](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) +> 提示: 此功能取决于Puppet的实现, 详见 [Puppet兼容表](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) -**Kind**: instance method of [`Room`](room.md#Room) +**类型**: [`Room`](room.md#Room)类的实例方法 -| Param | Type | Description | +| 参数 | 类型 | 描述 | | :--- | :--- | :--- | -| \[text\] | `string` | If set this para, it will change room announce. | +| \[text\] | `str` | 如果设置了这个参数, 则会更改群聊的公告 | -#### Example _\(When you say anything in a room, it will get room announce. \)_ +#### 示例 _\(当群聊内的任意联系人发送消息时, 您都会在控制台收到群公告的内容\)_ ```python -room = await bot.Room.find('your room') -announce = await room.announce() -print(f'room announce is : {announce}') +import asyncio +from wechaty import Wechaty, Room, Contact, Message + +class MyBot(Wechaty): + + async def on_message(self, msg: Message) -> None: + room: "Room" = msg.room() + announce = await room.announce() + print(f'群公告为: {announce}') + +asyncio.run(MyBot().start()) ``` -#### Example _\(When you say anything in a room, it will change room announce. \)_ +#### 示例 _\(每当机器人登陆账号时, 都会改变群聊公告的内容\)_ ```python -room = await bot.Room.find('your room') -old_announce = await room.announce() -new_announce = await room.announce('change announce to wechaty!') -print(f'room announce change from {old_announce} to {new_announce}') +import asyncio +from wechaty import Wechaty, Room, Contact, Message + +class MyBot(Wechaty): + + async def on_login(self, contact: Contact) -> None: + room = await bot.Room.find('your room') # 替换为您所加入的任意群聊 + old_announce = await room.announce() + new_announce = await room.announce('改变为wechaty!') + print(f'群聊的公告从{old_announce}改变为{new_announce}') + +asyncio.run(MyBot().start()) + + ``` -### room.qr_code\(\) ⇒ `str` +### async def qr_code\(self\) ⇒ `str` + +获取可以用于扫描加入房间的二维码。 -Get QR Code of the Room from the room, which can be used as scan and join the room. +> 提示: 此功能取决于Puppet的实现, 详见 [Puppet兼容表](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) -> Tips: This function is depending on the Puppet Implementation, see [puppet-compatible-table](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) +**类型**: [`Room`](room.md#Room)类的实例方法 -**Kind**: instance method of [`Room`](room.md#Room) +### async def alias\(self, member: `Contact`\) ⇒ `Optional[str]` -### room.alias\(contact\) ⇒ `Promise ` +返回群聊内联系人的别名\(备注\) -Return contact's roomAlias in the room +**类型**: [`Room`](room.md#Room)类的实例方法 -**Kind**: instance method of [`Room`](room.md#Room) **Returns**: `Promise ` - - If a contact has an alias in room, return string, otherwise return null +**返回值**: `Optional[str]` - - 如果用户在群聊内有备注则返回字符串类型的备注, 没有则返回None -| Param | Type | +| 参数 | 类型 | | :--- | :--- | | contact | `Contact` | -#### Exampl +#### 示例 ```python -room = await bot.Room.find('your room') -contact = await bot.Contact.find('lijiarui') -alias = await room.alias(contact) -print(f'{contact.name()} alias is {alias}') +room = await bot.Room.find('your room') # 要发送消息的群聊名 +contact = await bot.Contact.find('lijiarui') # 找到目标联系人 +alias = await room.alias(contact) # 获取该联系人的备注(别名) +print(f'{contact.name()}的别名是{alias}') ``` -### room.has\(contact\) ⇒ `bool` +### async def has\(self, contact: `Contact`\)⇒ `bool` + +检查这个群聊内是否有`contact`, 返回一个布尔类型的值 -Check if the room has member `contact`, the return is a Promise and must be `await`-ed +**类型**: [`Room`](room.md#Room)类的实例方法 -**Kind**: instance method of [`Room`](room.md#Room) **Returns**: `Promise.` - Return `true` if has contact, else return `false`. +**返回值**: `bool` - 返回 `True` 如果群聊内有该联系人, 没有则返回 `false`. -| Param | Type | +| 参数 | 类型 | | :--- | :--- | | contact | `Contact` | -#### Example _\(Check whether 'lijiarui' is in the room 'wechaty'\)_ +#### 示例 _\(检查好'lijiarui'是否在群聊'wechaty'内\)_ ```python contact = await bot.Contact.find('lijiarui') room = await bot.Room.find('wechaty') if contact and room: if await room.has(contact): - print(f'{contact.name()} is in the room wechaty!') + print(f'{contact.name()} 在群聊wechaty房间内!') else: - print(f'{contact.name()} is not in the room wechaty!') + print(f'{contact.name()} 不在群聊wechaty房间内!') ``` -### room.member_list\(\[query\]\) ⇒ `List[Contact]>` +### async def member_list(self, query: `Union[str, RoomMemberQueryFilter]` = None) ⇒ `List[Contact]>` -Find all contacts in a room +获取一个列表, 里面包含了所有联系人对象 #### definition -* `name` the name-string set by user-self, should be called name, equal to `Contact.name()` -* `roomAlias` the name-string set by user-self in the room, should be called roomAlias -* `contactAlias` the name-string set by bot for others, should be called alias, equal to `Contact.alias()` +* `name` 由联系人自身设置的名字, 叫做`name`, 等同于`Contact.name()` +* `roomAlias` 由联系人自身在群聊内设置的群别名\(备注, 昵称\), 叫做群昵称`roomAlias` +* `contactAlias` 由机器人为联系人设置的备注\(别名\), 叫做联系人备注`alias`, 等同于 `Contact.alias()` -**Kind**: instance method of [`Room`](room.md#Room) +**类型**: [`Room`](room.md#Room)类的实例方法 -| Param | Type | Description | +| 参数 | 类型 | 描述 | | :--- | :--- | :--- | -| \[query\] | [`RoomMemberQueryFilter`](room.md#RoomMemberQueryFilter) \| `string` | Optional parameter, When use memberAll\(name:string\), return all matched members, including name, roomAlias, contactAlias | +| \[query\] | [`RoomMemberQueryFilter`](room.md#RoomMemberQueryFilter) \| `str` | 可选的参数, 当时用 memberAll\(name:str\)时, 返回所有匹配到的成员, 包含名字, 群昵称, 联系人备注 | -#### Example +#### 示例 ```python member_list = await room.member_list() @@ -410,116 +453,132 @@ member_contact_list = await room.member_list('abc') print(f'contact list with all name, room alias, alias are abc: {member_contact_list}') ``` -### room.member\(queryArg\) ⇒ `Contact | None` +### async def member(self, query: `Union[str, RoomMemberQueryFilter]` = None) ⇒ `Optional[Contact]` -Find all contacts in a room, if get many, return the first one. +查找一个房间里的联系人,如果获取到的联系人多于一个,则返回第一个。 -**Kind**: instance method of [`Room`](room.md#Room) +**类型**: [`Room`](room.md#Room)类的实例方法 -| Param | Type | Description | +| 参数 | 类型 | 描述 | | :--- | :--- | :--- | -| queryArg | [`RoomMemberQueryFilter`](room.md#RoomMemberQueryFilter) \| `string` | When use member\(name:string\), return all matched members, including name, roomAlias, contactAlias | +| queryArg | [`RoomMemberQueryFilter`](room.md#RoomMemberQueryFilter) \| `str` | When use member\(name:string\), return all matched members, including name, roomAlias, contactAlias | -#### Example _\(Find member by name\)_ +#### 示例 _\(通过名字寻找联系人\)_ ```python room = await bot.Room.find('wechaty') if room: member = await room.member('lijiarui') if member: - print(f'wechaty room got the member: {member.name()}') + print(f'wechaty 群聊内找到了联系人: {member.name()}') else: - print(f'cannot get member in wechaty room!') + print(f'wechaty群聊内找不到该联系人') ``` -#### Example _\(Find member by MemberQueryFilter\)_ +#### 示例 _\(通过MemberQueryFilter类来查找\)_ ```python -room = await bot.Room.find('wechaty') -if room: - member = await room.member('lijiarui') - if member: - print(f'wechaty room got the member: {member.name()}') - else: - print(f'cannot get member in wechaty room!') +import asyncio +from wechaty import Wechaty, Room, Message +from wechaty_puppet.schemas.room import RoomMemberQueryFilter + +class MyBot(Wechaty): + + async def on_message(self, msg: Message) -> None: + room: "Room" = msg.room() + if room: + member = await room.member(RoomMemberQueryFilter(name="lijiarui")) + if member: + print(f'wechaty room got the member: {member.name}') + else: + print(f'cannot get member in wechaty room!') + + +asyncio.run(MyBot().start()) ``` -### room.owner\(\) ⇒ `Contact` \| `null` +### async def owner\(self\) ⇒ `Optional[Contact]` + +获取该群聊的群主. -Get room's owner from the room. +> 提示: 此功能取决于Puppet的实现, 详见 [Puppet兼容表](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) -> Tips: This function is depending on the Puppet Implementation, see [puppet-compatible-table](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) +**类型**: [`Room`](room.md#Room)类的实例方法 -**Kind**: instance method of [`Room`](room.md#Room) **Example** +**示例** ```python owner = await room.owner() ``` -### room.avatar\(\) ⇒ `FileBox` +### async def avatar\(self\) ⇒ `FileBox` -Get room's avatar +获取群聊的头像. -> Tips: This function is depending on the Puppet Implementation, see [puppet-compatible-table](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) +> 提示: 此功能取决于Puppet的实现, 详见 [Puppet兼容表](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) -**Kind**: instance method of [`Room`](room.md#room) **Example** +**类型**: [`Room`](room.md#Room)类的实例方法 + +**示例** ```python owner = await room.avatar() ``` -### Room.create\(contactList, \[topic\]\) ⇒ [`Room`](room.md#Room) +### `@classmethod` async def create\(cls, contacts: `List[Contact]`, topic: `str`\) ⇒ [`Room`](room.md#Room) -Create a new room. +创建一个新的群聊 -**Kind**: static method of [`Room`](room.md#Room) +**类型**: [`Room`](room.md#Room)类的静态方法 -| Param | Type | +| 参数 | 类型 | | :--- | :--- | -| contactList | `Array` | -| \[topic\] | `string` | +| contactList | `List` | +| \[topic\] | `str` | -#### Example _\(Creat a room with 'lijiarui' and 'juxiaomi', the room topic is 'ding - created'\)_ +#### 示例 _\(用联系人'lijiarui' 和 'juxiaomi'创建一个群聊, 群聊的名称为'ding - created'\)_ ```python helper_contact_a = await bot.Contact.find('lijiarui') helper_contact_b = await bot.Contact.find('juxiaomi') contact_list = [helper_contact_a, helper_contact_b] -print('Bot contact_list: %s', contact_list.join(',')) +print('机器人创建所用的联系人列表为: %s', contact_list.join(',')) room = await Room.create(contact_list, 'ding') print('Bot createDingRoom() new ding room created: %s', room) -await room.topic('ding - created') -await room.say('ding - created') +await room.topic('ding - created') # 设置群聊名称 +await room.say('ding - 创建完成') ``` -### Room.find_all\(\[query\]\) ⇒ `List[Room]` +### `@classmethod` async def find_all(cls, query: `Optional[Union[str, RoomQueryFilter, Callable[[Contact], bool]]]` = None) ⇒ `List[Room]` -Find room by by filter: {topic: string \| RegExp}, return all the matched room +通过过滤器寻找群聊: {topic: str \| RegExp}, 通过一个列表返回所有匹配的群聊对象 -**Kind**: static method of [`Room`](room.md#Room) +**类型**: [`Room`](room.md#Room)类的静态方法 -| Param | Type | +| 参数 | 类型 | | :--- | :--- | | \[query\] | [`RoomQueryFilter`](room.md#RoomQueryFilter) | -#### Exampl +#### 示例 ```python room_list = await bot.Room.find_all() room_list = await bot.Room.find_all('wechaty') ``` -### Room.find\(query\) ⇒ `Room` +### `@classmethod` async def find(cls, query: `Optional[Union[str, RoomQueryFilter, Callable[[Contact], bool]]]` = None) ⇒ `Optional[Room]` + +通过过滤器寻找群聊: {topic: str \| RegExp}, 如果获取到了多个群聊, 则返回第一个 -Try to find a room by filter: {topic: string \| RegExp}. If get many, return the first one. +**类型**: [`Room`](room.md#Room)类的静态方法 -**Kind**: static method of [`Room`](room.md#Room) **Returns**: `Room` - If can find the room, return Room, or return null +**返回值**: `Optional[Room]` - 如果可以找到该群聊, 则返回该群聊的对象, 如果不能则返回None -| Param | Type | +| 参数 | 类型 | | :--- | :--- | | query | [`RoomQueryFilter`](room.md#RoomQueryFilter) | -#### Exampl +#### 示例 ```python room_list = await bot.Room.find() @@ -528,46 +587,56 @@ room_list = await bot.Room.find('wechaty') ## RoomQueryFilter -The filter to find the room: {topic: string \| RegExp} +查找群聊的过滤器: {topic: string \| RegExp} -**Kind**: global typedef **Properties** +**类型**: 全局类型定义 -| Name | Type | -| :--- | :--- | -| topic | `string` | +**属性** + +| 参数 | 类型 | 描述 | +| :--- | :--- | :--- | +| topic | `str` | 群聊的名称| +| id | `str` | 群聊的id | ## RoomEventName -Room Class Event Type +群聊类的事件类型(Room Class Event Type) + +**类型**: 全局类型定义 -**Kind**: global typedef **Properties** +**属性** -| Name | Type | Description | +| 名称 | 类型 | 描述 | | :--- | :--- | :--- | -| join | `string` | Emit when anyone join any room. | -| topic | `string` | Get topic event, emitted when someone change room topic. | -| leave | `string` | Emit when anyone leave the room. If someone leaves the room by themselves, wechat will not notice other people in the room, so the bot will never get the "leave" event. | +| join | `str` | 当有人进入群聊时触发. | +| topic | `str` | 获取群名事件, 当有人改变群聊名称时候 | +| leave | `str` | 当有人退出群聊时触发.
`注意: 如果有人自己退出群聊,微信不会提醒房间里的其他人,所以机器人在此情况不会收到“leave”事件`。 | ## RoomEventFunction -Room Class Event Function +群聊事件函数, 供开发者重写 -**Kind**: global typedef **Properties** +**类型**: 全局类型定义 -| Name | Type | Description | -| :--- | :--- | :--- | -| room-join | `function` | \(this: Room, inviteeList: Contact\[\] , inviter: Contact\) => void | -| room-topic | `function` | \(this: Room, topic: string, oldTopic: string, changer: Contact\) => void | -| room-leave | `function` | \(this: Room, leaver: Contact\) => void | +**属性** +| 名称 | 类型 | 参数 | 描述| +| :--- | :--- | :--- |:--- | +| on_room_join | `function` | \(self: Wechaty, room_invitation: RoomInvitation\); None | 有人加入群聊时触发 | +| on_room_topic | `function` | \(self: Wechaty, room: Room, new_topic: str, old_topic: str, changer: Contact, date: datetime\); None | 有人改变群聊名称时触发 | +| on_room_leave | `function` | \(self: Wechaty, room: Room, leavers: List\[Contact\],remover: Contact, date: datetime\); None | 有人被移出群聊时触发 | +| on_room_invite | `function` | \(self, room_invitation: RoomInvitation\); None | 有人邀请Bot加入群聊时触发 | ## RoomMemberQueryFilter -The way to search member by Room.member\(\) +寻找群成员的一种方法Room.member\(\) + +**类型**: 全局类型定义 -**Kind**: global typedef **Properties** +**属性** -| Name | Type | Description | +| 名称 | 类型 | 描述 | | :--- | :--- | :--- | -| name | `string` | Find the contact by wechat name in a room, equal to `Contact.name()`. | -| roomAlias | `string` | Find the contact by alias set by the bot for others in a room. | -| contactAlias | `string` | Find the contact by alias set by the contact out of a room, equal to `Contact.alias()`. [More Detail](https://github.com/wechaty/wechaty/issues/365) | +| name | `string` | 由联系人自身设置的名字, 叫做`name`, 等同于`Contact.name()`. | +| roomAlias | `string` | 由联系人自身在群聊内设置的群别名\(备注, 昵称\), 叫做群昵称`roomAlias` | +| contactAlias | `string` | 由机器人为联系人设置的备注\(别名\), 叫做联系人备注`alias`, 等同于 `Contact.alias()`. 详见[issues#365](https://github.com/wechaty/wechaty/issues/365) | + diff --git a/docs/references/wechaty.md b/docs/references/wechaty.md index 908262da..4e4ee6d6 100644 --- a/docs/references/wechaty.md +++ b/docs/references/wechaty.md @@ -38,7 +38,7 @@ python-wechaty理论上能够对接所有IM平台,目前已经对接微信、 创建机器人实例: -| Param | Type | Default | +| 参数 | 类型 | 默认值 | | :--- | :--- | :--- | | \[options\] | [`WechatyOptions`](wechaty.md#WechatyOptions) | `{}` | @@ -55,26 +55,26 @@ bot.start() ### wechaty.on\(event, listener\) ⇒ [`Wechaty`](wechaty.md#Wechaty) -When the bot get message, it will emit the following Event. +当机器人获取到信息, 它会触发下面的事件 -You can do anything you want when in these events functions. The main Event name as follows: +在这些事件函数中,您可以做任何您想做的事情。 主要事件名称如下: -* **scan**: Emit when the bot needs to show you a QR Code for scanning. After scan the qrcode, you can login -* **login**: Emit when bot login full successful. -* **logout**: Emit when bot detected log out. -* **message**: Emit when there's a new message. +* **scan**: 当机器人需要向您出示二维码来扫码登入的时候触发. 当您扫描二维码之后, 您便可以登入 +* **login**: 当Bot成功登入时触发 +* **logout**: 当机器人探测到账号登出时触发 +* **message**: 当机器人收到新消息的时候触发 -see more in [WechatyEventName](wechaty.md#WechatyEventName) +更多详见[WechatyEventName](wechaty.md#WechatyEventName) -**Kind**: instance method of [`Wechaty`](wechaty.md#Wechaty) -**Returns**: [`Wechaty`](wechaty.md#Wechaty) - - this for chaining, see advanced [chaining usage](https://github.com/wechaty/wechaty-getting-started/wiki/FAQ-EN#36-why-wechatyonevent-listener-return-wechaty) +**类型**: [`Wechaty`](wechaty.md#Wechaty)的实例方法 +**返回值**: [`Wechaty`](wechaty.md#Wechaty) - - this for chaining, see advanced [chaining usage](https://github.com/wechaty/wechaty-getting-started/wiki/FAQ-EN#36-why-wechatyonevent-listener-return-wechaty) -| Param | Type | Description | +| 参数 | 类型 | 描述 | | :--- | :--- | :--- | -| event | [`WechatyEventName`](wechaty.md#WechatyEventName) | Emit WechatyEvent | -| listener | [`WechatyEventFunction`](wechaty.md#WechatyEventFunction) | Depends on the WechatyEvent | +| event | [`WechatyEventName`](wechaty.md#WechatyEventName) | 触发wechaty事件(WechatyEvent) | +| listener | [`WechatyEventFunction`](wechaty.md#WechatyEventFunction) | WechatyEvent绑定的触发函数 | -**Example** _\(Event:scan\)_ +**示例** _\(Event:scan\)_ ```javascript // Scan Event will emit when the bot needs to show you a QR Code for scanning @@ -84,7 +84,7 @@ bot.on('scan', (url, code) => { }) ``` -**Example** _\(Event:login \)_ +**示例** _\(Event:login \)_ ```javascript // Login Event will emit when bot login full successful. @@ -94,7 +94,7 @@ bot.on('login', (user) => { }) ``` -**Example** _\(Event:logout \)_ +**示例** _\(Event:logout \)_ ```javascript // Logout Event will emit when bot detected log out. @@ -104,7 +104,7 @@ bot.on('logout', (user) => { }) ``` -**Example** _\(Event:message \)_ +**示例** _\(Event:message \)_ ```javascript // Message Event will emit when there's a new message. @@ -114,7 +114,7 @@ wechaty.on('message', (message) => { }) ``` -**Example** _\(Event:friendship \)_ +**示例** _\(Event:friendship \)_ ```javascript // Friendship Event will emit when got a new friend request, or friendship is confirmed. @@ -134,7 +134,7 @@ bot.on('friendship', async (friendship) => { }) ``` -**Example** _\(Event:room-join \)_ +**示例** _\(Event:room-join \)_ ```javascript // room-join Event will emit when someone join the room. @@ -145,7 +145,7 @@ bot.on('room-join', async (room, inviteeList, inviter) => { }) ``` -**Example** _\(Event:room-leave \)_ +**示例** _\(Event:room-leave \)_ ```javascript // room-leave Event will emit when someone leave the room. @@ -156,7 +156,7 @@ bot.on('room-leave', async (room, leaverList, remover) => { }) ``` -**Example** _\(Event:room-topic \)_ +**示例** _\(Event:room-topic \)_ ```javascript // room-topic Event will emit when someone change the room's topic. @@ -166,7 +166,7 @@ bot.on('room-topic', async (room, topic, oldTopic, changer) => { }) ``` -**Example** _\(Event:room-invite, RoomInvitation has been encapsulated as a RoomInvitation Class. \)_ +**示例** _\(Event:room-invite, RoomInvitation 已经封装为一个 RoomInvitation类. \)_ ```javascript // room-invite Event will emit when there's an room invitation. @@ -181,7 +181,7 @@ bot.on('room-invite', async roomInvitation => { } ``` -**Example** _\(Event:error \)_ +**示例** _\(Event:error \)_ ```javascript // error Event will emit when there's an error occurred. @@ -191,50 +191,57 @@ bot.on('error', (error) => { }) ``` -### wechaty.start\(\) ⇒ `Promise ` +### wechaty.start\(\) ⇒ `None` -When you start the bot, bot will begin to login, need you wechat scan qrcode to login +当您启动机器人时,机器人便开始尝试登录,您需要微信扫描二维码登录 -> Tips: All the bot operation needs to be triggered after start\(\) is done +> 提示: 所有的bot操作都需要在start\(\)完成之后才可以触发 -**Kind**: instance method of [`Wechaty`](wechaty.md#Wechaty) +**类型**: [`Wechaty`](wechaty.md#Wechaty)的实例方法 -#### Example +#### 示例 -```javascript -await bot.start() -// do other stuff with bot here +```python +from wechaty import Wechaty +import asyncio + +async def main(): + bot = Wechaty() + await bot.start() + +asyncio.run(main()) ``` -### wechaty.stop\(\) ⇒ `Promise ` +### wechaty.stop\(\) ⇒ `None` -Stop the bot +停止机器人 -**Kind**: instance method of [`Wechaty`](wechaty.md#Wechaty) +**类型**: [`Wechaty`](wechaty.md#Wechaty)的实例方法 -#### Example +#### 示例 -```javascript +```python await bot.stop() ``` -### wechaty.logout\(\) ⇒ `Promise ` +### wechaty.logout\(\) ⇒ `None` -Logout the bot +让Bot登出微信 -**Kind**: instance method of [`Wechaty`](wechaty.md#Wechaty) +**类型**: [`Wechaty`](wechaty.md#Wechaty)的实例方法 -#### Example +#### 示例 -```javascript +```python await bot.logout() ``` -### wechaty.logonoff\(\) ⇒ `boolean` +### wechaty.logonoff\(\) ⇒ `bool` -Get the logon / logoff state +获取机器人的登入或者登出的状态, 返回一个布尔值 -**Kind**: instance method of [`Wechaty`](wechaty.md#Wechaty) +**类型**: [`Wechaty`](wechaty.md#Wechaty)的实例方法 +**返回值**: 登入状态则返回True, 登出则返回False #### Example @@ -248,11 +255,11 @@ if (bot.logonoff()) { ### wechaty.userSelf\(\) ⇒ `ContactSelf` -Get current user +获取当前用户 -**Kind**: instance method of [`Wechaty`](wechaty.md#Wechaty) +**类型**: [`Wechaty`](wechaty.md#Wechaty)的实例方法 -#### Example +#### 示例 ```javascript const contact = bot.userSelf() @@ -261,17 +268,17 @@ console.log(`Bot is ${contact.name()}`) ### wechaty.say\(textOrContactOrFileOrUrl\) ⇒ `Promise ` -Send message to userSelf, in other words, bot send message to itself. +向 userSelf 发送消息,换句话说,bot 向自己发送消息。 -> Tips: This function is depending on the Puppet Implementation, see [puppet-compatible-table](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) +> 注意: 此功能取决于Puppet的实现, 详见 [Puppet兼容表](https://github.com/wechaty/wechaty/wiki/Puppet#3-puppet-compatible-table) -**Kind**: instance method of [`Wechaty`](wechaty.md#Wechaty) +**类型**: [`Wechaty`](wechaty.md#Wechaty)的实例方法 -| Param | Type | Description | +| 参数 | 类型 | 描述 | | :--- | :--- | :--- | -| textOrContactOrFileOrUrl | `string` \| `Contact` \| `FileBox` \| `UrlLink` | send text, Contact, file or Link to bot. </br> You can use [FileBox](https://www.npmjs.com/package/file-box) to send file | +| 文本, 联系人对象, 文件对象, 链接或者小程序对象 | `str` \| [`Contact`](contact.md#Contact) \| `FileBox` \| `UrlLink` \| `MiniProgram` | 发送文本、联系人名片、文件或链接到目标联系人。 您可以使用 [FileBox](https://github.com/wechaty/python-wechaty-puppet/tree/master/src/wechaty_puppet/file_box) 类来发送文件。 | -#### Example +#### 示例 ```javascript const bot = new Wechaty() @@ -309,25 +316,29 @@ await bot.say(linkPayload) Get the global instance of Wechaty -**Kind**: static method of [`Wechaty`](wechaty.md#Wechaty) +**类型**: [`Wechaty`](wechaty.md#Wechaty)的实例方法 -| Param | Type | Default | +| 参数 | 类型 | 默认值 | | :--- | :--- | :--- | | \[options\] | [`WechatyOptions`](wechaty.md#WechatyOptions) | `{}` | -**Example** _\(The World's Shortest ChatBot Code: 6 lines of JavaScript\)_ +**示例** _\(世界上最短的Python ChatBot:9行代码\)_ -```javascript -const { Wechaty } = require('wechaty') +```python +from wechaty import Wechaty + +import asyncio +async def main(): + bot = Wechaty() + bot.on('scan', lambda status, qrcode, data: print('Scan QR Code to login: {}\nhttps://wechaty.js.org/qrcode/{}'.format(status, qrcode))) + bot.on('login', lambda user: print('User {} logged in'.format(user))) + bot.on('message', lambda message: print('Message: {}'.format(message))) + await bot.start() -Wechaty.instance() // Global instance -.on('scan', (url, code) => console.log(`Scan QR Code to login: ${code}\n${url}`)) -.on('login', user => console.log(`User ${user} logined`)) -.on('message', message => console.log(`Message: ${message}`)) -.start() +asyncio.run(main()) ``` -## PuppetName +## Puppet名称 The term [Puppet](https://github.com/wechaty/wechaty/wiki/Puppet) in Wechaty is an Abstract Class for implementing protocol plugins. The plugins are the component that helps Wechaty to control the Wechat\(that's the reason we call it puppet\). The plugins are named PuppetXXX, for example: