remove log

This commit is contained in:
Benedetta 2024-04-05 14:53:45 +02:00
parent b355e98bd3
commit 7d017f5579
6 changed files with 42 additions and 21 deletions

View file

@ -5,10 +5,17 @@ Example of payloads received from mq:
"room_id": "!PQHkyOTruVtZnMRCRe:goulash.lezzo.org"} "room_id": "!PQHkyOTruVtZnMRCRe:goulash.lezzo.org"}
''' '''
import aio_pika import aio_pika
import logging import log
import json import json
async def run(mq_url): async def run(mq_url):
while True:
await run_(mq_url)
async def run_(mq_url):
log.info('starting echobot')
connection = await aio_pika.connect_robust(mq_url) connection = await aio_pika.connect_robust(mq_url)
async with connection: async with connection:
@ -21,6 +28,7 @@ async def run(mq_url):
async for message in queue_iter: async for message in queue_iter:
async with message.process(): async with message.process():
body = message.body.decode() body = message.body.decode()
log.info(f'got new echo message: {body}')
br = json.loads(body) br = json.loads(body)
response = { response = {
'content': br['content'], 'content': br['content'],
@ -33,4 +41,4 @@ async def run(mq_url):
mqmsg = aio_pika.Message(body=btes) mqmsg = aio_pika.Message(body=btes)
await channel.default_exchange.publish(mqmsg, 'lanonna') await channel.default_exchange.publish(mqmsg, 'lanonna')
except Exception as e: except Exception as e:
logging.exception(f'Exception in mq loop: {e}') log.error(f'Exception in mq loop: {e}')

View file

@ -1,18 +1,13 @@
import asyncio import asyncio
import logging
import sys import sys
import psycopg import psycopg
import matrix import matrix
import mq import mq
import protocol import protocol
import config import config
import db import db
import log
logger = logging.getLogger('lanonna')
logger.setLevel(logging.WARNING)
logging.basicConfig(level=logging.INFO)
async def matrixmain(matrix_client: matrix.MatrixClient, mq_client: mq.MQClient, db_connection: psycopg.AsyncConnection): async def matrixmain(matrix_client: matrix.MatrixClient, mq_client: mq.MQClient, db_connection: psycopg.AsyncConnection):
@ -26,7 +21,7 @@ async def matrixmain(matrix_client: matrix.MatrixClient, mq_client: mq.MQClient,
server_timestamp = event.server_timestamp / 1000 server_timestamp = event.server_timestamp / 1000
dt_received = datetime.datetime.fromtimestamp(server_timestamp) dt_received = datetime.datetime.fromtimestamp(server_timestamp)
if dt_received > last_seen: if dt_received > last_seen:
handled = await matrix.message_received_cb(matrix_client, mq_client, logger, room, event) handled = await matrix.message_received_cb(matrix_client, mq_client, room, event)
if handled: if handled:
await db.update_last_seen(db_connection, dt_received) await db.update_last_seen(db_connection, dt_received)
@ -34,10 +29,10 @@ async def matrixmain(matrix_client: matrix.MatrixClient, mq_client: mq.MQClient,
try: try:
await client.sync_forever(timeout=30000, full_state=True) # milliseconds await client.sync_forever(timeout=30000, full_state=True) # milliseconds
logging.info('Exiting from the matrix loop') log.info('exiting from the matrix loop')
client.logout() client.logout()
except Exception as e: except Exception as e:
logging.exception(f'Exception in matrix loop: {e}') log.error(f'exception in matrix loop: {e}')
async def mqmain(rabbit_client: mq.MQClient, matrix_client: matrix.MatrixClient): async def mqmain(rabbit_client: mq.MQClient, matrix_client: matrix.MatrixClient):
@ -54,7 +49,7 @@ async def mqmain(rabbit_client: mq.MQClient, matrix_client: matrix.MatrixClient)
async with rabbit_client.connection: async with rabbit_client.connection:
await loop() await loop()
except Exception as e: except Exception as e:
logging.exception(f'Exception in mq loop: {e}') log.error(f'exception in mq loop: {e}')
async def main(conf: config.Configuration): async def main(conf: config.Configuration):

14
lanonna/log.py Normal file
View file

@ -0,0 +1,14 @@
import syslog
INFO = syslog.LOG_INFO
ERR = syslog.LOG_ERR
def info(msg):
msg = f'LANONNA: INFO - {msg}'
print(msg)
syslog.syslog(INFO, msg)
def error(msg):
msg = f'LANONNA: ERR - {msg}'
print(msg)
syslog.syslog(ERR, msg)

View file

@ -1,10 +1,10 @@
import logging
from collections import namedtuple from collections import namedtuple
from typing import Any from typing import Any
from nio import AsyncClient, InviteEvent, RoomMessageText, MatrixRoom from nio import AsyncClient, InviteEvent, RoomMessageText, MatrixRoom
from markdown import markdown from markdown import markdown
import protocol import protocol
import log
import mq import mq
import config import config
import commands import commands
@ -14,7 +14,8 @@ MatrixClient = namedtuple('MatrixClient', ('client'))
async def initialize(c: config.Configuration): async def initialize(c: config.Configuration):
client = AsyncClient(c.matrix_url, c.matrix_username) client = AsyncClient(c.matrix_url, c.matrix_username)
logging.info(await client.login(c.matrix_password))
log.info(await client.login(c.matrix_password))
# always accept every room invite # always accept every room invite
client.add_event_callback(lambda room, _: client.join(room.room_id), InviteEvent) client.add_event_callback(lambda room, _: client.join(room.room_id), InviteEvent)
@ -34,32 +35,33 @@ async def send_text(matrix_client: MatrixClient, response: protocol.BotResponse)
try: try:
await client.room_send(response.room_id, 'm.room.message', content) await client.room_send(response.room_id, 'm.room.message', content)
logging.info(f'Replied in matrix: {response}') log.info(f'Replied in matrix: {response}')
except Exception as e: except Exception as e:
logging.exception(f"Unable to send message response {response}|{e}") log.error(f"Unable to send message response {response}|{e}")
async def message_received_cb(matrix_client: MatrixClient, async def message_received_cb(matrix_client: MatrixClient,
rabbit_client: mq.MQClient, rabbit_client: mq.MQClient,
logger: logging.Logger,
room: MatrixRoom, room: MatrixRoom,
event: RoomMessageText) -> bool: event: RoomMessageText) -> bool:
'''Returns a boolean indicating if the message ct and could be handled''' '''Returns a boolean indicating if the message ct and could be handled'''
import mq import mq
cmd = commands.parse(event.body) cmd = commands.parse(event.body)
if cmd: if cmd:
logging.info(f'got new matrix command: {cmd}') log.info(f'got new matrix command: {cmd}')
swm = protocol.SwitchboardMessage(command=cmd[0], swm = protocol.SwitchboardMessage(command=cmd[0],
content=cmd[1], content=cmd[1],
source_message_id=event.event_id, source_message_id=event.event_id,
sender_nick=room.user_name(event.sender), sender_nick=room.user_name(event.sender),
room_id=room.room_id) room_id=room.room_id)
print(swm)
try: try:
if swm.command in commands.commands: if swm.command in commands.commands:
await mq.route_to_exchange(rabbit_client, swm) await mq.route_to_exchange(rabbit_client, swm)
print('mq routed')
else: else:
help_ = protocol.unknown_cmd_help_reply(swm) help_ = protocol.unknown_cmd_help_reply(swm)
await send_text(matrix_client, help_) await send_text(matrix_client, help_)
return True return True
except Exception as e: except Exception as e:
logging.exception(f"Can't route switchboard message: {swm}|{str(e)}") log.error(f"Can't route switchboard message: {swm}|{str(e)}")
return False return False

View file

@ -31,7 +31,7 @@ def unknown_cmd_help_reply(swm: SwitchboardMessage):
def json_to_bot_response(json_str: str) -> Optional[BotResponse]: def json_to_bot_response(json_str: str) -> Optional[BotResponse]:
import logging import log
try: try:
data = json.loads(json_str) data = json.loads(json_str)
@ -45,5 +45,5 @@ def json_to_bot_response(json_str: str) -> Optional[BotResponse]:
return BotResponse(content, source_message_id, room_id, as_reply, as_markdown) return BotResponse(content, source_message_id, room_id, as_reply, as_markdown)
except Exception as e: except Exception as e:
logging.exception(f"Error parsing JSON or missing required fields: {str(e)}") log.error(f"Error parsing JSON or missing required fields: {str(e)}")
return None return None

View file

@ -58,6 +58,8 @@ let make_get_request {requests; repos} =
resp.@$("text") resp.@$("text")
|> Py.String.to_string |> Py.String.to_string
in in
let _ = resp.@$("headers") |> Py.Dict.to_bindings_string |> List.iter (fun e -> e |> Batteries.dump |> print_endline)
in
let matrix_room = Datatypes.MatrixRoom.make m_room_string in let matrix_room = Datatypes.MatrixRoom.make m_room_string in
let value = let value =
issues_of_json matrix_room jsontext issues_of_json matrix_room jsontext