matrix-alertbot/my_project_name/main.py

104 lines
3.2 KiB
Python
Raw Normal View History

2019-09-25 14:26:29 +02:00
#!/usr/bin/env python3
import asyncio
2020-08-10 00:02:07 +02:00
import logging
import sys
2020-02-24 23:13:28 +01:00
from time import sleep
2020-08-10 00:02:07 +02:00
from aiohttp import ClientConnectionError, ServerDisconnectedError
2019-09-25 14:26:29 +02:00
from nio import (
AsyncClient,
AsyncClientConfig,
InviteMemberEvent,
2020-02-24 23:13:28 +01:00
LocalProtocolError,
2020-08-10 00:02:07 +02:00
LoginError,
RoomMessageText,
2020-02-24 23:13:28 +01:00
)
2020-08-10 00:02:07 +02:00
2020-08-06 22:16:57 +02:00
from my_project_name.callbacks import Callbacks
from my_project_name.config import Config
from my_project_name.storage import Storage
2019-09-25 14:26:29 +02:00
logger = logging.getLogger(__name__)
async def main():
# Read config file
# A different config file path can be specified as the first command line argument
if len(sys.argv) > 1:
config_filepath = sys.argv[1]
else:
config_filepath = "config.yaml"
config = Config(config_filepath)
2019-09-25 14:26:29 +02:00
# Configure the database
store = Storage(config)
2019-09-25 14:26:29 +02:00
# Configuration options for the AsyncClient
client_config = AsyncClientConfig(
max_limit_exceeded=0,
max_timeouts=0,
2020-02-24 23:13:28 +01:00
store_sync_tokens=True,
2020-05-31 21:57:26 +02:00
encryption_enabled=True,
2019-09-25 14:26:29 +02:00
)
# Initialize the matrix client
client = AsyncClient(
config.homeserver_url,
config.user_id,
device_id=config.device_id,
2020-02-25 00:56:09 +01:00
store_path=config.store_filepath,
2019-09-25 14:26:29 +02:00
config=client_config,
)
# Set up event callbacks
callbacks = Callbacks(client, store, config)
2019-09-25 14:26:29 +02:00
client.add_event_callback(callbacks.message, (RoomMessageText,))
client.add_event_callback(callbacks.invite, (InviteMemberEvent,))
2019-09-25 14:26:29 +02:00
2020-02-24 23:13:28 +01:00
# Keep trying to reconnect on failure (with some time in-between)
2019-09-25 14:26:29 +02:00
while True:
2020-02-24 23:13:28 +01:00
try:
# Try to login with the configured username/password
try:
login_response = await client.login(
2020-08-10 00:02:07 +02:00
password=config.user_password, device_name=config.device_name,
2020-02-24 23:13:28 +01:00
)
# Check if login failed
if type(login_response) == LoginError:
2020-08-10 00:02:07 +02:00
logger.error("Failed to login: %s", login_response.message)
2020-02-24 23:13:28 +01:00
return False
except LocalProtocolError as e:
2020-05-31 21:57:26 +02:00
# There's an edge case here where the user hasn't installed the correct C
# dependencies. In that case, a LocalProtocolError is raised on login.
logger.fatal(
"Failed to login. Have you installed the correct dependencies? "
"https://github.com/poljar/matrix-nio#installation "
2020-08-10 00:02:07 +02:00
"Error: %s",
e,
2020-05-31 21:57:26 +02:00
)
return False
2020-02-24 23:13:28 +01:00
# Login succeeded!
# Sync encryption keys with the server
# Required for participating in encrypted rooms
if client.should_upload_keys:
await client.keys_upload()
logger.info(f"Logged in as {config.user_id}")
await client.sync_forever(timeout=30000, full_state=True)
except (ClientConnectionError, ServerDisconnectedError):
logger.warning("Unable to connect to homeserver, retrying in 15s...")
# Sleep so we don't bombard the server with login requests
sleep(15)
finally:
# Make sure to close the client connection on disconnect
await client.close()
2019-09-25 14:26:29 +02:00
2020-08-10 00:02:07 +02:00
2019-09-25 14:26:29 +02:00
asyncio.get_event_loop().run_until_complete(main())