I have a bunch of scripts that are set up to send me things on Slack either at a regular interval, as cron jobs, or when certain things happen. I’d like to move this to Delta Chat.
Looking at the echo bot example, it’s a long running process that responds to incoming messages.
Is there an easy way to have a Python script that:
- Initialises whatever is needed.
- Sends a message to a given recipient.
- Then exits.
…?
I’m aware this might not be considered a “bot”, which is fair. I’m just trying to figure this out and the bot examples are the best I can find so far 
1 Like
hi, this is possible, here I created a bot that sends a message and exits in this small script:
from argparse import Namespace
from deltachat2 import Bot, EventType, MsgData, events
from deltabot_cli import BotCli
cli = BotCli("notifierbot")
@cli.on(events.RawEvent)
def log_event(bot: Bot, _accid: int, event) -> None:
if event.kind == EventType.INFO:
bot.logger.debug(event.msg)
elif event.kind == EventType.WARNING:
bot.logger.warning(event.msg)
elif event.kind == EventType.ERROR:
bot.logger.error(event.msg)
def send(cli: BotCli, bot: Bot, args: Namespace) -> None:
"""send a message"""
accid = bot.rpc.get_all_account_ids()[0]
# first fetch incoming messages to have updated chats state
bot.logger.info("first syncing chats state...")
bot.rpc.accounts_background_fetch(60)
bot.logger.info("sending message...")
chatid = cli.get_admin_chat(bot.rpc, accid)
msgid = bot.rpc.send_msg(accid, chatid, MsgData(text=args.text, file=args.file))
bot.run_until(
lambda ev: ev.event.kind in (EventType.MSG_DELIVERED, EventType.MSG_FAILED)
and ev.event.msg_id == msgid
)
bot.logger.info("Done, message sent")
if __name__ == "__main__":
send_subcmd = cli.add_subcommand(send)
send_subcmd.add_argument("text", help="the message's text")
send_subcmd.add_argument(
"file",
nargs="?",
help="path to a file to send as attachment",
)
cli.start()
save the code in a notifier.py file and run it with python, you first need to use the admin subcommand to get the invitation to the bot’s admin group chat, here is where the bot will be sending the notifications to keep the example simple, you could make the chat id configurable as a parameter in the script, this is an example output of the usage:
if this was useful for you, please consider supporting me
and/or donate to Delta Chat
2 Likes