summaryrefslogtreecommitdiff
path: root/crystal/irc.cr
blob: ceddd56d1b5cb101399825cbaf1e409f2a0bbd5b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
require "twitch/irc"
require "http"
require "uri"
require "twitcr"
require "json"
require "crystal_mpd"

STDOUT.sync = true

settings = Hash(String, String).new

settings["home"] = Path.home.to_s
["access_token", "channel", "channel_id", "client_id", "client_id_twitch"].each do |key|
  begin
    settings[key] = File.read( settings["home"] + "/.config/twitch/" + key ).chomp
  rescue IO::Error
    STDERR.puts "Warning: Missing " + settings["home"] + "/.config/twitch/" + key
  end
end

snifflast = Int64.new(0)

client = Twitcr::Client.new( settings )

def urbandef( term : String )
  #http://api.urbandictionary.com/v0/define?term=waifu
  client = HTTP::Client.new( "api.urbandictionary.com" )
  response = client.exec( "GET", "/v0/define?term=" + URI.encode_www_form( term ) )
  puts response.status_code
  json = JSON.parse( response.body )
  return json["list"][0]["definition"].to_s.gsub( /[\[\]]/, "" ).gsub( /\n/, "" )
end

def ircmsg( home : String, channel : String, msg : String)
  if msg !~ /(\r|\n)/
    sock = Socket.unix
#    sock.connect Socket::UNIXAddress.new( home + "/.irssi/twitch-socket".to_s, type: Socket::Type::DGRAM )
    sock.connect Socket::UNIXAddress.new( home + "/.irssi/twitch-socket".to_s )
    sock.puts( "#" + channel + " " + msg )
    sock.close
  end
end

def t2smsg( msg : String)
  sock = Socket.unix
  sock.connect Socket::UNIXAddress.new( ENV["HOME"] + "/.t2s.sock" )
  sock.puts( msg )
  sock.close
rescue ex
  puts ex
end

def effectsmsg( msg : String )
  sock = Socket.unix
  sock.connect Socket::UNIXAddress.new( ENV["HOME"] + "/.effects.sock" )
  sock.puts( msg )
  sock.close
rescue ex
  puts ex
end

def userlog( settings : Hash(String, String), message : FastIRC::Message )
  unless ( ( prefix = message.prefix ) && ( chatuser = prefix.source ) && ( uid = message.tags["user-id"]? ) )
    return nil
  end
  basedir = settings["home"] + "/.cache/twitchtools"
  userdir = basedir + "/uids/" + uid
  unless File.directory?( userdir )
    Dir.mkdir( userdir )
  end
  unless File.directory?( userdir + "/names" )
    Dir.mkdir( userdir + "/names" )
  end
    unless File.symlink?( userdir + "/names/" + chatuser )
      namelatest = ""
      datelatest = Time::UNIX_EPOCH
      Dir.each_child( userdir + "/names/" ) do |name|
        namedate = File.info( userdir + "/names/" + name ).modification_time
        if namedate > datelatest
          namelatest = name
          datelatest = namedate
        end
      end
      unless namelatest.empty?
        ircmsg( settings["home"], settings["channel"], "Rename detected: #{uid}: #{namelatest} -> #{chatuser}" )
      end
      File.symlink( "../", userdir + "/names/" + chatuser )
    end
    unless File.symlink?( basedir + "/names/" + chatuser )
      File.symlink( "../uids/" + uid, basedir + "/names/" + chatuser )
    end
  unless ( message.params[0] == "#bungmonkey" )
    return nil
  end
  return ( [ chatuser, uid, userdir ] )
rescue ex
  puts ex
end

def getvoice( settings : Hash(String, String), userdir : String, chatuser : String )
  if File.exists?( userdir + "/voice" )
    voice_output = File.read( userdir + "/voice" ).chomp
    voice_setting = voice_output
  else
    voice_output = File.read( settings["home"] + "/voicelist.txt" ).chomp.split( "\n" ).sample( 1 )[0].chomp
    voice_setting = "random"
  end
  if File.exists?( userdir + "/voicesub" )
    namesub = File.read( userdir + "/voicesub" ).chomp
  else
    namesub = chatuser
  end
  return( [namesub, voice_setting, voice_output ] )
end

def t2s( settings : Hash(String, String), userdir : String, chatuser : String, text : String )
  if ( text !~ /^ *(!|\|)/ )
    namesub, voice_setting, voice = getvoice( settings, userdir, chatuser )
    t2stext = text.gsub( /http(s|):\/\/([a-z0-9.]+)\/[a-zA-Z0-9\/&=%-_]+/, "link to ${2}" )
    t2stext = t2stext.gsub( /rrr.+/, "rr" )
    t2smsg( "#{voice} #{namesub} #{t2stext}" )
    return( voice )
  else
    return( nil )
  end
end

voices = Hash(String, String).new
File.each_line( settings["home"] + "/voicelist.txt" ) do |line|
  voices[ line.downcase ] = line
end

lastvoice = Array(String).new

bot = Twitch::IRC::Client.new( nick: "bungmonkey", token: "oauth:" + settings["access_token"], log_mode: true )
bot.tags = [ "membership", "tags", "commands" ]

# Reconnect on IO::Error?

# Create a handler to process incoming messages
bot.on_message do |message|
  spawn do
  next unless ( userlogreturn = userlog( settings, message ) )
  chatuser, uid, userdir = userlogreturn
  if ( chatuser == "pipne" ) && ( ( Time.utc.to_unix - snifflast ) >= 14400 )
    snifflast = Time.utc.to_unix
    t2smsg( chatuser + " sniff null" )
  end
  if ( t2sreturn = t2s( settings, userdir, chatuser, message.params[1] ) )
    lastvoice.insert( 0, t2sreturn )
    lastvoice = lastvoice[0..4]
  end
  next unless ( ( match = message.params[1].match(/^ *!([A-Za-z]+) (([a-zA-Z0-9= _\:,.&'\/?;\\\(\)\[\]+\-]|!)+)/) || message.params[1].match(/^ *!([A-Za-z]+)/) ) )
  cmd = match[1]
  own = ( message.tags["room-id"] == message.tags["user-id"] )
  vip = ( message.tags["badges"].to_s.matches?( /(^|,)vip\// ) )
  mod = ( message.tags["mod"] == "1" )
  sub = ( message.tags["subscriber"] == "1" )
  if ( ( cmd =~ /^(substitute|voicesub)$/ ) && ( mod || sub ) )
    case message.params[1].split( " " ).size
    when 1
      if File.exists?( userdir + "/voicesub" )
        bot.message( "#bungmonkey", "| Current name substitution is \"#{File.read( userdir + "/voicesub" )}\"." )
      else
        bot.message( "#bungmonkey", "| Current name substitution is disabled." )
      end
    else
      if match[2]?
          voicesub = match[2].downcase
        if voicesub =~ /^(disabled|null|disable|none)$/
          if File.exists?( userdir + "/voicesub" )
            File.delete( userdir + "/voicesub" )
            bot.message( "#bungmonkey", "| Name substitution for #{chatuser} is now disabled." )
          else
            bot.message( "#bungmonkey", "| Name substitution for #{chatuser} is already disabled." )
          end
        else
          File.directory?( userdir ) || Dir.mkdir( userdir )
          File.write( userdir + "/voicesub", voicesub )
          bot.message( "#bungmonkey", "| Name substitution for #{chatuser} is now \"#{File.read( userdir + "/voicesub" )}\"." )
        end
      end
    end
  elsif ( cmd =~ /^(commands|help)$/ )
    bot.message( "#bungmonkey", "| https://bungmonkey.omgwallhack.org/txt/commands.txt" )
  elsif ( ( cmd == "lastvoice" ) && ( mod || sub ) )
    unless lastvoice.empty?
    bot.message( "#bungmonkey", "| Last voices were " + lastvoice.join( ", " ) )
    else
      bot.message( "#bungmonkey", "| No voices used so far." )
    end
  elsif ( ( cmd =~ /^(voices|voicelist)$/ ) && ( mod || sub ) )
    bot.message( "#bungmonkey", "| https://bungmonkey.omgwallhack.org/voicelist.txt" )
  elsif ( ( cmd =~ /^(setvoice|voice)$/ ) && ( mod || sub ) )
    case message.params[1].split( " " ).size
    when 1
      namesub, voice_setting, voice_output = getvoice( settings, userdir, chatuser )
      bot.message( "#bungmonkey", "| Current voice is #{voice_setting}" )
    when 2
      if match[2]?
        voice = match[2].downcase
        if voice =~ /disabled|null|disable|none|random/
          if File.exists?( userdir + "/voice" )
            File.delete( userdir + "/voice" )
            bot.message( "#bungmonkey", "| Voice for #{chatuser} is now random." )
          else
            bot.message( "#bungmonkey", "| Voice for #{chatuser} is already random." )
          end
        elsif voices.has_key?( voice )
          csvoice = voices[voice]
          File.directory?( userdir ) || Dir.mkdir( userdir )
          File.write( userdir + "/voice", csvoice )
          pp userdir
          bot.message( "#bungmonkey", "| Voice for #{chatuser} is now #{File.read( userdir + "/voice" )}." )
          # TODO: make separate script to print streamelements URLs to client machine
        else
          pp ( match )
          bot.message( "#bungmonkey", "| Invalid voice. To see list, use !voices" )
        end
      end
    when 3
    else
    end
  elsif ( ( cmd =~ /^(status|title)$/ ) && ( mod || own ) )
    begin
      if match[2]?
        client.put_channel!( settings["channel_id"].to_u64, title: match[2] )
        json = JSON.parse( client.get_channel( settings["channel_id"].to_u64 ) )
        ircmsg( settings["home"], settings["channel"], "Title is now \"#{ json["data"][0]["title"] }\"")
      else
        json = JSON.parse( client.get_channel( settings["channel_id"].to_u64 ) )
        ircmsg( settings["home"], settings["channel"], "| Title is currently \"#{ json["data"][0]["title"] }\"")
      end
    rescue ex
      ircmsg( settings["home"], settings["channel"], "| An error occurred! " + ex.message.to_s )
    end
  elsif ( ( cmd =~ /^(game|category)$/ ) && ( mod || own ) )
    begin
      if match[2]?
          puts "2 matches"
        client.put_channel!( settings["channel_id"].to_u64, game: match[2] )
        json = JSON.parse( client.get_channel( settings["channel_id"].to_u64 ) )
        ircmsg( settings["home"], settings["channel"], "Game is now \"#{ json["data"][0]["game_name"] }\"")
      else
        puts "1 matches"
        json = JSON.parse( client.get_channel( settings["channel_id"].to_u64 ) )
        ircmsg( settings["home"], settings["channel"], "| Game is currently \"#{ json["data"][0]["game_name"] }\"")
      end
    rescue ex
      ircmsg( settings["home"], settings["channel"], "| An error occurred! " + ex.message.to_s )
    end
  elsif ( ( cmd == "urban" ) && ( mod || own || sub || vip ) )
    if match[2]? && match[2] =~ /^([a-zA-Z0-9 -])+$/
      definition = urbandef( match[2] )
      ircmsg( settings["home"], settings["channel"], definition[0,400] )
    else
      ircmsg( settings["home"], settings["channel"], "| Urban Dictionary search term should consist of letters, numbers, spaces, and/or hyphens." )
    end
  elsif ( cmd == "matrix" )
    effectsmsg( "overlay glmatrix" )
  elsif ( cmd =~ /juggle|juggler/ )
    effectsmsg( "overlay juggler3d" )
  elsif ( cmd =~ /fireworks|firework/ )
    effectsmsg( "overlay fireworkx" )
  elsif ( cmd == "pipes" )
    if match[2]? && match[2] =~ /^(fast|faster)$/
      effectsmsg( "overlay pipes " + match[2] )
    else
      effectsmsg( "overlay pipes" )
    end
  elsif ( cmd == "jellyfish" )
    effectsmsg( "overlay hydrostat" )
  elsif ( cmd == "gluten" )
    effectsmsg( "overlay flyingtoasters" )
  elsif ( cmd =~ /^(glsnake|glmatrix|gibson|xmatrix|flyingtoasters|moebiusgears|fireworkx|hydrostat|hypertorus|jigsaw|juggler3d|kaleidocycle|kumppa|molecule|noof|polyhedra)$/ )
    effectsmsg( "overlay " + cmd )
  elsif ( cmd =~ /gltext|cowsay|xcowsay/ )
    if ( match[2]? ) && ( gltextargs = match[2].match( /^([0-9]+) +(.+)$/ ) )
      seconds=UInt64.new( 1 )
      seconds=gltextargs[1].to_u64
      if ( own || mod || vip )
        effectsmsg( "overlay #{cmd} #{match[2]}" )
        puts "matched #{cmd} #{match[2]}"
      elsif ( sub )
        if ( seconds > 20 )
          seconds=20
        end
        effectsmsg( "overlay #{cmd} #{seconds} #{gltextargs[2]}" )
        puts "matched #{cmd} #{seconds} #{gltextargs[2]}"
      else
        if ( seconds > 5 )
          seconds=5
        end
        effectsmsg( "overlay #{cmd} #{seconds} #{gltextargs[2]}" )
        puts "matched #{cmd} #{seconds} #{gltextargs[2]}"
      end
    elsif match[2]? && match[2] =~ /^.+$/
      effectsmsg( "overlay #{cmd} #{match[2]}" )
      puts "matched #{cmd} #{match[2]}"
    else
      effectsmsg( "overlay #{cmd}" )
      puts "failed to match gltext"
    end
  elsif ( cmd =~ /cow|cowabunga|holycow/ )
    if match[2]? && match[2] =~ /^([0-9])+$/
      effectsmsg( "overlay bouncingcow #{match[2]}" )
    else
      effectsmsg( "overlay bouncingcow" )
    end
  elsif ( cmd == "overlay" )
    if match[2]? && match[2] =~ /^[a-z]+$/
        ircmsg( settings["home"], settings["channel"], "| overlay requires an argument consisting wholly of lower case characters.")
      effectsmsg( "overlay #{match[2]}" )
    else
    end
  elsif ( cmd == "hackerman" )
    ircmsg( settings["home"], settings["channel"], "| https://bungmonkey.omgwallhack.org/img/hackerman.jpg" )
  elsif ( cmd =~ /^(songrequest|sr)$/ ) && match[2]?
    puts ("song detected: #{match[2]}")
    if ( ( match[2] =~ /list=/ ) && ( match[2] !~ /v=/ ) )
      ircmsg( settings["home"], settings["channel"], "| Lists are not accepted.\n" )
    elsif Process.run( "sraddsong.sh", {match[2]} )
      m = MPD::Client.new
      currentsong = m.currentsong
      if ( currentsong ) && ( currentsong["file"].to_s == "http://music/music.ogg" )
        m.next
      end
      if ( status = m.status ) && ( playlistinfo = m.playlistinfo )
        ircmsg( settings["home"], settings["channel"], "| " + playlistinfo[ status["playlistlength"].to_i - 1 ]["file"].to_s + " added in position " + status["playlistlength"].to_s )
      else
        ircmsg( settings["home"], settings["channel"], "| A failure occured." )
      end
      m.disconnect
    else
    end
  elsif ( cmd =~ /^current(|song)$/ )
    m = MPD::Client.new
    if ( currentsong = m.currentsong )
        ircmsg( settings["home"], settings["channel"], "| Currently playing: " + currentsong["file"].to_s )
    else
      ircmsg( settings["home"], settings["channel"], "| A failure occured." )
    end
    m.disconnect
  elsif ( cmd =~ /^seek$/ )
    if ( ( match[2] ) && ( match[2] =~ /([+-]|)[0-9]/ ) )
      m = MPD::Client.new
      m.seekcur( match[2] )
      if ( ( musicstatus = m.status ) && ( pos = musicstatus["elapsed"].to_f.to_u64 ) )
        min=( pos / 60 ).to_u64
        sec=( pos % 60 ).to_u64
        ircmsg( settings["home"], settings["channel"], "| " + sprintf( "2%d:2%d", min, sec ) )
      else
        ircmsg( settings["home"], settings["channel"], "| An error occurred. " )
      end
      m.disconnect
    else
      ircmsg( settings["home"], settings["channel"], "| Seek requires an argument of an absolute position in integer number of seconds, or a relative position in in signed integer number of seconds such as +60" )
    end
  elsif ( cmd =~ /^next(|song)$/ )
    m = MPD::Client.new
    m.next
    if ( status = m.status ) && ( status["playlistlength"].to_i > 0 )
      if ( currentsong = m.nextsong )
        ircmsg( settings["home"], settings["channel"], "| Currently playing: " + currentsong["file"].to_s )
      else
        ircmsg( settings["home"], settings["channel"], "| A failure occured." )
      end
    else
      ircmsg( settings["home"], settings["channel"], "| Playlist is now empty." )
    end
    m.disconnect
  elsif ( cmd == "followage" )
    begin
      if match[2]?
        args = match[2].split(/\s/)
        if args[1]?
          json = JSON.parse( client.get_user_follows( from: client.user_id( args[0] ).to_u64 , to: client.user_id( args[1] ).to_u64 ) )
          puts client.user_id( args[0] ).to_s
          puts client.user_id( args[1] ).to_s
          puts json
          ircmsg( settings["home"], settings["channel"], "| " + json["data"][0]["followed_at"].to_s )
        elsif args[0]?
          json = JSON.parse( client.get_user_follows( from: client.user_id( args[0] ).to_u64 , to: settings["channel_id"].to_u64 ) )
          puts client.user_id( args[0] ).to_s
          puts json
          ircmsg( settings["home"], settings["channel"], "| " + json["data"][0]["followed_at"].to_s )
        end
      else
        json = JSON.parse( client.get_user_follows( from: uid.to_u64 , to: settings["channel_id"].to_u64 ) )
        puts json
        ircmsg( settings["home"], settings["channel"], "| " + json["data"][0]["followed_at"].to_s )
      end
    rescue ex
      ircmsg( settings["home"], settings["channel"], "An error occurred! " + ex.message.to_s )
    end
  end
  end
end


rooms = Array( String ).new
rooms = [ "#bungmonkey", "kr3wzz" ]

while true
  begin
# Connect to Twitch
    bot.run( rooms.map{ | room | room.sub( /^#/, "") } )
  rescue ex : IO::Error
    pp ex
    # loop to reconnect
  rescue ex
    pp ex
    exit 1
  end
end


# FastIRC::Message.to_s
# @badge-info=;badges=;color=;display-name=BungMonkey;emotes=;flags=;id=20fcc358-4fc3-4919-8229-f1034743d18f;mod=0;room-id=46694819;subscriber=0;tmi-sent-ts=1587876383907;turbo=0;user-id=59895482;user-type= :bungmonkey!bungmonkey@bungmonkey.tmi.twitch.tv PRIVMSG #kr3wzz test

# FastIRC::Message.tags
# {"badge-info" => "subscriber/34",
#  "badges" => "broadcaster/1,subscriber/12",
#  "color" => "",
#  "display-name" => "BungMonkey",
#  "emote-only" => "1",
#  "emotes" => "300780134:0-9",
#  "flags" => "",
#  "id" => "c5c08c05-6e39-483f-b426-488dfc477a6c",
#  "mod" => "0",
#  "room-id" => "59895482",
#  "subscriber" => "1",
#  "tmi-sent-ts" => "1587871386678",
#  "turbo" => "0",
#  "user-id" => "59895482",
#  "user-type" => ""}

#command = "PRIVMSG"
#prefix = Prefix(@source="bungmonkey", @user="bungmonkey", @host="bungmonkey.tmi.twitch.tv")
#params = ["#bungmonkey", "test test test test"]