Skip to content

add friendship & scheduler bot #11

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 28, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 19 additions & 5 deletions examples/advanced/busy-bot.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,28 @@
"""doc"""
# pylint: disable=R0801
"""
Python Wechaty - https://github.com/wechaty/python-wechaty
Authors: Huan LI (李卓桓) <https://github.com/huan>
Jingjing WU (吴京京) <https://github.com/wj-Mcat>
2020 @ Copyright Wechaty Contributors <https://github.com/wechaty>
Licensed under the Apache License, Version 2.0 (the 'License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an 'AS IS' BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import asyncio
import logging
from typing import Optional

# waiting for wechaty-puppet new version
from wechaty_puppet import ScanStatus # type: ignore

from wechaty import Wechaty, Contact
from wechaty.user import Message
from wechaty import (
Wechaty, Contact, Message
)

logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)
Expand Down Expand Up @@ -62,7 +77,6 @@ async def on_scan(self, status: ScanStatus, qr_code: Optional[str] = None,

async def main():
"""doc"""
# pylint: disable=W0603
global bot
bot = MyBot()
await bot.start()
Expand Down
87 changes: 87 additions & 0 deletions examples/advanced/friendship-bot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
"""
Python Wechaty - https://github.com/wechaty/python-wechaty
Authors: Huan LI (李卓桓) <https://github.com/huan>
Jingjing WU (吴京京) <https://github.com/wj-Mcat>
2020 @ Copyright Wechaty Contributors <https://github.com/wechaty>
Licensed under the Apache License, Version 2.0 (the 'License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an 'AS IS' BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import os
import asyncio
from typing import Optional

from wechaty import (
Wechaty, Contact, Friendship, FriendshipType
)


class MyBot(Wechaty):
"""
listen wechaty event with inherited functions, which is more friendly for
oop developer
"""
def __init__(self):
super().__init__()
self.busy = False
self.auto_reply_comment = "Automatic Reply: I cannot read your message because I'm busy now, will talk to you when I get back."

async def on_friendship(self, friendship: Friendship):
administrator = bot.Contact.load('admin-id')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can we define a admin-id as a global variable? Then it is easier to understand.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

local variable or global variable pattern depends on the developers. Even admin-id from database is all supported. This is the only contact-id string here. I believe it's easier to understand.

await administrator.ready()

contact = friendship.contact()
await contact.ready()

log_msg = f'receive "friendship" message from {contact.name}'
await administrator.say(log_msg)

if friendship.type() == FriendshipType.FRIENDSHIP_TYPE_RECEIVE:
if friendship.hello() == 'ding':
log_msg = 'accepted automatically because verify messsage is "ding"'
print('before accept ...')
await friendship.accept()
# if want to send msg, you need to delay sometimes

print('waiting to send message ...')
await asyncio.sleep(3)
await contact.say('hello from wechaty ...')
print('after accept ...')
else:
log_msg = 'not auto accepted, because verify message is: ' + friendship.hello()

elif friendship.type() == FriendshipType.FRIENDSHIP_TYPE_CONFIRM:
log_msg = 'friend ship confirmed with ' + contact.name

print(log_msg)
await administrator.say(log_msg)

async def on_login(self, contact: Contact):
print(f'user: {contact} has login')


bot: Optional[MyBot] = None


async def main():
"""Async Main Entry"""
if 'WECHATY_PUPPET_HOSTIE_TOKEN' not in os.environ:
print('''
Error: WECHATY_PUPPET_HOSTIE_TOKEN is not found in the environment variables
You need a TOKEN to run the Java Wechaty. Please goto our README for details
https://github.com/wechaty/python-wechaty-getting-started/#wechaty_puppet_hostie_token
''')

global bot
bot = MyBot()
await bot.start()


asyncio.run(main())

49 changes: 30 additions & 19 deletions examples/advanced/scheduler-bot.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,27 @@
"""doc"""
# pylint: disable=R0801
"""
Python Wechaty - https://github.com/wechaty/python-wechaty
Authors: Huan LI (李卓桓) <https://github.com/huan>
Jingjing WU (吴京京) <https://github.com/wj-Mcat>
2020 @ Copyright Wechaty Contributors <https://github.com/wechaty>
Licensed under the Apache License, Version 2.0 (the 'License');
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an 'AS IS' BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import os
import asyncio
import logging
from typing import Optional, Union

from wechaty_puppet import ScanStatus # type: ignore

from wechaty import Wechaty, Contact, Room
from wechaty.user import Message

from apscheduler.schedulers.asyncio import AsyncIOScheduler

logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)


class MyBot(Wechaty):
"""
Expand All @@ -25,7 +33,7 @@ def __init__(self):
self.busy = False
self.auto_reply_comment = "Automatic Reply: I cannot read your message because I'm busy now, will talk to you when I get back."

async def message(msg: Message):
async def message(self, msg: Message):
"""back on message"""
from_contact = msg.talker()
text = msg.text()
Expand All @@ -39,27 +47,30 @@ async def message(msg: Message):
async def on_login(self, contact: Contact):
print(f'user: {contact} has login')

async def on_scan(self, status: ScanStatus, qr_code: Optional[str] = None,
data: Optional[str] = None):
contact = self.Contact.load(self.contact_id)
print(f'user <{contact}> scan status: {status.name} , '
f'qr_code: {qr_code}')


bot: Optional[MyBot] = None


async def tick(bot: Wechaty):
"""
find a specific room, and say something to it.
"""
room = bot.Room.load('room-id')
await room.ready()
from datetime import datetime
await room.say(f'say ding automatically, {datetime.now()}')
await room.say('ding')
await room.say(f'it"s a new day, let"s welcome, now it"s {datetime.now()}')
await room.say('hello world !')


async def main():
"""doc"""
# pylint: disable=W0603
"""Async Main Entry"""
if 'WECHATY_PUPPET_HOSTIE_TOKEN' not in os.environ:
print('''
Error: WECHATY_PUPPET_HOSTIE_TOKEN is not found in the environment variables
You need a TOKEN to run the Java Wechaty. Please goto our README for details
https://github.com/wechaty/python-wechaty-getting-started/#wechaty_puppet_hostie_token
''')

global bot
bot = MyBot()

Expand Down