Last active
February 1, 2019 08:56
-
-
Save JcMinarro/6fd5ceb82808079b7b58 to your computer and use it in GitHub Desktop.
Script that get the free book of the day and send info to slack
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/groovy | |
import org.codehaus.jettison.json.JSONObject | |
import groovyx.net.http.ContentType | |
import groovyx.net.http.Method | |
import org.jsoup.Jsoup | |
import groovyx.net.http.HTTPBuilder | |
import org.jsoup.nodes.Document | |
@Grapes( @Grab('org.jsoup:jsoup:1.7.3')) | |
@Grapes( @Grab('org.codehaus.jettison:jettison:1.3.7')) | |
@Grapes( @Grab('org.codehaus.groovy.modules.http-builder:http-builder:0.7')) | |
final PACKTPUB_FREE_BOOK_URL = "http://www.packtpub.com/packt/offers/free-learning" | |
final SLACK_WEBHOOKS = "YOUR_SLACK_WEBHOOKS" | |
Document getDocument(String url) { | |
Jsoup.connect(url).timeout(30000).get() | |
} | |
Document doc = getDocument(PACKTPUB_FREE_BOOK_URL) | |
def title = doc?.getElementsByClass("dotd-title")?.first()?.text() | |
def image | |
URL urlImage = doc?.getElementsByClass("imagecache-dotd_main_image")?.first()?.attr("src")/*?.replaceFirst("//", "https://")*/?.toURL() | |
urlImage?.with { | |
try { | |
image = new URI(getProtocol(), getUserInfo(), getHost(), getPort(), getPath(), getQuery(), getRef()).toString() | |
} catch(Exception e) { | |
println e | |
} | |
} | |
doc = getDocument("https://www.packtpub.com${doc?.getElementsByClass("dotd-main-book-image")?.first()?.getElementsByTag("a")?.first()?.attr("href")}") | |
def description = doc?.getElementsByClass("book-info-bottom-indetail-text")?.text() | |
def payload = [text: "Libro gratuito del día:", attachments: [[title: title, text: description, thumb_url: image, title_link: PACKTPUB_FREE_BOOK_URL]]] | |
def httpPush = new HTTPBuilder(SLACK_WEBHOOKS) | |
httpPush.request(Method.POST, ContentType.JSON) { | |
body = (payload as JSONObject).toString() | |
response.success = { resp -> | |
println "Success" | |
println "Response -----------------" | |
println resp.dump() | |
println "----------------- Response" | |
} | |
response.failure = { resp -> | |
println "failure" | |
println "Error -----------------" | |
println resp.dump() | |
println "----------------- Error" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment