set tgqdb "/home/d/eggdrop/scripts/trivia.questions"
set tgqdbsep "|"

#  What you set here defines how the bot expects the question/answer
#  pairs to be arranged.
#  If set to 1, bot expects lines in the format:
#    question<seperator>answer
#  If set to 0, bot expects lines in the format:
#    answer<seperator>question
set tgqdbquestionfirst 1
set tgerrmethod 0
set tgerremail "indra82@gmail.com"
set tgerrmailtmp "/tmp"
set tghtmlrefresh 0
set tghtmlfont "verdana,helvetica,arial"
set tgchan "#Tegal"
set tgpointsperanswer 10
set tgmaxhint 3

#  Should the bot show the question on each hint (1) or only on the first (0)?
set tgalwaysshowq 0
set tgcapsquestion 0
set tgcapsanswer 0
set tgcapshint 0
set tgstreakmin 0
set tgmaxmissed 0
set tghintchar "*"
set tgtimehint 15
set tgtimenext 5
set tgcongrats [list "Nice" "Well done" "Nice going" "VeryWeLL" "Good" "Excelent" "Bravo" "Yes"]
set tgnobodygotit [list "Time is Up." "No Body Answer" "Try harder!" "Ohh No" "NoBody?"]
set tgtrythenextone [list "Next.." "Get ready..." "Move on..." "Try next one..." "Next one..."]
set tgtimeanswer 1
set tgshowanswer 1
set tgshowallscores 0
set tgusebold 0
set tgpriv2msg 0
set tgcmdstart "!starttrv"
set tgflagsstart "-|-"
set tgcmdstop "!stoptrv"
set tgflagsstop "m|m"
set tgcmdhint "!hinttrv"
set tgflagshint "m|m"
set tgtempnohint 10
set tgcmdskip "!skiptrv"
set tgflagsskip "m|m"
set tgcmdtop10 "!top10trv"
set tgflagstop10 "m|m"
set tgcmdreset "reset"
set tgflagsreset "m|m"
set tgresetreqpw 1

set tgcolourstart "03"		;#Game has started.
set tgcolourstop "04"		;#Game has stopped.
set tgcolourskip "10"		;#Question has been skipped.
set tgcolourerr "04"		;#How to report errors.
set tgcolourmiss "10"		;#Nobody answered the question.
set tgcolourqhead "04"		;#Question heading.
set tgcolourqbody "12"		;#Question text
set tgcolourhint "03"		;#Hint.
set tgcolourstrk "12"		;#Person is on a winning streak.
set tgcolourscr1 "04"		;#Score of person in first place.
set tgcolourscr2 "12"		;#Score of person in second place.
set tgcolourscr3 "03"		;#Score of person in third place.
set tgcolourrset "04"		;#Scores have been reset.
set tgcolourstend "12"		;#Winning streak ended.
set tgcolourmisc1 "06"		;#Miscellaneous colour #1.
set tgcolourmisc2 "04"		;#Miscellaneous colour #2.


# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#                                                                   #
#    Any editing done beyond this point is done at your own risk!   #
#                                                                   #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#Misc checks & var initialisations
set tgver "1.3.4"
set tgrel "release"
if {[info tclversion]<8.2} {
	putlog "\002[file tail [info script]]\002 failed to load: in order to use this script, eggdrop needs to be compiled to use tcl 8.2 or higher (recommended: latest stable version)."
	return
}
if {$tgtimeanswer==1&&[info tclversion]<8.3} {
	putlog "\002[file tail [info script]]\002 warning: timing of answers has been automatically disabled. this feature requires tcl 8.3 or higher."
	set tgtimeanswer 0
}
if {![info exists alltools_loaded]||$allt_version<205} {
	putlog "\002[file tail [info script]]\002 failed to load: please load alltools.tcl v1.14 or higher (available with eggdrop 1.6.13 or higher) before attempting to load this script."
	return
}
if {[utimerexists tghtml]!=""} {killutimer $tghtmlrefreshtimer}
if {$tghtmlrefresh>0} {
	set tghtmlrefreshtimer [utimer $tghtmlrefresh tghtml]
}
if {![file exists $tgqdb]} {
	putlog "\002[file tail [info script]]\002 failed to load: $tgqdb does not exist."
	return
}
if {[llength [split $tgchan]]!=1} {
	putlog "\002[file tail [info script]]\002 failed to load: too many channels specified."
	return
}
if {![info exists tgplaying]} {
	set ctcp-version "${ctcp-version} (with trivia.tcl)"
	set tgplaying 0
}
if {![info exists tghintnum]} {set tghintnum 0}
if {![info exists tgmissed]} {set tgmissed 0}

#Binds
bind pubm $tgflagsstart "$tgchan %$tgcmdstart" tgstart
bind pubm $tgflagsstop "$tgchan %$tgcmdstop" tgstop
proc tgbindhintcmd {} {
	global tgflagshint tgcmdhint
	bind pubm $tgflagshint "$::tgchan %$tgcmdhint" tgforcehint
}
proc tgunbindhintcmd {} {
	global tgflagshint tgcmdhint
	unbind pubm $tgflagshint "$::tgchan %$tgcmdhint" tgforcehint
}
tgbindhintcmd
bind pubm $tgflagsskip "$tgchan %$tgcmdskip" tgskip
bind pubm $tgflagstop10 "$tgchan %$tgcmdtop10" tgshowtop10
bind msg $tgflagsreset "$tgcmdreset" tgresetscores
bind kick - "$tgchan $botnick" tgbotgotkicked
bind evnt - disconnect-server tgbotgotdisconnected



#starts the game if it isn't running.
proc tgstart {nick host hand chan text} {
	global tgplaying tgstreak tgchan  tgmissed
#tgerrremindtime tgerrremindtimer
	if {[strlwr $tgchan]==[strlwr $chan]} {
		if {$tgplaying==0} {
#			tggamemsg "[tgcolstart]Trivia game started by $nick!"
			tgnextq
			set tgplaying 1
			set tgstreak 0
			set tgmissed 0
#			set tgerrremindtimer [timer $tgerrremindtime tgerrremind]
		}
	}
}

#stops the game if it's running.
proc tgstop {nick host hand chan text} {
	global tghinttimer tgnextqtimer tgplaying tgchan tgcurrentanswer tgstreak tgstreakmin
#	global tgerrremindtimer tgrebindhinttimer
	if {[strlwr $tgchan]==[strlwr $chan]} {
		if {$tgplaying==1} {
#			tggamemsg "4Game are now change to 12Scramble.4 Get Ready!"
			if {$tgstreakmin>0&&[lindex [split $tgstreak ,] 1]>=$tgstreakmin} { tgstreakend }
			set tgstreak 0
			set tgplaying 0
			catch {unbind pubm -|- "$tgchan *" tgcheckanswer}
			if {[utimerexists tghint]!=""} {killutimer $tghinttimer}
			if {[utimerexists tgnextq]!=""} {killutimer $tgnextqtimer}
#			if {[timerexists tgerrremind]!=""} {killtimer $tgerrremindtimer}
			if {[utimerexists tgrebindhinttimer]!=""} {killtimer $tgrebindhinttimer}
		}
	}
}

#gives a hint if there is currently a question to answer.
proc tgforcehint {nick host hand chan text} {
	global tghinttimer tgnextqtimer tgplaying tgchan tgcurrentanswer tgstreak tgstreakmin
	global tgtempnohint tgmaxhintcurrent tghintnum tgrebindhinttimer tgtempnohint
	if {[strlwr $tgchan]==[strlwr $chan]} {
		if {$tgplaying==1&&[utimerexists tghint]!=""} {
			killutimer $tghinttimer
			tghint
			tgunbindhintcmd
			if {$tghintnum<$tgmaxhintcurrent} {
				set tgrebindhinttimer [utimer $tgtempnohint tgbindhintcmd]
			}
		}
	}
}

#skips the current question if one has been asked.
proc tgskip {nick host hand chan text} {
	global tghinttimer tgnextqtimer tgplaying tgchan tgcurrentanswer tgstreak
	global tgstreakmin tgtimenext tgrebindhinttimer
	if {[strlwr $tgchan]==[strlwr $chan]} {
		if {$tgplaying==1&&[utimerexists tghint]!=""} {
			tggamemsg "[tgcolskip]Skipping to next question by [tgcolmisc2]$nick's[tgcolskip] request..."
			if {$tgstreakmin>0&&[lindex [split $tgstreak ,] 1]>=$tgstreakmin&&[strlwr [lindex [split $tgstreak ,] 0]]==[strlwr $nick]} {
				tgstreakend
				set tgstreak 0
			}
			catch {unbind pubm -|- "$tgchan *" tgcheckanswer}
			killutimer $tghinttimer
			if {[utimerexists tgrebindhinttimer]!=""} {killtimer $tgrebindhinttimer}
			set tgnextqtimer [utimer $tgtimenext tgnextq]
		}
	}
}


#bot got kicked. stop the game.
proc tgbotgotkicked {nick host hand chan targ text} {
	tgquietstop
}

#bot got disconnected. stop the game.
proc tgbotgotdisconnected {disconnect-server} {
	tgquietstop
}

#stops the game without telling the channel.
proc tgquietstop {} {
	global tgplaying tgstreak tgchan tgcurrentanswer tghinttimer tgnextqtimer 
#tgerrremindtimer
	global tgrebindhinttimer
	if {$tgplaying==1} {
		set tgstreak 0
		set tgplaying 0
		catch {unbind pubm -|- "$tgchan *" tgcheckanswer}
		if {[utimerexists tghint]!=""} {killutimer $tghinttimer}
		if {[utimerexists tgnextq]!=""} {killutimer $tgnextqtimer}
#		if {[timerexists tgerrremind]!=""} {killtimer $tgerrremindtimer}
		if {[utimerexists tgrebindhinttimer]!=""} {killtimer $tgrebindhinttimer}
	}
}

#reads the question database.
proc tgreadqdb {} {
	global tgqdb tgquestionstotal tgquestionslist
	set tgquestionstotal 0
	set tgquestionslist ""
	set qfile [open $tgqdb r]
	set tgquestionslist [split [read -nonewline $qfile] "\n"]
	set tgquestionstotal [llength $tgquestionslist]
	close $qfile
}

#selects the next question.
proc tgnextq {} {
	global tgqdb tgcurrentquestion tgcurrentanswer tgquestionnumber
	global tgquestionstotal tghintnum tgchan tgquestionslist tgqdbsep tgqdbquestionfirst
	global tgcapsquestion tgcapsanswer
	tgreadqdb
	set tgcurrentquestion ""
	set tgcurrentanswer ""
	while {$tgcurrentquestion == ""} {
		set tgquestionnumber [rand [llength $tgquestionslist]]			
		set tgquestionselected [lindex $tgquestionslist $tgquestionnumber]
		set tgcurrentquestion [lindex [split $tgquestionselected $tgqdbsep] [expr $tgqdbquestionfirst^1]]
		if {$tgcapsquestion==1} {
			set tgcurrentquestion [strupr $tgcurrentquestion]
		}
		set tgcurrentanswer [string trim [lindex [split $tgquestionselected $tgqdbsep] $tgqdbquestionfirst]]
		if {$tgcapsanswer==1} {
			set tgcurrentanswer [strupr $tgcurrentanswer]
		}
	}
	unset tghintnum
	tghint
	bind pubm -|- "$tgchan *" tgcheckanswer
	return
}

#shows timed hints.
proc tghint {} {
	global tgmaxhint tghintnum tgcurrentanswer tghinttimer tgchan
	global tgtimehint tghintchar tgquestionnumber tgquestionstotal
	global tgcurrentquestion tghintcharsused tgnextqtimer tgtimenext tgstreak tgstreakmin
	global tgnobodygotit tgtrythenextone tgmissed tgmaxmissed tgcmdstart tgshowanswer
	global tgtimestart tgtimeanswer tgalwaysshowq tgmaxhintcurrent tgtempnohint tgcapshint

	global tccurrentanswer tchinttimer tctimenext tcchan tcnextqtimer tcstreak tcstreakmin
	global tcscoresbyname tcranksbyname tcranksbynum tccongrats tcscorestotal tcmissed
	global tctimestart tcshowallscores tcrealnames tcscoresbyrank tctimeanswer

        #global KAOSAnswers KAOSNumAnswered KAOSQuestionTimer KAOSAdTimer

	if {[catch {incr tghintnum}]!=0} {
		set tghintnum 0
		regsub -all -- "\[^A-Za-z0-9\]" $tgcurrentanswer "" _hintchars
		set tgmaxhintcurrent [expr [strlen $_hintchars]<=$tgmaxhint?[expr [strlen $_hintchars]-1]:$tgmaxhint]
		catch {tgunbindhintcmd}
		if {$tgmaxhintcurrent>0} {
			set tgrebindhinttimer [utimer $tgtempnohint tgbindhintcmd]
		}
	}
	if {$tghintnum >= [expr $tgmaxhintcurrent+1]} {
		incr tgmissed
		set _msg ""
		append _msg "\0032Waktunya telah habis..."
		if {$tgshowanswer==1} {
			append _msg "\0036 $tgcurrentanswer"
		}
		if {$tgmaxmissed>0&&$tgmissed>=$tgmaxmissed} {
			append _msg " That's $tgmissed questions gone by unanswered! The game is now automatically disabled. To start the game again, type $tgcmdstart"
			tgquietstop
		} else {
			append _msg ""
		}
		tggamemsg "[tgcolmiss]$_msg"
		if {$tgstreakmin>0&&[lindex [split $tgstreak ,] 1]>=$tgstreakmin} { tgstreakend }
		set tgstreak 0
		catch {unbind pubm -|- "$tgchan *" tgcheckanswer}
		if {$tgmaxmissed==0||$tgmissed<$tgmaxmissed} {
		#KAOSAskQuestion
		set tcnextqtimer [utimer $tctimenext tcnextq]
 			set tcplaying 1
 			set tcstreak 0
 			set tcmissed 0

#			set tgnextqtimer [utimer $tgtimenext tgnextq]
		}
		return
	} elseif {$tghintnum == 0} {
		set i 0
		set _hint {}
		set tghintcharsused {}
		foreach word [split $tgcurrentanswer] {
			regsub -all -- "\[A-Za-z0-9\]" $word $tghintchar _current
			lappend _hint $_current
		}
		if {$tgtimeanswer==1} {
			set tgtimestart [clock clicks -milliseconds]
		}
	} elseif {$tghintnum == 1} {
		set i 0
		set _hint {}
		while {$i<[llength [split $tgcurrentanswer]]} {
			set _word [lindex [split $tgcurrentanswer] $i]
			set j 0
			set _newword {}
			while {$j<[strlen $_word]} {
				if {$j==0} {
					append _newword [stridx $_word $j]
					lappend tghintcharsused $i,$j
				} else {
					if {[string is alnum [stridx $_word $j]]} {
						append _newword $tghintchar
					} else {
						append _newword [stridx $_word $j]
						lappend tghintcharsused $i,$j
					}
				}
				incr j
			}
			lappend _hint $_newword
			incr i
		}
		} else {
			set i 0
			set _hint {}
			while {$i<[llength [split $tgcurrentanswer]]} {
				set _word [lindex [split $tgcurrentanswer] $i]
				set j 0
				set _newword {}
				set _selected [rand [strlen $_word]]
				regsub -all -- "\[^A-Za-z0-9\]" $_word "" _wordalnum
				if {[strlen $_wordalnum]>=$tghintnum} {
					while {[lsearch $tghintcharsused $i,$_selected]!=-1||[string is alnum [stridx $_word $_selected]]==0} {
					 set _selected [rand [strlen $_word]]
					}
				}
				lappend tghintcharsused $i,$_selected
				while {$j<[strlen $_word]} {
					if {[lsearch $tghintcharsused $i,$j]!=-1||[string is alnum [stridx $_word $j]]==0} {
						append _newword [stridx $_word $j]
					} else {
						if {[string is alnum [stridx $_word $j]]} {
							append _newword $tghintchar
						}
				}
				incr j
			}
			lappend _hint $_newword
			incr i
		}
	}
	if {$tgcapshint==1} {
		set _hint [strupr $_hint]
	}
	if {$tgalwaysshowq==1||$tghintnum==0} {
	tggamemsg "0,2..:: Competition Game 8\[11 Trivia8 \] 0 Tegal@DALnet ::.."
	tggamemsg "2Word: $tgcurrentquestion"
	tggamemsg "2Hint: $_hint"
	tggamemsg "0,2..:: 11+10 0Points Bila Anda Menjawab Dengan Benar ::.."
	}
	tggamemsg "2Hint: [join $_hint]"
	#tggamemsg "[tginfoadv]"
	set tghinttimer [utimer $tgtimehint tghint]
}

#checks if anyone has said the correct answer on channel.
proc tgcheckanswer {nick host hand chan text} {
	global tgcurrentanswer
	if {[strlwr $tgcurrentanswer] == [tgstripcodes [strlwr [string trim $text]]]} {
		tgcorrectanswer $nick
	}
}

#triggered when someone says the correct answer.
proc tgcorrectanswer {nick} {
	global tgcurrentanswer tghinttimer tgtimenext tgchan tgnextqtimer tgstreak tgstreakmin
	global tgcongrats tgmissed
	global tgtimestart tgrealnames tgtimeanswer tgpointsperanswer
	
	global tccurrentanswer tchinttimer tctimenext tcchan tcnextqtimer tcstreak tcstreakmin
	global tcscoresbyname tcranksbyname tcranksbynum tccongrats tcscorestotal tcmissed
	global tcimestart tcshowallscores tcrealnames tcscoresbyrank tctimeanswer

    #global KAOSAnswers KAOSNumAnswered KAOSQuestionTimer KAOSAdTimer
    global lastwinner lastwinnercount botnick userlist quizconf rankfile timerankreset


    variable bestscore 0 lastbestscore 0 lastbest ""
    variable userarray
    variable waitforrank 0 gameend 0

    mx_getcreate_userentry $nick $nick
    array set userarray $userlist($nick)
#    set hostmask $userarray(mask)

	    set lastbest [lindex [lsort -command mx_sortrank [array names userlist]] 0]
	    if {$lastbest == ""} {
		set lastbestscore 0
	    } else {
		array set aa $userlist($lastbest)
		set lastbestscore $aa(score)
	    }
	    incr userarray(score) $tgpointsperanswer
	    if {$userarray(score) == 1} {
		set userarray(started) [unixtime]
	    }
	    set userlist($nick) [array get userarray]

	set _timetoanswer ""
	if {$tgtimeanswer==1} {
		set _timetoanswer [expr [expr [clock clicks -milliseconds]-$tgtimestart]/1000]
	}
	set _msg "\0032Jawaban Benar: \0036 $tgcurrentanswer \0032Oleh \0036 $nick \0032setelah \0036 $_timetoanswer \0032Detik - Score: \0036+10 \0032Points. Total Score:\0036 $userarray(score) \0032Points - Rank:\0036 [mx_get_rank_pos $nick]"
	tggamemsg "$_msg"
#	pushmode $tgchan +v $nick
	if {$tgstreak!=0} {
		if {[lindex [split $tgstreak ,] 0]==[strlwr $nick]} {
			set tgstreak [strlwr $nick],[expr [lindex [split $tgstreak ,] 1]+1]
			if {$tgstreakmin>0&&[lindex [split $tgstreak ,] 1]>=$tgstreakmin} {
				tggamemsg "[tgcolstrk][tgcolmisc2]$nick[tgcolstrk] is on a winning streak! [tgcolmisc2][lindex [split $tgstreak ,] 1] [tgcolstrk]in a row so far!"
			}
		} else {
			if {$tgstreakmin>0&&[lindex [split $tgstreak ,] 1]>=$tgstreakmin} { tgstreakend }
			set tgstreak [strlwr $nick],1
		}
	} else {
		set tgstreak [strlwr $nick],1
	}
	set tgmissed 0
	catch {unbind pubm -|- "$tgchan *" tgcheckanswer}
	killutimer $tghinttimer
      tmcquiz_rank_save {} {} {}    
       #KAOSAskQuestion
       set tcnextqtimer [utimer $tctimenext tcnextq]
 			set tcplaying 1
 			set tcstreak 0
 			set tcmissed 0
#	set tgnextqtimer [utimer $tgtimenext tgnextq]
}


