Skip to content

Commit

Permalink
update tonew deltabot-cli API
Browse files Browse the repository at this point in the history
  • Loading branch information
adbenitez committed Feb 4, 2024
1 parent ea94d9b commit d02f005
Show file tree
Hide file tree
Showing 6 changed files with 71 additions and 70 deletions.
1 change: 1 addition & 0 deletions faqbot/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""FAQ bot."""

from .hooks import cli


Expand Down
1 change: 1 addition & 0 deletions faqbot/__main__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""Support for package execution."""

from . import main

main()
120 changes: 60 additions & 60 deletions faqbot/hooks.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
"""Event Hooks"""
import logging

import os
from argparse import Namespace
from tempfile import TemporaryDirectory
Expand All @@ -16,10 +16,11 @@

@cli.on_init
def on_init(bot: Bot, _args: Namespace) -> None:
if not bot.account.get_config("displayname"):
bot.account.set_config("displayname", "FAQ Bot")
status = "I am a Delta Chat bot, send me /help for more info"
bot.account.set_config("selfstatus", status)
for accid in bot.rpc.get_all_account_ids():
if not bot.rpc.get_config(accid, "displayname"):
bot.rpc.set_config(accid, "displayname", "FAQ Bot")
status = "I am a Delta Chat bot, send me /help for more info"
bot.rpc.set_config(accid, "selfstatus", status)


@cli.on_start
Expand All @@ -29,17 +30,17 @@ def _on_start(_bot: Bot, args: Namespace) -> None:


@cli.on(events.RawEvent)
def log_event(event: AttrDict) -> None:
if event.type == EventType.INFO:
logging.info(event.msg)
elif event.type == EventType.WARNING:
logging.warning(event.msg)
elif event.type == EventType.ERROR:
logging.error(event.msg)
def log_event(bot: Bot, _accid: int, event: AttrDict) -> None:
if event.kind == EventType.INFO:
bot.logger.info(event.msg)
elif event.kind == EventType.WARNING:
bot.logger.warning(event.msg)
elif event.kind == EventType.ERROR:
bot.logger.error(event.msg)


@cli.on(events.NewMessage(command="/help"))
def _help(event: AttrDict) -> None:
def _help(bot: Bot, accid: int, event: AttrDict) -> None:
text = """**Available commands**
/faq - sends available topics.
Expand All @@ -54,34 +55,24 @@ def _help(event: AttrDict) -> None:
**How to use me?**
Add me to a group then you can use the /save and /faq commands there"""
event.message_snapshot.chat.send_text(text)
bot.rpc.send_msg(accid, event.msg.chat_id, {"text": text})


@cli.on(events.NewMessage(command="/faq"))
def _faq(event: AttrDict) -> None:
msg = event.message_snapshot
chat = msg.chat.get_basic_snapshot()
if chat.chat_type == const.ChatType.SINGLE:
msg.chat.send_message(
text="Can't save notes in private, add me to a group and use the command there",
quoted_msg=msg.id,
)
def _faq(bot: Bot, accid: int, event: AttrDict) -> None:
msg = event.msg
if replyToCommandInDM(bot, accid, msg):
return

with session_scope() as session:
text = get_faq(msg.chat_id, session)
msg.chat.send_text(f"**FAQ**\n\n{text}")
bot.rpc.send_msg(accid, msg.chat_id, {"text": f"**FAQ**\n\n{text}"})


@cli.on(events.NewMessage(command="/remove"))
def _remove(event: AttrDict) -> None:
msg = event.message_snapshot
chat = msg.chat.get_basic_snapshot()
if chat.chat_type == const.ChatType.SINGLE:
msg.chat.send_message(
text="Can't save notes in private, add me to a group and use the command there",
quoted_msg=msg.id,
)
def _remove(bot: Bot, accid: int, event: AttrDict) -> None:
msg = event.msg
if replyToCommandInDM(bot, accid, msg):
return

question = event.payload
Expand All @@ -91,30 +82,27 @@ def _remove(event: AttrDict) -> None:
faq = (session.execute(stmt)).scalars().first()
if faq:
session.delete(faq)
msg.chat.send_message(text="✅ Note removed", quoted_msg=msg.id)
reply = {"text": "✅ Note removed", "quoted_message_id": msg.id}
bot.rpc.send_msg(accid, msg.chat_id, reply)


@cli.on(events.NewMessage(command="/save"))
def _save(event: AttrDict) -> None:
msg = event.message_snapshot
chat = msg.chat.get_basic_snapshot()
if chat.chat_type == const.ChatType.SINGLE:
msg.chat.send_message(
text="Can't save notes in private, add me to a group and use the command there",
quoted_msg=msg.id,
)
def _save(bot: Bot, accid: int, event: AttrDict) -> None:
msg = event.msg
if replyToCommandInDM(bot, accid, msg):
return

question = event.payload
if question.startswith(const.COMMAND_PREFIX):
msg.chat.send_message(
text=f"Invalid text, can not start with {const.COMMAND_PREFIX}",
quoted_msg=msg.id,
)
reply = {
"text": f"Invalid text, can not start with {const.COMMAND_PREFIX}",
"quoted_message_id": msg.id,
}
bot.rpc.send_msg(accid, msg.chat_id, reply)
return
quote = msg.quote
assert quote
quote = msg.message.account.get_message_by_id(quote.message_id).get_snapshot()
quote = bot.rpc.get_message(accid, quote.message_id)
if quote.file:
with open(quote.file, mode="rb") as attachment:
file_bytes = attachment.read()
Expand All @@ -133,21 +121,22 @@ def _save(event: AttrDict) -> None:
answer_viewtype=quote.view_type,
)
)
msg.chat.send_message(text="✅ Saved", quoted_msg=msg.id)
reply = {"text": "✅ Saved", "quoted_message_id": msg.id}
except IntegrityError:
msg.chat.send_message(
text="❌ Error: there is already a saved reply for that tag/question,"
reply = {
"text": "❌ Error: there is already a saved reply for that tag/question,"
" use /remove first to remove the old reply",
quoted_msg=msg.id,
)
"quoted_message_id": msg.id,
}
bot.rpc.send_msg(accid, msg.chat_id, reply)


@cli.on(events.NewMessage(is_info=False, func=cli.is_not_known_command))
def _answer(event: AttrDict) -> None:
msg = event.message_snapshot
chat = msg.chat.get_basic_snapshot()
def _answer(bot: Bot, accid: int, event: AttrDict) -> None:
msg = event.msg
chat = bot.rpc.get_basic_chat_info(accid, msg.chat_id)
if chat.chat_type == const.ChatType.SINGLE:
_help(event)
_help(bot, accid, event)
return
if event.command or not msg.text:
return
Expand All @@ -157,15 +146,26 @@ def _answer(event: AttrDict) -> None:
faq = (session.execute(stmt)).scalars().first()
if faq:
quoted_msg_id = msg.quote.message_id if msg.quote else msg.id
kwargs = {
"text": get_answer_text(faq, msg, session),
"quoted_msg": quoted_msg_id,
reply = {
"text": get_answer_text(bot, accid, faq, msg, session),
"quoted_message_id": quoted_msg_id,
}
if faq.answer_file:
with TemporaryDirectory() as tmp_dir:
filename = os.path.join(tmp_dir, faq.answer_filename)
with open(filename, mode="wb") as attachment:
attachment.write(faq.answer_file)
msg.chat.send_message(file=filename, **kwargs)
else:
msg.chat.send_message(**kwargs)
reply["file"] = filename
bot.rpc.send_msg(accid, msg.chat_id, reply)


def replyToCommandInDM(bot: Bot, accid: int, msg: AttrDict) -> bool:
chat = bot.rpc.get_basic_chat_info(accid, msg.chat_id)
if chat.chat_type == const.ChatType.SINGLE:
reply = {
"text": "Can't save notes in private, add me to a group and use the command there",
"quoted_message_id": msg.id,
}
bot.rpc.send_msg(accid, msg.chat_id, reply)
return True
return False
1 change: 1 addition & 0 deletions faqbot/orm.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""database"""

from contextlib import contextmanager
from threading import Lock

Expand Down
15 changes: 7 additions & 8 deletions faqbot/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Utilities"""
from deltabot_cli import AttrDict

from deltabot_cli import AttrDict, Bot
from sqlalchemy.future import select

from .orm import FAQ
Expand All @@ -14,20 +15,18 @@ def get_faq(chat_id: int, session) -> str:
return text


def get_answer_text(faq: FAQ, msg: AttrDict, session) -> str:
def get_answer_text(bot: Bot, accid: int, faq: FAQ, msg: AttrDict, session) -> str:
"""Generate the answer from the given FAQ entry's template answer."""
if not faq.answer_text:
return ""
kwargs = {}
if msg.quote:
kwargs["name"] = msg.quote.override_sender_name or msg.quote.author_display_name
quote = msg.message.account.get_message_by_id(
msg.quote.message_id
).get_snapshot()
sender = quote.sender.get_snapshot()
else:
sender = msg.sender.get_snapshot()
kwargs["name"] = msg.override_sender_name or sender.display_name
kwargs["name"] = (
msg.override_sender_name
or bot.rpc.get_contact(accid, msg.sender.id).display_name
)
kwargs["faq"] = get_faq(msg.chat_id, session)

return faq.answer_text.format(**kwargs)
3 changes: 1 addition & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,7 @@ classifiers = [
]
dependencies = [
"SQLAlchemy>=1.4.44",
"deltabot-cli>=0.1.0",
"deltachat-rpc-server>=1.127.0",
"deltabot-cli>=2.0.0,<3.0",
]

[project.optional-dependencies]
Expand Down

0 comments on commit d02f005

Please sign in to comment.