diff --git a/lib/commands/shorten.rb b/lib/commands/shorten.rb new file mode 100644 index 0000000..d238614 --- /dev/null +++ b/lib/commands/shorten.rb @@ -0,0 +1,18 @@ +module Bot + module DiscordCommands + module ShortenCommands + extend Discordrb::Commands::CommandContainer + + require 'json' + + SHORTEN_URL = 'https://www.googleapis.com/urlshortener/v1/url?key=' + + command(:shorten, usage: 'shorten ', description: '短縮URLを生成', min_args: 1) do |event, url| + body = {"longUrl" => url}.to_json + res = post_json(SHORTEN_URL + CONFIG[:google][:apikey], body) + json = JSON.parse(res.body) + event.respond json["id"] + end + end + end +end \ No newline at end of file diff --git a/lib/methods.rb b/lib/methods.rb index 815fb5e..c472a12 100644 --- a/lib/methods.rb +++ b/lib/methods.rb @@ -27,4 +27,14 @@ def get_json(location, limit = 10) puts [uri.to_s, e.class, e].join(" : ") # handle error end +end + +def post_json(location, json) + uri = URI.parse(location) + https = Net::HTTP.new(uri.host, uri.port) + https.use_ssl = true + req = Net::HTTP::Post.new(uri.request_uri) + req["Content-Type"] = "application/json" + req.body = json + return https.request(req) end \ No newline at end of file