matrix-alertbot/my_project_name/bot_commands.py

96 lines
2.8 KiB
Python
Raw Normal View History

2021-01-10 04:30:07 +01:00
from nio import AsyncClient, MatrixRoom, RoomMessageText
2019-09-25 14:26:29 +02:00
2021-01-10 04:30:07 +01:00
from my_project_name.chat_functions import react_to_event, send_text_to_room
from my_project_name.config import Config
from my_project_name.storage import Storage
class Command:
def __init__(
self,
client: AsyncClient,
store: Storage,
config: Config,
command: str,
room: MatrixRoom,
event: RoomMessageText,
):
"""A command made by a user.
2019-09-25 14:26:29 +02:00
Args:
client: The client to communicate to matrix with.
2019-09-25 14:26:29 +02:00
store: Bot storage.
2019-09-25 14:26:29 +02:00
config: Bot configuration parameters.
command: The command and arguments.
2019-09-25 14:26:29 +02:00
room: The room the command was sent in.
2019-09-25 14:26:29 +02:00
event: The event describing the command.
2019-09-25 14:26:29 +02:00
"""
self.client = client
self.store = store
2019-10-26 01:40:05 +02:00
self.config = config
2019-09-25 14:26:29 +02:00
self.command = command
self.room = room
self.event = event
self.args = self.command.split()[1:]
async def process(self):
"""Process the command"""
if self.command.startswith("echo"):
await self._echo()
elif self.command.startswith("react"):
await self._react()
2019-09-25 14:26:29 +02:00
elif self.command.startswith("help"):
await self._show_help()
else:
await self._unknown_command()
async def _echo(self):
"""Echo back the command's arguments"""
response = " ".join(self.args)
await send_text_to_room(self.client, self.room.room_id, response)
async def _react(self):
"""Make the bot react to the command message"""
# React with a start emoji
reaction = ""
await react_to_event(
self.client, self.room.room_id, self.event.event_id, reaction
)
# React with some generic text
reaction = "Some text"
await react_to_event(
self.client, self.room.room_id, self.event.event_id, reaction
)
2019-09-25 14:26:29 +02:00
async def _show_help(self):
"""Show the help text"""
if not self.args:
2020-08-10 00:02:07 +02:00
text = (
"Hello, I am a bot made with matrix-nio! Use `help commands` to view "
"available commands."
)
2019-09-25 14:26:29 +02:00
await send_text_to_room(self.client, self.room.room_id, text)
return
topic = self.args[0]
if topic == "rules":
text = "These are the rules!"
elif topic == "commands":
text = "Available commands: ..."
2019-09-25 14:26:29 +02:00
else:
text = "Unknown help topic!"
await send_text_to_room(self.client, self.room.room_id, text)
async def _unknown_command(self):
await send_text_to_room(
self.client,
self.room.room_id,
f"Unknown command '{self.command}'. Try the 'help' command for more information.",
)