Skip to content

Instantly share code, notes, and snippets.

Last active August 29, 2015 14:10
Show Gist options
  • Save brentc/63ce932e6c0dd8ea3b7a to your computer and use it in GitHub Desktop.
Save brentc/63ce932e6c0dd8ea3b7a to your computer and use it in GitHub Desktop.
# A script to remove messages added by hubot. Depends on the flowdock adapter
# Commands:
# hubot abortbot [n] - Delete the nth most recent message by hubot (defaults to 1) in the thread (or nth most recent message in the flow if not threaded)
# Dependencies:
# "hubot-flowdock": "0.7"
sortByKey = (array, key, ascending=true) ->
array.sort (a, b) ->
x = a[key]
y = b[key]
(if (x < y) then -1 else if (x > y) then 1 else 0) * (if not ascending then -1 else 1)
module.exports = (robot) ->
robot.respond /abortbot(?: (\d+))?$/i, (msg) ->
whichMessage = parseInt msg.match[1] || 1
room =
# Currently message_id is coming in as a string if the message is from a thread, so
# we use forced string comparison for this check
parent_message_id = if "#{}" != "#{msg.message.metadata.message_id}" then msg.message.metadata.message_id else false
if not room
robot.logger.error "Cannot process an abort command without a message flow"
flow = robot.adapter.flowFromParams({room: room})
if not flow
robot.logger.error "Cannot find a matching flow for #{room}"
botUserId = @robot.brain.userForName(
if not botUserId
robot.logger.error "Cannot determine Hubot's user id"
url = if parent_message_id
robot.logger.debug "Querying messages for #{}: #{url}"
event: "message,comment"
limit: 50
.get() (err, messages, body) ->
if err
robot.logger.error "Error querying messages: #{err}"
msg.send "Uh... sorry, I can't query my message history. Check the logs."
messages = sortByKey JSON.parse(body), 'id', false
if not messages
robot.logger.error "Couldn't parse messages response #{body}"
msg.send "Uh... sorry, I can't parse my message history. Check the logs."
msgCount = 0
for message in messages
if not minId or minId >
minId =
robot.logger.error "Messages not strictly ordered. Cannot continue."
msg.send "Uh... sorry, my message history is strange. Check the logs."
if parseInt(message.user) == botUserId # user id is a string in the API response
robot.logger.debug "Message Match #{msgCount} Found!"
if msgCount == whichMessage
deleteUrl = "#{flow.url}/messages/#{}"
robot.logger.debug "Calling delete URL: #{deleteUrl}"
msg.http(deleteUrl).auth("#{process.env.HUBOT_FLOWDOCK_USER_TOKEN}:").del() (err, res, body) ->
if err
robot.logger.error "Error deleting message: #{err}"
robot.logger.debug "Message delete response: #{body}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment