Code Monkey home page Code Monkey logo

go-wechaty's Introduction

Wechaty Join Wechaty Discord Developer Community NPM Version NPM Docker

Wechaty

Downloads GitHub stars Docker Pulls ES Modules

TypeScript JavaScript Python Go Java .NET PHP Rust Scala

WeChat Whatsapp

Elevator Pitch

Wechaty is a conversational RPA SDK that simplifies the process of building chatbots. It's like a Swiss Army knife for chatbot development, providing a universal interface to various messaging platforms such as WhatsApp, WeChat, and more. With Wechaty, you write your bot code once, and it runs on any of the supported platforms. This means you can focus on creating engaging conversational experiences without worrying about the underlying complexities of each platform's API. It's open-source, easy to use, and backed by a vibrant community that's ready to help you bring your chatbot ideas to life.

Connecting Chatbots

Wechaty is an RPA (Robotic Process Automation) SDK for Chatbot Makers which can help you create a bot in 6 lines of JavaScript, Python, Go, and Java, with cross-platform support including Linux, Windows, MacOS, and Docker.

🕸️ https://wechaty.js.org
:octocat: https://github.com/Wechaty/wechaty
🪲 https://github.com/Wechaty/wechaty/issues
📖 https://github.com/Wechaty/wechaty-getting-started
🐳 https://hub.docker.com/r/wechaty/wechaty

Breaking News

Voice of Developers

"Wechaty is a great solution; I believe there would be much more users who recognize it." link
— @Gcaufy, Tencent Engineer, Author of WePY

"太好用,好用的想哭"
— @xinbenlv, Google Engineer, Founder of HaoShiYou.org

”好用到哭“——你们对得起这个评价! link
@bigbrother666sh, creator of《社长不见了》剧本杀 NPC DM

"最好的微信开发库" link
— @Jarvis, Baidu Engineer

"Wechaty让运营人员更多的时间思考如何进行活动策划、留存用户,商业变现" link
— @lijiarui, Founder & CEO of Juzi.BOT.

"If you know js ... try Wechaty. It's easy to use."
— @Urinx Uri Lee, Author of WeixinBot(Python)

"Wechaty is a good project; I hope it can continue! Therefore, I became a contributor in open collective."
@Simple

See more at Wiki:Voice Of Developer

Join Us on Discord

Join Wechaty Discord Developer Community Wechaty Discord

Wechaty is used in many ChatBot projects by thousands of developers. To talk with other developers, scan the QR Code below and join our Wechaty Developer Community.

Wechaty Discord Community QR Code

Scan now because other Wechaty developers want to talk with you, too!

Resource

Wechaty has already held lots of talks and got a lot of blogs in the past years; here are all of the wechaty resources:

🚀 The World's Shortest ChatBot Code: 6 lines of JavaScript

import { WechatyBuilder } from 'wechaty'

const wechaty = WechatyBuilder.build() // get a Wechaty instance
wechaty
  .on('scan', (qrcode, status) => console.log(`Scan QR Code to login: ${status}\nhttps://wechaty.js.org/qrcode/${encodeURIComponent(qrcode)}`))
  .on('login',            user => console.log(`User ${user} logged in`))
  .on('message',       message => console.log(`Message: ${message}`))
wechaty.start()

Notice: Wechaty requires Node.js version >= 16

This bot can log all messages to the console after login by the scan.

You can find Wechaty's Official Examples at examples/ding-dong-bot.ts and more from our Example Directory.

🏁 Requirements

  1. Node.js version 16+
  2. NPM version 7+
  3. TypeScript version 4.4+

Getting Started

node

We have a Wechaty starter repository for beginners with the simplest setting. It will be work out-of-the-box after you clone & npm install & npm start.

If you are new to Wechaty and want to try it the first time, we'd like to strong recommend you starting from this repository, and using it as your starter template for your project.

Otherwise, please saved the above The World's Shortest ChatBot Code: 6 lines of JavaScript example to a file named bot.js before you can use either NPM or Docker to run it.

1. Npm

NPM Version npm (tag)

Downloads install size

npm init
npm install wechaty

# create your first bot.js file, you can copy/paste from the above "The World's Shortest ChatBot Code: 6 lines of JavaScript"
# then:
node bot.js

2. Docker

Docker Pulls Docker Layers

Wechaty Docker supports both JavaScript and TypeScript. To use TypeScript just write in TypeScript and save with extension name .ts, no need to compile because we use ts-node to run it.

2.1. Run JavaScript

# for JavaScript
docker run -ti --rm --volume="$(pwd)":/bot wechaty/wechaty bot.js

2.2. Run TypeScript

# for TypeScript
docker run -ti --rm --volume="$(pwd)":/bot wechaty/wechaty bot.ts

Learn more about Wechaty Docker at Wiki:Docker.

3. Switch Protocol(Puppet)

Wechaty is very powerful that it can run over different protocols. You can specify the protocol by set the environment variable WECHATY_PUPPET to different puppet provider.

If you cannot use Web protocol, you can apply other protocal following the instruction here: https://github.com/wechaty/wechaty/wiki/Support-Developers We provide free token to support developers build a valuable WeChat chatbot.

Currently we support the following puppet providers :

Protocol Puppet Provider Environment Variable
Web PuppetPuppeteer export WECHATY_PUPPET=wechaty-puppet-puppeteer
Windows PuppetWorkPro export WECHATY_PUPPET=wechaty-puppet-service
Mock PuppetMock export WECHATY_PUPPET=wechaty-puppet-mock
Web PuppetWechat4u export WECHATY_PUPPET=wechaty-puppet-wechat4u
iPad PuppetRock export WECHATY_PUPPET=wechaty-puppet-service
iPad PuppetPadLocal export WECHATY_PUPPET=wechaty-puppet-service
Windows PuppetDonut export WECHATY_PUPPET=wechaty-puppet-service
iPad PuppetPadpro DEPRECATED export WECHATY_PUPPET=wechaty-puppet-padpro
iPad PuppetPadchat DEPRECATED export WECHATY_PUPPET=wechaty-puppet-padchat
iPad PuppetPadplus DEPRECATED export WECHATY_PUPPET=wechaty-puppet-padplus
Mac PuppetMacpro DEPRECATED export WECHATY_PUPPET=wechaty-puppet-macpro
Windows PuppetWxwork DEPRECATED export WECHATY_PUPPET=wechaty-puppet-service

Learn more about Wechaty Puppet from the Puppet Wiki:

  1. Puppet Directory: https://github.com/Wechaty/wechaty-puppet/wiki/Directory
  2. Puppet Compatibility: https://github.com/Wechaty/wechaty-puppet/wiki/Compatibility

🎸 API

Read the Full Documentation at Wechaty Official API Reference

1 Class Wechaty

Main bot class.

A Bot is a Wechaty instance that control a specific wechaty-puppet.

Wechaty API Description
event login emit after bot login full successful
event logout emit after the bot log out
event friendship emit when someone sends bot a friend request
event message emit when there's a new message
event room-join emit when anyone join any room
event room-topic emit when someone change room topic
event room-leave emit when anyone leave the room
event room-invite emit when there is a room invitation
event scan emit when the bot needs to show you a QR Code for scanning
method start(): Promise<void> start the bot
method stop(): Promise<void> stop the bot
method logonoff(): boolean bot login status
method logout(): Promise<void> logout the bot
method currentUser(): ContactSelf get the login-ed bot contact
method say(text: string): Promise<void> let bot say text to itself

2 Class Contact

All wechat contacts(friends/non-friends) will be encapsulated as a Contact.

