matrix-alertbot/my_project_name/callbacks.py

84 lines
2.7 KiB
Python
Raw Normal View History

2020-08-10 00:02:07 +02:00
import logging
from nio import JoinError
2020-08-06 22:16:57 +02:00
from my_project_name.bot_commands import Command
from my_project_name.message_responses import Message
2019-09-25 14:26:29 +02:00
logger = logging.getLogger(__name__)
class Callbacks(object):
def __init__(self, client, store, config):
2019-09-25 14:26:29 +02:00
"""
Args:
client (nio.AsyncClient): nio client used to interact with matrix
store (Storage): Bot storage
config (Config): Bot configuration parameters
2019-09-25 14:26:29 +02:00
"""
self.client = client
self.store = store
self.config = config
self.command_prefix = config.command_prefix
2019-09-25 14:26:29 +02:00
async def message(self, room, event):
"""Callback for when a message event is received
Args:
room (nio.rooms.MatrixRoom): The room the event came from
event (nio.events.room_events.RoomMessageText): The event defining the message
"""
# Extract the message text
msg = event.body
# Ignore messages from ourselves
if event.sender == self.client.user:
return
logger.debug(
f"Bot message received for room {room.display_name} | "
f"{room.user_name(event.sender)}: {msg}"
)
# Process as message if in a public room without command prefix
2019-09-25 14:26:29 +02:00
has_command_prefix = msg.startswith(self.command_prefix)
if not has_command_prefix and not room.is_group:
# General message listener
message = Message(self.client, self.store, self.config, msg, room, event)
await message.process()
2019-09-25 14:26:29 +02:00
return
# Otherwise if this is in a 1-1 with the bot or features a command prefix,
# treat it as a command
2019-09-25 14:26:29 +02:00
if has_command_prefix:
# Remove the command prefix
2020-08-10 00:02:07 +02:00
msg = msg[len(self.command_prefix) :]
2019-09-25 14:26:29 +02:00
command = Command(self.client, self.store, self.config, msg, room, event)
2019-09-25 14:26:29 +02:00
await command.process()
async def invite(self, room, event):
"""Callback for when an invite is received. Join the room specified in the invite"""
logger.debug(f"Got invite to {room.room_id} from {event.sender}.")
# Attempt to join 3 times before giving up
for attempt in range(3):
result = await self.client.join(room.room_id)
if type(result) == JoinError:
logger.error(
f"Error joining room {room.room_id} (attempt %d): %s",
2020-08-10 00:02:07 +02:00
attempt,
result.message,
2019-09-25 14:26:29 +02:00
)
else:
break
2020-06-23 03:11:31 +02:00
else:
logger.error("Unable to join room: %s", room.room_id)
2019-09-25 14:26:29 +02:00
2020-06-23 03:11:31 +02:00
# Successfully joined room
logger.info(f"Joined {room.room_id}")