Skip to content

Instantly share code, notes, and snippets.

@s3krit
Created January 28, 2017 21:24
Show Gist options
  • Save s3krit/d7a32990f89f4e9fb7c5c2847ab7b7b8 to your computer and use it in GitHub Desktop.
Save s3krit/d7a32990f89f4e9fb7c5c2847ab7b7b8 to your computer and use it in GitHub Desktop.
lostfm.rb
require 'dbi'
require 'pry'
require 'cinch'
require 'httpclient'
require 'json'
require 'lastfm'
# Connect to the DB and init
$dbh = DBI.connect('DBI:SQLite3:nickdb')
$dbh.do('CREATE TABLE users(nick varchar(9), lastfm varchar(20));') rescue puts 'Table users already exists'
# Then lastfm
$api_key = ""
$shared_secret = ""
$lastfm = Lastfm.new($api_key,$shared_secret)
def lastfm_exists?(username)
return true if $lastfm.user.get_info(username) rescue return false
end
def get_latest_track(username)
# lastfm gem won't let us do this...
url = "http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=#{username}&api_key=#{$api_key}&nowplaying=true&format=json"
JSON.parse(HTTPClient.get_content(url))['recenttracks']['track'].first
end
def add_user(nick, lastfm_username)
add_sql = 'INSERT INTO users (lastfm,nick) VALUES (?, ?)'
update_sql = 'UPDATE users SET lastfm=? where nick=?'
if lookup_lastfm_username(nick)
sql = update_sql
else
sql = add_sql
end
$dbh.prepare(sql) do |sth|
sth.execute(lastfm_username,nick)
end
end
def lookup_lastfm_username(nick)
sql = 'SELECT lastfm FROM users WHERE nick=?'
row = $dbh.select_one(sql,nick)
return nil unless row
return row[0]
end
# Define the bot
bot = Cinch::Bot.new do
configure do |c|
c.server = "irc.rizon.net"
c.channels = []
c.nick = "lostfm"
end
on :message, /^\.lastfm add (\w+)$/ do |m,lastfm_username|
if lastfm_exists?(lastfm_username)
add_user(m.user.nick,lastfm_username) rescue m.reply "Error adding user (do they exist?)"
m.reply "User #{lastfm_username} set for #{m.user.nick}"
end
end
on :message, /^\.np$/ do |m|
lastfm_username = lookup_lastfm_username(m.user.nick)
if lastfm_username
track = get_latest_track(lastfm_username)
m.reply "NP: "+track['artist']['#text']+" - "+track['name']+" ("+track['album']['#text']+")"
else
m.reply "No lastfm username specified. Type '.lastfm add username' to add your user"
end
end
on :invite do |m|
bot.join(m.channel)
end
end
bot.start
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment