Fixed documentation references to some non-existing events.

This commit is contained in:
Fabio Manganiello 2023-09-17 02:41:55 +02:00
parent 0421325b26
commit 190cfa21b5
Signed by untrusted user: blacklight
GPG key ID: D90FBA7F76362774
6 changed files with 128 additions and 65 deletions

View file

@ -4,9 +4,17 @@ from typing import Type, Optional, Union, List
from platypush.backend import Backend from platypush.backend import Backend
from platypush.context import get_plugin from platypush.context import get_plugin
from platypush.message.event.chat.telegram import MessageEvent, CommandMessageEvent, TextMessageEvent, \ from platypush.message.event.chat.telegram import (
PhotoMessageEvent, VideoMessageEvent, ContactMessageEvent, DocumentMessageEvent, LocationMessageEvent, \ MessageEvent,
GroupChatCreatedEvent CommandMessageEvent,
TextMessageEvent,
PhotoMessageEvent,
VideoMessageEvent,
ContactMessageEvent,
DocumentMessageEvent,
LocationMessageEvent,
GroupChatCreatedEvent,
)
from platypush.plugins.chat.telegram import ChatTelegramPlugin from platypush.plugins.chat.telegram import ChatTelegramPlugin
@ -23,7 +31,7 @@ class ChatTelegramBackend(Backend):
* :class:`platypush.message.event.chat.telegram.ContactMessageEvent` when a contact is received. * :class:`platypush.message.event.chat.telegram.ContactMessageEvent` when a contact is received.
* :class:`platypush.message.event.chat.telegram.DocumentMessageEvent` when a document is received. * :class:`platypush.message.event.chat.telegram.DocumentMessageEvent` when a document is received.
* :class:`platypush.message.event.chat.telegram.CommandMessageEvent` when a command message is received. * :class:`platypush.message.event.chat.telegram.CommandMessageEvent` when a command message is received.
* :class:`platypush.message.event.chat.telegram.GroupCreatedEvent` when the bot is invited to a new group. * :class:`platypush.message.event.chat.telegram.GroupChatCreatedEvent` when the bot is invited to a new group.
Requires: Requires:
@ -31,7 +39,9 @@ class ChatTelegramBackend(Backend):
""" """
def __init__(self, authorized_chat_ids: Optional[List[Union[str, int]]] = None, **kwargs): def __init__(
self, authorized_chat_ids: Optional[List[Union[str, int]]] = None, **kwargs
):
""" """
:param authorized_chat_ids: Optional list of chat_id/user_id which are authorized to send messages to :param authorized_chat_ids: Optional list of chat_id/user_id which are authorized to send messages to
the bot. If nothing is specified then no restrictions are applied. the bot. If nothing is specified then no restrictions are applied.
@ -39,40 +49,52 @@ class ChatTelegramBackend(Backend):
super().__init__(**kwargs) super().__init__(**kwargs)
self.authorized_chat_ids = set(authorized_chat_ids or []) self.authorized_chat_ids = set(authorized_chat_ids or [])
self._plugin: ChatTelegramPlugin = get_plugin('chat.telegram') self._plugin: ChatTelegramPlugin = get_plugin('chat.telegram') # type: ignore
def _authorize(self, msg): def _authorize(self, msg):
if not self.authorized_chat_ids: if not self.authorized_chat_ids:
return return
if msg.chat.type == 'private' and msg.chat.id not in self.authorized_chat_ids: if msg.chat.type == 'private' and msg.chat.id not in self.authorized_chat_ids:
self.logger.info('Received message from unauthorized chat_id {}'.format(msg.chat.id)) self.logger.info(
self._plugin.send_message(chat_id=msg.chat.id, text='You are not allowed to send messages to this bot') 'Received message from unauthorized chat_id %s', msg.chat.id
)
self._plugin.send_message(
chat_id=msg.chat.id,
text='You are not allowed to send messages to this bot',
)
raise PermissionError raise PermissionError
def _msg_hook(self, cls: Type[MessageEvent]): def _msg_hook(self, cls: Type[MessageEvent]):
# noinspection PyUnusedLocal # noinspection PyUnusedLocal
def hook(update, context): def hook(update, _):
msg = update.effective_message msg = update.effective_message
try: try:
self._authorize(msg) self._authorize(msg)
self.bus.post(cls(chat_id=update.effective_chat.id, self.bus.post(
cls(
chat_id=update.effective_chat.id,
message=self._plugin.parse_msg(msg).output, message=self._plugin.parse_msg(msg).output,
user=self._plugin.parse_user(update.effective_user).output)) user=self._plugin.parse_user(update.effective_user).output,
)
)
except PermissionError: except PermissionError:
pass pass
return hook return hook
def _group_hook(self): def _group_hook(self):
# noinspection PyUnusedLocal
def hook(update, context): def hook(update, context):
msg = update.effective_message msg = update.effective_message
if msg.group_chat_created: if msg.group_chat_created:
self.bus.post(GroupChatCreatedEvent(chat_id=update.effective_chat.id, self.bus.post(
GroupChatCreatedEvent(
chat_id=update.effective_chat.id,
message=self._plugin.parse_msg(msg).output, message=self._plugin.parse_msg(msg).output,
user=self._plugin.parse_user(update.effective_user).output)) user=self._plugin.parse_user(update.effective_user).output,
)
)
elif msg.photo: elif msg.photo:
self._msg_hook(PhotoMessageEvent)(update, context) self._msg_hook(PhotoMessageEvent)(update, context)
elif msg.video: elif msg.video:
@ -92,27 +114,33 @@ class ChatTelegramBackend(Backend):
return hook return hook
def _command_hook(self): def _command_hook(self):
# noinspection PyUnusedLocal def hook(update, _):
def hook(update, context):
msg = update.effective_message msg = update.effective_message
m = re.match('\s*/([0-9a-zA-Z_-]+)\s*(.*)', msg.text) m = re.match(r'\s*/([0-9a-zA-Z_-]+)\s*(.*)', msg.text)
if not m:
self.logger.warning('Invalid command: %s', msg.text)
return
cmd = m.group(1).lower() cmd = m.group(1).lower()
args = [arg for arg in re.split('\s+', m.group(2)) if len(arg)] args = [arg for arg in re.split(r'\s+', m.group(2)) if len(arg)]
try: try:
self._authorize(msg) self._authorize(msg)
self.bus.post(CommandMessageEvent(chat_id=update.effective_chat.id, self.bus.post(
CommandMessageEvent(
chat_id=update.effective_chat.id,
command=cmd, command=cmd,
cmdargs=args, cmdargs=args,
message=self._plugin.parse_msg(msg).output, message=self._plugin.parse_msg(msg).output,
user=self._plugin.parse_user(update.effective_user).output)) user=self._plugin.parse_user(update.effective_user).output,
)
)
except PermissionError: except PermissionError:
pass pass
return hook return hook
def run(self): def run(self):
# noinspection PyPackageRequirements
from telegram.ext import MessageHandler, Filters from telegram.ext import MessageHandler, Filters
super().run() super().run()
@ -120,12 +148,24 @@ class ChatTelegramBackend(Backend):
dispatcher = telegram.dispatcher dispatcher = telegram.dispatcher
dispatcher.add_handler(MessageHandler(Filters.group, self._group_hook())) dispatcher.add_handler(MessageHandler(Filters.group, self._group_hook()))
dispatcher.add_handler(MessageHandler(Filters.text, self._msg_hook(TextMessageEvent))) dispatcher.add_handler(
dispatcher.add_handler(MessageHandler(Filters.photo, self._msg_hook(PhotoMessageEvent))) MessageHandler(Filters.text, self._msg_hook(TextMessageEvent))
dispatcher.add_handler(MessageHandler(Filters.video, self._msg_hook(VideoMessageEvent))) )
dispatcher.add_handler(MessageHandler(Filters.contact, self._msg_hook(ContactMessageEvent))) dispatcher.add_handler(
dispatcher.add_handler(MessageHandler(Filters.location, self._msg_hook(LocationMessageEvent))) MessageHandler(Filters.photo, self._msg_hook(PhotoMessageEvent))
dispatcher.add_handler(MessageHandler(Filters.document, self._msg_hook(DocumentMessageEvent))) )
dispatcher.add_handler(
MessageHandler(Filters.video, self._msg_hook(VideoMessageEvent))
)
dispatcher.add_handler(
MessageHandler(Filters.contact, self._msg_hook(ContactMessageEvent))
)
dispatcher.add_handler(
MessageHandler(Filters.location, self._msg_hook(LocationMessageEvent))
)
dispatcher.add_handler(
MessageHandler(Filters.document, self._msg_hook(DocumentMessageEvent))
)
dispatcher.add_handler(MessageHandler(Filters.command, self._command_hook())) dispatcher.add_handler(MessageHandler(Filters.command, self._command_hook()))
self.logger.info('Initialized Telegram backend') self.logger.info('Initialized Telegram backend')