Contact API Description
static find(query: string): Promise<null | Contact> find contact by name or alias, if the result more than one, return the first one.
static findAll(query: string): Promise<Contact[]> find contact by name or alias
static load(query: string): Contact get contact by id
property id: readonly string get contact id
method sync(): Promise<void> force reload data for contact , sync data from lowlevel API again
method say(text: string): Promise<void | Message> send text, Contact, or file to contact, return the message which the bot sent (only puppet-padplus supported).
method self(): boolean check if contact is self
method name(): string get the name from a contact
method alias(): Promise<string> get the alias for a contact
method alias(newAlias: string): Promise<void> set or delete the alias for a contact
method friend(): boolean check if contact is friend
method type(): ContactType return the type of the Contact
method province(): string get the region 'province' from a contact
method city(): string get the region 'city' from a contact
method avatar(): Promise<FileBox> get avatar picture file stream
method gender(): ContactGender get gender from a contact

2.1 Class ContactSelf

Class ContactSelf is extended from Contact.

ContactSelf API Description
method avatar(file: FileBox): Promise<void> set avatar for bot
method qrcode(): Promise<string> get qrcode for bot
method signature(text: string): Promise<void> set signature for bot

2.2 Class Friendship

Send, receive friend request, and friend confirmation events.

Friendship API Description
static add(contact: Contact, hello?: string): Promise<void> send a friend invitation to contact
method accept(): Promise<void> accept Friend Request
method hello(): string get the hello string from a friendship invitation
method contact(): Contact get the contact from friendship
method type(): FriendshipType return the Friendship Type(unknown, confirm, receive, verify)

3 Class Message

All wechat messages will be encapsulated as a Message.

Message API Description
static find(query: string): Promise<null | Message> find message in cache and return the first one
static findAll(query: string): Promise<Message[]> find messages in cache, return a message list
method from(): Contact get the sender from a message
method to(): Contact get the destination of the message
method room(): null | Room get the room from the message.(If the message is not in a room, then will return null)
method text(): string get the text content of the message
method say(text: string): Promise<void | Message> reply a Text, Media File , or contact message to the sender, return the message which the bot sent (only puppet-padplus supported).
method type(): MessageType get the type from the message
method self(): boolean check if a message is sent by self
method mention(): Contact[] get message mentioned contactList.
method mentionSelf(): boolean check if a message is mention self
method forward(to: Contact): Promise<void> Forward the received message
method age(): number the number of seconds since it has been created
method date(): Date the time it was created
method toFileBox(): Promise<FileBox> extract the Media File from the Message, and put it into the FileBox.
method toContact(): Promise<Contact> get Share Card of the Message

4 Class Room

All wechat rooms(groups) will be encapsulated as a Room.

Room API Description
static create(contactList: Contact[], topic?: string): Promise<Room> create a new room
static find(query: string): Promise<null | Room> Try to find a room by filter. If get many, return the first one.
static findAll(query: string): Promise<Room[]> Find all contacts in a room
static load(query: string): Room load room by room id
property id: readonly string
event join emit when anyone join any room
event topic emit when someone change room topic
event leave emit when anyone leave the room
event invite emit when receive a room invitation
method sync(): <Promise<void> force reload data for room, sync data from lowlevel API again.
method say(text: string): Promise<void | Message> Send text,media file, contact card, or text with mention @mention contact inside Room, return the message which the bot sent (only puppet-padplus supported).
method add(contact: Contact): Promise<void> Add contact in a room
method del(contact: Contact): Promise<void> Delete a contact from the room
method quit(): Promise<void> Bot quit the room itself
method topic(): Promise<string> GET topic from the room
method topic(newTopic: string): Promise<void> SET topic from the room
method announce(text: string): Promise<void> SET/GET announce from the room
method qrcode(): Promise<string> Get QR Code of the Room from the room, which can be used as scan and join the room.
method alias(contact: Contact): Promise<string> Return contact's roomAlias in the room
method roomAlias(contact: Contact): Promise<string | null> Same as function alias
method has(contact: Contact): Promise<boolean> Check if the room has member contact
method memberAll(query?: string): Promise<Contact[]> Find all contacts or with specific name in a room
method member(query: string): Promise<null | Contact> Find all contacts in a room, if get many, return the first one.
method memberList():Promise<Contact[]> get all room member from the room
method owner(): null | Contact Get room's owner from the room.

4.1 Class RoomInvitation

Accept room invitation

RoomInvitation API Description
method accept(): Promise<void> accept Room Invitation
method inviter(): Contact get the inviter from room invitation
method roomTopic(): Promise<string> get the room topic from room invitation
method date(): Promise<Date> the time it was created
method age(): Promise<number> the number of seconds since it has been created

TEST

NPM Docker Coverage Status

Known Vulnerabilities

Wechaty is fully automatically tested by unit and integration tests, with Continious Integration & Continious Deliver(CI/CD) support powered by CI like Travis, Shippable and Appveyor.

To test Wechaty, run:

npm test

Get to know more about the tests from Wiki:Tests

CREATING WECHATY PLUGIN

Creating and publishing a Wechaty Plugin is simple. Simply expose your module as a function that takes 1 parameter: wechaty. When your plugin is imported by Wechaty, it will pass itself in as the argument, and so you are free to add any configuration that Wechaty supports.

import { WechatyPlugin } from 'wechaty'

export default const MyPlugin: WechatyPlugin = (wechaty: Wechaty) => {
  // ...
}

The config exist so the user can pass in customizations to your Plugin. In documenting your Wechaty Plugin, you would lay out your supported config for the user.

See:

  1. Wechaty Plugin Support with KickOut Example #1939
  2. Wechaty Plugins Contrib

📝 RELEASE NOTES

🎷 Views Since Feb 15, 2019

HitCount

💖 POWERED BY WECHATY

Powered by Wechaty

✨ Wechaty Badge

