Handle re-joining on restart

Closes https://git.vvvvvvaria.org/decentral1se/xbotlib/issues/11.
This commit is contained in:
Luke Murphy 2021-02-02 21:27:51 +01:00
parent 2a5d20f7d4
commit 0043e7563a
No known key found for this signature in database
GPG Key ID: 5E2EF5A63E3718CC
2 changed files with 22 additions and 2 deletions

View File

@ -28,6 +28,7 @@ XMPP bot experiments going on in
- [Storage back-end](#storage-back-end)
- [Loading Plugins](#loading-plugins)
- [Serving HTTP](#serving-http)
- [Invitations](#invitations)
- [API Reference](#api-reference)
- [Bot.direct(message)](#bot-direct-message)
- [Bot.group(message)](#bot-group-message)
@ -200,8 +201,7 @@ deployments.
In order to store data you can make use of the `self.db` attribute of the `Bot`
class. It is a Python dictionary which will be saved to disk automatically for
you as a `<nick>.json` in your current working directory. The name and path to
this file can be configured using the output option (e.g. `python bot.py
--output /var/www/html`)
this file can be configured using the output option (e.g. `python bot.py --output /var/www/html`)
```python
def group(self, message):
@ -302,6 +302,15 @@ storage](#storage-back-end). Your `serve` function can read from the storage
back-end and then respond. This is usually as simple as accessing the `self.db`
attribute.
### Invitations
As long as the `--no-auto-join` option is not set (via the configuration file
or environment also), then your bot will automatically join any room it is
invited to. Rooms that your bot has been invited to will be stored in the
`.xbotlib/data.json` file. If your bot is turned off or fails for some reason
then it will read this file when turned back on to see what rooms it should
re-join automatically. The `data.json` file can be edited freely by hand.
### API Reference
When writing your own bot, you always sub-class the `Bot` class provided from

View File

@ -594,6 +594,10 @@ class Bot(ClientXMPP):
self.plugin["xep_0045"].join_muc(room, self.config.nick)
self.log.info(f"Joining {room} automatically")
for room in self._data["invited"]:
self.plugin["xep_0045"].join_muc(room, self.config.nick)
self.log.info(f"Re-joining {room} (invited previously)")
def group_invite(self, message):
"""Accept invites to group chats."""
room = message["from"]
@ -604,6 +608,10 @@ class Bot(ClientXMPP):
self.plugin["xep_0045"].join_muc(room, self.config.nick)
self.log.info(f"Joining {room} as invited")
if room not in self._data["invited"]:
self._data["invited"].append(str(room))
self._data._dumps()
def group_message(self, message):
"""Handle group chat message events."""
message = SimpleMessage(message, self)
@ -706,6 +714,9 @@ class Bot(ClientXMPP):
self.log.error(message)
exit(1)
if "invited" not in self._data:
self._data["invited"] = []
def run(self):
"""Run the bot."""
self.connect()