Skip to content

add gitlab event plugin & make CI green #2

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 12 commits into from
Dec 2, 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
22 changes: 16 additions & 6 deletions .github/workflows/pypi.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,37 +16,47 @@ jobs:

steps:
- uses: actions/checkout@v2
- name: Set up Python 3.8
- name: Set up Python 3.7
uses: actions/setup-python@v2
with:
python-version: 3.8
python-version: 3.7
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install flake8 pytest
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
if [ -f requirements-dev.txt ]; then pip install -r requirements-dev.txt; fi

- name: run test
run:
run:
make test

deploy:

deploy:
if: github.event_name == 'push' && (github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/heads/v'))
runs-on: ubuntu-latest
needs: [build]

steps:
- uses: actions/checkout@v2

- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: '3.x'

- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install setuptools wheel twine
- name: Check Branch
id: check-branch
run: |
if [[ ${{ github.ref }} =~ ^refs/heads/(master|v[0-9]+\.[0-9]+.*)$ ]]; then
echo ::set-output name=match::true
fi # See: https://stackoverflow.com/a/58869470/1123955

- name: Build and publish
if: steps.check-branch.outputs.match == 'true'
env:
TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }}
TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }}
Expand Down
Empty file added Dockerfile
Empty file.
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.0.1
0.0.3
24 changes: 12 additions & 12 deletions examples/daily_plugin_bot.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
"""daily plugin bot examples"""
import asyncio
from datetime import datetime

from wechaty import Wechaty # type: ignore
from wechaty_puppet import RoomQueryFilter # type: ignore

from wechaty_plugin_contrib.daily_plugin import DailyPluginOptions, DailyPlugin
from wechaty_plugin_contrib.ding_dong_plugin import DingDongPlugin


async def say_hello(bot: Wechaty):
"""say hello to the room"""
room = await bot.Room.find(query=RoomQueryFilter(topic='小群,小群1'))
if room:
await room.say(f'hello bupt ... {datetime.now()}')


async def run():
"""async run method"""
morning_plugin = DailyPlugin(DailyPluginOptions(
Expand All @@ -18,21 +28,11 @@ async def run():
},
msg='宝贝,早安,爱你哟~'
))

eating_plugin = DailyPlugin(DailyPluginOptions(
name='girl-friend-bot-eating',
contact_id='some-one-id',
trigger='cron',
kwargs={
'hour': 11,
'minute': 30
},
msg='中午要记得好好吃饭喔~'
))
morning_plugin.add_interval_job(say_hello)

ding_dong_plugin = DingDongPlugin()

bot = Wechaty().use(morning_plugin).use(eating_plugin).use(ding_dong_plugin)
bot = Wechaty().use(morning_plugin).use(ding_dong_plugin)
await bot.start()

asyncio.run(run())
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
wechaty>=0.5.dev1
jieba
aiohttp
11 changes: 9 additions & 2 deletions src/wechaty_plugin_contrib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,20 @@
DailyPluginOptions,
DailyPlugin
)
from wechaty_plugin_contrib.messager_plugin import MessagerPlugin

from wechaty_plugin_contrib.contrib import (
AutoReplyRule,
AutoReplyOptions,
AutoReplyPlugin
)

__all__ = [
'DingDongPlugin',

'DailyPluginOptions',
'DailyPlugin',

'MessagerPlugin'
'AutoReplyRule',
'AutoReplyOptions',
'AutoReplyPlugin'
]
24 changes: 24 additions & 0 deletions src/wechaty_plugin_contrib/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""import basic config from wechaty-puppet"""

from wechaty import ( # type: ignore
Room,
Contact,
Message,

Wechaty
)

from wechaty_puppet import get_logger # type: ignore

from .version import version

__all__ = [
'get_logger',
'version',

'Room',
'Contact',
'Message',

'Wechaty'
]
11 changes: 11 additions & 0 deletions src/wechaty_plugin_contrib/contrib/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from .auto_reply_plugin import (
AutoReplyRule,
AutoReplyOptions,
AutoReplyPlugin
)

__all__ = [
'AutoReplyOptions',
'AutoReplyPlugin',
'AutoReplyRule'
]
11 changes: 11 additions & 0 deletions src/wechaty_plugin_contrib/contrib/auto_reply_plugin/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from .plugin import (
AutoReplyRule,
AutoReplyOptions,
AutoReplyPlugin
)

__all__ = [
'AutoReplyOptions',
'AutoReplyPlugin',
'AutoReplyRule'
]
53 changes: 53 additions & 0 deletions src/wechaty_plugin_contrib/contrib/auto_reply_plugin/plugin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"""AutoReply to someone according to keywords"""
from dataclasses import dataclass, field
from typing import Union, List, Dict

from wechaty import ( # type: ignore
WechatyPlugin,
WechatyPluginOptions,
FileBox,
Contact,
Message
)

from wechaty_puppet import ( # type: ignore
get_logger
)


@dataclass
class AutoReplyRule:
keyword: str
reply_content: Union[str, FileBox, Contact]


@dataclass
class AutoReplyOptions(WechatyPluginOptions):
rules: List[AutoReplyRule] = field(default_factory=list)


logger = get_logger('AutoReplyPlugin')


class AutoReplyPlugin(WechatyPlugin):

def __init__(self, options: AutoReplyOptions):
super().__init__(options)

self.rule_map: Dict[str, AutoReplyRule] = {}
if options.rules:
self.rule_map = {rule.keyword: rule for rule in options.rules}

async def on_message(self, msg: Message):
"""check the keyword and reply to talker"""
text = msg.text()

if text in self.rule_map:
room = msg.room()
if room:
await room.ready()
await room.say(self.rule_map[text])
else:
talker = msg.talker()
await talker.ready()
await talker.say(self.rule_map[text])
27 changes: 21 additions & 6 deletions src/wechaty_plugin_contrib/daily_plugin.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
"""daily plugin"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Optional, Union
from typing import Optional, Union, List, Any

