Sends a Slack message with the contents of a text file

        :param: test_file: (str) Full path to text file to send
        :return: None
        :raises: Cons3rtSlackerError
198877
def send_text_file(self, text_file):
        
        log = logging.getLogger(self.cls_logger + '.send_text_file')

        if not isinstance(text_file, basestring):
            msg = 'arg text_file must be a string, found type: {t}'.format(t=text_file.__class__.__name__)
            raise Cons3rtSlackerError(msg)

        if not os.path.isfile(text_file):
            msg = 'The provided text_file was not found or is not a file: {f}'.format(f=text_file)
            raise Cons3rtSlackerError(msg)

        log.debug('Attempting to send a Slack message with the contents of file: {f}'.format(f=text_file))
        try:
            with open(text_file, 'r') as f:
                file_text = f.read()
        except (IOError, OSError):
            _, ex, trace = sys.exc_info()
            msg = '{n}: There was a problem opening file: {f}\n{e}'.format(
                n=ex.__class__.__name__, f=text_file, e=str(ex))
            raise Cons3rtSlackerError, msg, trace

        # Take the last 7000 characters
        file_text_trimmed = file_text[-7000:]
        attachment = SlackAttachment(fallback=file_text_trimmed, text=file_text_trimmed, color='#9400D3')
        self.add_attachment(attachment)
        self.send()
1003925
def send_file(resource, env)
      file     = ::Rack::File.new nil
      path     = resource.file_descriptor[:full_path]
      if !file.respond_to?(:path=)
        request  = ::Rack::Request.new(env)
        response = file.serving(request, path)
      else
        file.path = path
        response = file.serving(env)
      end
      status = response[0]
      response[1]['Content-Encoding'] = 'gzip' if %w[.svgz .gz].include?(resource.ext)
      # Do not set Content-Type if status is 1xx, 204, 205 or 304, otherwise
      # Rack will throw an error (500)
      if !(100..199).cover?(status) && ![204, 205, 304].include?(status)
        response[1]['Content-Type'] = resource.content_type || (resource.binary? ? 'application/octet-stream' : 'text/plain')
      end

      halt response
    end
683711
def send_message(slack):
    
    channel = input('Which channel would you like to message? ')
    message = input('What should the message be? ')
    channel_id = channel_to_id(slack, channel)

    print(f"Sending message to #{channel} (id: {channel_id})!")
    slack.rtm_send_message(channel_id, message)
824400
def send_message(message, pipe='public'):
    
    if pipe not in ['public', 'private']:
        raise ValueError('pipe argument can be only "public" or "private"')
    else:
        pipe = pipe.upper()

    pipe_path = PUBLIC_PIPE if pipe == 'PUBLIC' else PRIVATE_PIPE

    # create file if it doesn't exist, append contents
    pipeout = open(pipe_path, 'a')

    pipeout.write('%s\n' % message)
    pipeout.close()
327140
def insert_line_in_file_after_regex(path, line, after_regex, use_sudo=False):
    

    tmpfile = str(uuid.uuid4())
    get_file(path, tmpfile, use_sudo=use_sudo)
    with open(tmpfile) as f:
        original = f.read()

    if line not in original:
        outfile = str(uuid.uuid4())
        with open(outfile, 'w') as output:
            for l in original.split('\n'):
                output.write(l + '\n')
                if re.match(after_regex, l) is not None:
                    output.write(line + '\n')

        upload_file(local_path=outfile,
                    remote_path=path,
                    use_sudo=use_sudo)
        os.unlink(outfile)
    os.unlink(tmpfile)
