From 92c9072257c9f6e74ec8bbcd1447d58973cde6d4 Mon Sep 17 00:00:00 2001 From: Tulir Asokan Date: Wed, 16 Jan 2019 11:40:51 +0200 Subject: [PATCH] Add WIP example of database usage in bot --- examples/README.md | 1 + examples/database/databasebot.py | 39 ++++++++++++++++++++++++++++++++ examples/database/maubot.yaml | 10 ++++++++ 3 files changed, 50 insertions(+) create mode 100644 examples/database/databasebot.py create mode 100644 examples/database/maubot.yaml diff --git a/examples/README.md b/examples/README.md index 1837fec..2efabca 100644 --- a/examples/README.md +++ b/examples/README.md @@ -4,3 +4,4 @@ All examples are published under the [MIT license](LICENSE). * [Hello World](helloworld/) - Very basic event handling bot that responds "Hello, World!" to all messages. * [Echo bot](https://github.com/maubot/echo) - Basic command handling bot with !echo and !ping commands * [Config example](config/) - Simple example of using a config file +* [Database example](database/) - Simple example of using a database diff --git a/examples/database/databasebot.py b/examples/database/databasebot.py new file mode 100644 index 0000000..8cebab6 --- /dev/null +++ b/examples/database/databasebot.py @@ -0,0 +1,39 @@ +from typing import Type + +from sqlalchemy import Column, String, Text, Table, MetaData, orm, func + +from mautrix.types import EventType +from maubot import Plugin, MessageEvent +from maubot.handlers import event, command + + +class DatabaseBot(Plugin): + db: orm.Session + events: Type[Table] + + async def start(self) -> None: + await super().start() + + db_factory = orm.sessionmaker(bind=self.database) + self.db = orm.scoped_session(db_factory) + table_meta = MetaData(bind=self.db) + self.events = Table("event", table_meta, + Column("room_id", String(255), primary_key=True), + Column("event_id", String(255), primary_key=True), + Column("sender", String(255)), + Column("body", Text)) + # In the future, there will be a proper way to include Alembic upgrades in plugins. + table_meta.create_all() + + @event.on(EventType.ROOM_MESSAGE) + async def handler(self, event: MessageEvent) -> None: + self.db.add(self.events(room_id=event.room_id, event_id=event.event_id, + sender=event.sender, body=event.content.body)) + + @command.new("stats") + async def find(self, _: MessageEvent) -> None: + res = (self.db + .query(func.sum(self.events.event_id)) + .group_by(self.events.room_id, self.events.sender) + .all()) + print(res) diff --git a/examples/database/maubot.yaml b/examples/database/maubot.yaml new file mode 100644 index 0000000..00c5673 --- /dev/null +++ b/examples/database/maubot.yaml @@ -0,0 +1,10 @@ +maubot: 0.1.0 +id: xyz.maubot.databasebot +version: 1.0.0 +license: MIT +modules: +- databasebot +main_class: DatabaseBot + +# This is required for a database to be available. +database: true