This is the new home of the egghelp.org community forum.
All data has been migrated (including user logins/passwords) to a new phpBB version.


For more information, see this announcement post. Click the X in the top right-corner of this box to dismiss this message.

Sun and Moon script

Help for those learning Tcl or writing their own scripts.
User avatar
bayo
Voice
Posts: 15
Joined: Tue Jan 25, 2022 4:14 pm
Location: Bulgaria
Contact:

Sun and Moon script

Post by bayo »

Hi all! I'm trying to get some data from an API but doesn't seems to work.

Could you have a look and point some guidance. Thanks!

So far the error on partyline is can't read "location": no such variable

Code: Select all

namespace eval SunMoon {
	### REQUIREMENTS ###
	package require json
	package require http
	package require tls

	### SETTINGS ###
	set apikeys(astro) "bbad2aa9d2644775a722b7380194dd68"
	
	### BINDS ###
	bind PUB - !sun ::SunMoon::pub_sun
	bind PUB - !moon ::SunMoon::pub_moon

}
	### PROCS ###
proc ::SunMoon::download_data {url} {
	
	::http::register https 443 [list ::tls::socket -tls1 1]
	::http::config -useragent "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)"
	set sun_moon [http::geturl $url -timeout 5000]
	set sun_moon_data [http::data $sun_moon]
	if {[http::status $sun_moon] ne "ok" || [http::ncode $sun_moon] != 200} {
		
		set code [http::code $sun_moon]
		putlog "\00304***\003 SunMoon HTTP error: $code"
		putlog "\00304***\003 Requested url is: $url"
		http::cleanup $sun_moon
		return 0
	}
	http::cleanup $sun_moon  
	return $sun_moon_data
}
proc ::SunMoon::pub_sun {nick uhost hand chan arg} {
	if {$arg == ""} { putserv "PRIVMSG $chan :Sun or Moon Syntax: !sun <city> or !moon <city>" ; return }
	
	set sun_moon_data [::SunMoon::download_data https://api.ipgeolocation.io/astronomy?[http::formatQuery apiKey $::SunMoon::apikeys(astro) $location]]
	if {$sun_moon_data == 0} { return }
	set sunmoon_dict [::json::json2dict $sun_moon_data]
	
	set location [::json::json2dict location $sun_moon_data]
	set country [dict get $sunmoon_dict location country]
	set state [dict get $sunmoon_dict location state]
	set city [dict get $sunmoon_dict location city]
	set current_time [lindex [split [dict get $sunmoon_dict current_time] .] 0]
	set sunrise [dict get $sunmoon_dict sunrise]
	set sunset [dict get $sunmoon_dict sunset]
	set daylength [dict get $location dict daylength]
	
	putserv "PRIVMSG $chan :\0314 Слънцето над \003\00307\002$city, $country\003\002"
	putserv "PRIVMSG $chan :\00307Изгрев\003 \00314в\003 \00304$sunrise\ч\003 \00314и\003 \00307Залез\003 \00314в\003 \00304$sunset\ч.\003 \00307Продължителност на деня\003 - \00304$daylength\ч.\003"	
	
}
proc ::SunMoon::pub_moon {nick uhost hand chan arg} {
	if {$arg == ""} { putserv "PRIVMSG $chan :Sun or Moon Syntax: !sun <city> or !moon <city>" ; return }
	
	set sun_moon_data [::SunMoon::download_data https://api.ipgeolocation.io/astronomy?[http::formatQuery apiKey $::SunMoon::apikeys(astro) city $city state $state country $country]]
	if {$sun_moon_data == 0} { return }
	set sunmoon_dict [::json::json2dict $sun_moon_data]
	
	set location [::json::json2dict location $sun_moon_data]
	set country [dict get $sunmoon_dict location country]
	set state [dict get $sunmoon_dict location state]
	set city [dict get $sunmoon_dict location city]
	set current_time [lindex [split [dict get $sunmoon_dict current_time] .] 0]
	set moonrise [dict get $sunmoon_dict moonrise]
	set moonset [dict get $sunmoon_dict moonset]
	set moon_status [dict get $sunmoon_dict moon_status]

	putserv "PRIVMSG $chan :\00314 Луната над \003\00307\002$city, $country \003\002 - \00307Ще изгрее\003 \00314в\003 \00304$moonrise\ч\003 \00314и\003 \00307ще залезе\003 \00314в\003 \00304$moonset\ч.\003"	

}
User avatar
SpiKe^^
Owner
Posts: 831
Joined: Fri May 12, 2006 10:20 pm
Location: Tennessee, USA
Contact:

Post by SpiKe^^ »

That error is probably coming from this line where you call $location before you set that variable...

Code: Select all

set sun_moon_data [::SunMoon::download_data https://api.ipgeolocation.io/astronomy?[http::formatQuery apiKey $::SunMoon::apikeys(astro) $location]]
SpiKe^^

Get BogusTrivia 2.06.4.7 at www.mytclscripts.com
or visit the New Tcl Acrhive at www.tclarchive.org
.
User avatar
bayo
Voice
Posts: 15
Joined: Tue Jan 25, 2022 4:14 pm
Location: Bulgaria
Contact:

Post by bayo »

Hello, I managed to sort out the script in another way but I have a question in regards to some conversion. My question is how to replace certain numbers to become names.

The moon phase number represents the fractional portion through the current moon lunation cycle ranging from 0 (the new moon) to 0.5 (the full moon) and back to 1 (the next new moon).

Traditional, western moon cycles are therefore represented by the following values:

0 –> new moon
0-0.25 –> waxing crescent
0.25 –> first quarter
0.25-0.5 –> waxing gibbous
0.5 –> full moon
0.5-0.75 –> waning gibbous
0.75 –> last quarter
0.75 -1 –> waning crescent

Is there an easy way to do this? Thanks!
User avatar
SpiKe^^
Owner
Posts: 831
Joined: Fri May 12, 2006 10:20 pm
Location: Tennessee, USA
Contact:

Moon phases

Post by SpiKe^^ »

While I have no idea if there is an easier way to do this, this is how I might do it...

Code: Select all

if {$phnumber==0 || $phnumber==1} {  set phase "new moon"
} elseif {$phnumber<0.25} {  set phase "waxing crescent"
} elseif {$phnumber==0.25} {  set phase "first quarter"
} elseif {$phnumber<0.5} {  set phase "waxing gibbous"
} elseif {$phnumber==0.5} {  set phase "full moon"
} elseif {$phnumber<0.75} {  set phase "waning gibbous"
} elseif {$phnumber==0.75} {  set phase "last quarter"
} elseif {$phnumber<1} {  set phase "waning crescent"
} else {  set phase "Unknown"  }
Goodluck
SpiKe^^

Get BogusTrivia 2.06.4.7 at www.mytclscripts.com
or visit the New Tcl Acrhive at www.tclarchive.org
.
User avatar
bayo
Voice
Posts: 15
Joined: Tue Jan 25, 2022 4:14 pm
Location: Bulgaria
Contact:

Post by bayo »

It worked. Thanks man!
User avatar
bayo
Voice
Posts: 15
Joined: Tue Jan 25, 2022 4:14 pm
Location: Bulgaria
Contact:

Post by bayo »

Hi again :lol: I've been puzzling around something I'm trying to achieve, but don't know where to start from. I'm trying to implement the table below and change the words depending on the type of the day "Day" or "Night"

https://ibb.co/xJTTDBK

Where during the day if the sky is clear will say "Sunny" but if its night will say "Clear"

So far this is my code but don't know how to continue. Pardon the two dicts. I'm using two different APIs

Code: Select all

set cloudcover [dict get [lindex $values 0] cloudcover]
	if {$cloudcover == 0} { set skymsg "Sunny"
	}	elseif {$cloudcover == 10} { set skymsg "Mostly Sunny" 
	}	elseif {$cloudcover == 20} { set skymsg "Mostly Sunny Spells"
	}	elseif {$cloudcover < 50} { set skymsg "Partly Sunny"
	}	elseif {$cloudcover < 70} { set skymsg "Mostly Cloudy"
	}	elseif {$cloudcover < 99 || $cloudcover == 100 } { set skymsg "Cloudy"
	} else { set skymsg $cloudcover}

set current_time [string range [dict get $sunmoon_dict current_time] 0 4]
	if {$current_time <= 18} { set currtime "Day"
    } elseif {$current_time > 18} { set currtime "Night"
	} else { set currtime $current_time}
Any suggestions? :roll: :oops: :idea:
User avatar
CrazyCat
Revered One
Posts: 1304
Joined: Sun Jan 13, 2002 8:00 pm
Location: France
Contact:

Post by CrazyCat »

You can use a string map to replace days sentences with the night ones:

Code: Select all

set day2night {"Sunny to Mostly sunny" "Fair" "Mostly sunny" "Mostly fair" "Partly sunny" "Partly cloudy" "Sunny" "Clear"}
set night [string map $day2night $day]
($day is the text for day conditions)

Note that the order of sentences in day2night is important, because the replacement will be done using this order.
User avatar
bayo
Voice
Posts: 15
Joined: Tue Jan 25, 2022 4:14 pm
Location: Bulgaria
Contact:

Post by bayo »

Hello again. Can someone explain this to me please? :lol:

[16:58] <BAYO> (bin) 39 % set current_time "aa"
[16:58] <BAYO> (bin) 40 % set sunset "18:27"
[16:58] <BAYO> (bin) 41 % if {$current_time <= $sunset} { set currtime "day" } else { set currtime "night" }
[16:58] <BAYO> night
[16:58] <BAYO> HOW!?!?!?

:?
User avatar
SpiKe^^
Owner
Posts: 831
Joined: Fri May 12, 2006 10:20 pm
Location: Tennessee, USA
Contact:

Post the code

Post by SpiKe^^ »

Post the entire code you are currently running.
SpiKe^^

Get BogusTrivia 2.06.4.7 at www.mytclscripts.com
or visit the New Tcl Acrhive at www.tclarchive.org
.
User avatar
bayo
Voice
Posts: 15
Joined: Tue Jan 25, 2022 4:14 pm
Location: Bulgaria
Contact:

Post by bayo »

Well, this is it, not much different of what I posted earlier:

I'm trying to identify from the "sunset" if it's day or night. Then based on this, I'm trying to make the bot tell me the cloudcover info from the api (returns in percents) and post this: https://ibb.co/xJTTDBK

If it's Day -> The text from the column for the Day
If it's Night -> The text from the column for the Night
Cloudcover from the api shows (example) - 74.1
Info from Api Docs: cloudcover – how much of the sky is covered in cloud ranging from 0-100%

Code: Select all

### The Fourth Stack
	set sun_moon_data [::Visualcrossing::download_weather https://api.ipgeolocation.io/astronomy?[http::formatQuery apiKey $::Visualcrossing::apikey location $arg]]
	if {$sun_moon_data == 0} { return }
	set sunmoon_dict [::json::json2dict $sun_moon_data]
	
	set current_time [string range [dict get $sunmoon_dict current_time] 0 4]
	set sunset [dict get $sunmoon_dict sunset]
	set sunrise [dict get $sunmoon_dict sunrise]
	if {$current_time <= $sunset} { set currtime "Day" } else { set currtime "Night" } 
Hope this helps :|
User avatar
SpiKe^^
Owner
Posts: 831
Joined: Fri May 12, 2006 10:20 pm
Location: Tennessee, USA
Contact:

Basic if/elseif/else logic...

Post by SpiKe^^ »

You didn't bother to "Post the entire code you are currently running."
But here is some basic if/elseif/else logic and layout again...

Code: Select all

if {$cloudcover < 10} {
  if {$currtime eq "Day"} {  set sky "Sunny"
  } else {  set sky "Clear"  }
} elseif {$cloudcover < 20} {
  if {$currtime eq "Day"} {  set sky "Sunny to Mostly Sunny"
  } else {  set sky "Fair"  }
} elseif {$cloudcover < 30} {
  if {$currtime eq "Day"} {  set sky "Mostly Sunny"
  } else {  set sky "Mostly Fair"  }
} elseif {$cloudcover < 60} {
  if {$currtime eq "Day"} {  set sky "Partly Sunny"
  } else {  set sky "Partly Cloudy"  }
} elseif {$cloudcover < 90} {  set sky "Mostly Cloudy"
} else {  set sky "Cloudy"  }

SpiKe^^

Get BogusTrivia 2.06.4.7 at www.mytclscripts.com
or visit the New Tcl Acrhive at www.tclarchive.org
.
User avatar
bayo
Voice
Posts: 15
Joined: Tue Jan 25, 2022 4:14 pm
Location: Bulgaria
Contact:

Post by bayo »

Thank you, SpiKe^^ I promice when I finish it to post it in the forum. Thanks.
User avatar
bayo
Voice
Posts: 15
Joined: Tue Jan 25, 2022 4:14 pm
Location: Bulgaria
Contact:

Post by bayo »

Hello all, I'm trying to figure out how to create the API so I can replace (in this case LONDON,UK) with any location by search. The API link at the bottom:

I was thinking to do something like that:

https://weather.visualcrossing.com/Visu ... s/timeline?[::http::formatQuery location $arg next5days $systemTime key $apikey]

where $arg is is the searched location, $systemTime is the local machine time and the key is the $apikey.

Code: Select all

https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/London,UK/next5days?key=YOUR_API_KEY

Thank you in advance :D
User avatar
SpiKe^^
Owner
Posts: 831
Joined: Fri May 12, 2006 10:20 pm
Location: Tennessee, USA
Contact:

Try to be more helpful to the helpers

Post by SpiKe^^ »

Sure would be easier to help with a script if you posted that entire script?!

Guessing at context and variable names is challenging for others.

Every API is different, you can't just copy and reuse that ?[::http::formatQuery string from your earlier api query and expect it to work with this new API.

According to the new api docs...
https://weather.visualcrossing.com/Visu ... UR_API_KEY

Try replacing "London,UK" with the variable that contains your location info???

AGAIN, post the script here for more context correct help...
SpiKe^^

Get BogusTrivia 2.06.4.7 at www.mytclscripts.com
or visit the New Tcl Acrhive at www.tclarchive.org
.
User avatar
bayo
Voice
Posts: 15
Joined: Tue Jan 25, 2022 4:14 pm
Location: Bulgaria
Contact:

Post by bayo »

So be it. Bear in mind the script is translated and when I release it will be much shorter version. Still Alpha version :oops:

Code: Select all

######################################
# @UniBG irc.chatpat.bg				 #
# @FreeUniBG irc.interbg.org 		 #	
# Credits: MeMoreX & SpiKe^^		 #
# Est: 01\2022						 #
######################################

namespace eval Visualcrossing {
	### Requirements
	package require json
	package require tls
	package require http

	### Binding
	bind PUB -|- !g ::Visualcrossing::group_weather	
	bind PUB -|- !w ::Visualcrossing::pub_weather
	
  
	### The API Keys
	set appid "Openweather api website"
	set apiKey "ipgeoinfo website"
	set key "visualcrossing website"
}	
	### Procedures start here
proc ::Visualcrossing::download_weather {url} {
    ::http::register https 443 [list ::tls::socket -tls1 1]
	::http::config -useragent "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)"
	set socket [http::geturl $url -timeout 5000]
	set items_data [http::data $socket]
	if {[http::status $socket] ne "ok" || [http::ncode $socket] != 200} {
		set code [http::code $socket]
		putlog "\00304***\003 Weather HTTP error: $code"
		putlog "\00304***\003 Request url is: $url"
		http::cleanup $socket
		return 0
    }
	http::cleanup $socket
	return $items_data
}

	### The Main Proc
proc ::Visualcrossing::pub_weather {nick uhost hand chan arg} {
	set items_data [::Visualcrossing::download_weather https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/weatherdata/forecast?[::http::formatQuery location $arg aggregateHours 24 forecastdays 3 includeAstronomy true locationMode lookup unitGroup metric shortColumnNames false contentType json alertLevel event lang en nonulls true key $::Visualcrossing::key]]
	if {$arg == ""} { putserv "PRIVMSG $chan :Правилно: !w града/локацията" ; return }
	
	### The Main Dict
	set connect	[::json::json2dict $items_data]
	
	### The First Stack 
	set locations [dict get $connect locations]
	set cityname [lindex $locations 0]
	set citydata [lindex $locations 1]
	set tz [dict get $citydata tz]
	set long [dict get $citydata longitude]
	set lat [dict get $citydata latitude]

	### The Second Stack
	set current [dict get $citydata currentConditions]
	if {$current != "null"} { set conditions $current }
	if {$current == "null" || $current == "" || $current == " "} { set currCond "Няма информация. Моля опитайте по-късно." } else { set currCond $current }
	set wdir [join [::Visualcrossing::deg_to_dir [dict get $current wdir]]]
	set wspd [dict get $current wspd]
	if {$wdir == "null" || $wdir == "" || $wdir == " "} { set windir "Няма информация. Моля опитайте по-късно." } else { set windir $wdir }
	if {$wspd == "null" || $wspd == "" || $wspd == " "} { set wspeed "Нe се усеща" } else { set wspeed [expr round($wspd)]км/ч}
	if {$wspd != "null"} {set wspd [expr round($wspd)]} 
	set wgust [dict get $current wgust]
	if {$wgust == "null" || $wgust == "" || $wgust == " "} { set wgustmsg "Нe се усеща" } else { set wgustmsg [expr round($wgust)]км/ч}
	if {$wgust != "null"} {set wgust [expr round($wgust)]}
	set temp [dict get $current temp]
	set temp [expr round($temp)]
	

	### The Third Stack
	set values [dict get $citydata values]
	
	set alert [dict get [lindex $values 0] alerts]
	if {$alert == "null"} { set alertmsg "Няма!" } else { set alertmsg $alert }
	set mint [dict get [lindex $values 0] mint]
	set mint [expr round($mint)]
	set maxt [dict get [lindex $values 0] maxt]
	set maxt [expr round($maxt)]
	set humi [dict get [lindex $values 0] humidity]
	set humi [expr round($humi)]
	set cond [dict get [lindex $values 0] conditions]
	if {$cond == "Rain, Overcast"} {set condmsg "\u2614 Дъжд"
	}	elseif {$cond == "Snow"} { set condmsg "\u2744 Сняг"
	}	elseif {$cond == "Rain, Partially cloudy"} { set condmsg "Дъжд, превалява на моменти" 
	}	elseif {$cond == "Snow, Overcast"} { set condmsg "Сняг, сиво, мрачно"
	}	elseif {$cond == "Overcast"} { set condmsg "Облачно, сиво, мрачно"
	}	elseif {$cond == "Clear"} { set condmsg "Ясно"
	}	elseif {$cond == "Partially cloudy"} { set condmsg "Частична облачност"
	} else { set condmsg $cond }
	set cloud [dict get [lindex $values 0] cloudcover]

	### The Fourth Stack
	set sun_moon_data [::Visualcrossing::download_weather https://api.ipgeolocation.io/astronomy?[http::formatQuery apiKey $::Visualcrossing::apiKey location $arg]]
	if {$sun_moon_data == 0} { return }
	set sunmoon_dict [::json::json2dict $sun_moon_data]
	
	set sunrise [dict get $sunmoon_dict sunrise]
	set sunset [dict get $sunmoon_dict sunset]
	set current_time [string range [dict get $sunmoon_dict current_time] 0 4]
	if {$current_time > $sunset} { set currtime "Нощ" } { set currtime "Ден" }
	if {$cloud < 10} {
		if {$currtime eq "Ден"} { set sky "Слънчево" } else { set sky "Ясно" }
	} elseif {$cloud < 20} {
		if {$currtime eq "Ден"} { set sky "Приятно" } else { set sky "Меко" }
	} elseif {$cloud < 30} {
		if {$currtime eq "Ден"} { set sky "Предимно слънчево" } else { set sky "Предимно ясно" }
	} elseif {$cloud < 60} {
		if {$currtime eq "Ден"} { set sky "\u26c5 Слънчево на моменти" } else { set sky "Облачно на моменти" }
	} elseif {$cloud < 90} { set sky "Предимно облачно" } else { set sky "Облачно" }
			#putlog "Day\Night -> $currtime | CloudCover% -> $cloud | Conditions -> $cond | Sunset time: $sunset and Current time is $current_time ?"

	### The Fifth Stack
	set weather_data [::Visualcrossing::download_weather https://api.openweathermap.org/data/2.5/weather?[http::formatQuery q $arg appid $::Visualcrossing::appid lang bg units metric]]
	if {$weather_data == 0} { return }
	set weather_dict [::json::json2dict $weather_data]
	
	set city [dict get $weather_dict name]
	set country [join [dict get $weather_dict sys country]]
	
	putserv "PRIVMSG $chan :\00307\002$city, $country\003\002 \00314в момента: \00307$condmsg\003  \002\00307$temp°C\002\003 \00314Влажност \00307$humi\%\003 \00314Вятър\003 \00307$wspeed \00314от \00307$wdir\003 \00314Скорост на поривите\003 \00307$wgustmsg\003 \00314Облачна покривка\003 \00307$sky\003 \00314Утре: Мин/Макс (\003\00307↓$mint\°C\003\00314/\00307↑$maxt\C°\003\00314)\003"
	putserv "PRIVMSG $chan :\00314Сигнали за опасност:\003 \00304$alertmsg\003"
		
	set alerts [dict get $citydata alerts]
	if {$alerts != "null"} { set alert $alerts }
	set head [dict get [lindex $alerts 0] headline]
	set onsetEpoch [dict get [lindex $alerts 0] onsetEpoch]
	set endsEpoch [dict get [lindex $alerts 0] endsEpoch]
	set ondate [clock format $onsetEpoch -format "%a, %e %b %Y %H:%M"]
	set offdate [clock format $endsEpoch -format "%a, %e %b %Y %H:%M"]
	
	putserv "PRIVMSG $chan :\[\00304!\003\00314Опасност\00304!\003]\ \00304$head \003\[\00314FROM:\003]\00304 $ondate \003\[\00314TO:\003]\00304 $offdate\003"
}
	### The Second proc for the group cities by ID
proc ::Visualcrossing::group_weather {nick uhost hand chan arg} {
	set group_data [::Visualcrossing::download_weather https://api.openweathermap.org/data/2.5/group?[http::formatQuery id 727447,726051,727011,2643743,7839805 appid $::Visualcrossing::appid lang bg units metric]]
	if {$group_data == 0} { return }
	set group_dict [::json::json2dict $group_data]
	
	set cities [dict get $group_dict list]
	set cities_info ""
	foreach city $cities { 
		set temp [dict get $city main temp]
		set temp [expr round($temp)]
		if {$temp >=0} {
			set temp "$temp"
			}
		set name [dict get $city name]
		set des [dict get [lindex [dict get $city weather] 0] description]
		lappend cities_info "\00307$name \00304$temp°C\003 /\00314$des\003/" 
	}
		putserv "PRIVMSG $chan :\00314Времето в момента:\003 [join $cities_info " "]" 
}
	### Calculates the degrees from the API and converts them to words expresion like the string below
	### Attached to the Second Stack of the Main proc 
proc ::Visualcrossing::deg_to_dir {value} {
	set calc [expr ($value / 22.5) + 0.5]
	set dirs "Север Север-Североизток Североизток Изток-Североизток Изток Изток-Югоизток Югоизток Юг-Югоизток Юг Юг-Югозапад Югозапад Запад-Югозапад Запад Запад-Северозапад Северозапад Север-Североизток"
	return [lindex $dirs [expr int($calc) % 16]]
}
		
	### Sets the crontab expresion like the string below
proc ::Visualcrossing::auto_say {min hour day month week} {
	::Visualcrossing::group_weather "-" "-" "-" "#Forbidden"
}
	### Timer for making the weather posted in a channel, depends on the preference (refer to https://crontab.guru/)
	bind cron -|- "0 */6 * * *" ::Visualcrossing::auto_say
	
	### The Third Proc for 3 days Forecast 
#proc ::Visualcrossing::forecast_weather {nick uhost hand chan arg} {
#	set group_data [::Visualcrossing::download_weather https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/
#	
	
	

namespace eval SunMoon {
	### Requirements 
	package require json
	package require http
	package require tls
	package require Trf
	
	### Binding 
	bind PUB - !a ::SunMoon::pub_sun_moon

	### The API Keys 
	set appid "a12c83435763f3cc1342eecb4de4d48e"
	set apiKey "388be6b288bd45b8966c90dcf40517b0"
	set key "Z3UDHRSCXQHNDZRQXT2PDDGW4"
	
	### The Main Astro Proc 
proc ::SunMoon::download_data {url} {
	
	::http::register https 443 [list ::tls::socket -tls1 1]
	::http::config -useragent "Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)"
	set sun_moon [http::geturl $url -timeout 5000]
	set sun_moon_data [http::data $sun_moon]
	if {[http::status $sun_moon] ne "ok" || [http::ncode $sun_moon] != 200} {
		
	set code [http::code $sun_moon]
	putlog "\00304***\003 SunMoon HTTP error: $code"
	putlog "\00304***\003 Requested url is: $url"
	http::cleanup $sun_moon
	return 0
	}
	http::cleanup $sun_moon  
	return $sun_moon_data
}
proc ::SunMoon::pub_sun_moon {nick uhost hand chan arg} {
	if {$arg == ""} { putserv "PRIVMSG $chan :Правилно: !a <Град/Локация>" ; return }
	
	set sun_moon_data [::SunMoon::download_data https://api.ipgeolocation.io/astronomy?[http::formatQuery apiKey $::SunMoon::apiKey location $arg]]
	if {$sun_moon_data == 0} { return }
	set sunmoon_dict [::json::json2dict $sun_moon_data]
	
	set current_time [string range [dict get $sunmoon_dict current_time] 0 4]	
	set sunrise [dict get $sunmoon_dict sunrise]
	set sunset [dict get $sunmoon_dict sunset]
	set daylength [dict get $sunmoon_dict day_length]
	set moonrise [dict get $sunmoon_dict moonrise]
	set moonset [dict get $sunmoon_dict moonset]
	set moon_status [dict get $sunmoon_dict moon_status]
	if {$current_time < $sunset} { set currtime "Ден" } { set currtime "Вечер" }
	
	set items_data [::SunMoon::download_data https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/weatherdata/forecast?[::http::formatQuery location $arg aggregateHours 24 forecastDays 3 includeAstronomy true locationMode lookup unitGroup metric shortColumnNames false contentType json alertLevel event lang en nonulls true key $::SunMoon::key]]
	
	### The Main Astro Dict
	set connect	[::json::json2dict $items_data]
	
	###The First Astro Stack 
	set locations [dict get $connect locations]
	set cityname [lindex $locations 0]
	set citydata [lindex $locations 1]
	set tz [dict get $citydata tz]

	## The Second Astro Stack
	set current [dict get $citydata currentConditions]
	set moon [dict get $current moonphase]
	if {$moon==0 || $moon== 1} {  set phase "Новолуние"
} 	elseif {$moon<0.25} {  set phase "Изгряващ полумесец"
} 	elseif {$moon==0.25} {  set phase "Първа четвърт"
} 	elseif {$moon<0.5} {  set phase "Растяща луна"
} 	elseif {$moon==0.5} {  set phase "Пълнолуние"
} 	elseif {$moon<0.75} {  set phase "Намаляваща луна"
} 	elseif {$moon==0.75} {  set phase "Последна четвърт"
} 	elseif {$moon<1} {  set phase "Залязващ полумесец"
} 	else {  set phase "Грешка. Опитайте пак."	}

	### The Third Astro Stack
	set values [dict get $citydata values]
	set uv [dict get [lindex $values 0] uvindex]
	if {$uv==0} {	set index "Нисък"
}	elseif {$uv<5 || $uv==6}  {	set index "Умерен"
}	elseif {$uv<7 || $uv==8}  {	set index "Висок"
}	elseif {$uv<9 || $uv==10} {	set index "Много висок"
}	elseif {$uv>11} {	set index "Екстремен"
}	else {	set index "Грешка. Няма данни."	}
	set radiation [dict get [lindex $values 0] solarradiation]
	set energy [dict get [lindex $values 0] solarenergy]
	
	### The Fourth Astro Stack
	set weather_data [::SunMoon::download_data https://api.openweathermap.org/data/2.5/weather?[http::formatQuery q $arg appid $::SunMoon::appid lang bg units metric]]
	if {$weather_data == 0} { return }
	set weather_dict [::json::json2dict $weather_data]
	
	set city [dict get $weather_dict name]
	set country [join [dict get $weather_dict sys country]]
	putserv "PRIVMSG $chan :				\002\00314 ---=== Астрономическа информация ===---\003\002"
	putserv "PRIVMSG $chan :\00314Часът в \00307\002$city, $country\003\002 \00314е \00307$current_time\ч.\003 \00314Часова зона\003 \00307$tz ($currtime) \003\00314Продължителност на деня\003 \00304$daylength\ч."
	putserv "PRIVMSG $chan :\00314Слънцето: \00307Изгрев в\003 \00304$sunrise\ч\003 \00314и\003 \00307Залез в\003 \00304$sunset\ч.\003 \00307УВ индекс: \00304$index\003 ☀️ \00314радиация \00304$radiation\W/m2\003 ☀️\u26a1 \00314енергия \00304$energy\kWh/m2\003"	
	putserv "PRIVMSG $chan :\00314Луната: \00307Ще изгрее в\003 \00304$moonrise\ч\003 \00314и\003 \00307ще залезе в\003 \00304$moonset\ч.\00307 Лунна фаза: \00304$phase\003"	
	}
}
	### Lastly, help section on NOTICE for a bit more information
	### Binding
	bind pub -|- !weather pub:help

proc pub:help {nick uhost hand chan text} {
	global botnick
	set text [cleanarg $text]
	if {[llength $text]<1} {
	putserv "NOTICE $nick :----------==========\002Weather Commands\002==========--------------"
	putserv "NOTICE $nick :!w града/локация - показва времето в момента."
	putserv "NOTICE $nick :!a града/локация - показва астрономическа информация"
	putserv "NOTICE $nick :!3 града/локация показва времето за три дни напред."
	putserv "NOTICE $nick :!g - показва информация за предварително зададени градове в една група"
	}
}
putlog "The complete Weather Tcl ...Loaded"


Post Reply