273977
def send_text_file(self, text_file, sender=None, recipient=None):
        
        log = logging.getLogger(self.cls_logger + '.send_text_file')

        if not isinstance(text_file, basestring):
            msg = 'arg text_file must be a string, found type: {t}'.format(t=text_file.__class__.__name__)
            raise AssetMailerError(msg)

        if not os.path.isfile(text_file):
            msg = 'The provided text_file was not found or is not a file: {f}'.format(f=text_file)
            raise AssetMailerError(msg)

        # Determine sender/recipient
        if sender is None:
            sender = default_sender_email
        if recipient is None:
            recipient = self.recipient_email

        # Set the email subject
        file_name = text_file.split(os.path.sep)[-1]
        subject = self.subject + file_name

        # Read the input text file
        try:
            fp = open(text_file, 'rb')
            mail_message = MIMEText(fp.read())
            fp.close()
        except OSError:
            _, ex, trace = sys.exc_info()
            msg = '{n}: There was a problem reading text file: {f}\n{e}'.format(
                n=ex.__class__.__name__, f=text_file, e=str(ex))
            raise AssetMailerError, msg, trace

        # Configure the mail message
        mail_message['Subject'] = subject
        mail_message['From'] = sender
        mail_message['To'] = recipient

        # Configure the SMTP server
        log.debug('Configuring the SMTP server...')
        try:
            s = smtplib.SMTP(self.smtp_server)
        except (smtplib.SMTPConnectError, socket.timeout, socket.error):
            _, ex, trace = sys.exc_info()
            msg = '{n}: There was a problem connecting to SMTP server: {s}\n{e}'.format(
                n=ex.__class__.__name__, s=self.smtp_server, e=str(ex))
            raise AssetMailerError, msg, trace

        # Set the SMTP log level
        # s.set_debuglevel(debuglevel=__debug__)

        # Set the SMTP server to be localhost
        log.debug('Sending email with subject {s} to {e}...'.format(s=subject, e=recipient))
        try:
            s.sendmail(sender, [recipient], mail_message.as_string())
        except smtplib.SMTPRecipientsRefused:
            _, ex, trace = sys.exc_info()
            msg = '{n}: All recipients were refused, nobody got the mail: {r}:\n{e}'.format(
                n=ex.__class__.__name__, r=recipient, e=str(ex))
            raise AssetMailerError, msg, trace
        except smtplib.SMTPSenderRefused:
            _, ex, trace = sys.exc_info()
            msg = '{n}: The server did not accept the sender address: {s}:\n{e}'.format(
                n=ex.__class__.__name__, s=sender, e=str(ex))
            raise AssetMailerError, msg, trace
        except smtplib.SMTPHeloError:
            _, ex, trace = sys.exc_info()
            msg = '{n}: The server did not respond to the HELO greeting\n{e}'.format(
                n=ex.__class__.__name__, e=str(ex))
            raise AssetMailerError, msg, trace
        except smtplib.SMTPDataError:
            _, ex, trace = sys.exc_info()
            msg = '{n}: The server replied with an unexpected error code (other than a refusal of a recipient)\n{e}'.\
                format(n=ex.__class__.__name__, r=recipient, e=str(ex))
            raise AssetMailerError, msg, trace
        except smtplib.SMTPConnectError:
            _, ex, trace = sys.exc_info()
            msg = '{n}: There was a connection error\n{e}'. \
                format(n=ex.__class__.__name__, r=recipient, e=str(ex))
            raise AssetMailerError, msg, trace
        else:
            log.info('Sent email to: {r}'.format(r=recipient))
        finally:
            s.quit()
355463
def loop(server, test_loop=None):
    
    try:
        loops_without_activity = 0
        while test_loop is None or test_loop > 0:
            start = time.time()
            loops_without_activity += 1

            events = server.slack.rtm_read()
            for event in events:
                loops_without_activity = 0
                logger.debug("got {0}".format(event))
                response = handle_event(event, server)

                # The docs (https://api.slack.com/docs/message-threading)
                # suggest looking for messages where `thread_ts` != `ts`,
                # but I can't see anywhere that it would make a practical
                # difference. If a message is part of a thread, respond to
                # that thread.
                thread_ts = None
                if 'thread_ts' in event:
                    thread_ts = event['thread_ts']

                while response:
                    # The Slack API documentation says:
                    #
                    # Clients should limit messages sent to channels to 4000
                    # characters, which will always be under 16k bytes even
                    # with a message comprised solely of non-BMP Unicode
                    # characters at 4 bytes each.
                    #
                    # but empirical testing shows that I'm getting disconnected
                    # at 4000 characters and even quite a bit lower. Use 1000
                    # to be safe
                    server.slack.rtm_send_message(event["channel"],
                                                  response[:1000], thread_ts)
                    response = response[1000:]

            # Run the loop hook. This doesn't send messages it receives,
            # because it doesn't know where to send them. Use
            # server.slack.post_message to send messages from a loop hook
            run_hook(server.hooks, "loop", server)

            # The Slack RTM API docs say:
            #
            # > When there is no other activity clients should send a ping
            # > every few seconds
            #
            # So, if we've gone >5 seconds without any activity, send a ping.
            # If the connection has broken, this will reveal it so slack can
            # quit
            if loops_without_activity > 5:
                server.slack.ping()
                loops_without_activity = 0

            end = time.time()
            runtime = start - end
            time.sleep(max(1 - runtime, 0))

            if test_loop:
                test_loop -= 1
    except KeyboardInterrupt:
        if os.environ.get("LIMBO_DEBUG"):
            import ipdb
            ipdb.set_trace()
        raise
858847
async def _send_plain_text(self, request: Request, stack: Stack):
        

        await self._send_text(request, stack, None)
1217257
def send(self, msg, error_check=False):
        
        with self.lock:
            msg = msg.replace('\r', '\\r').replace('\n', '\\n') + self._crlf
            try:
                data = msg.encode(self.encoding)
            except UnicodeEncodeError:
                data = msg.encode(self.fallback_encoding)
            if len(data) > 512:
                raise self.MessageTooLong("LurklibError: MessageTooLong")
            self._socket.send(data)
            if error_check and self.readable():
                self._recv()
                self.stepback()
1233831
def communicate_through(self, file):
        
        if self._communication is not None:
            raise ValueError("Already communicating.")
        self._communication = communication = Communication(
            file, self._get_needle_positions,
            self._machine, [self._on_message_received],
            right_end_needle=self.right_end_needle,
            left_end_needle=self.left_end_needle)
        return communication
1363184
def send_line(self, data, nowait=False):
        """"""
        data = data.replace('\n', ' ').replace('\r', ' ')
        f = asyncio.Future(loop=self.loop)
        if self.queue is not None and nowait is False:
            self.queue.put_nowait((f, data))
        else:
            self.send(data.replace('\n', ' ').replace('\r', ' '))
            f.set_result(True)
        return f
773238
def put(self, file):
        
        input_ = {
            "message": file.logs,
            "author": file.author.dict(),
            "content": file.base64,
            "branch": file.branch
        }
        uri = "{api}/repos/{origin}/contents/{path}".format(
            api=self.github_api_url,
            origin=self.origin,
            path=file.path
        )
        data = self.request("PUT", uri, data=input_)

        if data.status_code == 201:
            file.pushed = True
            return file
        else:
            decoded_data = json.loads(data.content.decode("utf-8"))
            return self.ProxyError(
                data.status_code, (decoded_data, "message"),
                step="put", context={
                    "uri": uri,
                    "params": input_
                }
            )
895537
def send_inline_comment(issues)
      target_files = (git.modified_files - git.deleted_files) + git.added_files
      dir = "#{Dir.pwd}/"
      SEVERITY_LEVELS.reverse.each do |level|
        filtered = issues.select { |issue| issue.get("severity") == level }
        next if filtered.empty?
        filtered.each do |r|
          location = r.parent
          filename = location.get("name").gsub(dir, "")
          next unless !filtering || (target_files.include? filename)
          line = (r.get("line") || "0").to_i
          send(level == "warning" ? "warn" : "fail", r.get("message"), file: filename, line: line)
        end
      end
    end
1194105
def upload(self, **kwargs):
        
        if kwargs:
            self.params.update(kwargs)
        return FromUrl('https://slack.com/api/files.upload', self._requests)(data=self.params).post()
630493
function withFilePath (file, msg) {
	if (file && file.path) {
		msg += `\n    ${file.path}`;
	}
	return msg;
}
476798
def send_slack_message(message):
    """"""

    if 'SLACK_WEB_HOOK' not in os.environ:
        raise EnvironmentError("Could not find SLACK_WEB_HOOK environment variable")

    webhook = os.environ['SLACK_WEB_HOOK']

    r = requests.post(webhook, json={'text':message, 'username': 'Release Bot'})
    if r.status_code != 200:
        raise RuntimeError("Could not post message to slack channel")
515263
def do_failures(self, arg):
        
        usable, filename, append = self._redirect_split(arg)
        a = self.tests[self.active]
        args = self.curargs
        splitargs = usable.split()
        if len(splitargs) > 0:
            tfilter = splitargs[0]
        else:
            tfilter = "*"

        outfiles = None
        if len(splitargs) > 1:
            outfiles = splitargs[1:len(splitargs)]

        result = a.failures(outfiles, args["threshold"], tfilter)
        self._redirect_output(result, filename, append, msg.info)