class SlackWebhookNotification(MessageAction): """Watchdog action to notify to a Slack channel by an incoming webhook. See https://api.slack.com/incoming-webhooks for more detail. Args: url (str) : URL string of an incoming webhook. channel (str) : Channel name with `#` prefix or user name with `@` prefix. """ def __init__(self, url, channel, **kwargs): super(SlackWebhookNotification, self).__init__(**kwargs) try: from slackweb import Slack except ImportError as e: logger.error( 'You must insatll `slackweb` package to take this action.') raise e self._slack = Slack(url=url) self._channel = channel def __call__(self, tick_time, estimated_trigger_time, message): self._slack.notify(channel=self._channel, text=self._get_message(tick_time, estimated_trigger_time, message))
def __init__(self, url, channel, **kwargs): super(SlackWebhookNotification, self).__init__(**kwargs) try: from slackweb import Slack except ImportError as e: logger.error( 'You must insatll `slackweb` package to take this action.') raise e self._slack = Slack(url=url) self._channel = channel
def send_slack_notify(message): slack = Slack(url=urlSlackWebhook) # slack.notify(text="Release at catalog", channel="#test", username="******", icon_emoji=":sushi:") # sending notify to Slack attachments = [] attachment = { "title": title, "text": message, "mrkdwn_in": ["text", "pretext"] } attachments.append(attachment) slack.notify(attachments=attachments)
def push_msg_slack(message): if 'SLACK_WEBHOOK' not in os.environ or len( os.environ['SLACK_WEBHOOK']) == 0: return SLACK_WEBHOOK = os.environ['SLACK_WEBHOOK'] slack = Slack(url=SLACK_WEBHOOK) try: res = slack.notify( text="<!channel> Error on PowEUs:\n```\n{}\n```".format(message), ) print(res) except Exception as e: print("Slack exception: {}".format(e)) # if slack is down or if we reach rate limits (\o/) don't fail !! pass
def send_to_slack(sender, **kwargs): hooks = getattr(settings, 'PUBLISH_SLACK_HOOKS', []) if not hooks: return page = kwargs['instance'] # It is the first publish if there is no time between first publish and latest revision. published_since = page.latest_revision_created_at - page.first_published_at # Add a 5 sec delta to account for slowness of the server. is_first_publish = published_since <= timedelta(seconds=5) if is_first_publish: for hook in hooks: Slack(hook).send({ 'text': 'New site published! :rocket:', 'username': '******', 'icon_emoji': ':bird:', 'attachments': [{ 'fallback': force_text(page), 'title': page.title, 'text': page.full_url, 'color': '#43b1b0', }] })
def send_slack_message(channel: str, slack_url: str, bot_name: str, message: str): if not settings.IS_SLACK_ENABLED: return slack = Slack(url=slack_url) try: slack.notify( text=message, channel=channel, username=bot_name, ) except: # noqa # we really don't want this to break the flow for whatever reason if settings.LEVEL != EnvLevel.PRODUCTION: raise logger.exception( 'Failed to send Slack message to channel {}'.format(channel), exc_info=True)
class SlackClient: slack: Slack def __init__(self, url: str): self.slack = Slack(url=url) def post(self, message): logger = AppLogger.get_logger(__name__) try: self.slack.notify(text=message) except HTTPError as error: logger.error('Error code: %s' % error.code) except URLError as error: logger.error('Reason: %s' % error.reason)
class SlackNotifier(object): def __init__(self, recipient: SlackRecipient): self.recipient: SlackRecipient = recipient self.slack = Slack(self.recipient.url) def send( self, current_state: StateHistory, base_url: str = None, ): # Build message site = self.recipient.site message = dedent(f"""\ <!here> *Yagura notification: Site state is changed* - URL: {site.url} - Status: {current_state.state} - History: {base_url}{site.get_absolute_url()} """) if self.recipient.channel: self.slack.notify(text=message, channel=self.recipient.channel) else: self.slack.notify(text=message)
def __init__(self, recipient: SlackRecipient): self.recipient: SlackRecipient = recipient self.slack = Slack(self.recipient.url)
def __init__(self, url: str): self.slack = Slack(url=url)
handler.setLevel(logging.INFO) formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) handler.setFormatter(formatter) logger.addHandler(handler) try: from settings import SLACK_URL except ImportError: logger.error("Unable to load `SLACK_URL` from settings.py. Does it exist?") # Build the Slack client slack = Slack(url=SLACK_URL) path = os.path.split(os.path.abspath(__file__))[0] url = "https://canvas.instructure.com/doc/api/all_resources.html" cache_location = os.path.join(path, 'cache') try: first_run = not bool(os.listdir(cache_location)) except OSError: os.mkdir(cache_location) first_run = True changes = [] # Fetch the API docs response = requests.get(url)
se_key = config.stackexchange['api_key'] post_url = config.slack['post_url'] except: se_key = os.environ.get('SE_KEY') post_url = os.environ.get('POST_URL') if not (se_key and post_url): import sys print 'No config.py file found. Exiting...' sys.exit(0) MAX_QUESTIONS = 5 app = Flask(__name__) so = Site(StackOverflow, se_key) slack = Slack(url=post_url) def get_response_string(q): q_data = q.json check = ' :white_check_mark:' if q.json['is_answered'] else '' return "|{0:d}|{1} <{2}|{3}> ({4:d} answers)".format( q_data['score'], check, q.url, q.title, q_data['answer_count']) @app.route('/overflow', methods=['post']) def overflow(): """ Example: /overflow python list comprehension """
def __notify(self, text=None, attachments=None): return Slack(url=self.channel).notify(text=text, attachments=attachments)
# -*- coding: utf-8 -*- from chalice import Chalice from slackweb import Slack import json slack_url = "SLACK_URL" backlog_url = "BACKLOG_URL" channel = "SLACK_CHANNEL" # TODO: 環境変数で設定したい # slack_url = os.environ['SLACK_URL'] # backlog_url = os.environ['BACKLOG_URL'] # channel = os.environ['SLACK_CHANNEL'] slack = Slack(url=slack_url) app = Chalice(app_name='backlog2slack') app.debug = True def to_slack(attachments): slack.notify(attachments=attachments, channel=channel, username="******") def get_project(body): project_key = body['project']['projectKey'] project_id = body['content']['key_id'] summary = body['content']['summary'] task_key = "%s-%d" % (project_key, project_id) task = "%s:%s" % (task_key, summary)