Skip to content

Instantly share code, notes, and snippets.

@hyuki

hyuki/README.md Secret

Last active November 11, 2022 11:06
Show Gist options
  • Select an option

  • Save hyuki/69fb131924f086cfd1555a5736ca19d4 to your computer and use it in GitHub Desktop.

Select an option

Save hyuki/69fb131924f086cfd1555a5736ca19d4 to your computer and use it in GitHub Desktop.
mastodon-cli.rb - Rubyでマストドンインスタンスに投稿する最低限のコード

要点

参照

手順

  • gem install mastodon-api
  • 投稿したいマストドンインスタンスにアプリを作る。
  • ENVに適切な値を設定。
  • 走らせるとメッセージ投稿する。
  • MASTODON_CLIENT_ID,MASTODON_CLIENT_SECRET,MASTODON_TOKENは一度得た後、環境変数に入れておけばいい。
  • 詳しくは上の参照ページを読む。
#!/usr/bin/env ruby
require 'mastodon'
require 'oauth2'
require 'pp'
message = "Hello, world at #{Time.now}"
ENV['MASTODON_APP'] = 'YOUR-APP-NAME' # https://MASTODON_URL/settings/applications
ENV['MASTODON_URL'] = 'https://YOUR-INSTANCE-URL'
ENV['MASTODON_LOGIN_ID'] = 'YOURMAIL@EXAMPLE.COM'
ENV['MASTODON_PASSWORD'] = 'YOUR-PASSWORD'
SCOPES = "read write follow"
# Client
client = Mastodon::REST::Client.new(base_url: ENV['MASTODON_URL'])
app = client.create_app(ENV['MASTODON_APP'],
"urn:ietf:wg:oauth:2.0:oob",
SCOPES)
ENV['MASTODON_CLIENT_ID'] = app.client_id
ENV['MASTODON_CLIENT_SECRET'] = app.client_secret
# Token
client = OAuth2::Client.new(ENV['MASTODON_CLIENT_ID'],
ENV['MASTODON_CLIENT_SECRET'],
site: ENV['MASTODON_URL'])
token = client.password.get_token(ENV['MASTODON_LOGIN_ID'],
ENV['MASTODON_PASSWORD'],
scope: SCOPES)
ENV['MASTODON_TOKEN'] = token.token
# Status
client = Mastodon::REST::Client.new(base_url: ENV['MASTODON_URL'],
bearer_token: ENV['MASTODON_TOKEN'])
response = client.create_status(message)
puts response.attributes['url']
@hyuki
Copy link
Copy Markdown
Author

hyuki commented Nov 11, 2022

image

@hyuki
Copy link
Copy Markdown
Author

hyuki commented Nov 11, 2022

いったんMASTODON_TOKENを得たならば、必要なのはMASTODON_URLとMASTODON_TOKENだけ。

#!/usr/bin/env ruby

require 'mastodon'
require 'oauth2'
require 'pp'

client = Mastodon::REST::Client.new(base_url: ENV['MASTODON_URL'], bearer_token: ENV['MASTODON_TOKEN'])
message = 'Hello, world!'
response = client.create_status(message)

puts response.attributes['url']

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment