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: 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.context import get_plugin
from platypush.message.event.chat.telegram import MessageEvent, CommandMessageEvent, TextMessageEvent, \
PhotoMessageEvent, VideoMessageEvent, ContactMessageEvent, DocumentMessageEvent, LocationMessageEvent, \
GroupChatCreatedEvent
from platypush.message.event.chat.telegram import (
MessageEvent,
CommandMessageEvent,
TextMessageEvent,
PhotoMessageEvent,
VideoMessageEvent,
ContactMessageEvent,
DocumentMessageEvent,
LocationMessageEvent,
GroupChatCreatedEvent,
)
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.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.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:
@ -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
the bot. If nothing is specified then no restrictions are applied.
@ -39,40 +49,52 @@ class ChatTelegramBackend(Backend):
super().__init__(**kwargs)
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):
if not self.authorized_chat_ids:
return
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._plugin.send_message(chat_id=msg.chat.id, text='You are not allowed to send messages to this bot')
self.logger.info(
'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
def _msg_hook(self, cls: Type[MessageEvent]):
# noinspection PyUnusedLocal
def hook(update, context):
def hook(update, _):
msg = update.effective_message
try:
self._authorize(msg)
self.bus.post(cls(chat_id=update.effective_chat.id,
message=self._plugin.parse_msg(msg).output,
user=self._plugin.parse_user(update.effective_user).output))
self.bus.post(
cls(
chat_id=update.effective_chat.id,
message=self._plugin.parse_msg(msg).output,
user=self._plugin.parse_user(update.effective_user).output,
)
)
except PermissionError:
pass
return hook
def _group_hook(self):
# noinspection PyUnusedLocal
def hook(update, context):
msg = update.effective_message
if msg.group_chat_created:
self.bus.post(GroupChatCreatedEvent(chat_id=update.effective_chat.id,
message=self._plugin.parse_msg(msg).output,
user=self._plugin.parse_user(update.effective_user).output))
self.bus.post(
GroupChatCreatedEvent(
chat_id=update.effective_chat.id,
message=self._plugin.parse_msg(msg).output,
user=self._plugin.parse_user(update.effective_user).output,
)
)
elif msg.photo:
self._msg_hook(PhotoMessageEvent)(update, context)
elif msg.video:
@ -92,27 +114,33 @@ class ChatTelegramBackend(Backend):
return hook
def _command_hook(self):
# noinspection PyUnusedLocal
def hook(update, context):
def hook(update, _):
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()
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:
self._authorize(msg)
self.bus.post(CommandMessageEvent(chat_id=update.effective_chat.id,
command=cmd,
cmdargs=args,
message=self._plugin.parse_msg(msg).output,
user=self._plugin.parse_user(update.effective_user).output))
self.bus.post(
CommandMessageEvent(
chat_id=update.effective_chat.id,
command=cmd,
cmdargs=args,
message=self._plugin.parse_msg(msg).output,
user=self._plugin.parse_user(update.effective_user).output,
)
)
except PermissionError:
pass
return hook
def run(self):
# noinspection PyPackageRequirements
from telegram.ext import MessageHandler, Filters
super().run()
@ -120,12 +148,24 @@ class ChatTelegramBackend(Backend):
dispatcher = telegram.dispatcher
dispatcher.add_handler(MessageHandler(Filters.group, self._group_hook()))
dispatcher.add_handler(MessageHandler(Filters.text, self._msg_hook(TextMessageEvent)))
dispatcher.add_handler(MessageHandler(Filters.photo, self._msg_hook(PhotoMessageEvent)))
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.text, self._msg_hook(TextMessageEvent))
)
dispatcher.add_handler(
MessageHandler(Filters.photo, self._msg_hook(PhotoMessageEvent))
)
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()))
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.DocumentMessageEvent: when a document is
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.
platypush.message.event.chat.telegram.LocationMessageEvent: when a location is
received.

View File

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

View File

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

View File

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

View File

@ -1,6 +1,6 @@
manifest:
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
install:
pip: []