Skip to content

Instantly share code, notes, and snippets.

@icelander
Last active August 13, 2020 21:46
Show Gist options
  • Save icelander/5550c9c27e25724b4e9db30dcab319d5 to your computer and use it in GitHub Desktop.
Save icelander/5550c9c27e25724b4e9db30dcab319d5 to your computer and use it in GitHub Desktop.
post_as_a_bot.rb is a Ruby script that posts a message in a Mattermost channel as a bot user
#!/bin/ruby
require 'uri'
require 'httparty'
# ## post_as_a_bot.rb
#
# ### About
#
# post_as_a_bot.rb is a Ruby script that posts a message in a Mattermost channel as a bot user
#
# ### Usage:
#
# **Dependencies:** This script requires that you install Ruby -
# https://www.ruby-lang.org/en/documentation/installation/ - and install the
# required gems:
#
# - uri
# - httparty
#
# Once you have Ruby installed, install them with this command:
#
# gem install uri httparty
#
# 1. Create a a bot account and record the authentication token
# 2. Add the bot account to the team and channel you want it to post to
# 3. Create a file in this directory with the following format:
#
# ```yaml
# test_server:
# url: https://<Mattermost Server URL>/ <- INCLUDE TRAILING SLASH
# login_id: <Bot username>
# auth_token: <Auth Token>
# ```
#
# 4. Get the team name and channel name from the channel URL, which is available
# in the channel menu. For example, this URL -
# https://mattermost.example.com/ad-1/channels/saepe-5 - will have the team
# `ad-1` and the channel `saepe-5`
#
# 5. Run the script through Ruby: `ruby post_as_a_bot.rb team-name channel-name "This is a bot"`
$config = YAML.load(
File.open('conf.yaml').read
)
class MattermostApi
include HTTParty
format :json
# UNCOMMENT NEXT LINE TO DEBUG REQUESTS
debug_output $stdout
def initialize(config)
# Default Options
@options = {
headers: {
'Content-Type' => 'application/json',
'User-Agent' => 'Mattermost-HTTParty'
},
# TODO Make this more secure
verify: false
}
# check the config for mattermost_url
if ! (config.key?("url") && url_valid?(config['url']))
raise 'url is required in configuration'
end
@base_uri = config['url'] + 'api/v4/'
token = nil
if config.key?('auth_token')
token = config['auth_token']
else
# Use password login
if (config.key?('login_id') && config.key?('password'))
token = get_login_token(config['login_id'], config['password'])
end
end
if token.nil?
raise 'token not set, check for token or login_id and password'
end
@options[:headers]['Authorization'] = "Bearer #{token}"
@options[:body] = nil
end
def url_valid?(url)
url = URI.parse(url) rescue false
end
def post_to_channel(team_name, channel_name, message)
team_id = get_team_id(team_name)
channel_id = get_channel_id_by_name(channel_name, team_id)['id']
create_post(channel_id, message)
end
def get_channel_id_by_name(channel_name, team_id)
get_url("teams/#{team_id}/channels/name/#{channel_name}")
end
def create_post(channel_id, message)
data = {channel_id: channel_id, message: message}
post_data(data, 'posts')
end
## Sends a direct message to a user
def send_direct_message(to_user, message)
# Find the recipient's user ID
to_id = get_user_by_name(to_user)['id']
# Get the current user's ID
from_id = self.get_current_user['id']
data = [to_id, from_id]
# Create the direct message channel if it isn't already
channel = post_data(data, 'channels/direct')
# create the post int he channel
create_post(channel['id'], message)
end
def get_user_by_name(login_id)
JSON.parse(self.class.get("#{@base_uri}users/username/#{login_id}", @options).to_s)
end
def get_current_user
get_url('users/me')
end
def get_team_id(team_name)
team = self.get_url("teams/name/#{team_name}")
return team['id']
end
def post_data(payload, request_url)
options = @options
options[:body] = payload.to_json
return self.class.post("#{@base_uri}#{request_url}", options)
end
def get_url(url)
JSON.parse(self.class.get("#{@base_uri}#{url}", @options).to_s)
end
end
$mm = MattermostApi.new($config['test_server'])
team_name = ARGV[0]
channel_name = ARGV[1]
message = ARGV[2]
if channel_name.start_with?("@")
$mm.send_direct_message(channel_name[1...], message)
else
$mm.post_to_channel(team_name, channel_name, message)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment