Exemple #1
0
def send_message(
    touser=None,
    content=None,
    msg_type="text",
    toparty=None,
    totag=None,
    **kwargs,
):
    secret = get_config("wework")
    CORPID, CORPSECRET, APPID = secret.split(":")
    agentid = int(APPID)
    api = WeChatClient(CORPID, CORPSECRET)
    message = dict(
        agent_id=agentid,
        user_ids=touser,
        content=content,
        party_ids=toparty,
        tag_ids=totag,
    )

    if msg_type == "text":
        ret = api.message.send_text(**message)
    elif msg_type == "markdown":
        ret = api.message.send_markdown(**message)
    else:
        raise Exception("unsupported message type")
    return ret
Exemple #2
0
def get_icinga_api(icinga_cluster_config):
    global icinga_api
    if icinga_api is None:
        api_user, passwd = get_config('icinga').split(':')
        ICINGA_AUTH = (api_user, passwd)
        icinga_api = IcingaApi(icinga_cluster_config.get_icinga_hosts(),
                               ICINGA_AUTH, ICINGA_CACERT)
    return icinga_api
Exemple #3
0
def send_message(chatid, content):
    PUSH_KEY = get_config('telegram')
    PUSH_URL = 'https://api.telegram.org/bot%s/sendMessage' % PUSH_KEY

    message = {"chat_id": chatid, "text": content}

    req = requests.post(PUSH_URL, json=message, proxies=PROXIES)
    resp = req.json()
    if not resp['ok']:
        raise Exception('api failed, resp: %s' % resp)
Exemple #4
0
def get_api_token_by_domain(domain):
    """
    config file example:
    token_id,token,domain
    111,yyy,*
    222,xxx,domain1.com|domain2.com|domain3.co
    """
    result = {}
    for conf in get_config('dnspod').splitlines():
        id_token, domains = conf.rsplit(',', 1)
        for scope in domains.split('|'):
            result[scope] = id_token
    logger.debug("domain config is %s", result)
    return result[domain] if domain in result else result['*']
Exemple #5
0
def send_message(user_key, message):
    # APP_TOKEN created on pushover.net
    APP_TOKEN = get_config('pushover')

    data = {
        "token": APP_TOKEN,
        "user": user_key,
        "message": message,
    }
    payload = urllib.urlencode(data)

    resp = json.loads(urllib.urlopen(PUSHOVER_URL, payload).read())
    if int(resp['status']) != 1:
        raise Exception('api failed, resp: %s' % resp)
Exemple #6
0
def send_message(touser=None,
                 content=None,
                 safe="0",
                 msg_type='text',
                 toparty=None,
                 totag=None,
                 qy=False,
                 **kwargs):
    if qy:
        secret = get_config('wework')
        safe = None
    else:
        secret = get_config('wechat')
    CORPID, CORPSECRET, APPID = secret.split(':')
    agentid = int(APPID)
    api = WxApi(CORPID, CORPSECRET)

    ret, api_error = api.send_message(
        msg_type=msg_type,
        content=content,
        agentid=agentid,  # APP ID
        safe=safe,
        # 成员ID列表(消息接收者,多个接收者用‘|’分隔,最多支持1000个)。特殊情况:指定为@all,则向关注该企业应用的全部成员发送
        touser=touser,
        # 部门ID列表,多个接收者用‘|’分隔,最多支持100个。当touser为@all时忽略本参数
        toparty=toparty,
        # 标签ID列表,多个接收者用‘|’分隔。当touser为@all时忽略本参数
        totag=totag,
    )
    if api_error:
        logger.error(
            ('send_message({touser}, {content}) get {err_code}, {err_msg}'.
             format(touser=touser,
                    content=content,
                    err_code=api_error.code,
                    err_msg=api_error.message)))
    return ret, api_error
Exemple #7
0
def send_message(addrs: [str], content: str, **kwargs):
    """
    发送消息
    :param addrs: 接收人的邮箱地址, 或部门id
    :param content: 消息内容, 可以是字符串, 也可以是json格式的字符串
    :param kwargs: 其他参数
    :return: None
    """
    secret = get_config("lark-multi-tenant")
    # config template:
    # {
    #     "your_company": {
    #        "app_id": "1",
    #        "app_secret": "1",
    #        "encrypt_key": "1",
    #        "verification_token": "1"
    #    }
    # }
    lark_bundle = LarkApp.load_from_configs(configs=json.loads(secret))
    company = kwargs.get("company", DEFAULT_LARK_TENANT) or DEFAULT_LARK_TENANT
    lark = lark_bundle.get_lark(company=company)
    address_type = kwargs.get("address_type", "email")
    msg_type = kwargs.get("msg_type", "text")
    if address_type == "email":
        if msg_type == "text":
            content = json.dumps({"text": content})
        for addr in addrs:
            lark.message.send_raw_message(
                pylark.SendRawMessageReq(
                    receive_id_type="email",
                    receive_id=addr,
                    content=content,
                    msg_type=msg_type,
                )
            )

        return
    if address_type == "department_id":
        if msg_type == "text":
            content = {"text": content}
        else:
            content = json.loads(content)
        lark.message.batch_send_old_raw_message(pylark.BatchSendOldRawMessageReq(
            department_ids=addrs,
            content=content,
            msg_type=msg_type,
        ))
        return
Exemple #8
0
def send_message(chatid, content, msg_type="text"):
    PUSH_KEY = get_config("telegram")
    PUSH_URL = "https://api.telegram.org/bot%s/sendMessage" % PUSH_KEY

    message = {
        "chat_id": chatid,
        "text": content,
    }
    if msg_type == "markdown":
        message["parse_mode"] = "Markdown"
    elif msg_type == "html":
        message["parse_mode"] = "HTML"

    req = requests.post(PUSH_URL, json=message, proxies=PROXIES)
    resp = req.json()
    if not resp["ok"]:
        raise Exception("api failed, resp: %s" % resp)
Exemple #9
0
def send_message(email, title, body):
    PUSH_KEY = get_config('pushbullet')

    data = {
        "email": email,
        "type": 'note',
        "title": title,
        "body": body,
    }
    payload = urlencode(data)
    req = Request(PUSH_URL)
    base64string = base64.encodestring('%s:%s' % (PUSH_KEY, ''))[:-1]
    authheader = "Basic %s" % base64string
    req.add_header("Authorization", authheader)

    resp = json.loads(urlopen(req, payload).read())
    if not resp['receiver_email'] == email:
        raise Exception('api failed, resp: %s' % resp)
Exemple #10
0
def send_mail(to_addrs,
              content,
              subject='Sent via sa-tools',
              from_addr=SYSADMIN_EMAIL):
    server_info = (SMTP_SERVER, SMTP_SERVER_PORT)
    smtp = smtplib.SMTP_SSL(*server_info) if SMTP_SSL else smtplib.SMTP(
        *server_info)
    if SMTP_CREDENTIALS_CONFIG:
        user, password = get_config(SMTP_CREDENTIALS_CONFIG).split(':')
        smtp.login(user, password)
    msg = MIMEText(content, 'plain')
    msg['Subject'] = subject
    msg['From'] = from_addr
    msg['To'] = ', '.join(to_addrs)

    try:
        smtp.sendmail(from_addr, to_addrs, msg.as_string())
        logger.info('sent email to %s, title: %s', to_addrs, subject)
    except Exception:
        raise
    finally:
        smtp.quit()
Exemple #11
0
import requests
import base64
import json
import logging
import datetime
from pathlib import Path, PurePath

from sa_tools_core.consts import GITHUB_API_ENTRYPOINT
from sa_tools_core.utils import get_config

logger = logging.getLogger(__name__)

github_secret_func = lambda: get_config('github')


class GithubRepo:
    def __init__(self,
                 org,
                 repo,
                 entrypoint=None,
                 user_name=None,
                 personal_token=None,
                 secret_func=None,
                 author=None,
                 skip_ssl=False):
        self.org = org
        self.repo = repo
        self.author = author
        self.entrypoint = entrypoint
        self.base_commit = None
        self.base_tree = None
Exemple #12
0
import pkgutil
import logging
import argparse
import importlib
from html.parser import HTMLParser

import yaml
import inflection

from sa_tools_core.consts import TENCENT_DEFAULT_PARAMS, TENCENT_DEFAULT_REGIN

from sa_tools_core.utils import get_config

logger = logging.getLogger(__name__)

tencent_config_func = lambda: get_config('tencent')  # NOQA

RE_PARAM = re.compile(r'^:(param|type)\ (\w+):\ (.*)$')
COMMON_PARAM_TYPES = {
    'str': str,
    'int': int,
    'bool': bool,
    'int non-negative': int,
}


class KVParamType:
    def __init__(self, kname, vname, multi_value=False):
        self.kname = kname
        self.vname = vname
        self.multi_value = multi_value
Exemple #13
0
DEFAULT_MX = 10
DEFAULT_LINE = '默认'
DNSPOD_TO_TINYDNS = {
    'A': ['={domain}:{value}:{ttl}', '+{domain}:{value}:{ttl}'],
    'AAAA': ':{domain}:28:{value}:{ttl}',
    'MX': '@{domain}::{value}:{dist}:{ttl}',
    'NS': '.{domain}::{value}:{ttl}',
    'TXT': '\'{domain}:{value}:{ttl}',
    'CNAME': 'C{domain}:{value}:{ttl}',
}
MAX_RECORDS_COUNT = 3000

DNSPOD_TIMEOUT = 5
DNSPOD_RETRIES = 3

dns_monitor_cb_key_func = lambda: get_config('dns_monitor_callback_key'
                                             )  # NOQA

external_domains_config = ConfigParser(allow_no_value=True)
external_domains_config.read(EXTERNAL_DOMAINS_CONFIG_FILE)


def get_api_token_by_domain(domain):
    """
    config file example:
    token_id,token,domain
    111,yyy,*
    222,xxx,domain1.com|domain2.com|domain3.co
    """
    result = {}
    for conf in get_config('dnspod').splitlines():
        id_token, domains = conf.rsplit(',', 1)
Exemple #14
0
def github_secret_func():
    return get_config('github')