[![Powered by Wechaty](https://img.shields.io/badge/Powered%20By-Wechaty-brightgreen.svg)](https://wechaty.js.org)

Get more embed html/markdown code from Wiki:Badge

🌟 Projects Using Wechaty

  1. 一个用CNN深度神经网络给图片评分的wechaty项目
  2. Relay between Telegram and WeChat
  3. A chat bot managing the HaoShiYou wechat groups run by volunteers of haoshiyou.org
  4. An interactive chat bot to manage a TODO list
  5. Forward WeChat messages to telegram
  6. koa与wechaty实现的微信小助手,可定时提醒与发消息设定定时任务
  7. Wechaty Pay - 让线上没有难做的生意
  8. 开源社的微信机器人项目

Pull Request is welcome to add yours!

Learn more about Projects Using Wechaty at Wiki:Projects Using Wechaty

😇 Find a Good Server

The best practice for running Wechaty Docker/NPM is using a VPS(Virtual Private Server) outside of China, which can save you hours of time because npm install and docker pull will run smoothly without any problem.

The following VPS providers are used by the Wechaty team, and they worked perfectly in production. You can use the following link to get one in minutes. Also, doing this can support Wechaty because you are referred by us.

Location Price Ram Payment Provider
Singapore $5 512MB Paypal DigitalOcean
Japan $5 1GB Paypal Linode
Korea $10 1GB Alipay, Paypal Netdedi
Singapore $3.5 512MB Alipay, Wechat Vultr

🎶 See Also

💩 The Story

In 2017 ...

Huan's daily life/work depends on too much chat on wechat.

  • Almost 14,000 wechat friends in May 2014, before wechat restricts a total number of friends to 5,000.
  • Almost 400 wechat rooms, and most of them have more than 400 members.

Can you imagine that? He was dying...

So a tireless bot working for me 24x7 on wechat, monitoring/filtering the most important message is badly needed. For example, it highlights discussion which contains the KEYWORDS which he want to follow up(especially in a noisy room). ;-)

At last, It's built for huan's personal study purpose of Automatically Testing.

Stargazers over time

Stargazers over time

💕 Contributors

GitHub issues GitHub pull requests Open Collective Backers Open Collective Sponsors

contributor contributor contributor contributor contributor contributor contributor contributor

This project exists thanks to all the people who contribute. [Contribute].


Contribute

😎 Backers

Backers on Open Collective

Thank you to all our backers! 🙏 [Become a backer]

Open Collective Wechaty

😏 Sponsors

Sponsors on Open Collective

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

Wechaty Sponsor

Multi-language Wechaty

Python Wechaty Go Wechaty Java(Kotlin) Wechaty Scala Wechaty PHP Wechaty .NET(C#) Wechatyin

History

main v1.11 (Nov 22, 2021)

Working on reduxify the Wechaty ecosystem for applying the CQRS pattern.

v1.10 (Nov 21, 2021)

Second beta release of Wechaty, with all ecosystem npm modules with version v1.10 (wechaty-puppet, wechaty-puppet-service, etc)

v1.0 (Sep 2021)

  • Release v1.0 of Wechaty is the first beta release of Wechaty.

v0.69

  1. v0.69: Supports ES Modules (with CJS dual support) (#2232)

v0.68 (Aug 27, 2021)

  1. TLS support (#2231)
  2. The latest CommonJS version

Creators

  1. Huan (LinkedIn), 🐧 Tencent TVP of Chatbot・🤖 Chatie Architect・⭐️ GitHub Star・🚀 YC W19・🌐 Microsoft RD & AI MVP・🦾 Google ML GDE ・🤠 Serial Entrepreneur・🔥 Burner
  2. Rui (李佳芮), Microsoft AI MVP & RD, Co-founder & CEO of Juzi.BOT (YC W19 Alumni)

Profile of Huan Li on StackOverflow

Cite Wechaty

To cite this project in publications:

@misc{Wechaty,
  author = {Huan Li, Rui Li},
  title = {Wechaty: Conversational SDK for Chatbot Makers},
  year = {2016},
  publisher = {GitHub},
  journal = {GitHub Repository},
  howpublished = {\url{https://github.com/wechaty/wechaty}},
}

Copyright & License

  • Code & Docs © 2016-now Huan, Rui, and Wechaty Community Contributors
  • Code released under the Apache-2.0 License
  • Docs released under Creative Commons

go-wechaty's People

Contributors

chensanle avatar dchaofei avatar dingdayu avatar finctive avatar huan avatar nebell avatar silkagenet avatar simpleapples avatar yy1987316 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

go-wechaty's Issues

[BUG] 无法获取到图片信息

源码:
// ToImage extract the Image File from the Message, so that we can use different image sizes.
func (m *Message) ToImage() (_interface.IImage, error) {
if m.Type() != schemas.MessageTypeImage {
return nil, errors.New("not a image type message")
}
return m.GetWechaty().Image().Create(m.id), nil
}

测试。。。。。。

方式一
img,_:=message.ToImage()
fmt.Println(img.HD())
获取不到任何图片信息

方式二
img,_:=message.ToFileBox()
fmt.Println(img.ToDataURL())

无法获取到图片信息

A JavaScript interpreter in Go (golang)

https://github.com/robertkrimen/otto

It seems very interesting...

Run JavaScript inside Go!

vm := otto.New()
vm.Run(`
    abc = 2 + 2;
    console.log("The value of abc is " + abc); // 4
`)

Run Go inside JavaScript!

vm.Set("sayHello", func(call otto.FunctionCall) otto.Value {
    fmt.Printf("Hello, %s.\n", call.Argument(0).String())
    return otto.Value{}
})

vm.Set("twoPlus", func(call otto.FunctionCall) otto.Value {
    right, _ := call.Argument(0).ToInteger()
    result, _ := vm.ToValue(2 + right)
    return result
})

result, _ = vm.Run(`
    sayHello("Xyzzy");      // Hello, Xyzzy.
    sayHello();             // Hello, undefined

    result = twoPlus(2.0); // 4
`)

[Linting] Make the go linter happy

Let's fix the listing problems.

Current state: make lint

$ make lint
~/go/bin/golint wechaty
wechaty/accessory.go:7:6: exported type Accessory should have comment or be unexported
wechaty/type.go:7:6: exported type Sayable should have comment or be unexported
wechaty/wechaty.go:1:1: package comment should be of the form "Package wechaty ..."
~/go/bin/golint wechaty-puppet
wechaty-puppet/file_box.go:1:1: don't use an underscore in package name
wechaty-puppet/file_box.go:3:6: exported type FileBox should have comment or be unexported
wechaty-puppet/file_box.go:7:19: method ToJson should be ToJSON
wechaty-puppet/file_box.go:16:1: comment on exported method FileBox.FromQrCode should be of the form "FromQrCode ..."
wechaty-puppet/puppet.go:1:1: don't use an underscore in package name
wechaty-puppet/puppet.go:9:6: exported type PuppetInterface should have comment or be unexported
wechaty-puppet/puppet.go:10:15: interface method parameter messageId should be messageID
wechaty-puppet/puppet.go:13:6: exported type Puppet should have comment or be unexported
wechaty-puppet/puppet.go:19:1: comment on exported method Puppet.MessageList should be of the form "MessageList ..."
wechaty-puppet/puppet.go:30:1: exported method Puppet.MessageSearch should have comment or be unexported
wechaty-puppet/puppet.go:31:2: var allMessageIdList should be allMessageIDList
wechaty-puppet/puppet.go:42:6: var messageIdList should be messageIDList
wechaty-puppet/puppet.go:57:1: comment on exported method Puppet.MessagePayload should be of the form "MessagePayload ..."
wechaty-puppet/puppet.go:58:33: method parameter messageId should be messageID

Naming Style for Go: same name in package is not allowed

Questions from WIP: add user/message.go #4

Q1

Q1: Go does not allow const of the same name and different types in the same package; so I changed the name of the constant, which may differ from the community specification, I wonder if it is appropriate?

I understand the naming style is different between the language specifications.

From TypeScript to Go means, we have to change some of our naming specifications so that the code can fit the Go styles.

My opinion is: we should follow the style from TS Wechaty as our default, and only change it when there's a must.

For the Go Lang, I believe we can follow another official style which will be a perfect match: @chatie/grpc (Wechaty has dependency to this module)

You can find the Image definition here:

https://github.com/Chatie/grpc/blob/ab85b7345b90c167a031710b9a819f9220c09002/proto/wechaty/puppet/message.proto#L25-L30

enum ImageType {
  IMAGE_TYPE_UNSPECIFIED = 0;
  IMAGE_TYPE_THUMBNAIL   = 1;
  IMAGE_TYPE_HD          = 2;
  IMAGE_TYPE_ARTWORK     = 3;
}

Which means in Go, we can align to:

  ImageTypeUnspecified ImageType = 0
  ImageTypeThumbnail = 1
  ImageTypeHd = 2
  ImageTypeArtwork = 3

[BUG] message.mentionSelf() && puppet-xp

@https://github.com/wechaty/puppet-xp
@https://github.com/wechaty/go-wechaty
@zhangchunsheng
@atorber

Docs.Api.Message. Example

if (await message.mentionSelf()) {
 console.log('this message were mentioned me! [You were mentioned] tip ([有人@我]的提示)')
}

golang

func Chat(context *wechaty.Context, message *user.Message) {
	log.Printf("%sGroup Chat:%s %s \n", viper.GetString("info"), message.From().Name(), message.Text())
	if message.MentionSelf() {
		log.Printf("有人@我了 %s: %s", message.From().Name(), message.Text())
		return
	}
}

Log

[xrsec] 10:02:52 botAPI.go:69: [✓]  已设置钉钉提醒
[xrsec] 10:02:52 puppet_service.go:96: PuppetService Start()
[xrsec] 10:02:53 puppet_service.go:232: PuppetService onGrpcStreamEvent({type:EVENT_TYPE_LOGIN payload:{"contactId":"wxid"}})
[xrsec] 10:02:53 puppet_service.go:384: PuppetService ContactRawPayload(wxid)
[xrsec] 10:02:53 puppet_service.go:232: PuppetService onGrpcStreamEvent({type:EVENT_TYPE_HEARTBEAT payload:{"data":"Wechaty Puppet gRPC stream connect successfully"}})
[xrsec] 10:02:53 main.go:76: [✓] 机器人 Bot 上线
[xrsec] 10:03:01 puppet_service.go:232: PuppetService onGrpcStreamEvent({type:EVENT_TYPE_MESSAGE payload:{"messageId":"cl1lhyi3p000j4olc4n0j5pfz"}})
[xrsec] 10:03:01 puppet_service.go:504: PuppetService MessagePayload(cl1lhyi3p000j4olc4n0j5pfz)
[xrsec] 10:03:01 puppet_service.go:671: PuppetService RoomRawPayload(11111111chatroom)
[xrsec] 10:03:01 puppet_service.go:384: PuppetService ContactRawPayload(wxid)
[xrsec] 10:03:01 chat.go:11: [➜] Group Chat:星冉 #XRSec @Bot 
[xrsec] 10:03:01 puppet_service.go:802: PuppetService RoomMemberList(11111111chatroom)
[xrsec] 10:03:01 puppet_service.go:814: PuppetService RoomMemberRawPayload(11111111chatroom, wxid)
[xrsec] 10:03:01 puppet_service.go:802: PuppetService RoomMemberList(11111111chatroom)
[xrsec] 10:03:01 chat.go:13: 星冉 #XRSec: @Bot
[xrsec] 10:03:01 chat.go:14: 有人@我了
[xrsec] 10:03:04 puppet_service.go:232: PuppetService onGrpcStreamEvent({type:EVENT_TYPE_MESSAGE payload:{"messageId":"cl1lhyjzh000k4olc9f4l8hos"}})
[xrsec] 10:03:04 puppet_service.go:504: PuppetService MessagePayload(cl1lhyjzh000k4olc9f4l8hos)
[xrsec] 10:03:04 chat.go:11: [➜] Group Chat:星冉 #XRSec @Bot 1 
[xrsec] 10:03:04 puppet_service.go:802: PuppetService RoomMemberList(11111111chatroom)
[xrsec] 10:03:27 puppet_service.go:232: PuppetService onGrpcStreamEvent({type:EVENT_TYPE_MESSAGE payload:{"messageId":"cl1lhz1m4000l4olc5fvsekpx"}})
[xrsec] 10:03:27 puppet_service.go:504: PuppetService MessagePayload(cl1lhz1m4000l4olc5fvsekpx)
[xrsec] 10:03:27 puppet_service.go:802: PuppetService RoomMemberList(11111111chatroom)
[xrsec] 10:03:27 puppet_service.go:384: PuppetService ContactRawPayload(wxid)

[BUG] PuppetService Start() rejection 【已解决】

docker wecahty:latest
go-wecahty v0.31 or v0.35

docker wecahty 不管是true还是false,均正常运行
export WECHATY_PUPPET_SERVICE_NO_TLS_INSECURE_CLIENT="true"
export WECHATY_PUPPET_SERVICE_NO_TLS_INSECURE_CLIENT="false"

环境变量

export WECHATY_LOG="verbose"
export WECHATY_PUPPET="wechaty-puppet-padlocal"
export WECHATY_PUPPET_PADLOCAL_TOKEN="puppet_padlocal_xxxxxxxxxxxxxxxxxxxxxx"
export WECHATY_PUPPET_SERVICE_NO_TLS_INSECURE_CLIENT="true"
export WECHATY_PUPPET_SERVER_PORT="8788"
export WECHATY_TOKEN=$(curl -s https://www.uuidgenerator.net/api/version4)
echo "WECHATY_TOKEN=$WECHATY_TOKEN"
```

启动参数
```docker
docker run -ti \
  -d \
  --name wxservice \
  --restart=always \
  --privileged \
  --network=host \
  -e WECHATY_LOG \
  -e WECHATY_PUPPET \
  -e WECHATY_PUPPET_SERVER_PORT \
  -e WECHATY_PUPPET_PADLOCAL_TOKEN \
  -e WECHATY_PUPPET_SERVICE_NO_TLS_INSECURE_SERVER \
  -p "$WECHATY_PUPPET_SERVER_PORT:$WECHATY_PUPPET_SERVER_PORT" \
  -e WECHATY_TOKEN \
  wechaty/wechaty:latest
```

但是要么是这个报错的信息,要么是0.0.0.0的JSON数据,即使有正确的IP地址和端口JSON返回,也无法让go-wechaty连接上去。

```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Error</title>
</head>
<body>
<pre>Cannot GET /v0/hosties/</pre>
</body>
</html>
root@userroot:/home/userroot#
```

```go
bot := wechaty.NewWechaty(wechaty.WithPuppetOption(wp.Option{
		Endpoint: "113.74.111.111:8788",
		//Token:token,
		// 超时控制
		Timeout: time.Duration(2 * time.Minute),
	}), wechaty.WithName("IpadLocalWechat"))
```

但 go-wechaty始终连接不上去,报如下的问题。

2021/10/07 16:12:56 PuppetService Start()
2021/10/07 16:12:56 puppet start err:  PuppetService Start() rejection: startGrpcStream err:rpc error: code = Unavailable desc = connection closed
panic: PuppetService Start() rejection: startGrpcStream err:rpc error: code = Unavailable desc = connection closed

[BUG]使用go ding-dong-bot无法连接上padlocal本地服务

请教,使用的是最新版代码,本地docker 部署的padlocal服务已登录运行正常。
本地运行ding-dong-bot, 报错无法连接上服务,请大佬帮看下

错误输出:
image

docker启动配置:
image

本地环境变量配置:
image

请大佬指点。

Need a boost ? [Feature]

It seems from README that wechaty-puppet used by go-wechaty are all outdated, and as per commit logs and #74, no attempts had been made to incorporated the current/new wechaty-puppets. I.e., it seems the project died after the wechaty-puppet-padplus had died, which is what I really don't want to see.

Describe the solution you'd like
A clear and concise description of what you want to happen.

看一下这个
https://github.com/wechaty/summer-of-wechaty/issues

这个是目前其他的mentor已经发出来的project,在我看来,go wechaty的功能迫切需要完善,这同一个项目里面不要说放一两个学生,我觉得就是放上十几个也没问题,他们都是在做同一个项目,只不过分别到具体的方面不一样
具体到这个特别的项目,分工如何,看什么做了,什么还没做,指导我都不行,不过我可以在具体的某一些点上做一些帮助。比如,只是说比如,我可以帮着做基于go 的 unit test 框架,不过还是那点,让我做框架设计肯定不行,我能帮到的就是在大的框架结构下面做一些具体的工作

[Circler Dependencies]: import cycle not allowed

We need to find a way to avoid the circle dependencies problem.

Current state: make bot

$ make bot
go run examples/ding-dong-bot.go
import cycle not allowed
package main
	imports github.com/wechaty/go-wechaty/wechaty
	imports github.com/wechaty/go-wechaty/wechaty/user
	imports github.com/wechaty/go-wechaty/wechaty
make: *** [Makefile:40: bot] Error 1

message.MentionText Error

1MentionText 不生效问题 (怀疑是特殊字符串导致)

快速定位

2022/04/16 23:06:31 MentionText:[@可馨 add @Chumo(初墨)六号技师 ]

完整日志

2022/04/16 23:06:21 PuppetService onGrpcStreamEvent({type:EVENT_TYPE_HEARTBEAT payload:{"data":"heartbeat@padlocal"}})
2022/04/16 23:06:31 PuppetService onGrpcStreamEvent({type:EVENT_TYPE_MESSAGE payload:{"messageId":"xxxxxxxxxxxxxxx"}})
2022/04/16 23:06:31 PuppetService MessagePayload(xxxxxxxx))
2022/04/16 23:06:31 PuppetService RoomMemberList(xxxxxxxxxxxxx@chatroom)
2022/04/16 23:06:31 PuppetService ContactRawPayload(wxid_xxxxxxxxxx)
2022/04/16 23:06:31 PuppetService RoomMemberList(xxxxxxxxxxxxx@chatroom)
2022/04/16 23:06:31 PuppetService RoomMemberRawPayload(xxxxxxxxxxxxx@chatroom, wxid_xxxxxxxxxx)
2022/04/16 23:06:31 PuppetService RoomMemberList(xxxxxxxxxxxxx@chatroom)
2022/04/16 23:06:31 PuppetService ContactRawPayload(wxid_xxxxxxxxxx)
2022/04/16 23:06:31 PuppetService RoomMemberList(xxxxxxxxxxxxx@chatroom)
2022/04/16 23:06:31 MentionText:[@可馨 add @Chumo(初墨)六号技师 ]

代码

log.Printf("MentionText:[%s]", message.MentionText())

web 协议 总是 提示断线

亲爱的大佬,请问一下,就现在为止,该怎么搭配 purper
wecahty4u 好几年没维护了,wechaty4u 搭配的是 docker 0.65版本

最新版的 docker 镜像登录web版微信没有问题,但是 客户端提示连接失败,是否需要添加其他的参数呢?

Python 库 试用过了,还有提示,go 库 直接丢出报错,让我这个不怎么读代码的 菜鸟来说有点难受

调用Puppet().Stop()会出现invalid memory address or nil pointer dereference

请问能不能提供一个Stop方法用于正常关闭bot ,现在通过Puppet().Stop() 关闭的话,因为autoReconnectGrpcConn()的存在,会导致程序panic
panic: runtime error: invalid memory address or nil pointer dereference
goroutine 275 [running]:
google.golang.org/grpc.(*ClientConn).GetState(0x0, 0x0)
github.com/wechaty/go-wechaty/wechaty-puppet-service.(*PuppetService).autoReconnectGrpcConn(0xc002501b30)
created by github.com/wechaty/go-wechaty/wechaty-puppet-service.(*PuppetService).startGrpcClient

登录一段时间微信会自动退出

这几天运行发现隔个二三天左右微信账号就会自动退出,这种自动退出后,是否可以设置自动登录或者怎么不自动退出登录?在手机微信端无任何操作
docker日志
21:48:07 VERB EventStreamManager grpcEmit(EVENT_TYPE_HEARTBEAT[1], {"data":"heartbeat@browserbridge ding"})
21:48:22 VERB EventStreamManager grpcEmit(EVENT_TYPE_HEARTBEAT[1], {"data":"heartbeat@browserbridge ding"})
21:48:32 VERB PuppetWeChatBridge onLoad() page.url=https://wx2.qq.com/?&lang=en
21:48:32 VERB PuppetWeChatBridge readyAngular()
21:48:32 VERB PuppetWeChatBridge inject()
21:48:32 VERB EventStreamManager grpcEmit(EVENT_TYPE_HEARTBEAT[1], {"data":"heartbeat@browserbridge ding"})
21:48:32 VERB PuppetWeChatBridge ding(ding() OK!)
21:48:32 VERB EventStreamManager grpcEmit(EVENT_TYPE_DONG[3], {"data":"ding() OK!"})
21:48:32 VERB PuppetWeChatBridge clickSwitchAccount()
21:48:33 VERB PuppetWeChatEvent onScan({code: 0, url: https://login.weixin.qq.com/qrcode/QaUgZVng2g==})
21:48:33 VERB MemoryCard set(PUPPET_WECHAT, [object Object],[object Object],[object Object],[object Object],[object Object],[object Object])
21:48:33 VERB MemoryCard save() to StorageFile</wechaty/e4604ef1-f823-bd1f-3e6d-cebd84842d9d.memory-card.json>
21:48:33 VERB StorageFile save() to /wechaty/e4604ef1-f823-bd1f-3e6d-cebd84842d9d.memory-card.json
21:48:33 VERB PuppetWeChatEvent onScan() there has user when got a scan event. emit logout and set it to null
21:48:33 VERB PuppetWeChat logout()
21:48:33 VERB Puppet selfId()
21:48:33 VERB PuppetWeChatBridge logout()
21:48:33 VERB EventStreamManager grpcEmit(EVENT_TYPE_LOGOUT[26], {"contactId":"@0bac3b4fe04e292c879bf1013577feb27b98c3dd8aaad177d4c7cf7173842a56","data":"logout()"})
21:48:33 VERB ContactSelf name()
21:48:33 INFO IoClient 哈 logged out
21:48:33 VERB EventStreamManager grpcEmit(EVENT_TYPE_HEARTBEAT[1], {"data":{"code":0,"url":"https://login.weixin.qq.com/qrcode/QaUgZVng2g=="},"type":"scan"})
21:48:33 INFO IoClient [2] https://login.weixin.qq.com/l/QaUgZVng2g==
Online QR Code Image: https://wechaty.js.org/qrcode/https%3A%2F%2Flogin.weixin.qq.com%2Fl%2FQaUgZVng2g%3D%3D
21:48:33 VERB EventStreamManager grpcEmit(EVENT_TYPE_SCAN[22], {"qrcode":"https://login.weixin.qq.com/l/QaUgZVng2g==","status":2})
21:48:34 VERB PuppetWeChatBridge onLoad() page.url=https://wx2.qq.com/?&lang=en
21:48:34 VERB PuppetWeChatBridge readyAngular()
21:48:34 VERB PuppetWeChatBridge inject()
21:48:34 VERB EventStreamManager grpcEmit(EVENT_TYPE_HEARTBEAT[1], {"data":"heartbeat@browserbridge ding"})
21:48:34 VERB PuppetWeChatBridge ding(ding() OK!)
21:48:34 VERB EventStreamManager grpcEmit(EVENT_TYPE_DONG[3], {"data":"ding() OK!"})
21:48:34 VERB PuppetWeChatBridge clickSwitchAccount()

ding-dong 机器人日志:
2021/06/23 05:48:32 PuppetService onGrpcStreamEvent({type:EVENT_TYPE_HEARTBEAT payload:{"data":"heartbeat@browserbridge ding"}})
2021/06/23 05:48:32 PuppetService onGrpcStreamEvent({type:EVENT_TYPE_DONG payload:{"data":"ding() OK!"}})
2021/06/23 05:48:33 PuppetService onGrpcStreamEvent({type:EVENT_TYPE_LOGOUT payload:{"contactId":"@0bac3b4fe04e292c879bf1013577feb27b98c3dd8aaad177d4c7cf7173842a56","data":"logout()"}})
User Contact<哈> logouted: logout()
2021/06/23 05:48:33 PuppetService onGrpcStreamEvent({type:EVENT_TYPE_SCAN payload:{"qrcode":"https://login.weixin.qq.com/l/QaUgZVng2g==","status":2}})
Scan QR Code to login: ScanStatusWaiting
https://wechaty.js.org/qrcode/https://login.weixin.qq.com/l/QaUgZVng2g==
2021/06/23 05:48:33 PuppetService onGrpcStreamEvent({type:EVENT_TYPE_HEARTBEAT payload:{"data":{"code":0,"url":"https://login.weixin.qq.com/qrcode/QaUgZVng2g=="},"type":"scan"}})
2021/06/23 05:48:33 PuppetService unMarshal err: json: cannot unmarshal object into Go struct field BaseEventPayload.Data of type string
2021/06/23 05:48:34 PuppetService onGrpcStreamEvent({type:EVENT_TYPE_HEARTBEAT payload:{"data":"heartbeat@browserbridge ding"}})
2021/06/23 05:48:34 PuppetService onGrpcStreamEvent({type:EVENT_TYPE_DONG payload:{"data":"ding() OK!"}})
2021/06/23 05:48:35 PuppetService onGrpcStreamEvent({type:EVENT_TYPE_SCAN payload:{"qrcode":"https://login.weixin.qq.com/l/AdN2-vpRtQ==","status":2}})
Scan QR Code to login: ScanStatusWaiting
https://wechaty.js.org/qrcode/https://login.weixin.qq.com/l/AdN2-vpRtQ==
2021/06/23 05:48:35 PuppetService onGrpcStreamEvent({type:EVENT_TYPE_HEARTBEAT payload:{"data":{"code":0,"url":"https://login.weixin.qq.com/qrcode/AdN2-vpRtQ=="},"type":"scan"}})
2021/06/23 05:48:35 PuppetService unMarshal err: json: cannot unmarshal object into Go struct field BaseEventPayload.Data of type string
2021/06/23 05:48:49 PuppetService onGrpcStreamEvent({type:EVENT_TYPE_HEARTBEAT payload:{"data":"heartbeat@browserbridge ding"}})

About go.sum file submit repository

We continue to discuss whether go.sum is submitted to the repository.

I suggest to submit this file.

As @eslizn quoted Go official discussion on this issue:
https://github.com/golang/go/wiki/Modules#releasing-modules-all-versions

Related documents:

submit go.sum the reason:

  • reliance on version unification.
  • Provide package management dependent content verification in a distributed environment

Many open source projects are like this.

go-wechaty使用问题

我不知道该如何实现如下的问题
当我获取到群好友中的关键信息后,如何私聊答复,但我不希望在群里面@好友.

系统默认方式:message.Say("txtMsg")

但我期待的是
message.Say("txtMsg",frind_ID)

请问如何实现。

Shall we use the go-wechaty repo as a publish-only repo?

The Go Wechaty will be installed from github.com/wechaty/go-wechaty, so the wechaty/go-wechaty is our deploy repo for the Go Lang.

The Problem

However, currently, we are developing based on this repo too, which makes it complicated to maintain and not very clean.

The Solution

Shall we use this wechaty/go-wechaty for our publish-only repo, and we deploy the code from our developing repo to this publish-only repo by DevOps & CI/CD? That would help us make sure the published code is with high quality as we expected.

RFC

For the simplest way to archive this goal, we can just rename wechaty/go-wechaty to another name which can stands for the developing, like wechaty/go-wechaty-src (good suggestions are welcome!), and then create a new repo named wechaty/go-wechaty for the deployment.

If we think it's necessary to continue this discussion, please feel free to share your thoughts by commenting on this issue, thank you very much!

[Feature] Can ContactPayload increase the Uin field?

Is your feature request related to a problem? Please describe.
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

Describe the solution you'd like
A clear and concise description of what you want to happen.

Describe alternatives you've considered
A clear and concise description of any alternative solutions or features you've considered.

Please rate Feature
Please consider the scope of application and the difficulty of development.

Additional context
Add any other context or screenshots about the feature request here.

使用message.Forward(room.ID())和message.ToFileBox()时,消息类型如果是image和video都报错:“json: cannot unmarshal string into Go struct field FileBoxOptions.headers of type []string”。

使用的是web协议,DIY Puppet Service:
export WECHATY_LOG="verbose"
export WECHATY_PUPPET="wechaty-puppet-wechat"
export WECHATY_PUPPET_SERVER_PORT="9999"
export WECHATY_TOKEN=“My token”
docker run
-d
-ti
--name wechaty_puppet_service_token_gateway
--rm
--privileged
--network=host
-e WECHATY_LOG
-e WECHATY_PUPPET
-e WECHATY_PUPPET_SERVER_PORT
-e WECHATY_TOKEN
wechaty/wechaty

在使用message.Forward(room.ID())和message.ToFileBox()时,消息类型是text没问题,消息类型是image和video时都报:“json: cannot unmarshal string into Go struct field FileBoxOptions.headers of type []string”这个错误,其他类型没测试,有解决办法吗,谢谢。
go version:1.17

[BUG] 在使用wechaty-puppet-wechat 同步通讯录时报错

Describe the bug
在使用wechaty-puppet-wechat 同步通讯录时报错
使用参考文章:https://wechaty.js.org/2021/04/16/go-wechaty-use-web/

To Reproduce
Steps to reproduce the behavior:
1.其他微信号主动添加微信机器人

bot.OnFriendship(func(context *wechaty.Context, friendship *user.Friendship) { fmt.Printf("received friend event from " + friendship.Contact().Name()) if friendship.Type() == schemas.FriendshipTypeReceive { fmt.Printf("Have Friend " + friendship.Contact().Name()) err := friendship.Accept() } })

发现Docker容器循环提示错误

07:22:33 VERB PuppetCacheMixin dirtyPayload(Room<3>, @@819dc5a932922d0XXXXX1237552f59973f173c11904dca2312d7509936a8b)
07:22:33 VERB PuppetRoomMemberMixin roomMemberPayloadDirty(@@819dc5a932922d0XXXXX1237552f59973f173c11904dca2312d7509936a8b)
07:22:33 VERB PuppetCacheMixin __dirtyPayloadAwait(RoomMember<4>, @@819dc5a932922d0XXXXX1237552f59973f173c11904dca2312d7509936a8b)
07:22:33 VERB PuppetCacheMixin dirtyPayload(RoomMember<4>, @@819dc5a932922d0XXXXX1237552f59973f173c11904dca2312d7509936a8b)
07:22:33 VERB PuppetCacheMixin onDirty(RoomMember<4>, @@819dc5a932922d0XXXXX1237552f59973f173c11904dca2312d7509936a8b)
07:22:33 VERB EventStreamManager grpcEmit(EVENT_TYPE_DIRTY[27], {"payloadId":"@@819dc5a932922d0XXXXX1237552f59973f173c11904dca2312d7509936a8b","payloadType":4})
07:22:33 VERB PuppetContactMixin contactPayloadDirty(@@819dc5a932922d0XXXXX1237552f59973f173c11904dca2312d7509936a8b)
07:22:33 VERB PuppetCacheMixin __dirtyPayloadAwait(Contact<2>, @@819dc5a932922d0XXXXX1237552f59973f173c11904dca2312d7509936a8b)
07:22:33 VERB PuppetCacheMixin dirtyPayload(Contact<2>, @@819dc5a932922d0XXXXX1237552f59973f173c11904dca2312d7509936a8b)
07:22:33 VERB PuppetCacheMixin onDirty(Contact<2>, @@819dc5a932922d0XXXXX1237552f59973f173c11904dca2312d7509936a8b)

2021/11/18 15:23:40 PuppetService onGrpcStreamEvent({type:EVENT_TYPE_DIRTY payload:{"payloadId":"@@819dc5a932922d0XXXXX1237552f59973f173c11904dca2312d7509936a8b","payloadType":2}})
2021/11/18 15:23:40 PuppetService onGrpcStreamEvent({type:EVENT_TYPE_DIRTY payload:{"payloadId":"@@819dc5a932922d0XXXXX1237552f59973f173c11904dca2312d7509936a8b","payloadType":2}})
2021/11/18 15:23:40 PuppetService onGrpcStreamEvent({type:EVENT_TYPE_DIRTY payload:{"payloadId":"@@819dc5a932922d0XXXXX1237552f59973f173c11904dca2312d7509936a8b","payloadType":2}})
2021/11/18 15:23:40 PuppetService onGrpcStreamEvent({type:EVENT_TYPE_DIRTY payload:{"payloadId":"@@819dc5a932922d0XXXXX1237552f59973f173c11904dca2312d7509936a8b","payloadType":2}})

Generate Puppet Schema from TypeScript Automatically

As mentioned by @suntong from #11 (comment):

"Convert TypeScript types to GO" right? -- https://app.quicktype.io/#l=Go
Meaning that we should make TypeScript type definitions as individual files, separate their implementations from them. So whenever the types get changed, the Go/Java/Python type definition files can be changed semi-automatically as well.

I believe it will be great if we can have a good design to use the automatic generation from this tool because the wechaty-puppet will be changed in the future frequently, and it will be great if we can be prepared and leave all the work to the machine.

Link to Python: wechaty/python-wechaty#10

[为啥 程序不能从环境变量读取?]

之前我在终端设置过了环境变量,以为 在程序里面设置也可以,但是我刚刚退出程序重新进入才发现,程序里面设置的环境变量压根没有用,我不理解,你们这也太。。。
人都麻了,我不理解,连os.Setenv 都不能读取到吗?
image
image

统计小帮手(statistic genie)

统计小帮手(statistic genie)

  • 群里谁经常踊跃发言,大家一般都会有个直觉。但真要定性定量的出一张排行榜,一般人还做不到。
  • 再者,更重要的问题是,一方面群人满为患,很多人想进进不来,而另一方面,群里却存在着很多自从进群以后就从来没有参与交流过的僵尸用户。

发言排行榜鼓励积极参与者,用沉睡鞭策榜提醒不参与交流的用户,统计小帮手(statistic genie)能帮助群主更加有效的调动群成员的积极参与意识。

名词简介

每一个群成员都有以下(在统计区间内的)重要指数:

指数名称 含义 数据库字段名
贡献指数 发言总字数累计 word_total
爱心指数 发言后又撤回重新修改的总字数累计 correction_total
分享指数 除纯文字以外,任何其他分享的次数累计 share_count
热闹指数 贴表情包图的次数累计(表情包不统计在分享指数之中) ??_count

Plan

I plan to implement this once the go-wechaty project is usable.

This is just a blue-print for now, if anyone has any more interesting idea, please chip in. Feature planned in design phase would much easier than adding them later on when design is done.

Thanks

Planned commands

commands Explanation Plan/Implemented
sg-period set default reporting period from the command line. phase 1
sg-top give 发言排行榜, the top 10 (or 20 or defined value) of most participated users phase 1
sg-warn give 沉睡鞭策榜,the bottom 10 of least participated users, @ them when listing phase 1
sg-kick kick the person(s) given on the command line phase 2
sg-shovel kick bottom 10 of least participated users, @ them before kicking phase 2

Syntax

sg-period days-top [days-warn]

E.g.,

  • sg-period 7 30 means to give statistics of active users for the past week, and least active users for the past 30 days.

On second thought, I might not need this.

sg-top [number [period]]

E.g.,

  • sg-top, or sg-top 10 will give top 10 active users for the past week.
  • sg-top 20 10 will give top 20 active user for the past 10 days.

sg-warn [number [period]]

E.g.,

  • sg-warn or sg-warn 10, will warn the least 10 active users of the past 30 days.

sg-kick reason person [person...]

  • kick the person(s) given on the command line.
  • explain the reason and @ them before kicking.

E.g., sg-kick "group rule violation" @him @her ...

Question(s)

  • I remember it was difficult to get the "group alias" (named used within this group) from weixin API. That will affect the listing of all the lists, as not using the group alias might confuse some people. I don't know what's the situation now.

Design considerations

  • The "贡献指数" is named "word" total in DB, instead of "char" total, is manly for clarification purpose:
    • Each Chinese character will be counted as 1, yet
    • Each English word will be counted as 1, if they show up in the message

Support WECHATY_PUPPET_SERVICE_TOKEN

  1. Add WECHATY_PUPPET_SERVICE_TOKEN support for all our Polyglot Wechaty projects.
  2. Make WECHATY_PUPPET_HOSTIE_TOKEN an alias for WECHATY_PUPPET_SERVICE_TOKEN, and print a warning message to let the user know it was deprecated with it has been set.

Learn more from wechaty/wechaty#2123

[BUG] 客户端运行时报错

客户端运行错误信息:
puppet start err: PuppetService Start() rejection: rpc error: code = Unknown desc = TypeError [ERR_INVALID_ARG_TYPE]: The "listener" argument must be of type function. Received undefined
image
客户端 golang 代码
image

服务端运行错误信息:
image

docker 使用的 lastest 和 next 版本都均会报错
image

GetWechaty().Friendship().Add(member, "") Error

已经在群聊中找到用户ID 但是无法加好友(怀疑是特殊字符串导致)

快速定位

2022/04/16 23:06:32 添加好友失败, 用户名: [Chumo(初墨)]用户ID:[wxid_xxxxxxxxxx], Error: [rpc error: code = Internal desc = [tid:57221f39] request has been cancelled for reason: SERVER_ERROR: 2 UNKNOWN: [tid:57221f39] wechat bad request error]

完整日志

2022/04/16 23:06:21 PuppetService onGrpcStreamEvent({type:EVENT_TYPE_HEARTBEAT payload:{"data":"heartbeat@padlocal"}})
2022/04/16 23:06:31 PuppetService onGrpcStreamEvent({type:EVENT_TYPE_MESSAGE payload:{"messageId":"xxxxxxxxxxxxxxx"}})
2022/04/16 23:06:31 PuppetService MessagePayload(xxxxxxxx))
2022/04/16 23:06:31 PuppetService RoomMemberList(xxxxxxxxxxxxx@chatroom)
2022/04/16 23:06:31 PuppetService ContactRawPayload(wxid_xxxxxxxxxx)
2022/04/16 23:06:31 PuppetService RoomMemberList(xxxxxxxxxxxxx@chatroom)
2022/04/16 23:06:31 PuppetService RoomMemberRawPayload(xxxxxxxxxxxxx@chatroom, wxid_xxxxxxxxxx)
2022/04/16 23:06:31 PuppetService RoomMemberList(xxxxxxxxxxxxx@chatroom)
2022/04/16 23:06:31 PuppetService ContactRawPayload(wxid_xxxxxxxxxx)
2022/04/16 23:06:31 PuppetService RoomMemberList(xxxxxxxxxxxxx@chatroom)
2022/04/16 23:06:31 MentionText:[@可馨 add @Chumo(初墨)六号技师 ]
2022/04/16 23:06:31 PuppetService RoomMemberList(xxxxxxxxxxxxx@chatroom)
2022/04/16 23:06:31 搜索用户名ID成功!
2022/04/16 23:06:31 您与对方不是好友, 正在尝试添加!
2022/04/16 23:06:31 PuppetService FriendshipAdd(wxid_xxxxxxxxxx, 你好,我是可馨,以后请多多关照!)
2022/04/16 23:06:32 添加好友失败, 用户名: [Chumo(初墨)]用户ID:[wxid_xxxxxxxxxx], Error: [rpc error: code = Internal desc = [tid:57221f39] request has been cancelled for reason: SERVER_ERROR: 2 UNKNOWN: [tid:57221f39] wechat bad request error]
2022/04/16 23:06:32 PuppetService messageSendText(xxxxxxxxxxxxx@chatroom, 好友申请失败!)
2022/04/16 23:06:32 PuppetService MessagePayload(xxxxxxxx))
2022/04/16 23:06:32 好友申请失败 通知成功!
2022/04/16 23:06:36 PuppetService onGrpcStreamEvent({type:EVENT_TYPE_HEARTBEAT payload:{"data":"heartbeat@padlocal"}})

代码

log.Printf("MentionText:[%s]", message.MentionText())

if strings.Contains(message.MentionText(), "add") { 			// 添加好友 匹配关键字
	addUserName := strings.Replace(strings.Replace(message.Text(), "\u2005", "", -1), "@可馨add @", "", 1) 	// 去掉特殊符号 再 过滤用户名
	if member, err := message.Room().Member(addUserName); err != nil && member == nil { 										//查找用户的 ID
		log.Printf("搜索用户名ID成功!")
		if message.GetWechaty().Friendship().Load(member.ID()).IsReady() { 				// 判断是否是好友
			log.Printf("已经是好友啦!")
		} else { 			// 不是好友
			log.Printf("您与对方不是好友, 正在尝试添加!")
			if err = message.GetWechaty().Friendship().Add(member, "你好,我是可馨,以后请多多关照!"); err != nil {
				log.Printf("添加好友失败, 用户名: [%s]用户ID:[%s], Error: [%s]", member.Name(), member.ID(), err)
			} else {
					log.Printf("成功发送好友申请!")
				}
			}
		}
	}

写了一篇使用感受,接下来就是细致的优化啦!

这篇文章仅授权 wecahty


关于 wechaty 使用一周的感受与教程

你被骗了!!只有标题和这一句话使用中文,其他的都是英文,请手动点击翻译

Type: Individual user
usage mode: Store messages and manage messages

How to Use

What are you going to do

  1. Make for the company

    1. Recommend to use

      Polyglot TypeScript,JavaScript,Java,Python,Go
      Puppet-providers: Service, PadLocal, Xp, Wechat, Wechat4u

  2. Make it for yourself

    1. Recommend to use

      Polyglot JavaScript,Php,Python,Go
      Puppet-providers: Service, Xp, Wechat, Wechat4u

  3. Eazy to use

    ## Gateway
    cnpm install -g wechaty wechaty-puppet-xp
    wechaty gateway --puppet {WECHATY_PUPPET} --port {WECHATY_PUPPET_SERVER_PORT} --token {WECHATY_PUPPET_SERVICE_TOKEN} --puppet-token {WECHATY_TOKEN}
    
    ## Server
    .......

How to find Problems

  1. Check the issues
  2. Chat with everyone

example:

Network error: https://github.com/wechaty/wechaty/issues?q=network+error
Rpc error: https://github.com/wechaty/go-wechaty/search?q=err%3Arpc+error%3A+code+%3D+Unavailable+desc+%3D+connection&type=issues

How to find Document

Api : Message, Room, Friendship

Polyglot : Go, Java, Python

Puppet Providers : WeChat, XP, WeChat4U

Puppet Services : PadLocal, WXWork

Specifications : Wechaty, Plugin, Puppet, Service, Token, Gateway

Quick start

@gateway

## windows puppet-xp port 30000

cnpm install -g [email protected] wechaty-puppet-xp
@wechaty gateway --puppet wechaty-puppet-xp --port 30000 --token insecure_559c97f1-c6a9-39b0-8f98-288b05f315cd --puppet-token f5c70044-42ea-12ca-ae78-b5ece72dde59

## save to bat

@server

// 1. Viper Get config
// 2. viper.Getstring set Arg (wechaty-puppet-xp)
// 3. Third party robot corpus(tuling123)
// 4. WebHook(Dingding,Telegram)

// >>> config.yaml <<<
BOT:
  CHAT: off
Wechaty:
  WECHATY_PUPPET: wechaty-puppet-xp
...

// >>> main.go <<<
package main
import (
	"github.com/spf13/viper"
	"github.com/wechaty/go-wechaty/wechaty"
  // ...
)
func init() {
	log.SetPrefix("[WechatyBot] ") // 设置日志前缀
	log.SetFlags(log.Ltime | log.Lshortfile)

	success := "[\033[01;32m✓\033[0m] "
	faild := "[\033[01;31m✗\033[0m] "
	info := "[\033[01;33m➜\033[0m] "
	rootPath, _ := os.Getwd()

	viper.Set("rootPath", rootPath)
	//...
	if err = viper.ReadInConfig(); err != nil {
		log.Printf("%v读取配置文件失败%v", os.Getenv("faild"), err)
	} else {
		viper.Set("success", success)
		viper.Set("rootPath", rootPath)
		//...
	}
}

func main() {
	Api.DingBot() // Check the dingding configuration
		var bot = wechaty.NewWechaty(wechaty.WithPuppetOption(wp.Option{
		Token:    viper.GetString("Wechaty.WECHATY_PUPPET_SERVICE_TOKEN"),
		Endpoint: viper.GetString("Wechaty.URL"),
	}))
	// 根据观察,这里不要设置 TOKEN 了,全部用Option吧,少年
        // Token 要填写 WECHATY_PUPPET_SERVICE_TOKEN
	bot.OnScan(onScan).
		OnLogin(onLogin).
		OnLogout(onLogout).
		OnError(onError).
		OnMessage(onMessage).
		OnFriendship(onFriendShip)
	bot.DaemonStart()
}

func onMessage(context *wechaty.Context, message *user.Message) {
	if message.Self() {
		log.Printf("%sBot Chat:%s %s \n", viper.GetString("info"), message.From().Name(), message.Text())
	} else if message.From().ID() == viper.GetString("AdminID") {
		if message.Text() == "chat.off" {
			setEnv("CHAT", "off")
		} else if message.Text() == "chat.on" {
			setEnv("CHAT", "on")
		} else {
			Admin.Admin(context, message)
		}
	} else if message.Room() != nil {
    	if viper.GetString("CHAT") !="off"{
				// Private.Chat(context, message)
				message.Say(TulingBot(message.Text())) // TulingBot use tuling123 api
        log.Printf("%s%s @我了 ta 说: %s, 回复了: %s", viper.GetString("info"), message.From().Name(), message.Text(), reply)
		}
	} else {
		//	如果不是群消息,那就是联系人消息
		if viper.GetString("CHAT") !="off"{
      if string(message.Text())=="在吗?" {
        message.Say("来了老弟!")
      }
		}
	}
}
...............
Auth WrchatID == XRSec_MSG

Debug

  1. I am using the xp protocol and go language, so I need a gateway as support. It seems that the new version of wechaty will automatically determine whether the IP of the gateway and the server is equal to the IP of the same exit. If they are equal, there is no need to open the port, and no public IP is required
  2. The new version requires TLS encryption, if you need to cancel encryption, please set WECHATY_PUPPET_SERVICE_NO_TLS_INSECURE_SERVER=true parameter @environment

XRSec has the right to modify and interpret this article. If you want to reprint or disseminate this article, you must ensure the integrity of this article, including all contents such as copyright notice. Without the permission of the author, the content of this article shall not be modified or increased or decreased arbitrarily, and it shall not be used for commercial purposes in any way

contact.alias() 拆分为 get 和 set

在 ts 版本中:

  • alias() 代表 get
  • alias(newAlias) 代表 set
  • alias(null) 代表 delete

但是在 go 语言里边参数是必传的,所以我准备把 alias 拆分为两个方法。

  • GetAlias() 代表 get
  • SetAlias("newAlias") 代表 set
  • SetAlias("") 代表 delete

这样做是否可以? @huan

Abstract Class design pattern in Go

Questions from WIP: add user/message.go #4

Q3

Q3: In my understanding, Puppet should be an interface definition, different protocols to implement different classes, but some methods of Puppet have logic, and they cannot have logic in Go's interface definition. I don't know what to do.

Sorry, maybe my understanding of wechaty and wechat-puppet is too simple, and I may need to read and understand them as a whole.

If I'm understanding correctly, our problem is the Go Lang does not permit an abstract class to have any implementation in it?

Please feel free to correct me if I'm wrong.

To be updated... I'm going to study Go now...

Updated Links

Suggest to stop auto rewriting code in the PR

Currently, we are doing a code rewrite and commit automatically in every PR:

github-actions bot commented 24 minutes ago
🚀 Your go files have been formatted successfully

I'd like to change this behavior from rewrite automatically to throw a failure via CI if the code has not been formatted as expected, which can leave the responsibility of the code formatting to the PR author.

Another benefit after this change is that we can also keep our contributor record clean because it can prevent lots of unnecessary commits.

升级 v0.4.x 注意事项

从低版本升级到 v0.4.x 的注意事项

  • go-wecahty v0.4.x 可以搭配镜像 wechaty/wechaty:0.78 或 wechaty/wechaty:1.19+ 使用
  • 优化了 filebox 设计,修改了 filebox 一些方法的签名,如果升级后编译不通过,不要惊慌,根据编译器提示更改即可(0.x版本非最终确定版本,所以随着使用会重构掉之前不合理的设计)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.