View file

@ -5,7 +5,7 @@ manifest:
platypush.message.event.chat.telegram.ContactMessageEvent: when a contact is received. platypush.message.event.chat.telegram.ContactMessageEvent: when a contact is received.
platypush.message.event.chat.telegram.DocumentMessageEvent: when a document is platypush.message.event.chat.telegram.DocumentMessageEvent: when a document is
received. received.
platypush.message.event.chat.telegram.GroupCreatedEvent: when the bot is invited platypush.message.event.chat.telegram.GroupChatCreatedEvent: when the bot is invited
to a new group. to a new group.
platypush.message.event.chat.telegram.LocationMessageEvent: when a location is platypush.message.event.chat.telegram.LocationMessageEvent: when a location is
received. received.

View file

@ -6,8 +6,12 @@ from websocket import WebSocketApp
from platypush.backend import Backend from platypush.backend import Backend
from platypush.context import get_plugin from platypush.context import get_plugin
from platypush.message.event.trello import MoveCardEvent, NewCardEvent, ArchivedCardEvent, \ from platypush.message.event.trello import (
UnarchivedCardEvent MoveCardEvent,
NewCardEvent,
ArchivedCardEvent,
UnarchivedCardEvent,
)
from platypush.plugins.trello import TrelloPlugin from platypush.plugins.trello import TrelloPlugin
@ -33,9 +37,9 @@ class TrelloBackend(Backend):
Triggers: Triggers:
* :class:`platypush.message.event.trello.NewCardEvent` when a card is created. * :class:`platypush.message.event.trello.NewCardEvent` when a card is created.
* :class:`platypush.message.event.MoveCardEvent` when a card is moved. * :class:`platypush.message.event.trello.MoveCardEvent` when a card is moved.
* :class:`platypush.message.event.ArchivedCardEvent` when a card is archived/closed. * :class:`platypush.message.event.trello.ArchivedCardEvent` when a card is archived/closed.
* :class:`platypush.message.event.UnarchivedCardEvent` when a card is un-archived/opened. * :class:`platypush.message.event.trello.UnarchivedCardEvent` when a card is un-archived/opened.
""" """
@ -69,21 +73,26 @@ class TrelloBackend(Backend):
def _initialize_connection(self, ws: WebSocketApp): def _initialize_connection(self, ws: WebSocketApp):
for board_id in self._boards_by_id.keys(): for board_id in self._boards_by_id.keys():
self._send(ws, { self._send(
ws,
{
'type': 'subscribe', 'type': 'subscribe',
'modelType': 'Board', 'modelType': 'Board',
'idModel': board_id, 'idModel': board_id,
'tags': ['clientActions', 'updates'], 'tags': ['clientActions', 'updates'],
'invitationTokens': [], 'invitationTokens': [],
}) },
)
self.logger.info('Trello boards subscribed') self.logger.info('Trello boards subscribed')
def _on_msg(self): def _on_msg(self):
def hndl(*args): def hndl(*args):
if len(args) < 2: if len(args) < 2:
self.logger.warning('Missing websocket argument - make sure that you are using ' self.logger.warning(
'a version of websocket-client < 0.53.0 or >= 0.58.0') 'Missing websocket argument - make sure that you are using '
'a version of websocket-client < 0.53.0 or >= 0.58.0'
)
return return
ws, msg = args[:2] ws, msg = args[:2]
@ -96,7 +105,9 @@ class TrelloBackend(Backend):
try: try:
msg = json.loads(msg) msg = json.loads(msg)
except Exception as e: except Exception as e:
self.logger.warning('Received invalid JSON message from Trello: {}: {}'.format(msg, e)) self.logger.warning(
'Received invalid JSON message from Trello: {}: {}'.format(msg, e)
)
return return
if 'error' in msg: if 'error' in msg:
@ -119,8 +130,12 @@ class TrelloBackend(Backend):
args = { args = {
'card_id': delta['data']['card']['id'], 'card_id': delta['data']['card']['id'],
'card_name': delta['data']['card']['name'], 'card_name': delta['data']['card']['name'],
'list_id': (delta['data'].get('list') or delta['data'].get('listAfter', {})).get('id'), 'list_id': (
'list_name': (delta['data'].get('list') or delta['data'].get('listAfter', {})).get('name'), delta['data'].get('list') or delta['data'].get('listAfter', {})
).get('id'),
'list_name': (
delta['data'].get('list') or delta['data'].get('listAfter', {})
).get('name'),
'board_id': delta['data']['board']['id'], 'board_id': delta['data']['board']['id'],
'board_name': delta['data']['board']['name'], 'board_name': delta['data']['board']['name'],
'closed': delta.get('closed'), 'closed': delta.get('closed'),
@ -134,14 +149,20 @@ class TrelloBackend(Backend):
self.bus.post(NewCardEvent(**args)) self.bus.post(NewCardEvent(**args))
elif delta.get('type') == 'updateCard': elif delta.get('type') == 'updateCard':
if 'listBefore' in delta['data']: if 'listBefore' in delta['data']:
args.update({ args.update(
{
'old_list_id': delta['data']['listBefore']['id'], 'old_list_id': delta['data']['listBefore']['id'],
'old_list_name': delta['data']['listBefore']['name'], 'old_list_name': delta['data']['listBefore']['name'],
}) }
)
self.bus.post(MoveCardEvent(**args)) self.bus.post(MoveCardEvent(**args))
elif 'closed' in delta['data'].get('old', {}): elif 'closed' in delta['data'].get('old', {}):
cls = UnarchivedCardEvent if delta['data']['old']['closed'] else ArchivedCardEvent cls = (
UnarchivedCardEvent
if delta['data']['old']['closed']
else ArchivedCardEvent
)
self.bus.post(cls(**args)) self.bus.post(cls(**args))
return hndl return hndl
@ -185,11 +206,13 @@ class TrelloBackend(Backend):
self._req_id += 1 self._req_id += 1
def _connect(self) -> WebSocketApp: def _connect(self) -> WebSocketApp:
return WebSocketApp(self.url, return WebSocketApp(
self.url,
on_open=self._on_open(), on_open=self._on_open(),
on_message=self._on_msg(), on_message=self._on_msg(),
on_error=self._on_error(), on_error=self._on_error(),
on_close=self._on_close()) on_close=self._on_close(),
)
def run(self): def run(self):
super().run() super().run()

View file

@ -1,8 +1,8 @@
manifest: manifest:
events: events:
platypush.message.event.ArchivedCardEvent: when a card is archived/closed. platypush.message.event.trello.ArchivedCardEvent: when a card is archived/closed.
platypush.message.event.MoveCardEvent: when a card is moved. platypush.message.event.trello.MoveCardEvent: when a card is moved.
platypush.message.event.UnarchivedCardEvent: when a card is un-archived/opened. platypush.message.event.trello.UnarchivedCardEvent: when a card is un-archived/opened.
platypush.message.event.trello.NewCardEvent: when a card is created. platypush.message.event.trello.NewCardEvent: when a card is created.
install: install:
pip: [] pip: []

View file

@ -15,7 +15,7 @@ class WiimoteBackend(Backend):
Triggers: Triggers:
* :class:`platypush.message.event.Wiimote.WiimoteEvent` \ * :class:`platypush.message.event.wiimote.WiimoteEvent` \
when the state of the Wiimote (battery, buttons, acceleration etc.) changes when the state of the Wiimote (battery, buttons, acceleration etc.) changes
Requires: Requires:

View file

@ -1,6 +1,6 @@
manifest: manifest:
events: events:
platypush.message.event.Wiimote.WiimoteEvent: when the state of the Wiimote (battery, platypush.message.event.wiimote.WiimoteEvent: when the state of the Wiimote (battery,
buttons, acceleration etc.) changes buttons, acceleration etc.) changes
install: install:
pip: [] pip: []