from apscheduler.schedulers.asyncio import AsyncIOScheduler # type: ignore
from apscheduler.schedulers.base import BaseScheduler # type: ignore

from wechaty import Wechaty, get_logger, Room, Contact # type: ignore
from wechaty.plugin import WechatyPlugin, WechatyPluginOptions # type: ignore
Expand Down Expand Up @@ -42,6 +43,8 @@ def __init__(self, options: DailyPluginOptions):
raise Exception('msg should not be none')

self.options: DailyPluginOptions = options
self.scheduler: BaseScheduler = AsyncIOScheduler()
self._scheduler_jobs: List[Any] = []

@property
def name(self) -> str:
Expand All @@ -67,8 +70,20 @@ async def tick(self, msg: str):
async def init_plugin(self, wechaty: Wechaty):
"""init plugin"""
await super().init_plugin(wechaty)
scheduler = AsyncIOScheduler()
scheduler.add_job(self.tick, self.options.trigger,
kwargs={'msg': self.options.msg},
**self.options.kwargs)
scheduler.start()
for job in self._scheduler_jobs:
job(wechaty)
self.scheduler.start()

def add_interval_job(self, func):
"""add interval job"""

def add_job(bot: Wechaty):
self.scheduler.add_job(
func,
trigger='interval',
seconds=5,
kwargs={
'bot': bot
}
)
self._scheduler_jobs.append(add_job)
13 changes: 6 additions & 7 deletions src/wechaty_plugin_contrib/ding_dong_plugin.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""basic ding-dong bot for the wechaty plugin"""
from typing import Union, Optional, List
from dataclasses import dataclass
from typing import List, Union
from dataclasses import dataclass, field
from wechaty import Message, Contact, Room, get_logger # type: ignore
from wechaty.plugin import WechatyPlugin, WechatyPluginOptions # type: ignore

Expand All @@ -15,13 +15,13 @@ class DingDongPluginOptions(WechatyPluginOptions):

only one of [include_conversation_ids,exclude_conversation_ids] can be empty
"""
include_conversation_ids: Optional[List[str]] = None
exclude_conversation_ids: Optional[List[str]] = None
include_conversation_ids: List[str] = field(default_factory=list)
exclude_conversation_ids: List[str] = field(default_factory=list)


class DingDongPlugin(WechatyPlugin):
"""basic ding-dong plugin"""
def __init__(self, options: Optional[DingDongPluginOptions] = None):
def __init__(self, options: DingDongPluginOptions = None):
super().__init__(options)

if options is not None:
Expand Down Expand Up @@ -59,8 +59,7 @@ async def on_message(self, msg: Message):
text = msg.text()
room = msg.room()
if text == '#ding':
conversation: Union[
Room, Contact] = from_contact if room is None else room
conversation: Union[Room, Contact] = from_contact if room is None else room
conversation_id = from_contact.contact_id if room is None \
else room.room_id
if self.can_send_dong(conversation_id):
Expand Down
Empty file.
56 changes: 56 additions & 0 deletions src/wechaty_plugin_contrib/finders/contact_finder.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
"""Message Finder to match the specific message"""
import re
from re import Pattern
import inspect
from typing import List

from wechaty_plugin_contrib.config import (
get_logger,
Contact,
Wechaty
)

from .finder import Finder


logger = get_logger("MessageFinder")


class MessageFinder(Finder):
async def match(self, wechaty: Wechaty) -> List[Contact]:
"""match the room"""
logger.info(f'MessageFinder match({Wechaty})')

contacts: List[Contact] = []

for option in self.options:
if isinstance(option, Pattern):

# search from all of the friends
re_pattern = re.compile(option)
# match the room with regex pattern
all_friends = await wechaty.Contact.find_all()
for friend in all_friends:
alias = await friend.alias()
if re.match(re_pattern, friend.name) or re.match(re_pattern, alias):
contacts.append(friend)

elif isinstance(option, str):
contact = wechaty.Contact.load(option)
await contact.ready()
contacts.append(contact)
elif hasattr(option, '__call__'):
"""check the type of the function
refer: https://stackoverflow.com/a/56240578/6894382
"""
if inspect.iscoroutinefunction(option):
# pytype: disable=bad-return-type
targets = await option(wechaty)
else:
targets = option(wechaty)

if isinstance(targets, List[Contact]):
contacts.extend(targets)
else:
raise ValueError(f'unknown type option: {option}')
return contacts
Loading