Jake.codes

GroupMe Mentions

Sunday, July 14, 2013

Set up Twitter direct message notifications when you are mentioned in a GroupMe

#!/usr/bin/env ruby
require 'json'
require 'open-uri'
require 'yaml'
require 'faraday_middleware'
require 'twitter'

GROUPID = '' # Open GroupMe in the browser, https://web.groupme.com/groups/YOUR-GROUP-ID
ACCESS_TOKEN = '' # https://dev.groupme.com/
API_URL = 'https://api.groupme.com/v3/'

# https://dev.twitter.com
Twitter.configure do |config|
    config.consumer_key = ''
    config.consumer_secret = ''
    config.oauth_token = ''
    config.oauth_token_secret = ''
end

# This works like GroupMe's mentions in that if
# your name is 'Jake Bilbrey', 'Jake' will trigger
# a mention towards 'Jake Bilbrey'.
TWITTER_HANDLES = {
        "jake" => "jakebilbrey",
        "groupme-name" => "twitter-name"
    }

# Leave these blank, declaring arrays
USER_LIST = []
PREVIOUS_MENTIONS = []

# API Methods system picked up from
# dwradcliffe https://github.com/dwradcliffe/groupme
def fget(path)
    frequest(:get, path)
end
def fpost(path, data)
    frequest(:post, path, data)
end
def frequest(method, path, data={})
    res = fconnection.send(method, "#{path}", data)
    if res.status == 200
        return res.body.response
    else
        return res
    end
end
def fconnection
    @connection ||= Faraday.new API_URL do |f|
      f.request :json
      f.headers[:user_agent] = "Mentions App"
      f.headers["X-Access-Token"] = ACCESS_TOKEN
      f.response :mashify
      f.response :json, :content_type => /\bjson$/
      f.adapter Faraday.default_adapter
    end
end

def gmGetUsers
    users = fget("groups/#{GROUPID}")
    users.members.each { |user|
        # Push the first name of every group member to
        # the previously declared array.
        USER_LIST.push(user['nickname'].gsub(/ +.+/,''))
    }
end

def gmGetMessages
    newMessages = Array.new()
    messages = fget("groups/#{GROUPID}/messages")
    messages['messages'].each { |message|
        if message['text'].to_s.empty? == false
            # Grab the batch of the most recent 20 messages
            # with the message ID and user who sent it. 
            newMessages.push([ message['id'], message['name'], message['text'] ])
        end
    }
    return newMessages
end

def getmentions
    gmGetMessages.each { |message|
        # Prevent previously found mentions,
        # and prevent GroupMe Group Avatar/Name changes
        # that get sent to the chat from 'GroupMe'
        if PREVIOUS_MENTIONS.include?(message[0]) == false and message[1].gsub(/ +.+/,'') != 'GroupMe'
            USER_LIST.each { |user|
                if message[2].downcase.include? user.downcase and message[1].gsub(/ +.+/,'') != user
                    if TWITTER_HANDLES.has_key?(user.downcase)
                        tweet = 'd ' + TWITTER_HANDLES[user.downcase] + ' ' + message[1].gsub(/ +.+/,'') + ': ' + message[2]
                        if tweet.length > 140
                            # Truncate for 140 characters
                            tweet = tweet[0, 138] + '..'
                        end
                        # Echo out the tweet to the console
                        puts tweet
                        # Send to Twitter
                        Twitter.update(tweet)
                    end
                end
            }
        end
        # Add the message ID to the array so we don't send
        # a direct message twice.
        PREVIOUS_MENTIONS.push(message[0])
    }
end

# On launch, grab the list of users
gmGetUsers
while true do
    # Get the last 20 messages, check for mentions of people with Twitter accounts.
    getmentions

    # Wait 30 seconds and do it again
    sleep 30
end