diff --git a/Daeghrefn/Communication.tcl b/Daeghrefn/Communication.tcl --- a/Daeghrefn/Communication.tcl +++ b/Daeghrefn/Communication.tcl @@ -209,6 +209,11 @@ } } + "reconfigure" { + twitter_update_short_url_length + return 1 + } + default { putdcc $idx "Unknown Twitter command: $arg"} } } @@ -336,9 +341,9 @@ putquick "NOTICE $nick :Syntaxe : !pub " return } - set len [string length $text] + set len [twitter_compute_len $text] if {$len > 140} { - putquick "NOTICE $nick :140 caractères max, là il y en a $len." + putquick "NOTICE $nick :140 caractères max, là il y en a $len ([twitter_get_short_url_length] par lien)." return } if [twitterpost $account $text] { @@ -376,6 +381,36 @@ twitter_query $url $account "" POST } +# @param param The parameter to fetch in the API reply +# return The value from configuration the JSON document, or a dict if it contains several parameters +proc twitter_get_configuration_parameter {param} { + set account [registry get twitter.default_account] + set url https://api.twitter.com/1.1/help/configuration.json + set config [twitter_query $url $account] + dict get $config $param +} + +proc twitter_update_short_url_length {} { + set len [twitter_get_configuration_parameter short_url_length] + registry set twitter.short_url_length $len +} + +proc twitter_get_short_url_length {} { + registry get twitter.short_url_length +} + +# Computes len of a tweet, taking in consideration t.co URL length +# See https://dev.twitter.com/basics/tco +proc twitter_compute_len {text} { + set short_url_length [twitter_get_short_url_length] + + set len [strlen $text] + foreach url [geturls $text] { + incr len [expr $short_url_length - [strlen $url]] + } + return $len +} + # # Mail # diff --git a/tests/Communication.test b/tests/Communication.test new file mode 100644 --- /dev/null +++ b/tests/Communication.test @@ -0,0 +1,40 @@ +package require tcltest +namespace import ::tcltest::* + +### +### Init +### + +# Tested code +source init.tcl +source $dir/Daeghrefn/Communication.tcl + +### +### Mocks +### + +# This value is normally given by a cached value in the registry +# and updated through an API call to /help/configuration.json. +proc twitter_get_short_url_length {} { return 23 } + +### +### Tests +### + +test twitter_compute_len_empty {} -body { + twitter_compute_len "" +} -result 0 + +test twitter_compute_len_regular_string {} -body { + twitter_compute_len "quux" +} -result 4 + +test twitter_compute_len_links {} -body { + twitter_compute_len "Je vais sur http://www.perdu.com pour y lire https://fr.wikipedia.org/w/index.php?title=Les_B%C3%A2tards_du_Nord&type=revision&diff=133589772&oldid=133589631" +} -result 71 + +### +### Cleanup +### + +cleanupTests diff --git a/tests/init.tcl b/tests/init.tcl --- a/tests/init.tcl +++ b/tests/init.tcl @@ -13,3 +13,8 @@ # Standard procedures source $dir/Core.tcl + +# Eggdrop procedures +proc strlen {text} { + string length $text +}