Skip to content

Instantly share code, notes, and snippets.

@FennyFatal
Created January 2, 2017 22:55
Show Gist options
  • Save FennyFatal/7437504e1e33facc1d2eda3aa5a10dce to your computer and use it in GitHub Desktop.
Save FennyFatal/7437504e1e33facc1d2eda3aa5a10dce to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
require 'cinch'
require 'sqlite3'
require 'json'
require 'net/http'
require 'uri'
require 'ud'
require 'date'
:TitsMagoo
$api_key = "5f4535e87c41fd9033304d2f3eba7125"
$admin = "Fenny"
$db = SQLite3::Database.new "FapDB"
$db.execute "CREATE TABLE IF NOT EXISTS Urls(Id INTEGER PRIMARY KEY AUTOINCREMENT, Url TEXT)"
$db.execute "CREATE TABLE IF NOT EXISTS Tags(Id INTEGER REFERENCES Urls(Id), TAG TEXT, PRIMARY KEY (Id, TAG))"
$db.execute "CREATE TABLE IF NOT EXISTS LFMUsers(User TEXT, LFMUser TEXT, PRIMARY KEY (User, LFMUser))"
$db.execute "CREATE TABLE IF NOT EXISTS JAIL (Date INTEGER PRIMARY KEY, Jailed INTEGER, User TEXT)"
def make_placeholders(array)
if array.is_a? Array
return Array.new(array.count, '?').join(", ")
else
return '?'
end
end
def has_been_in_jail?(a_user)
retval = $db.get_first_value("Select count(User) from JAIL where User=?", [a_user])
true if retval > 0
end
def is_in_jail?(a_user)
retval = $db.get_first_value("Select Jailed from JAIL where User = ? order by Date DESC LIMIT 1", [a_user])
true if retval > 0
end
def jail_how_long(a_user)
$db.get_first_value("Select Date from JAIL where User = ? order by Date DESC LIMIT 1", [a_user])
end
def add_jail_record(a_user, status, date)
$db.execute("INSERT INTO JAIL (Date,Jailed,User) values (?, ? , ?)", [date, status, a_user] )
"#{a_user} was #{status > 0 ? 'jailed' : 'released'} on #{Date.jd(date)}."
end
def is_biskits_in_jail?
retval = $db.get_first_value("Select Jailed from JAIL where User = 'biskits' order by Date DESC LIMIT 1")
true if retval > 0
end
def biskits_jail_how_long
$db.get_first_value("Select Date from JAIL where User = 'biskits' order by Date DESC LIMIT 1")
end
def db_has_user?(a_user)
retval = $db.get_first_value("Select count(User) from LFMUsers where User=?", [a_user])
true if retval > 0
end
def db_get_lfm_user(a_user)
$db.get_first_value("Select LFMUser from LFMUsers where User=?", [a_user])
end
def get_user(a_user)
if (db_has_user?(a_user))
db_get_lfm_user(a_user)
else
a_user
end
end
def set_user(a_user, a_lfm_user)
if !db_has_user?(a_user)
$db.execute( "INSERT INTO LFMUsers (User, LFMUser) VALUES ( ? , ? )", [a_user, a_lfm_user])
"Set User for #{a_user} to #{a_lfm_user}"
else
$db.execute( "UPDATE LFMUsers SET LFMUser = ? WHERE User = ?", [a_lfm_user, a_user])
"Updated User for #{a_user} to #{a_lfm_user}"
end
end
def do_compare(a_user,another_user)
begin
response = Net::HTTP.get_response("ws.audioscrobbler.com", "/2.0/?method=tasteometer.compare&type1=user&type2=user&value1=#{get_user(a_user)}&value2=#{get_user(another_user)}&api_key=#{$api_key}&format=json")
jresponse = JSON.parse(response.body)
"#{a_user} and #{another_user} are #{"%3.2f" % (100 * jresponse["comparison"]["result"]["score"].to_f)}% compatible.\n" +
"Common artists: #{jresponse["comparison"]["result"]["artists"]["artist"].map{|a| "#{a["name"]}"}.join(', ')}"
rescue
"Error: Could not compare #{get_user(a_user)} and #{get_user(another_user)}."
end
end
def get_track_runtime(track)
return nil if track.nil?
if track["duration"] != nil
minutes = track["duration"].to_i / 1000 / 60
seconds = (track["duration"].to_i / 1000 ) - (minutes * 60)
"[#{minutes}:#{"%02d" % seconds}]"
else
nil
end
end
def get_track_tags(track, max_count)
return nil if track.nil?
if !track["toptags"].nil?
if !track["toptags"]["tag"].nil?
tag_count = track["toptags"]["tag"].count > 5 ? 5 : track["toptags"]["tag"].count
else
return nil
end
if !track["toptags"]["tag"][0]["name"].nil?
"(#{track["toptags"]["tag"][0..tag_count].map{|a| "#{a["name"]}"}.join(', ')})"
else
"(#{track["toptags"]["tag"]["name"]})"
end
end
end
def get_play_count(track_data)
return nil if track_data.nil?
if track_data["userplaycount"] != nil
"Played #{track_data["userplaycount"]} times"
else
nil
end
end
def is_now_playing?(track)
puts track
return nil if track.nil?
true if !track["@attr"].nil? && !track["@attr"].nil? && track["@attr"]["nowplaying"] == "true"
end
def get_when_last_played(track)
return if track.nil? || track["date"].nil? || track["date"]["uts"].nil?
timed = ((Time.now.utc.to_i - (track["date"]["uts"].to_i)) / 60)
timed > 60 ? (timed > 60*24 ? (timed > 60*24*365 ? "%3.2f Years ago" % (timed.to_f / (60*24*365)) : "%3.2f Days ago" % (timed.to_f / (60*24))) : "%3.2f Hours ago" % (timed.to_f / 60)) : "%d Minutes ago" % timed.to_f
end
def now_playing(a_user)
begin
jresponse = JSON.parse(Net::HTTP.get_response("ws.audioscrobbler.com", "/2.0/?method=user.getrecenttracks&user=#{get_user(a_user)}&limit=1&api_key=#{$api_key}&format=json").body)
puts jresponse
track = ( !jresponse["recenttracks"]["track"][0].nil? && !jresponse["recenttracks"]["track"][0]["@attr"].nil? ? jresponse["recenttracks"]["track"][0] : jresponse["recenttracks"]["track"] )
puts track
begin
track_data = JSON.parse(Net::HTTP.get_response("ws.audioscrobbler.com","/2.0/?method=track.getInfo&api_key=#{$api_key}&mbid=#{track["mbid"]}&username=#{get_user(a_user)}&format=json").body)["track"]
results = [["#{track["artist"]["#text"]} - #{track["name"]}",
get_track_runtime(track_data),
get_track_tags(track_data,5)].compact.map{|a| "#{a}"}.join(' '),
get_play_count(track_data),
get_when_last_played(track)].compact.map{|a| "#{a}"}.join(' : ')
rescue
begin
results = "#{track["artist"]["#text"]} - #{track["name"]} : #{get_when_last_played(track)}"
rescue
track = track.first
results = "#{
track["artist"]["#text"]
} - #{
track["name"]
} : #{
get_when_last_played(track)
}"
end
end
"* #{a_user} #{is_now_playing?(track) ? "is currently" : "was last"} playing: #{results}"
rescue => exception
puts exception.backtrace
puts exception
"Error: Could not get now playing for #{get_user(a_user)}"
end
end
def ud_define(query)
result = UD.query(query)
#puts UD.format_results(result, false)
puts "Word: #{result[0][:word]} Definition: #{result[0][:definition]}"
"%s: %s" % [Cinch::Formatting.format(:underline, "%s" % [Cinch::Formatting.format(:bold, "#{result[0][:word]}")]), result[0][:definition]]
end
def db_count_tag(tag)
return $db.get_first_value("Select count(Id) from Tags where Tag=?", [tag])
end
def db_has_url?(a_url)
$db.get_first_value("Select count(Id) from Urls where URL=?", [a_url]) > 0
end
def db_has_tag_for_id?(a_id, tag)
$db.get_first_value("Select count(Id) from Tags where Tag=? and Id=?", [tag, a_id]) > 0
end
def add_tag_to_id(a_id, tag)
if !db_has_tag_for_id?(a_id,tag)
$db.execute( "INSERT INTO Tags (Id, TAG) VALUES ( ? , ? )", [a_id, tag])
true
else
false
end
end
def get_id_for_url(a_url)
$db.get_first_value("Select Id from Urls where Url=?", [a_url])
end
def db_add_url(a_url)
$db.execute( "INSERT INTO Urls (URL) VALUES ( ? )", a_url)
$db.last_insert_row_id
end
def add_url(a_url, tags)
aTags = tags.strip.split(/[\s,]+/)
#puts aTags.inspect
if db_has_url?(a_url)
a_id = get_id_for_url(a_url)
rTags = []
aTags.each do |tag|
if add_tag_to_id(a_id, tag.strip)
rTags << tag
end
#puts tag
end
if rTags.count > 0
return "#{a_url} exists, added TAGS: #{rTags.join(", ")}"
else
"#{a_url} already exists!"
end
else
a_id = db_add_url(a_url)
aTags.each do |tag|
add_tag_to_id(a_id, tag.strip)
end
"Added: #{a_url} TAGS: #{aTags.join(", ")}"
end
end
def get_random_url_from_tag(tag)
aTags = tag.strip.split(/[\s,]+/).to_a
array = []
rows = $db.query("Select Id FROM Tags where tag in ( #{make_placeholders(aTags)} ) GROUP BY (Id) HAVING COUNT(Id) = #{aTags.count} ", aTags).each do |row|
array << row
end
return get_url_by_id(array.flatten[rand(array.flatten.count)])
end
def remove_url_by_url?(url)
if ($db.get_first_value( "select count(Id) from Urls where Url=?", url ) > 0)
id = get_id_for_url url
$db.query( "Delete from Tags where id=?", id )
$db.query( "Delete from Urls where id=?", id )
true
else
false
end
end
def get_url_by_id(tag_id)
#puts tag_id
array = []
rs = $db.query( "Select URL, TAG from Urls AS ur LEFT JOIN Tags as tg on tg.Id = ur.Id where tg.Id in( #{make_placeholders(tag_id)} ) ", [tag_id]).each do |row|
array << row
end
return array
end
def get_random_pretty_url_from_tag(tag)
pairs = get_random_url_from_tag(tag)
pretty = pairs[0][0]
tags = []
pairs.each do |pair|
tags << pair[1]
end
return "#{pretty} TAGS: #{tags.join(", ")}"
end
def startbot
$bot = Cinch::Bot.new do
helpers do
def is_admin?(user)
true if user.nick == $admin
end
end
configure do |c|
c.server = "irc.passtheheadphones.me"
c.channels = ["#boobs"]
c.nick = :TitsMagoo
c.realname = :TitsMagoo
end
on :connect do
end
on :message, /^hello[:,]{0,1} .*#{:Tits_Magoo}/i do |m|
m.reply "Hello, #{m.user.nick}"
end
on :message, /^[!.]get (.+)/i do |m, tag|
m.reply get_random_pretty_url_from_tag(tag)
end
on :message, /^[!.]remove (https?[:].+) ?/i do |m, url|
m.reply "#{remove_url_by_url?(url) ? "Removed #{url}" : "There is no #{url}" }"
end
on :message, /^[!.]help/i do |m|
m.reply 'Commands:'
m.reply '!get <tag>'
m.reply '!count <tag>'
m.reply '!add <url> <tag1> (<tag2> <tag3> ...)'
m.reply '!remove <url>'
end
on :message, /^[!.]add (https?[:].+?) (.*)/i do |m, url, tags|
m.reply "#{add_url(url,tags)}"
end
on :message, /^[!.]compare (.+)/ do |m, user|
m.reply "#{do_compare(m.user.name,user)}"
end
on :message, /^[!.]jail (.+?) (.*)$/ do |m, user, arg|
end
on :message, /^[!.]jail (.*)$/ do |m, user, arg|
epoch = Date.new(1970,1,1)
if has_been_in_jail?(user)
m.reply "#{user} has been #{is_in_jail?(user) ? 'in jail' : 'out of jail'} for #{'%.2f' %((Time.now.to_f/86400) - jail_how_long(user))} day(s)."
else
m.reply "#{user} has not been in jail according to our records."
end
end
on :message, /^[!.]setuser (\S+)$/ do |m, user|
m.reply "#{set_user(m.user.name, user)}"
end
on :message, /^[!.]setuser$/i do |m|
m.reply "Usage: !setuser <Last.FM Username>"
end
on :message, /^[!.]setuser (.+?) (.+)$/i do |m, a_user, lfm_user|
if is_admin?(m.user)
m.reply "#{set_user(a_user, lfm_user)}"
end
end
on :message, /^[!.]np$/ do |m|
m.reply "#{now_playing(m.user.name)}"
end
on :message, /^[!.]np (.+)/ do |m, user|
m.reply "#{now_playing(user)}"
end
on :message, /^[!.]ud (.+)/ do |m, query|
m.reply "#{ud_define(query)}"
end
on :message, /^[!.]count (.+)/ do |m, tag|
m.reply "Count of '#{tag}': #{db_count_tag(tag)}"
end
on :message, /^[!.]join (.+)/i do |m, channel|
if is_admin?(m.user)
$bot.join(channel)
end
end
on :message, "die" do |m|
if is_admin?(m.user)
$bot.quit
end
end
end
$bot.start
end
startbot
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment