Skip to content

Commit

Permalink
update to new deltachat2 API
Browse files Browse the repository at this point in the history
also add --version command
  • Loading branch information
adbenitez committed Apr 27, 2024
1 parent cf38453 commit 459be6c
Show file tree
Hide file tree
Showing 5 changed files with 34 additions and 32 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ build
dist
.eggs
*.egg-info
*/_version.py

*~
.#*
Expand Down
18 changes: 9 additions & 9 deletions matterdelta/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
from typing import Dict, List, Tuple

import requests
from deltabot_cli import AttrDict, Bot, JsonRpcError, ViewType
from deltachat2 import Bot, JsonRpcError, Message, MessageViewtype, MsgData

mb_config = {}
chat2gateway: Dict[Tuple[int, int], List[str]] = {}
Expand All @@ -33,7 +33,7 @@ def init_api(bot: Bot, config_dir: str) -> None:
Thread(target=listen_to_matterbridge, args=(bot,), daemon=True).start()


def dc2mb(bot: Bot, accid: int, msg: AttrDict) -> None:
def dc2mb(bot: Bot, accid: int, msg: Message) -> None:
"""Send a Delta Chat message to the matterbridge side."""
if not msg.text and not msg.file: # ignore buggy empty messages
return
Expand Down Expand Up @@ -88,21 +88,21 @@ def mb2dc(bot: Bot, msg: dict, exclude: Tuple[int, int] = (0, 0)) -> None: # no
text = msg.get("text") or ""
if msg["event"] == "user_action":
text = "/me " + text
reply = {
"text": text,
"overrideSenderName": msg["username"],
}
reply = MsgData(
text=text,
override_sender_name=msg["username"],
)
file = ((msg.get("Extra") or {}).get("file") or [{}])[0]
if file:
if text == file["Name"]:
text = ""
with tempfile.TemporaryDirectory() as tmp_dir:
reply["file"] = str(Path(tmp_dir, file["Name"]))
reply.file = str(Path(tmp_dir, file["Name"]))
data = base64.decodebytes(file["Data"].encode())
with open(reply["file"], mode="wb") as attachment:
with open(reply.file, mode="wb") as attachment:
attachment.write(data)
if file["Name"].endswith((".tgs", ".webp")):
reply["viewtype"] = ViewType.STICKER
reply.viewtype = MessageViewtype.STICKER
for accid, chat_id in chats:
try:
bot.rpc.send_msg(accid, chat_id, reply)
Expand Down
39 changes: 18 additions & 21 deletions matterdelta/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,15 @@

from argparse import Namespace

from deltabot_cli import (
AttrDict,
Bot,
BotCli,
ChatType,
EventType,
events,
is_not_known_command,
)
from deltabot_cli import BotCli
from deltachat2 import Bot, ChatType, CoreEvent, EventType, MsgData, NewMsgEvent, events
from rich.logging import RichHandler

from ._version import __version__
from .api import dc2mb, init_api

cli = BotCli("matterdelta")
cli.add_generic_option("-v", "--version", action="version", version=__version__)
cli.add_generic_option(
"--no-time",
help="do not display date timestamp in log messages",
Expand All @@ -33,7 +28,6 @@ def _on_init(bot: Bot, args: Namespace) -> None:
bot.rpc.set_config(accid, "displayname", "Matterbridge Bot")
status = "I am a Delta Chat bot, send me /help for more info"
bot.rpc.set_config(accid, "selfstatus", status)
bot.rpc.set_config(accid, "delete_server_after", "1")
bot.rpc.set_config(accid, "delete_device_after", str(60 * 60 * 24 * 30))


Expand All @@ -43,7 +37,7 @@ def _on_start(bot: Bot, args: Namespace) -> None:


@cli.on(events.RawEvent)
def _log_event(bot: Bot, accid: int, event: AttrDict) -> None:
def _log_event(bot: Bot, accid: int, event: CoreEvent) -> None:
if event.kind == EventType.INFO:
bot.logger.debug(event.msg)
elif event.kind == EventType.WARNING:
Expand All @@ -52,13 +46,16 @@ def _log_event(bot: Bot, accid: int, event: AttrDict) -> None:
bot.logger.error(event.msg)
elif event.kind == EventType.SECUREJOIN_INVITER_PROGRESS:
if event.progress == 1000:
bot.logger.debug("QR scanned by contact id=%s", event.contact_id)
chatid = bot.rpc.create_chat_by_contact_id(accid, event.contact_id)
_send_help(bot, accid, chatid)
if not bot.rpc.get_contact(accid, event.contact_id).is_bot:
bot.logger.debug("QR scanned by contact id=%s", event.contact_id)
chatid = bot.rpc.create_chat_by_contact_id(accid, event.contact_id)
_send_help(bot, accid, chatid)


@cli.on(events.NewMessage(is_info=False, is_bot=None, func=is_not_known_command))
def _bridge(bot: Bot, accid: int, event: AttrDict) -> None:
@cli.on(events.NewMessage(is_info=False, is_bot=None))
def _bridge(bot: Bot, accid: int, event: NewMsgEvent) -> None:
if bot.has_command(event.command):
return
msg = event.msg
chat = bot.rpc.get_basic_chat_info(accid, msg.chat_id)
if chat.chat_type == ChatType.SINGLE and not msg.is_bot:
Expand All @@ -69,16 +66,16 @@ def _bridge(bot: Bot, accid: int, event: AttrDict) -> None:


@cli.on(events.NewMessage(command="/id"))
def _id(bot: Bot, accid: int, event: AttrDict) -> None:
def _id(bot: Bot, accid: int, event: NewMsgEvent) -> None:
msg = event.msg
bot.rpc.markseen_msgs(accid, [msg.id])
chat = bot.rpc.get_basic_chat_info(accid, msg.chat_id)
if chat.chat_type == ChatType.SINGLE:
text = "You can't use /id command here, add me to a group and use the command there"
bot.rpc.send_msg(accid, msg.chat_id, {"text": text, "quotedMessageId": msg.id})
reply = MsgData(text=text, quoted_message_id=msg.id)
else:
reply = {"text": f"accountId: {accid}\nchatId: {msg.chat_id}"}
bot.rpc.send_msg(accid, msg.chat_id, reply)
reply = MsgData(text=f"accountId: {accid}\nchatId: {msg.chat_id}")
bot.rpc.send_msg(accid, msg.chat_id, reply)


def _send_help(bot: Bot, accid: int, chatid: int) -> None:
Expand All @@ -88,4 +85,4 @@ def _send_help(bot: Bot, accid: int, chatid: int) -> None:
"**Available commands**\n\n"
"/id - send me this command in a group to get its ID."
)
bot.rpc.send_msg(accid, chatid, {"text": text})
bot.rpc.send_msg(accid, chatid, MsgData(text=text))
2 changes: 1 addition & 1 deletion pylama.ini
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
[pylama]
linters=mccabe,pyflakes,pylint,isort,mypy
skip=.*,build/*,tests/*,*/flycheck_*
skip=.*,build/*,tests/*,*/_version.py,*/flycheck_*
6 changes: 5 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,13 @@ classifiers = [
"License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
]
dependencies = [
"deltabot-cli>=5.0.0,<6.0",
"deltabot-cli>=6.1.0,<7.0",
"requests",
]

[project.urls]
Homepage = "https://github.com/deltachat-bot/matterdelta"

[project.optional-dependencies]
fast = [
"cchardet>=2.1.7",
Expand All @@ -41,6 +44,7 @@ matterdelta = "matterdelta:main"

[tool.setuptools_scm]
# can be empty if no extra settings are needed, presence enables setuptools_scm
version_file = "matterdelta/_version.py"

[tool.isort]
profile = "black"
Expand Down

0 comments on commit 459be6c

Please sign in to comment.