#triggered when someone joins trivia chan.
proc tgjoinmsg {nick host hand chan} {
	global botnick tgplaying tgcmdstart tgflagsstart tgcmdstop tgflagsstop tgchan
	if {$nick != $botnick} {
		set _msg ""
		append _msg "Welcome to $botnick's trivia channel. Trivia game is currently"
		if {$tgplaying==1} {
			append _msg " \002on\002."
		} else {
			append _msg " \002off\002."
		}
		if {[matchattr $hand $tgflagsstart $tgchan]&&$tgplaying==0} {
			append _msg " To start the game, type \002$tgcmdstart\002 on $tgchan."
		}
		append _msg " Please type \002/MSG $botnick if you need help. Enjoy your stay! :-)"
#		[tgpriv] $nick "$_msg"
	}
}

# Returns text without colour, bold, etc. control codes.
# This is a stripped down version of the proc in MC_8's mc.moretools.tcl.
proc tgstripcodes {text} {
	regsub -all -- "\003(\[0-9\]\[0-9\]?(,\[0-9\]\[0-9\]?)?)?" $text "" text
	set text "[string map -nocase [list \002 "" \017 "" \026 "" \037 ""] $text]"
	return $text
}

proc tggamemsg {what} {
	global tgchan
	putquick "PRIVMSG $tgchan :[tgbold]$what"
}

proc tgbold {} {
	global tgusebold
	if {$tgusebold==1} { return "\002" }
}
proc tgcolstart {} {
	global tgcolourstart
	if {$tgcolourstart!=""} { return "\003$tgcolourstart" }
}
proc tgcolstop {} {
	global tgcolourstop
	if {$tgcolourstop!=""} { return "\003$tgcolourstop" }
}
proc tgcolskip {} {
	global tgcolourskip
	if {$tgcolourskip!=""} { return "\003$tgcolourskip" }
}
proc tgcolerr {} {
	global tgcolourerr
	if {$tgcolourerr!=""} { return "\003$tgcolourerr" }
}
proc tgcolmiss {} {
	global tgcolourmiss
	if {$tgcolourmiss!=""} { return "\003$tgcolourmiss" }
}
proc tgcolqhead {} {
	global tgcolourqhead
	if {$tgcolourqhead!=""} { return "\003$tgcolourqhead" }
}
proc tgcolqbody {} {
	global tgcolourqbody
	if {$tgcolourqbody!=""} { return "\003$tgcolourqbody" }
}
proc tgcolhint {} {
	global tgcolourhint
	if {$tgcolourhint!=""} { return "\003$tgcolourhint" }
}
proc tgcolstrk {} {
	global tgcolourstrk
	if {$tgcolourstrk!=""} { return "\003$tgcolourstrk" }
}
proc tgcolscr1 {} {
	global tgcolourscr1
	if {$tgcolourscr1!=""} { return "\003$tgcolourscr1" }
}
proc tgcolscr2 {} {
	global tgcolourscr2
	if {$tgcolourscr2!=""} { return "\003$tgcolourscr2" }
}
proc tgcolscr3 {} {
	global tgcolourscr3
	if {$tgcolourscr3!=""} { return "\003$tgcolourscr3" }
}
proc tgcolrset {} {
	global tgcolourrset
	if {$tgcolourrset!=""} { return "\003$tgcolourrset" }
}
proc tgcolstend {} {
	global tgcolourstend
	if {$tgcolourstend!=""} { return "\003$tgcolourstend" }
}
proc tgcolmisc1 {} {
	global tgcolourmisc1
	if {$tgcolourmisc1!=""} { return "\003$tgcolourmisc1" }
}
proc tgcolmisc2 {} {
	global tgcolourmisc2
	if {$tgcolourmisc2!=""} { return "\003$tgcolourmisc2" }
}
proc tgpriv {} {
	global tgpriv2msg
	if {$tgpriv2msg==1} { return "putmsg" } else { return "putnotc" }
}

#
putlog "Trivia By Roney ® Succesfully LoaDeD..."

