zaphodafier/src/zaphodafier/main.py

65 lines
2.2 KiB
Python

#!/usr/bin/env python3
import os
import sys
from pprint import pprint
from configparser import ConfigParser
from typing import List, Union
import telepot
import click
@click.command()
@click.option("-d", "--telegramid", help="Telegram ID/Chat ID to send the message to")
@click.option("-u", "--user", help="user to send the message to (defined in the config file)")
@click.option("-m", "--message", help="Message to send", required=False, default="read from stdin", show_default=True)
@click.option("--getupdates", help="Get updates from telegram and exit", is_flag=True, default=False, show_default=True)
@click.option(
"-c",
"--config",
multiple=True,
default=["zaphodafier.conf", "~/zaphodafier.conf", "~/.zaphodafier.conf", "/etc/zaphodafier.conf"],
help="Configuration file",
type=click.Path(),
show_default="True",
)
def main(telegramid: Union[str, int], user: str, config: List[str], getupdates: bool, message):
# Load config
if not any([os.path.exists(path) for path in config]):
print(f"Cannot find any configuration in {config}", file=sys.stderr)
sys.exit(1)
conf = ConfigParser()
# Loop over configs and use the first that works
for c in config:
if os.path.exists(c) and conf.read(c):
break
if not "telegram" in conf.sections():
print(f"Invalid config: {c}, check the sample configuration", file=sys.stderr)
sys.exit(1)
if not conf["telegram"]["token"]:
print(f"Telegram token: `token` must be defined in the configuration file", file=sys.stderr)
sys.exit(1)
bot = telepot.Bot(conf["telegram"]["token"])
bot.getMe()
if getupdates:
for msg in bot.getUpdates(): # TODO: would be cool to have an offset here
pprint(msg)
print("--------")
sys.exit(1)
if user:
telegramid = conf["telegram.users"].get(user, None)
if not telegramid:
telegramid = conf["telegram.users"]["default_user"]
if message == "read from stdin":
print("No input message, reading from stdin")
message = " ".join(sys.stdin.readlines())
bot.sendMessage(telegramid, message.encode("UTF-8"), parse_mode="HTML")