Skip to content
This repository was archived by the owner on Jun 8, 2023. It is now read-only.

adding a simple hashtag/mention tracker #1131

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions src/scripts/twitbot.coffee
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
# Description:
# Track hashtags and mentions, for fun.
#
# Dependencies:
# None
#
# Configuration:
# None
#
# Commands:
# #<hashtag> - increment hashtag counter
# @<mention> - increment mention counter
# hubot mentions - list the most popular mentions
# hubot hashtags - list the most popular hashtags
# hubot twitbot reset - reset twitbot data
#
# Author:
# robhurring

class Twitbot
constructor: (@robot) ->
@reset()
@robot.brain.on 'loaded', =>
if @robot.brain.data.twitbot
@cache = @robot.brain.data.twitbot

reset: ->
@cache =
mentions: {}
hashtags: {}

add_mention: (user) ->
user = user.trim().toLowerCase()
@cache.mentions[user] ?= 0
@cache.mentions[user] += 1
@robot.brain.data.twitbot = @cache

top_mentions: (n = 10) ->
sorted = @sort('mentions')
sorted.slice(0, n)

add_hashtag: (hashtag) ->
hashtag = hashtag.trim().toLowerCase()
@cache.hashtags[hashtag] ?= 0
@cache.hashtags[hashtag] += 1
@robot.brain.data.twitbot = @cache

top_hashtags: (n = 10) ->
sorted = @sort('hashtags')
sorted.slice(0, n)

sort: (bucket) ->
s = []
for key, val of @cache[bucket]
s.push({ data: key, count: val })
s.sort (a, b) -> b.count - a.count

module.exports = (robot) ->
twitbot = new Twitbot robot

robot.hear /(^|\s)@([A-Za-z0-9_]+)/g, (msg) ->
console.log msg.match
for mention in msg.match
twitbot.add_mention mention

robot.hear /(^|\s)#(\w+)/g, (msg) ->
for hashtag in msg.match
twitbot.add_hashtag hashtag

robot.respond /twitbot reset/i, (msg) ->
twitbot.reset()
msg.send "Ok. Twitbot is reset."

robot.respond /mentions$/i, (msg) ->
_output = []
for mention in twitbot.top_mentions()
_output.push "#{mention.data} has #{mention.count} mentions"

if _output.length
msg.send _output.join("\n")
else
msg.send "There are no mentions right now"

robot.respond /hashtags$/i, (msg) ->
_output = []
for hashtag in twitbot.top_hashtags()
_output.push "#{hashtag.data} was used #{hashtag.count} times"

if _output.length
msg.send _output.join("\n")
else
msg.send "There are no hashtags right now"