repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/api/endpoints/seasons_endpoint_spec.rb
spec/api/endpoints/seasons_endpoint_spec.rb
require 'spec_helper' describe Api::Endpoints::SeasonsEndpoint do include Api::Test::EndpointTest let!(:team) { Fabricate(:team, api: true) } before do @cursor_params = { team_id: team.id.to_s } end it_behaves_like 'a cursor api', Season it 'cannot return seasons for a team with api off' do team.update_attributes!(api: false) expect { client.seasons(team_id: team.id).resource }.to raise_error Faraday::ClientError do |e| json = JSON.parse(e.response[:body]) expect(json['error']).to eq 'Not Found' end end context 'season' do let(:existing_season) { Fabricate(:season) } it 'returns a season' do season = client.season(id: existing_season.id) expect(season.id).to eq existing_season.id.to_s expect(season._links.self._url).to eq "http://example.org/api/seasons/#{existing_season.id}" end it 'cannot return a season for a team with api off' do team.update_attributes!(api: false) expect { client.season(id: existing_season.id).resource }.to raise_error Faraday::ClientError do |e| json = JSON.parse(e.response[:body]) expect(json['error']).to eq 'Not Found' end end end context 'current season' do before do Fabricate(:match) end it 'returns the current season' do season = client.current_season(team_id: team.id.to_s) expect(season.id).to eq 'current' expect(season._links.self._url).to eq 'http://example.org/api/seasons/current' end it 'cannot return the current season for team with api off' do team.update_attributes!(api: false) expect { client.current_season(team_id: team.id.to_s).resource }.to raise_error Faraday::ClientError do |e| json = JSON.parse(e.response[:body]) expect(json['error']).to eq 'Not Found' end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/api/endpoints/users_endpoint_spec.rb
spec/api/endpoints/users_endpoint_spec.rb
require 'spec_helper' describe Api::Endpoints::UsersEndpoint do include Api::Test::EndpointTest let!(:team) { Fabricate(:team, api: true) } before do @cursor_params = { team_id: team.id.to_s } end it_behaves_like 'a cursor api', User context 'user' do let(:existing_user) { Fabricate(:user) } it 'returns a user' do user = client.user(id: existing_user.id) expect(user.id).to eq existing_user.id.to_s expect(user.user_name).to eq existing_user.user_name expect(user._links.self._url).to eq "http://example.org/api/users/#{existing_user.id}" end it 'cannot return a user for a team with api off' do team.update_attributes!(api: false) expect { client.user(id: existing_user.id).resource }.to raise_error Faraday::ClientError do |e| json = JSON.parse(e.response[:body]) expect(json['error']).to eq 'Not Found' end end end context 'users' do let!(:user_elo1) { Fabricate(:user, elo: 1, wins: 1, team:, captain: true) } let!(:user_elo3) { Fabricate(:user, elo: 3, wins: 3, team:) } let!(:user_elo2) { Fabricate(:user, elo: 2, wins: 2, team:) } it 'cannot return users for a team with api off' do team.update_attributes!(api: false) expect { client.users(team_id: team.id).resource }.to raise_error Faraday::ClientError do |e| json = JSON.parse(e.response[:body]) expect(json['error']).to eq 'Not Found' end end it 'returns users sorted by elo' do users = client.users(team_id: team.id, sort: 'elo') expect(users.map(&:id)).to eq [user_elo1, user_elo2, user_elo3].map(&:id).map(&:to_s) end it 'returns users sorted by -elo' do users = client.users(team_id: team.id, sort: '-elo') expect(users.map(&:id)).to eq [user_elo3, user_elo2, user_elo1].map(&:id).map(&:to_s) end it 'returns users sorted by rank' do users = client.users(team_id: team.id, sort: 'rank') expect(users.map(&:id)).to eq [user_elo3, user_elo2, user_elo1].map(&:id).map(&:to_s) end it 'returns users sorted by -rank' do users = client.users(team_id: team.id, sort: '-rank') expect(users.map(&:id)).to eq [user_elo1, user_elo2, user_elo3].map(&:id).map(&:to_s) end it 'returns captains' do users = client.users(team_id: team.id, captain: true) expect(users.map(&:id)).to eq [user_elo1].map(&:id).map(&:to_s) end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/api/endpoints/challenges_endpoint_spec.rb
spec/api/endpoints/challenges_endpoint_spec.rb
require 'spec_helper' describe Api::Endpoints::ChallengesEndpoint do include Api::Test::EndpointTest let!(:team) { Fabricate(:team, api: true) } before do @cursor_params = { team_id: team.id.to_s } end it_behaves_like 'a cursor api', Challenge it 'cannot return challenges for team with api off' do team.update_attributes!(api: false) expect { client.challenges(team_id: team.id).resource }.to raise_error Faraday::ClientError do |e| json = JSON.parse(e.response[:body]) expect(json['error']).to eq 'Not Found' end end context 'challenge' do let(:existing_challenge) { Fabricate(:challenge) } it 'returns a challenge' do challenge = client.challenge(id: existing_challenge.id) expect(challenge.id).to eq existing_challenge.id.to_s expect(challenge._links.self._url).to eq "http://example.org/api/challenges/#{existing_challenge.id}" expect(challenge._links.team._url).to eq "http://example.org/api/teams/#{existing_challenge.team.id}" end it 'cannot return a challenge for team with api off' do team.update_attributes!(api: false) expect { client.challenge(id: existing_challenge.id).resource }.to raise_error Faraday::ClientError do |e| json = JSON.parse(e.response[:body]) expect(json['error']).to eq 'Not Found' end end end context 'doubles challenge' do let(:existing_challenge) { Fabricate(:doubles_challenge) } before do existing_challenge.accept!(existing_challenge.challenged.first) existing_challenge.lose!(existing_challenge.challengers.first) end it 'returns a challenge with links to challengers, challenged and played match' do challenge = client.challenge(id: existing_challenge.id) expect(challenge.id).to eq existing_challenge.id.to_s expect(challenge._links.challengers._url).to eq existing_challenge.challengers.map { |user| "http://example.org/api/users/#{user.id}" } expect(challenge._links.challenged._url).to eq existing_challenge.challenged.map { |user| "http://example.org/api/users/#{user.id}" } expect(challenge._links.match._url).to eq "http://example.org/api/matches/#{existing_challenge.match.id}" end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/api/endpoints/matches_endpoint_spec.rb
spec/api/endpoints/matches_endpoint_spec.rb
require 'spec_helper' describe Api::Endpoints::MatchesEndpoint do include Api::Test::EndpointTest let!(:team) { Fabricate(:team, api: true) } before do @cursor_params = { team_id: team.id.to_s } end it_behaves_like 'a cursor api', Match it 'cannot return matches for a team with api off' do team.update_attributes!(api: false) expect { client.matches(team_id: team.id).resource }.to raise_error Faraday::ClientError do |e| json = JSON.parse(e.response[:body]) expect(json['error']).to eq 'Not Found' end end context 'match' do let(:existing_match) { Fabricate(:match, team:) } it 'returns a match' do match = client.match(id: existing_match.id) expect(match.id).to eq existing_match.id.to_s expect(match._links.self._url).to eq "http://example.org/api/matches/#{existing_match.id}" end it 'cannot return a match for a team with api off' do team.update_attributes!(api: false) expect { client.match(id: existing_match.id).resource }.to raise_error Faraday::ClientError do |e| json = JSON.parse(e.response[:body]) expect(json['error']).to eq 'Not Found' end end end context 'match' do let(:existing_match) { Fabricate(:match) } it 'returns a match with links to challenge' do match = client.match(id: existing_match.id) expect(match.id).to eq existing_match.id.to_s expect(match._links.challenge._url).to eq "http://example.org/api/challenges/#{existing_match.challenge.id}" expect(match._links.winners._url).to eq existing_match.winners.map { |user| "http://example.org/api/users/#{user.id}" } expect(match._links.losers._url).to eq existing_match.losers.map { |user| "http://example.org/api/users/#{user.id}" } end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/api/endpoints/root_endpoint_spec.rb
spec/api/endpoints/root_endpoint_spec.rb
require 'spec_helper' describe Api::Endpoints::RootEndpoint do include Api::Test::EndpointTest it 'hypermedia root' do get '/api/' expect(last_response.status).to eq 200 links = JSON.parse(last_response.body)['_links'] expect(links.keys.sort).to eq(%w[self status team teams user users challenge challenges credit_cards match matches current_season season seasons subscriptions game games].sort) end it 'follows all links' do get '/api/' expect(last_response.status).to eq 200 links = JSON.parse(last_response.body)['_links'] links.each_pair do |_key, h| href = h['href'] next if href.include?('{') # templated link next if href == 'http://example.org/api/subscriptions' next if href == 'http://example.org/api/credit_cards' get href.gsub('http://example.org', '') expect(last_response.status).to eq 200 expect(JSON.parse(last_response.body)).not_to eq({}) end end it 'rewrites encoded HAL links to make them clickable' do get '/api/teams/%7B?cursor,size%7D' expect(last_response.status).to eq 302 expect(last_response.headers['Location']).to eq '/api/teams/' end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/api/endpoints/teams_endpoint_spec.rb
spec/api/endpoints/teams_endpoint_spec.rb
require 'spec_helper' describe Api::Endpoints::TeamsEndpoint do include Api::Test::EndpointTest let!(:game) { Fabricate(:game) } context 'cursor' do it_behaves_like 'a cursor api', Team end context 'team' do let(:existing_team) { Fabricate(:team, game:) } it 'returns a team' do team = client.team(id: existing_team.id) expect(team.id).to eq existing_team.id.to_s expect(team._links.self._url).to eq "http://example.org/api/teams/#{existing_team.id}" end end context 'teams' do context 'active/inactive' do let!(:active_team) { Fabricate(:team, game:, active: true) } let!(:inactive_team) { Fabricate(:team, game:, active: false) } it 'returns all teams' do teams = client.teams expect(teams.count).to eq 2 end it 'returns active teams' do teams = client.teams(active: true) expect(teams.count).to eq 1 expect(teams.to_a.first.team_id).to eq active_team.team_id end end context 'game_id' do let!(:team1) { Fabricate(:team, game:) } let!(:team2) { Fabricate(:team, game: Fabricate(:game)) } it 'returns all teams' do teams = client.teams expect(teams.count).to eq 2 end it 'returns team by game' do teams = client.teams(game_id: game.id.to_s) expect(teams.count).to eq 1 expect(teams.to_a.first.team_id).to eq team1.team_id end end context 'api on/off' do let!(:team_api_on) { Fabricate(:team, game:) } let!(:team_api_off) { Fabricate(:team, api: false, game:) } it 'only returns teams with api on' do teams = client.teams expect(teams.count).to eq 1 expect(teams.to_a.first.team_id).to eq team_api_on.team_id end end context 'game_id' do let!(:team1) { Fabricate(:team, game:) } let!(:team2) { Fabricate(:team, game: Fabricate(:game)) } it 'returns all teams' do teams = client.teams expect(teams.count).to eq 2 end it 'returns team by game' do teams = client.teams(game_id: game.id.to_s) expect(teams.count).to eq 1 expect(teams.to_a.first.team_id).to eq team1.team_id end end end context 'team' do let(:existing_team) { Fabricate(:team, game:) } it 'returns a team with links to challenges, users and matches' do team = client.team(id: existing_team.id) expect(team.id).to eq existing_team.id.to_s expect(team._links.users._url).to eq "http://example.org/api/users?team_id=#{existing_team.id}" expect(team._links.challenges._url).to eq "http://example.org/api/challenges?team_id=#{existing_team.id}" expect(team._links.matches._url).to eq "http://example.org/api/matches?team_id=#{existing_team.id}" expect(team._links.seasons._url).to eq "http://example.org/api/seasons?team_id=#{existing_team.id}" expect(team._links.game._url).to eq "http://example.org/api/games/#{existing_team.game.id}" end it 'cannot return a team with api off' do existing_team.update_attributes!(api: false) expect { client.team(id: existing_team.id).resource }.to raise_error Faraday::ClientError do |e| json = JSON.parse(e.response[:body]) expect(json['error']).to eq 'Not Found' end end it 'cannot create a team without a game' do expect do expect { client.teams._post(code: 'code').resource }.to raise_error Faraday::ClientError do |e| json = JSON.parse(e.response[:body]) expect(json['message']).to eq 'Invalid parameters.' expect(json['detail']).to eq('game, game_id' => ['are missing, exactly one parameter must be provided']) end end.not_to change(Team, :count) end it 'requires code' do expect { client.teams._post }.to raise_error Faraday::ClientError do |e| json = JSON.parse(e.response[:body]) expect(json['message']).to eq 'Invalid parameters.' expect(json['type']).to eq 'param_error' end end context 'register' do before do oauth_access = { 'bot' => { 'bot_access_token' => 'token', 'bot_user_id' => 'bot_user_id' }, 'access_token' => 'access_token', 'user_id' => 'activated_user_id', 'team_id' => 'team_id', 'team_name' => 'team_name' } allow_any_instance_of(Slack::Web::Client).to receive(:oauth_access).with( hash_including( code: 'code', client_id: game.client_id, client_secret: game.client_secret ) ).and_return(oauth_access) end it 'creates a team with game name' do expect_any_instance_of(Team).to receive(:activated!) expect(SlackRubyBotServer::Service.instance).to receive(:start!) expect do team = client.teams._post(code: 'code', game: game.name) expect(team.team_id).to eq 'team_id' expect(team.name).to eq 'team_name' team = Team.find(team.id) expect(team.game).to eq game expect(team.token).to eq 'token' expect(team.aliases).to eq game.aliases expect(team.bot_user_id).to eq 'bot_user_id' expect(team.activated_user_id).to eq 'activated_user_id' end.to change(Team, :count).by(1) end it 'creates a team with game id' do expect_any_instance_of(Team).to receive(:activated!) expect(SlackRubyBotServer::Service.instance).to receive(:start!) expect do team = client.teams._post(code: 'code', game_id: game.id.to_s) expect(team.team_id).to eq 'team_id' expect(team.name).to eq 'team_name' team = Team.find(team.id) expect(team.game).to eq game expect(team.token).to eq 'token' expect(team.aliases).to eq game.aliases expect(team.bot_user_id).to eq 'bot_user_id' expect(team.activated_user_id).to eq 'activated_user_id' end.to change(Team, :count).by(1) end it 'reactivates a deactivated team' do allow_any_instance_of(Team).to receive(:activated!) expect(SlackRubyBotServer::Service.instance).to receive(:start!) existing_team = Fabricate(:team, game:, token: 'token', active: false, aliases: %w[foo bar]) expect do team = client.teams._post(code: 'code', game: existing_team.game.name) expect(team.team_id).to eq existing_team.team_id expect(team.name).to eq existing_team.name expect(team.active).to be true team = Team.find(team.id) expect(team.token).to eq 'token' expect(team.active).to be true expect(team.aliases).to eq %w[foo bar] expect(team.bot_user_id).to eq 'bot_user_id' expect(team.activated_user_id).to eq 'activated_user_id' end.not_to change(Team, :count) end it 'reactivates a team deactivated on slack' do allow_any_instance_of(Team).to receive(:activated!) expect(SlackRubyBotServer::Service.instance).to receive(:start!) existing_team = Fabricate(:team, game:, token: 'token', aliases: %w[foo bar]) expect do expect_any_instance_of(Team).to receive(:ping!) { raise Slack::Web::Api::Errors::SlackError, 'invalid_auth' } team = client.teams._post(code: 'code', game: existing_team.game.name) expect(team.team_id).to eq existing_team.team_id expect(team.name).to eq existing_team.name expect(team.active).to be true team = Team.find(team.id) expect(team.token).to eq 'token' expect(team.active).to be true expect(team.aliases).to eq %w[foo bar] expect(team.bot_user_id).to eq 'bot_user_id' expect(team.activated_user_id).to eq 'activated_user_id' end.not_to change(Team, :count) end it 'updates a reactivated team with a new token' do allow_any_instance_of(Team).to receive(:activated!) expect(SlackRubyBotServer::Service.instance).to receive(:start!) existing_team = Fabricate(:team, game:, token: 'old', team_id: 'team_id', active: false) expect do team = client.teams._post(code: 'code', game: existing_team.game.name) expect(team.team_id).to eq existing_team.team_id expect(team.name).to eq existing_team.name expect(team.active).to be true team = Team.find(team.id) expect(team.token).to eq 'token' expect(team.active).to be true expect(team.bot_user_id).to eq 'bot_user_id' expect(team.activated_user_id).to eq 'activated_user_id' end.not_to change(Team, :count) end it 'revives a dead team' do allow_any_instance_of(Team).to receive(:activated!) expect(SlackRubyBotServer::Service.instance).to receive(:start!) existing_team = Fabricate(:team, game:, token: 'old', aliases: %w[foo bar], team_id: 'team_id', active: false, dead_at: Time.now) expect do team = client.teams._post(code: 'code', game: existing_team.game.name) expect(team.team_id).to eq existing_team.team_id expect(team.name).to eq existing_team.name expect(team.active).to be true team = Team.find(team.id) expect(team.token).to eq 'token' expect(team.active).to be true expect(team.aliases).to eq %w[foo bar] expect(team.bot_user_id).to eq 'bot_user_id' expect(team.activated_user_id).to eq 'activated_user_id' expect(team.dead_at).to be_nil end.not_to change(Team, :count) end it 'cannot switch games' do expect(SlackRubyBotServer::Service.instance).not_to receive(:start!) Fabricate(:team, game: Fabricate(:game), token: 'token', active: false) expect { client.teams._post(code: 'code', game_id: game.id.to_s) }.to raise_error Faraday::ClientError do |e| json = JSON.parse(e.response[:body]) expect(json['error']).to eq 'Invalid Game' end end it 'returns a useful error when team already exists' do allow_any_instance_of(Team).to receive(:activated!) expect(SlackRubyBotServer::Service.instance).not_to receive(:start!) expect_any_instance_of(Team).to receive(:ping_if_active!) existing_team = Fabricate(:team, game:, token: 'token') expect { client.teams._post(code: 'code', game: game.name) }.to raise_error Faraday::ClientError do |e| json = JSON.parse(e.response[:body]) expect(json['message']).to eq "Team #{existing_team.name} is already registered." end end context 'with mailchimp settings' do before do SlackRubyBotServer::Mailchimp.configure do |config| config.mailchimp_api_key = 'api-key' config.mailchimp_list_id = 'list-id' end end after do SlackRubyBotServer::Mailchimp.config.reset! ENV.delete('MAILCHIMP_API_KEY') ENV.delete('MAILCHIMP_LIST_ID') ENV.delete('MAILCHIMP_API_KEY') ENV.delete('MAILCHIMP_LIST_ID') end let(:list) { double(Mailchimp::List, members: double(Mailchimp::List::Members)) } it 'subscribes to the mailing list' do allow_any_instance_of(Team).to receive(:activated!) expect(SlackRubyBotServer::Service.instance).to receive(:start!) allow_any_instance_of(Slack::Web::Client).to receive(:users_info).with( user: 'activated_user_id' ).and_return( user: { profile: { email: 'user@example.com', first_name: 'First', last_name: 'Last' } } ) allow_any_instance_of(Mailchimp::Client).to receive(:lists).with('list-id').and_return(list) expect(list.members).to receive(:where).with(email_address: 'user@example.com').and_return([]) expect(list.members).to receive(:create_or_update).with( email_address: 'user@example.com', merge_fields: { 'FNAME' => 'First', 'LNAME' => 'Last', 'BOT' => game.name.capitalize }, status: 'pending', name: nil, tags: %w[gamebot trial], unique_email_id: 'team_id-activated_user_id' ) client.teams._post(code: 'code', game: game.name) end end end it 'reactivates a deactivated team with a different code' do allow_any_instance_of(Team).to receive(:activated!).twice expect(SlackRubyBotServer::Service.instance).to receive(:start!) existing_team = Fabricate(:team, game:, token: 'token', active: false, aliases: %w[foo bar]) oauth_access = { 'bot' => { 'bot_access_token' => 'another_token', 'bot_user_id' => 'bot_user_id' }, 'user_id' => 'activated_user_id', 'team_id' => existing_team.team_id, 'team_name' => existing_team.name } allow_any_instance_of(Slack::Web::Client).to receive(:oauth_access).with( hash_including( code: 'code', client_id: game.client_id, client_secret: game.client_secret ) ).and_return(oauth_access) expect do team = client.teams._post(code: 'code', game: existing_team.game.name) expect(team.team_id).to eq existing_team.team_id expect(team.name).to eq existing_team.name expect(team.active).to be true team = Team.find(team.id) expect(team.token).to eq 'another_token' expect(team.active).to be true expect(team.aliases).to eq %w[foo bar] expect(team.bot_user_id).to eq 'bot_user_id' expect(team.activated_user_id).to eq 'activated_user_id' end.not_to change(Team, :count) end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/api/endpoints/games_endpoint_spec.rb
spec/api/endpoints/games_endpoint_spec.rb
require 'spec_helper' describe Api::Endpoints::GamesEndpoint do include Api::Test::EndpointTest it_behaves_like 'a cursor api', Game context 'game' do let(:existing_game) { Fabricate(:game) } it 'returns a game' do game = client.game(id: existing_game.id) expect(game.id).to eq existing_game.id.to_s expect(game._links.self._url).to eq "http://example.org/api/games/#{existing_game.id}" end end context 'game' do let(:existing_game) { Fabricate(:game) } it 'returns a game with links to teams' do game = client.game(id: existing_game.id) expect(game.id).to eq existing_game.id.to_s expect(game._links.teams._url).to eq "http://example.org/api/teams?game_id=#{existing_game.id}" end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/api/endpoints/subscriptions_endpoint_spec.rb
spec/api/endpoints/subscriptions_endpoint_spec.rb
require 'spec_helper' describe Api::Endpoints::SubscriptionsEndpoint do include Api::Test::EndpointTest context 'subcriptions' do it 'requires stripe parameters' do expect { client.subscriptions._post }.to raise_error Faraday::ClientError do |e| json = JSON.parse(e.response[:body]) expect(json['message']).to eq 'Invalid parameters.' expect(json['type']).to eq 'param_error' end end context 'subscribed team' do let!(:team) { Fabricate(:team, subscribed: true) } it 'fails to create a subscription' do expect do client.subscriptions._post( team_id: team._id, stripe_token: 'token', stripe_token_type: 'card', stripe_email: 'foo@bar.com' ) end.to raise_error Faraday::ClientError do |e| json = JSON.parse(e.response[:body]) expect(json['error']).to eq 'Already a Subscriber' end end end context 'team with a canceled subscription' do let!(:team) { Fabricate(:team, subscribed: false, stripe_customer_id: 'customer_id') } let(:stripe_customer) { double(Stripe::Customer) } before do allow(Stripe::Customer).to receive(:retrieve).with(team.stripe_customer_id).and_return(stripe_customer) end context 'with an active subscription' do before do allow(stripe_customer).to receive(:subscriptions).and_return([ double(Stripe::Subscription) ]) end it 'fails to create a subscription' do expect do client.subscriptions._post( team_id: team._id, stripe_token: 'token', stripe_token_type: 'card', stripe_email: 'foo@bar.com' ) end.to raise_error Faraday::ClientError do |e| json = JSON.parse(e.response[:body]) expect(json['error']).to eq 'Existing Subscription Already Active' end end end context 'without no active subscription' do before do allow(stripe_customer).to receive(:subscriptions).and_return([]) end it 'updates a subscription' do expect(Stripe::Customer).to receive(:update).with( team.stripe_customer_id, { source: 'token', plan: 'slack-playplay-yearly', email: 'foo@bar.com', coupon: nil, metadata: { id: team._id.to_s, team_id: team.team_id, name: team.name, domain: team.domain, game: team.game.name } } ).and_return('id' => 'customer_id') expect_any_instance_of(Team).to receive(:inform!).once client.subscriptions._post( team_id: team._id, stripe_token: 'token', stripe_token_type: 'card', stripe_email: 'foo@bar.com' ) team.reload expect(team.subscribed).to be true expect(team.subscribed_at).not_to be_nil expect(team.stripe_customer_id).to eq 'customer_id' end end end context 'existing team' do include_context 'stripe mock' let!(:team) { Fabricate(:team) } context 'with a plan' do before do expect_any_instance_of(Team).to receive(:inform!).once stripe_helper.create_plan(id: 'slack-playplay-yearly', amount: 2999) client.subscriptions._post( team_id: team._id, stripe_token: stripe_helper.generate_card_token, stripe_token_type: 'card', stripe_email: 'foo@bar.com' ) team.reload end it 'creates a subscription' do expect(team.subscribed).to be true expect(team.stripe_customer_id).not_to be_blank customer = Stripe::Customer.retrieve(team.stripe_customer_id) expect(customer).not_to be_nil expect(customer.metadata.to_h).to eq( id: team._id.to_s, name: team.name, team_id: team.team_id, domain: team.domain, game: team.game.name ) expect(customer.discount).to be_nil subscriptions = customer.subscriptions expect(subscriptions.count).to eq 1 end end context 'with a coupon' do before do expect_any_instance_of(Team).to receive(:inform!).once stripe_helper.create_plan(id: 'slack-playplay-yearly', amount: 2999) stripe_helper.create_coupon(id: 'slack-playplay-yearly-twenty-nine-ninety-nine', amount_off: 2999) client.subscriptions._post( team_id: team._id, stripe_token: stripe_helper.generate_card_token, stripe_token_type: 'card', stripe_email: 'foo@bar.com', stripe_coupon: 'slack-playplay-yearly-twenty-nine-ninety-nine' ) team.reload end it 'creates a subscription' do expect(team.subscribed).to be true expect(team.stripe_customer_id).not_to be_blank customer = Stripe::Customer.retrieve(team.stripe_customer_id) expect(customer).not_to be_nil subscriptions = customer.subscriptions expect(subscriptions.count).to eq 1 discount = customer.discount expect(discount.coupon.id).to eq 'slack-playplay-yearly-twenty-nine-ninety-nine' end end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/version_spec.rb
spec/slack-gamebot/version_spec.rb
require 'spec_helper' describe SlackGamebot do it 'has a version' do expect(SlackGamebot::VERSION).not_to be_nil end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/service_spec.rb
spec/slack-gamebot/service_spec.rb
require 'spec_helper' describe SlackRubyBotServer::Service do describe '#url' do before do @rack_env = ENV.fetch('RACK_ENV', nil) end after do ENV['RACK_ENV'] = @rack_env end it 'defaults to playplay.io in production' do expect(SlackRubyBotServer::Service.url).to eq 'https://www.playplay.io' end context 'in development' do before do ENV['RACK_ENV'] = 'development' end it 'defaults to localhost' do expect(SlackRubyBotServer::Service.url).to eq 'http://localhost:5000' end end context 'when set' do before do ENV['URL'] = 'updated' end after do ENV.delete('URL') end it 'defaults to ENV' do expect(SlackRubyBotServer::Service.url).to eq 'updated' end end end describe '#api_url' do it 'defaults to playplay.io in production' do expect(SlackRubyBotServer::Service.api_url).to eq 'https://www.playplay.io/api' end context 'when set' do before do ENV['API_URL'] = 'updated' end after do ENV.delete 'API_URL' end it 'defaults to ENV' do expect(SlackRubyBotServer::Service.api_url).to eq 'updated' end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/server_spec.rb
spec/slack-gamebot/server_spec.rb
require 'spec_helper' describe SlackGamebot::Server do let(:team) { Fabricate(:team) } let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } context 'send_gifs' do context 'default' do let(:team) { Fabricate(:team) } it 'true' do expect(app.send(:client).send_gifs?).to be true end end context 'on' do let(:team) { Fabricate(:team, gifs: true) } it 'true' do expect(app.send(:client).send_gifs?).to be true end end context 'off' do let(:team) { Fabricate(:team, gifs: false) } it 'false' do expect(app.send(:client).send_gifs?).to be false end end end context 'aliases' do let(:game) { Fabricate(:game, name: 'game', aliases: []) } let(:team) { Fabricate(:team, game:, aliases: %w[t1 t2]) } it 'combines game name and team aliases' do expect(app.send(:client).aliases).to eq %w[game t1 t2] end end context 'hooks' do let(:user) { Fabricate(:user, team:) } it 'renames user' do app.send(:hook_blocks)[:user_change].each do |hook| hook.call(client, Hashie::Mash.new(type: 'user_change', user: { id: user.user_id, name: 'updated' })) end expect(user.reload.user_name).to eq('updated') end it 'does not touch a user with the same name' do allow(User).to receive(:where).and_return([user]) app.send(:hook_blocks)[:user_change].each do |hook| hook.call(client, Hashie::Mash.new(type: 'user_change', user: { id: user.user_id, name: user.user_name })) end expect(user).not_to receive(:update_attributes!) end end describe '#channel_joined' do it 'sends a welcome message' do allow(client).to receive_message_chain(:self, :name).and_return('bot') expect(client).to receive(:say).with(channel: 'C12345', text: [ 'Hi! I am your friendly game bot. Register with `@bot register`.', "Challenge someone to a game of #{team.game.name} with `@bot challenge @someone`.", "Type `@bot help` fore more commands and don't forget to have fun at work!\n" ].join("\n")) client.send(:callback, Hashie::Mash.new('channel' => { 'id' => 'C12345' }), :channel_joined) end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/app_spec.rb
spec/slack-gamebot/app_spec.rb
require 'spec_helper' describe SlackGamebot::App do subject do SlackGamebot::App.instance end describe '#instance' do it 'is an instance of the market app' do expect(subject).to be_a(SlackRubyBotServer::App) expect(subject).to be_an_instance_of(SlackGamebot::App) end end context 'teams' do let!(:active_team) { Fabricate(:team, created_at: Time.now.utc) } let!(:active_team_one_week_ago) { Fabricate(:team, created_at: 1.week.ago) } let!(:active_team_four_weeks_ago) { Fabricate(:team, created_at: 5.weeks.ago) } let!(:subscribed_team_a_month_ago) { Fabricate(:team, created_at: 1.month.ago, subscribed: true) } let(:teams) { [active_team, active_team_one_week_ago, active_team_four_weeks_ago, subscribed_team_a_month_ago] } before do allow(Team).to receive(:active).and_return(teams) end describe '#deactivate_dead_teams!' do it 'deactivates teams inactive for two weeks' do expect(active_team).not_to receive(:inform!) expect(active_team).not_to receive(:inform_admin!) expect(active_team_one_week_ago).not_to receive(:inform!) expect(active_team_one_week_ago).not_to receive(:inform_admin!) expect(active_team_four_weeks_ago).to receive(:deactivate!).and_call_original expect(subscribed_team_a_month_ago).not_to receive(:inform!) expect(subscribed_team_a_month_ago).not_to receive(:inform_admin!) subject.send(:deactivate_dead_teams!) expect(active_team.reload.active).to be true expect(active_team_one_week_ago.reload.active).to be true expect(active_team_four_weeks_ago.reload.active).to be false expect(subscribed_team_a_month_ago.reload.active).to be true expect_any_instance_of(Team).to receive(:inform!).with(SlackGamebot::App::DEAD_MESSAGE, 'dead').once expect_any_instance_of(Team).to receive(:inform_admin!).with(SlackGamebot::App::DEAD_MESSAGE, 'dead').once subject.send(:inform_dead_teams!) end end end context 'subscribed' do include_context 'stripe mock' let(:plan) { stripe_helper.create_plan(id: 'slack-playplay-yearly', amount: 2999, name: 'Plan') } let(:customer) { Stripe::Customer.create(source: stripe_helper.generate_card_token, plan: plan.id, email: 'foo@bar.com') } let!(:team) { Fabricate(:team, subscribed: true, stripe_customer_id: customer.id) } describe '#check_subscribed_teams!' do it 'ignores active subscriptions' do expect_any_instance_of(Team).not_to receive(:inform!) expect_any_instance_of(Team).not_to receive(:inform_admin!) subject.send(:check_subscribed_teams!) end it 'notifies past due subscription' do customer.subscriptions.data.first['status'] = 'past_due' expect(Stripe::Customer).to receive(:retrieve).and_return(customer) expect_any_instance_of(Team).to receive(:inform_admin!).with("Your subscription to Plan ($29.99) is past due. #{team.update_cc_text}") subject.send(:check_subscribed_teams!) end it 'notifies canceled subscription' do customer.subscriptions.data.first['status'] = 'canceled' expect(Stripe::Customer).to receive(:retrieve).and_return(customer) expect_any_instance_of(Team).to receive(:inform_admin!).with('Your subscription to Plan ($29.99) was canceled and your team has been downgraded. Thank you for being a customer!') subject.send(:check_subscribed_teams!) expect(team.reload.subscribed?).to be false end it 'notifies no active subscriptions' do customer.subscriptions.data = [] expect(Stripe::Customer).to receive(:retrieve).and_return(customer) expect_any_instance_of(Team).to receive(:inform_admin!).with('Your subscription was canceled and your team has been downgraded. Thank you for being a customer!') subject.send(:check_subscribed_teams!) expect(team.reload.subscribed?).to be false end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/unknown_spec.rb
spec/slack-gamebot/commands/unknown_spec.rb
require 'spec_helper' describe SlackRubyBot::Commands::Unknown, vcr: { cassette_name: 'user_info' } do let!(:team) { Fabricate(:team) } let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } let(:message_hook) { SlackRubyBot::Hooks::Message.new } it 'invalid command' do expect(message: "#{SlackRubyBot.config.user} foobar").to respond_with_slack_message("Sorry <@user>, I don't understand that command!") end it 'does not respond to sad face' do expect(SlackRubyBot::Commands::Base).not_to receive(:send_message) message_hook.call(client, Hashie::Mash.new(text: ':((')) end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/promote_spec.rb
spec/slack-gamebot/commands/promote_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Promote, vcr: { cassette_name: 'user_info' } do let!(:team) { Fabricate(:team) } let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } let(:user) { Fabricate(:user, team:, user_name: 'username', captain: true) } it 'gives help' do expect(message: "#{SlackRubyBot.config.user} promote", user: user.user_id).to respond_with_slack_message( 'Try _promote @someone_.' ) end it 'promotes another user' do another_user = Fabricate(:user, team:) expect(message: "#{SlackRubyBot.config.user} promote #{another_user.user_name}", user: user.user_id).to respond_with_slack_message( "#{another_user.user_name} has been promoted to captain." ) expect(another_user.reload.captain?).to be true end it 'cannot promote self' do expect(message: "#{SlackRubyBot.config.user} promote username", user: user.user_id).to respond_with_slack_message( "#{user.user_name} is already a captain." ) expect(user.reload.captain?).to be true end it 'promotes multiple users' do another_user1 = Fabricate(:user, team:) another_user2 = Fabricate(:user, team:) another_user3 = Fabricate(:user, team:) expect(message: "#{SlackRubyBot.config.user} promote #{another_user1.user_name} #{another_user2.user_name} #{another_user3.user_name}", user: user.user_id).to respond_with_slack_message( "#{another_user1.user_name}, #{another_user2.user_name} and #{another_user3.user_name} have been promoted to captain." ) expect(another_user1.reload.captain?).to be true expect(another_user2.reload.captain?).to be true expect(another_user3.reload.captain?).to be true end it 'cannot promote another captain' do another_user = Fabricate(:user, team:, captain: true) expect(message: "#{SlackRubyBot.config.user} promote #{another_user.user_name}", user: user.user_id).to respond_with_slack_message( "#{another_user.user_name} is already a captain." ) expect(another_user.reload.captain?).to be true end it 'cannot promote when not a captain' do user.demote! another_user = Fabricate(:user, team:, captain: true) expect(message: "#{SlackRubyBot.config.user} promote #{another_user.user_name}", user: user.user_id).to respond_with_slack_message( "You're not a captain, sorry." ) expect(user.reload.captain?).to be false end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/resigned_spec.rb
spec/slack-gamebot/commands/resigned_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Resigned, vcr: { cassette_name: 'user_info' } do let!(:team) { Fabricate(:team) } let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } context 'with a challenge' do let(:challenged) { Fabricate(:user, user_name: 'username') } let!(:challenge) { Fabricate(:challenge, challenged: [challenged]) } before do challenge.accept!(challenged) end it 'resigned' do expect(message: "#{SlackRubyBot.config.user} resigned", user: challenged.user_id, channel: challenge.channel).to respond_with_slack_message( "Match has been recorded! #{challenge.challenged.map(&:display_name).and} resigned against #{challenge.challengers.map(&:display_name).and}." ) challenge.reload expect(challenge.state).to eq ChallengeState::PLAYED expect(challenge.match.winners).to eq challenge.challengers expect(challenge.match.losers).to eq challenge.challenged expect(challenge.match.resigned?).to be true end it 'resigned with score' do expect(message: "#{SlackRubyBot.config.user} resigned 15:21", user: challenged.user_id, channel: challenge.channel).to respond_with_slack_message( 'Cannot score when resigning.' ) end end context 'resigned to' do let(:loser) { Fabricate(:user, user_name: 'username') } let(:winner) { Fabricate(:user) } it 'a player' do expect do expect do expect(message: "#{SlackRubyBot.config.user} resigned to #{winner.display_name}", user: loser.user_id, channel: 'channel').to respond_with_slack_message( "Match has been recorded! #{loser.user_name} resigned against #{winner.display_name}." ) end.not_to change(Challenge, :count) end.to change(Match, :count).by(1) match = Match.asc(:_id).last expect(match.winners).to eq [winner] expect(match.losers).to eq [loser] expect(match.resigned?).to be true end it 'two players' do winner2 = Fabricate(:user, team:) loser2 = Fabricate(:user, team:) expect do expect do expect(message: "#{SlackRubyBot.config.user} resigned to #{winner.user_name} #{winner2.user_name} with #{loser2.user_name}", user: loser.user_id, channel: 'pongbot').to respond_with_slack_message( "Match has been recorded! #{loser.display_name} and #{loser2.display_name} resigned against #{winner.display_name} and #{winner2.display_name}." ) end.not_to change(Challenge, :count) end.to change(Match, :count).by(1) match = Match.asc(:_id).last expect(match.winners).to eq [winner2, winner] expect(match.losers).to eq [loser2, loser] expect(match.resigned?).to be true end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/accept_spec.rb
spec/slack-gamebot/commands/accept_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Accept, vcr: { cassette_name: 'user_info' } do let!(:team) { Fabricate(:team) } let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } context 'regular challenge' do let(:challenged) { Fabricate(:user, team:, user_name: 'username') } let!(:challenge) { Fabricate(:challenge, team:, challenged: [challenged]) } it 'accepts a challenge' do expect(message: "#{SlackRubyBot.config.user} accept", user: challenged.user_id, channel: challenge.channel).to respond_with_slack_message( "#{challenge.challenged.map(&:display_name).and} accepted #{challenge.challengers.map(&:display_name).and}'s challenge." ) expect(challenge.reload.state).to eq ChallengeState::ACCEPTED end end context 'open challenge' do let(:user) { Fabricate(:user, team:) } let(:acceptor) { Fabricate(:user, team:) } let(:anyone_challenged) { Fabricate(:user, team:, user_id: User::ANYONE) } let!(:challenge) { Fabricate(:challenge, team:, challengers: [user], challenged: [anyone_challenged]) } it 'accepts an open challenge' do allow_any_instance_of(Slack::Web::Client).to receive(:users_info).and_return(nil) expect(message: "#{SlackRubyBot.config.user} accept", user: acceptor.user_id, channel: challenge.channel).to respond_with_slack_message( "#{acceptor.display_name} accepted #{challenge.challengers.map(&:display_name).and}'s challenge." ) challenge.reload expect(challenge.state).to eq ChallengeState::ACCEPTED expect(challenge.challenged).to eq [acceptor] end it 'cannot accept an open challenge with themselves' do allow_any_instance_of(Slack::Web::Client).to receive(:users_info).and_return(nil) expect(message: "#{SlackRubyBot.config.user} accept", user: user.user_id, channel: challenge.channel).to respond_with_slack_message( "Player #{user.user_name} cannot play against themselves." ) challenge.reload expect(challenge.state).to eq ChallengeState::PROPOSED expect(challenge.challenged).to eq [anyone_challenged] end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/lost_spec.rb
spec/slack-gamebot/commands/lost_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Lost, vcr: { cassette_name: 'user_info' } do let!(:team) { Fabricate(:team) } let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } context 'with an existing challenge' do let(:challenged) { Fabricate(:user, user_name: 'username') } let!(:challenge) { Fabricate(:challenge, challenged: [challenged]) } before do challenge.accept!(challenged) end it 'lost' do expect(message: "#{SlackRubyBot.config.user} lost", user: challenged.user_id, channel: challenge.channel).to respond_with_slack_message( "Match has been recorded! #{challenge.challengers.map(&:display_name).and} defeated #{challenge.challenged.map(&:display_name).and}." ) challenge.reload expect(challenge.state).to eq ChallengeState::PLAYED expect(challenge.match.winners).to eq challenge.challengers expect(challenge.match.losers).to eq challenge.challenged winner = challenge.match.winners.first loser = challenge.match.losers.first expect(winner.elo).to eq 48 expect(winner.tau).to eq 0.5 expect(loser.elo).to eq(-48) expect(loser.tau).to eq 0.5 end it 'updates existing challenge when lost to' do expect(message: "#{SlackRubyBot.config.user} lost to #{challenge.challengers.first.user_name}", user: challenged.user_id, channel: challenge.channel).to respond_with_slack_message( "Match has been recorded! #{challenge.challengers.map(&:display_name).and} defeated #{challenge.challenged.map(&:display_name).and}." ) challenge.reload expect(challenge.state).to eq ChallengeState::PLAYED expect(challenge.match.winners).to eq challenge.challengers expect(challenge.match.losers).to eq challenge.challenged end it 'lost with score' do expect(message: "#{SlackRubyBot.config.user} lost 15:21", user: challenged.user_id, channel: challenge.channel).to respond_with_slack_message( "Match has been recorded! #{challenge.challengers.map(&:display_name).and} defeated #{challenge.challenged.map(&:display_name).and} with the score of 21:15." ) challenge.reload expect(challenge.match.scores).to eq [[15, 21]] expect(challenge.match.resigned?).to be false end it 'lost with invalid score' do expect(message: "#{SlackRubyBot.config.user} lost 21:15", user: challenged.user_id, channel: challenge.channel).to respond_with_slack_message( 'Loser scores must come first.' ) end it 'lost with scores' do expect(message: "#{SlackRubyBot.config.user} lost 21:15 14:21 5:11", user: challenged.user_id, channel: challenge.channel).to respond_with_slack_message( "Match has been recorded! #{challenge.challengers.map(&:display_name).and} defeated #{challenge.challenged.map(&:display_name).and} with the scores of 15:21 21:14 11:5." ) challenge.reload expect(challenge.match.scores).to eq [[21, 15], [14, 21], [5, 11]] end it 'lost with a crushing score' do expect(message: "#{SlackRubyBot.config.user} lost 5:21", user: challenged.user_id, channel: challenge.channel).to respond_with_slack_message( "Match has been recorded! #{challenge.challengers.map(&:display_name).and} crushed #{challenge.challenged.map(&:display_name).and} with the score of 21:5." ) end it 'lost in a close game' do expect(message: "#{SlackRubyBot.config.user} lost 19:21", user: challenged.user_id, channel: challenge.channel).to respond_with_slack_message( "Match has been recorded! #{challenge.challengers.map(&:display_name).and} narrowly defeated #{challenge.challenged.map(&:display_name).and} with the score of 21:19." ) end it 'lost amending scores' do challenge.lose!(challenged) expect(message: "#{SlackRubyBot.config.user} lost 21:15 14:21 5:11", user: challenged.user_id, channel: challenge.channel).to respond_with_slack_message( "Match scores have been updated! #{challenge.challengers.map(&:display_name).and} defeated #{challenge.challenged.map(&:display_name).and} with the scores of 15:21 21:14 11:5." ) challenge.reload expect(challenge.match.scores).to eq [[21, 15], [14, 21], [5, 11]] end it 'does not update a previously lost match' do challenge.lose!(challenged, [[11, 21]]) challenge2 = Fabricate(:challenge, challenged: [challenged]) challenge2.accept!(challenged) expect(message: "#{SlackRubyBot.config.user} lost", user: challenged.user_id, channel: challenge.channel).to respond_with_slack_message( "Match has been recorded! #{challenge2.challengers.map(&:display_name).and} defeated #{challenge2.challenged.map(&:display_name).and}." ) challenge.reload expect(challenge.match.scores).to eq [[11, 21]] challenge2.reload expect(challenge2.state).to eq ChallengeState::PLAYED expect(challenge2.match.scores).to be_nil end it 'does not update a previously won match' do challenge.lose!(challenge.challengers.first, [[11, 21]]) expect(message: "#{SlackRubyBot.config.user} lost", user: challenged.user_id, channel: challenge.channel).to respond_with_slack_message( 'No challenge to lose!' ) end end context 'with an existing unbalanced challenge' do let(:challenged1) { Fabricate(:user, user_name: 'username') } let(:challenged2) { Fabricate(:user) } let(:challenge) { Fabricate(:challenge, challenged: [challenged1, challenged2]) } before do team.update_attributes!(unbalanced: true) challenge.accept!(challenged1) end it 'lost' do expect(message: "#{SlackRubyBot.config.user} lost", user: challenged1.user_id, channel: challenge.channel).to respond_with_slack_message( "Match has been recorded! #{challenge.challengers.map(&:display_name).and} defeated #{challenge.challenged.map(&:display_name).and}." ) challenge.reload expect(challenge.state).to eq ChallengeState::PLAYED expect(challenge.match.winners).to eq challenge.challengers expect(challenge.match.losers).to eq challenge.challenged winner = challenge.match.winners.first loser = challenge.match.losers.first expect(winner.elo).to eq 48 expect(winner.tau).to eq 0.5 expect(loser.elo).to eq(-24) expect(loser.tau).to eq 0.5 end end context 'lost to' do let(:loser) { Fabricate(:user, user_name: 'username') } let(:winner) { Fabricate(:user) } it 'a player' do expect do expect do expect(message: "#{SlackRubyBot.config.user} lost to #{winner.user_name}", user: loser.user_id, channel: 'channel').to respond_with_slack_message( "Match has been recorded! #{winner.user_name} defeated #{loser.user_name}." ) end.not_to change(Challenge, :count) end.to change(Match, :count).by(1) match = Match.asc(:_id).last expect(match.winners).to eq [winner] expect(match.losers).to eq [loser] end it 'same player' do expect do expect do expect(message: "#{SlackRubyBot.config.user} lost to #{loser.user_name}", user: loser.user_id, channel: 'channel').to respond_with_slack_message( 'You cannot lose to yourself!' ) end.not_to change(Challenge, :count) end.not_to change(Match, :count) end it 'two players' do winner2 = Fabricate(:user, team:) loser2 = Fabricate(:user, team:) expect do expect do expect(message: "#{SlackRubyBot.config.user} lost to #{winner.user_name} #{winner2.user_name} with #{loser2.user_name}", user: loser.user_id, channel: 'pongbot').to respond_with_slack_message( "Match has been recorded! #{winner.user_name} and #{winner2.user_name} defeated #{loser.user_name} and #{loser2.user_name}." ) end.not_to change(Challenge, :count) end.to change(Match, :count).by(1) match = Match.asc(:_id).last expect(match.winners).to eq [winner2, winner] expect(match.losers).to eq [loser2, loser] end it 'two players with scores' do winner2 = Fabricate(:user, team:) loser2 = Fabricate(:user, team:) expect do expect do expect(message: "#{SlackRubyBot.config.user} lost to #{winner.user_name} #{winner2.user_name} with #{loser2.user_name} 15:21", user: loser.user_id, channel: 'pongbot').to respond_with_slack_message( "Match has been recorded! #{winner.user_name} and #{winner2.user_name} defeated #{loser.user_name} and #{loser2.user_name} with the score of 21:15." ) end.not_to change(Challenge, :count) end.to change(Match, :count).by(1) match = Match.asc(:_id).last expect(match.winners).to eq [winner2, winner] expect(match.losers).to eq [loser2, loser] expect(match.scores).to eq [[15, 21]] end it 'with score' do expect do expect do expect(message: "#{SlackRubyBot.config.user} lost to #{winner.user_name} 15:21", user: loser.user_id, channel: 'channel').to respond_with_slack_message( "Match has been recorded! #{winner.user_name} defeated #{loser.user_name} with the score of 21:15." ) end.not_to change(Challenge, :count) end.to change(Match, :count).by(1) match = Match.asc(:_id).last expect(match.winners).to eq [winner] expect(match.losers).to eq [loser] expect(match.scores).to eq [[15, 21]] expect(match.resigned?).to be false end it 'with scores' do expect do expect do expect(message: "#{SlackRubyBot.config.user} lost to #{winner.user_name} 21:15 14:21 5:11", user: loser.user_id, channel: 'channel').to respond_with_slack_message( "Match has been recorded! #{winner.user_name} defeated #{loser.user_name} with the scores of 15:21 21:14 11:5." ) end.not_to change(Challenge, :count) end.to change(Match, :count).by(1) match = Match.asc(:_id).last expect(match.winners).to eq [winner] expect(match.losers).to eq [loser] expect(match.scores).to eq [[21, 15], [14, 21], [5, 11]] expect(match.resigned?).to be false end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/season_spec.rb
spec/slack-gamebot/commands/season_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Season, vcr: { cassette_name: 'user_info' } do let!(:team) { Fabricate(:team) } let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } shared_examples_for 'season' do context 'no seasons' do it 'seasons' do expect(message: "#{SlackRubyBot.config.user} season").to respond_with_slack_message "There're no seasons." end end context 'current season' do context 'with a recorded loss' do let!(:winner) { Fabricate(:user, team:) } let!(:loser) { Fabricate(:user, team:) } before do Match.lose!(team:, winners: [winner], losers: [loser]) end it 'returns current season' do current_season = Season.new(team:) expect(message: "#{SlackRubyBot.config.user} season").to respond_with_slack_message current_season.to_s end end context 'with a match' do let!(:match) { Fabricate(:match) } it 'returns current season' do current_season = Season.new(team:) expect(message: "#{SlackRubyBot.config.user} season").to respond_with_slack_message current_season.to_s end context 'after reset' do before do Season.create!(team:, created_by: User.first) end it 'returns current season' do expect(message: "#{SlackRubyBot.config.user} season").to respond_with_slack_message 'No matches have been recorded.' end end end end end it_behaves_like 'season' context 'with another team' do let!(:team2) { Fabricate(:team) } let!(:match2) { Fabricate(:match, team: team2) } let!(:season2) { Fabricate(:season, team: team2) } it_behaves_like 'season' end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/team_spec.rb
spec/slack-gamebot/commands/team_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Team, vcr: { cassette_name: 'user_info' } do let!(:team) { Fabricate(:team) } let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } context 'no users' do it 'team' do allow(User).to receive(:find_create_or_update_by_slack_id!) expect(message: "#{SlackRubyBot.config.user} team").to respond_with_slack_message "Team _#{team.name}_ (#{team.team_id})." end end context 'with a captain' do let!(:user) { Fabricate(:user, team:, user_name: 'username', captain: true) } it 'team' do expect(message: "#{SlackRubyBot.config.user} team").to respond_with_slack_message "Team _#{team.name}_ (#{team.team_id}), captain username." end end context 'with two captains' do before do Array.new(2) { Fabricate(:user, team:, captain: true) } end it 'team' do expect(message: "#{SlackRubyBot.config.user} team").to respond_with_slack_message "Team _#{team.name}_ (#{team.team_id}), captains #{team.captains.map(&:display_name).and}." end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/challenge_spec.rb
spec/slack-gamebot/commands/challenge_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Challenge, vcr: { cassette_name: 'user_info' } do let!(:team) { Fabricate(:team) } let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } let(:user) { Fabricate(:user, user_name: 'username') } let(:opponent) { Fabricate(:user) } it 'creates a singles challenge by user id' do expect do expect(message: "#{SlackRubyBot.config.user} challenge <@#{opponent.user_id}>", user: user.user_id, channel: 'pongbot').to respond_with_slack_message( "#{user.slack_mention} challenged #{opponent.slack_mention} to a match!" ) end.to change(Challenge, :count).by(1) challenge = Challenge.last expect(challenge.channel).to eq 'pongbot' expect(challenge.created_by).to eq user expect(challenge.challengers).to eq [user] expect(challenge.challenged).to eq [opponent] end it 'creates a singles challenge by user name' do expect do expect(message: "#{SlackRubyBot.config.user} challenge #{opponent.slack_mention}", user: user.user_id, channel: 'pongbot').to respond_with_slack_message( "#{user.slack_mention} challenged #{opponent.slack_mention} to a match!" ) end.to change(Challenge, :count).by(1) end it 'creates a doubles challenge by user name' do opponent2 = Fabricate(:user, team:) teammate = Fabricate(:user, team:) expect do expect(message: "#{SlackRubyBot.config.user} challenge #{opponent.slack_mention} #{opponent2.user_name} with #{teammate.user_name}", user: user.user_id, channel: 'pongbot').to respond_with_slack_message( "#{user.slack_mention} and #{teammate.slack_mention} challenged #{opponent.slack_mention} and #{opponent2.slack_mention} to a match!" ) end.to change(Challenge, :count).by(1) challenge = Challenge.last expect(challenge.channel).to eq 'pongbot' expect(challenge.created_by).to eq user expect(challenge.challengers).to eq [teammate, user] expect(challenge.challenged).to eq [opponent2, opponent] end it 'creates a singles challenge by user name case-insensitive' do expect do expect(message: "#{SlackRubyBot.config.user} challenge #{opponent.user_name.capitalize}", user: user.user_id, channel: 'pongbot').to respond_with_slack_message( "#{user.slack_mention} challenged #{opponent.slack_mention} to a match!" ) end.to change(Challenge, :count).by(1) end it 'requires an opponent' do expect do expect(message: "#{SlackRubyBot.config.user} challenge", user: user.user_id, channel: 'pongbot').to respond_with_slack_message( 'Number of teammates (1) and opponents (0) must match.' ) end.not_to change(Challenge, :count) end it 'requires the same number of opponents' do opponent1 = Fabricate(:user) opponent2 = Fabricate(:user) expect do expect(message: "#{SlackRubyBot.config.user} challenge #{opponent1.slack_mention} #{opponent2.slack_mention}", user: user.user_id, channel: 'pongbot').to respond_with_slack_message( 'Number of teammates (1) and opponents (2) must match.' ) end.not_to change(Challenge, :count) end context 'with unbalanced option enabled' do before do team.update_attributes!(unbalanced: true) end it 'allows different number of opponents' do opponent1 = Fabricate(:user) opponent2 = Fabricate(:user) expect do expect(message: "#{SlackRubyBot.config.user} challenge #{opponent1.slack_mention} #{opponent2.slack_mention}", user: user.user_id, channel: 'pongbot').to respond_with_slack_message( "#{user.slack_mention} challenged #{opponent1.slack_mention} and #{opponent2.slack_mention} to a match!" ) end.to change(Challenge, :count).by(1) challenge = Challenge.last expect(challenge.challengers).to eq [user] expect(challenge.challenged).to eq [opponent1, opponent2] end end it 'does not butcher names with special characters' do allow(client.web_client).to receive(:users_info) expect(message: "#{SlackRubyBot.config.user} challenge Jung-hwa", user: user.user_id, channel: 'pongbot').to respond_with_slack_message( "I don't know who Jung-hwa is! Ask them to _register_." ) end context 'requires the opponent to be registered' do before do opponent.unregister! end it 'by slack id' do expect(message: "#{SlackRubyBot.config.user} challenge #{opponent.slack_mention}", user: user.user_id, channel: 'pongbot').to respond_with_slack_message( "I don't know who #{opponent.slack_mention} is! Ask them to _register_." ) end it 'requires the opponent to be registered by name' do expect(message: "#{SlackRubyBot.config.user} challenge #{opponent.user_name}", user: user.user_id, channel: 'pongbot').to respond_with_slack_message( "I don't know who #{opponent.user_name} is! Ask them to _register_." ) end end context 'subscription expiration' do before do team.update_attributes!(created_at: 3.weeks.ago) end it 'prevents new challenges' do expect(message: "#{SlackRubyBot.config.user} challenge <@#{opponent.user_id}>", user: user.user_id, channel: 'pongbot').to respond_with_slack_message( "Your trial subscription has expired. Subscribe your team for $29.99 a year at https://www.playplay.io/subscribe?team_id=#{team.team_id}&game=#{team.game.name}." ) end end User::EVERYONE.each do |username| it "challenges #{username}" do expect do expect(message: "#{SlackRubyBot.config.user} challenge <!#{username}>", user: user.user_id, channel: 'pongbot').to respond_with_slack_message( "#{user.slack_mention} challenged anyone to a match!" ) end.to change(Challenge, :count).by(1) challenge = Challenge.last expect(challenge.channel).to eq 'pongbot' expect(challenge.created_by).to eq user expect(challenge.challengers).to eq [user] expect(challenge.challenged).to eq team.users.everyone end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/default_spec.rb
spec/slack-gamebot/commands/default_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Default do let!(:team) { Fabricate(:team) } let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } let(:message_hook) { SlackRubyBot::Hooks::Message.new } it 'default' do expect(client).to receive(:say).with(channel: 'channel', text: SlackGamebot::INFO) expect(client).to receive(:say).with(channel: 'channel', gif: 'robot') message_hook.call(client, Hashie::Mash.new(channel: 'channel', text: SlackRubyBot.config.user)) end it 'upcase' do expect(client).to receive(:say).with(channel: 'channel', text: SlackGamebot::INFO) expect(client).to receive(:say).with(channel: 'channel', gif: 'robot') message_hook.call(client, Hashie::Mash.new(channel: 'channel', text: SlackRubyBot.config.user.upcase)) end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/rank_spec.rb
spec/slack-gamebot/commands/rank_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Rank, vcr: { cassette_name: 'user_info' } do let!(:team) { Fabricate(:team) } let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } shared_examples_for 'rank' do let!(:user_elo_12) { Fabricate(:user, elo: 12, wins: 0, losses: 25) } let!(:user_elo_38) { Fabricate(:user, elo: 38, wins: 3, losses: 3) } let!(:user_elo_42) { Fabricate(:user, elo: 42, wins: 3, losses: 2) } let!(:user_elo_67) { Fabricate(:user, elo: 67, wins: 5, losses: 2) } let!(:user_elo_98) { Fabricate(:user, elo: 98, wins: 7, losses: 0) } it 'ranks the requester if no argument is passed' do expect(message: "#{SlackRubyBot.config.user} rank", user: user_elo_42.user_id).to respond_with_slack_message '3. username: 3 wins, 2 losses (elo: 42)' end it 'ranks someone who is not ranked' do user = Fabricate(:user, team:) expect(message: "#{SlackRubyBot.config.user} rank", user: user.user_id).to respond_with_slack_message 'username: not ranked' end it 'ranks someone who is not ranked by default' do user1 = Fabricate(:user, team:) Fabricate(:user, team:) expect(message: "#{SlackRubyBot.config.user} rank", user: user1.user_id).to respond_with_slack_message 'username: not ranked' end it 'ranks someone who is not ranked by name' do user1 = Fabricate(:user, team:) Fabricate(:user, team:) expect(message: "#{SlackRubyBot.config.user} rank #{user1.user_name}", user: user1.user_id).to respond_with_slack_message "#{user1.user_name}: not ranked" end it 'ranks one player by slack mention' do expect(message: "#{SlackRubyBot.config.user} rank #{user_elo_42.slack_mention}").to respond_with_slack_message "3. #{user_elo_42}" end it 'ranks one player by user_id' do expect(message: "#{SlackRubyBot.config.user} rank <@#{user_elo_42.user_id}>").to respond_with_slack_message "3. #{user_elo_42}" end it 'shows the smallest range of ranks for a list of players' do users = [user_elo_38, user_elo_67].map(&:slack_mention) expect(message: "#{SlackRubyBot.config.user} rank #{users.join(' ')}").to respond_with_slack_message "2. #{user_elo_67}\n3. #{user_elo_42}\n4. #{user_elo_38}" end end it_behaves_like 'rank' context 'with another team' do let!(:team2) { Fabricate(:team) } let!(:user2_elo_42) { Fabricate(:user, team: team2, elo: 42, wins: 3, losses: 2) } let!(:user2_elo_48) { Fabricate(:user, team: team2, elo: 48, wins: 2, losses: 3) } it_behaves_like 'rank' end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/register_spec.rb
spec/slack-gamebot/commands/register_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Register, vcr: { cassette_name: 'user_info' } do let!(:team) { Fabricate(:team) } let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } it 'registers a new user and promotes them to captain' do Fabricate(:user, team: Fabricate(:team)) # another user in another team expect do expect(message: "#{SlackRubyBot.config.user} register", user: 'user').to respond_with_slack_message("Welcome <@user>! You're ready to play. You're also team captain.") end.to change(User, :count).by(1) end it 'registers a new user' do Fabricate(:user, team:, captain: true) expect do expect(message: "#{SlackRubyBot.config.user} register", user: 'user').to respond_with_slack_message("Welcome <@user>! You're ready to play.") end.to change(User, :count).by(1) end it 'renames an existing user' do Fabricate(:user, user_id: 'user') expect do expect(message: "#{SlackRubyBot.config.user} register", user: 'user').to respond_with_slack_message("Welcome back <@user>, I've updated your registration. You're also team captain.") end.not_to change(User, :count) end it 'already registered' do Fabricate(:user, user_id: 'user', user_name: 'username', captain: true) expect do expect(message: "#{SlackRubyBot.config.user} register", user: 'user').to respond_with_slack_message("Welcome back <@user>, you're already registered. You're also team captain.") end.not_to change(User, :count) end it 'registeres a previously unregistered existing user' do user = Fabricate(:user, user_id: 'user', registered: false) expect do expect(message: "#{SlackRubyBot.config.user} register", user: 'user').to respond_with_slack_message("Welcome back <@user>, I've updated your registration. You're also team captain.") end.not_to change(User, :count) expect(user.reload.registered?).to be true end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/unsubscribe_spec.rb
spec/slack-gamebot/commands/unsubscribe_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Unsubscribe, vcr: { cassette_name: 'user_info' } do let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } shared_examples_for 'unsubscribe' do context 'on trial' do before do team.update_attributes!(subscribed: false, subscribed_at: nil) end it 'displays all set message' do expect(message: "#{SlackRubyBot.config.user} unsubscribe").to respond_with_slack_message "You don't have a paid subscription, all set." end end context 'with subscribed_at' do before do team.update_attributes!(subscribed: true, subscribed_at: 1.year.ago) end it 'displays subscription info' do expect(message: "#{SlackRubyBot.config.user} unsubscribe").to respond_with_slack_message "You don't have a paid subscription, all set." end end context 'with a plan' do include_context 'stripe mock' before do stripe_helper.create_plan(id: 'slack-playplay-yearly', amount: 2999, name: 'Plan') end context 'a customer' do let!(:customer) do Stripe::Customer.create( source: stripe_helper.generate_card_token, plan: 'slack-playplay-yearly', email: 'foo@bar.com' ) end let(:active_subscription) { team.active_stripe_subscription } let(:current_period_end) { Time.at(active_subscription.current_period_end).strftime('%B %d, %Y') } before do team.update_attributes!(subscribed: true, stripe_customer_id: customer['id']) end it 'displays subscription info' do customer_info = [ "Subscribed to Plan ($29.99), will auto-renew on #{current_period_end}.", "Send `unsubscribe #{active_subscription.id}` to unsubscribe." ].join("\n") expect(message: "#{SlackRubyBot.config.user} unsubscribe").to respond_with_slack_message customer_info end it 'cannot unsubscribe with an invalid subscription id' do expect(message: "#{SlackRubyBot.config.user} unsubscribe xyz").to respond_with_slack_message 'Sorry, I cannot find a subscription with "xyz".' end it 'unsubscribes' do expect(message: "#{SlackRubyBot.config.user} unsubscribe #{active_subscription.id}").to respond_with_slack_message 'Successfully canceled auto-renew for Plan ($29.99).' team.reload expect(team.subscribed).to be true expect(team.stripe_customer_id).not_to be_nil end end end end context 'subscribed team' do let!(:team) { Fabricate(:team, subscribed: true) } it_behaves_like 'unsubscribe' context 'with another team' do let!(:team2) { Fabricate(:team) } it_behaves_like 'unsubscribe' end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/reset_spec.rb
spec/slack-gamebot/commands/reset_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Reset, vcr: { cassette_name: 'user_info' } do let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } let!(:team) { Fabricate(:team) } it 'requires a captain' do Fabricate(:user, captain: true, team:) Fabricate(:user, user_name: 'username') expect(User).not_to receive(:reset_all!).with(team) expect(message: "#{SlackRubyBot.config.user} reset").to respond_with_slack_message("You're not a captain, sorry.") end it 'requires a team name' do expect(User).not_to receive(:reset_all!).with(team) expect(message: "#{SlackRubyBot.config.user} reset").to respond_with_slack_message("Missing team name or id, confirm with _reset #{team.name}_ or _reset #{team.team_id}_.") end it 'requires a matching team name' do expect(User).not_to receive(:reset_all!).with(team) expect(message: "#{SlackRubyBot.config.user} reset invalid").to respond_with_slack_message("Invalid team name or id, confirm with _reset #{team.name}_ or _reset #{team.team_id}_.") end it 'resets with the correct team name' do Fabricate(:match) expect(User).to receive(:reset_all!).with(team).once expect(message: "#{SlackRubyBot.config.user} reset #{team.name}").to respond_with_slack_message('Welcome to the new season!') end it 'resets with the correct team id' do Fabricate(:match) expect(User).to receive(:reset_all!).with(team).once expect(message: "#{SlackRubyBot.config.user} reset #{team.team_id}").to respond_with_slack_message('Welcome to the new season!') end it 'resets a team that has a period and space in the name' do team.update_attributes!(name: 'Pets.com Delivery') Fabricate(:match) expect(User).to receive(:reset_all!).with(team).once expect(message: "#{SlackRubyBot.config.user} reset #{team.name}").to respond_with_slack_message('Welcome to the new season!') end it 'cancels open challenges' do proposed_challenge = Fabricate(:challenge, state: ChallengeState::PROPOSED) accepted_challenge = Fabricate(:challenge, state: ChallengeState::PROPOSED) accepted_challenge.accept!(accepted_challenge.challenged.first) expect(message: "#{SlackRubyBot.config.user} reset #{team.name}").to respond_with_slack_message('Welcome to the new season!') expect(proposed_challenge.reload.state).to eq ChallengeState::CANCELED expect(accepted_challenge.reload.state).to eq ChallengeState::CANCELED end it 'resets user stats' do Fabricate(:match) user = Fabricate(:user, elo: 48, losses: 1, wins: 2, tau: 0.5) expect(message: "#{SlackRubyBot.config.user} reset #{team.name}").to respond_with_slack_message('Welcome to the new season!') user.reload expect(user.wins).to eq 0 expect(user.losses).to eq 0 expect(user.tau).to eq 0 expect(user.elo).to eq 0 end it 'resets user stats for the right team' do Fabricate(:match) user1 = Fabricate(:user, elo: 48, losses: 1, wins: 2, tau: 0.5, ties: 3) team2 = Fabricate(:team) Fabricate(:match, team: team2) user2 = Fabricate(:user, team: team2, elo: 48, losses: 1, wins: 2, tau: 0.5, ties: 3) expect(message: "#{SlackRubyBot.config.user} reset #{team.name}").to respond_with_slack_message('Welcome to the new season!') user1.reload expect(user1.wins).to eq 0 expect(user1.losses).to eq 0 expect(user1.tau).to eq 0 expect(user1.elo).to eq 0 expect(user1.ties).to eq 0 user2.reload expect(user2.wins).to eq 2 expect(user2.losses).to eq 1 expect(user2.tau).to eq 0.5 expect(user2.elo).to eq 48 expect(user2.ties).to eq 3 end it 'cannot be reset unless any games have been played' do expect(message: "#{SlackRubyBot.config.user} reset #{team.name}").to respond_with_slack_message('No matches have been recorded.') end it 'can be reset with a match lost' do Match.lose!(team:, winners: [Fabricate(:user, team:)], losers: [Fabricate(:user, team:)]) expect(message: "#{SlackRubyBot.config.user} reset #{team.name}").to respond_with_slack_message('Welcome to the new season!') end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/demote_spec.rb
spec/slack-gamebot/commands/demote_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Demote, vcr: { cassette_name: 'user_info' } do let!(:team) { Fabricate(:team) } let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } context 'captain' do let(:user) { Fabricate(:user, team:, user_name: 'username', captain: true) } it 'demotes self' do another_user = Fabricate(:user, team:, captain: true) expect(message: "#{SlackRubyBot.config.user} demote me", user: user.user_id).to respond_with_slack_message( "#{user.user_name} is no longer captain." ) expect(another_user.reload.captain?).to be true end it 'cannot demote the last captain' do expect(message: "#{SlackRubyBot.config.user} demote me", user: user.user_id).to respond_with_slack_message( "You cannot demote yourself, you're the last captain. Promote someone else first." ) end it 'cannot demote another captain' do another_user = Fabricate(:user, team:, captain: true) expect(message: "#{SlackRubyBot.config.user} demote #{another_user.user_name}", user: user.user_id).to respond_with_slack_message( 'You can only demote yourself, try _demote me_.' ) expect(another_user.reload.captain?).to be true end end context 'not captain' do let!(:captain) { Fabricate(:user, team:, captain: true) } let(:user) { Fabricate(:user, team:, user_name: 'username') } it 'cannot demote' do expect(message: "#{SlackRubyBot.config.user} demote me", user: user.user_id).to respond_with_slack_message( "You're not a captain, sorry." ) expect(user.reload.captain?).to be false end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/subscription_spec.rb
spec/slack-gamebot/commands/subscription_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Subscription, vcr: { cassette_name: 'user_info' } do let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } shared_examples_for 'subscription' do context 'on trial' do before do team.update_attributes!(subscribed: false, subscribed_at: nil) end it 'displays subscribe message' do expect(message: "#{SlackRubyBot.config.user} subscription").to respond_with_slack_message team.trial_message end end context 'with subscribed_at' do it 'displays subscription info' do customer_info = "Subscriber since #{team.subscribed_at.strftime('%B %d, %Y')}." expect(message: "#{SlackRubyBot.config.user} subscription").to respond_with_slack_message customer_info end end context 'with a plan' do include_context 'stripe mock' before do stripe_helper.create_plan(id: 'slack-playplay-yearly', amount: 2999, name: 'Plan') end context 'a customer' do let!(:customer) do Stripe::Customer.create( source: stripe_helper.generate_card_token, plan: 'slack-playplay-yearly', email: 'foo@bar.com' ) end before do team.update_attributes!(subscribed: true, stripe_customer_id: customer['id']) end it 'displays subscription info' do card = customer.sources.first current_period_end = Time.at(customer.subscriptions.first.current_period_end).strftime('%B %d, %Y') customer_info = [ "Customer since #{Time.at(customer.created).strftime('%B %d, %Y')}.", "Subscribed to Plan ($29.99), will auto-renew on #{current_period_end}.", "On file Visa card, #{card.name} ending with #{card.last4}, expires #{card.exp_month}/#{card.exp_year}.", team.update_cc_text ].join("\n") expect(message: "#{SlackRubyBot.config.user} subscription").to respond_with_slack_message customer_info end context 'past due subscription' do before do customer.subscriptions.data.first['status'] = 'past_due' allow(Stripe::Customer).to receive(:retrieve).and_return(customer) end it 'displays subscription info' do customer_info = "Customer since #{Time.at(customer.created).strftime('%B %d, %Y')}." customer_info += "\nPast Due subscription created November 03, 2016 to Plan ($29.99)." card = customer.sources.first customer_info += "\nOn file Visa card, #{card.name} ending with #{card.last4}, expires #{card.exp_month}/#{card.exp_year}." customer_info += "\n#{team.update_cc_text}" expect(message: "#{SlackRubyBot.config.user} subscription").to respond_with_slack_message customer_info end end end end end context 'subscribed team' do let!(:team) { Fabricate(:team, subscribed: true) } it_behaves_like 'subscription' context 'with another team' do let!(:team2) { Fabricate(:team) } it_behaves_like 'subscription' end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/leaderboard_spec.rb
spec/slack-gamebot/commands/leaderboard_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Leaderboard do let!(:team) { Fabricate(:team) } let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } shared_examples_for 'leaderboard' do context 'with players' do let!(:user_elo_42) { Fabricate(:user, elo: 42, wins: 3, losses: 2) } let!(:user_elo_48) { Fabricate(:user, elo: 48, wins: 2, losses: 3) } it 'displays leaderboard sorted by elo' do expect(message: "#{SlackRubyBot.config.user} leaderboard").to respond_with_slack_message "1. #{user_elo_48}\n2. #{user_elo_42}" end it 'excludes unregistered users' do user_elo_48.unregister! expect(message: "#{SlackRubyBot.config.user} leaderboard").to respond_with_slack_message "1. #{user_elo_42}" end it 'limits to max' do expect(message: "#{SlackRubyBot.config.user} leaderboard 1").to respond_with_slack_message "1. #{user_elo_48}" end it 'limits to team leaderboard max' do team.update_attributes!(leaderboard_max: 1) expect(message: "#{SlackRubyBot.config.user} leaderboard").to respond_with_slack_message "1. #{user_elo_48}" end it 'supports infinity' do user_elo_43 = Fabricate(:user, elo: 43, wins: 2, losses: 3) user_elo_44 = Fabricate(:user, elo: 44, wins: 2, losses: 3) expect(message: "#{SlackRubyBot.config.user} leaderboard infinity").to respond_with_slack_message "1. #{user_elo_48}\n2. #{user_elo_44}\n3. #{user_elo_43}\n4. #{user_elo_42}" end it 'supports -infinity' do user_elo_43 = Fabricate(:user, elo: 43, wins: 2, losses: 3) user_elo_44 = Fabricate(:user, elo: 44, wins: 2, losses: 3) expect(message: "#{SlackRubyBot.config.user} leaderboard -infinity").to respond_with_slack_message "1. #{user_elo_42}\n2. #{user_elo_43}\n3. #{user_elo_44}\n4. #{user_elo_48}" end it 'supports -number' do user_elo_43 = Fabricate(:user, elo: 43, wins: 2, losses: 3) expect(message: "#{SlackRubyBot.config.user} leaderboard -2").to respond_with_slack_message "1. #{user_elo_42}\n2. #{user_elo_43}" end end context 'without players' do it 'says no players' do expect(message: "#{SlackRubyBot.config.user} leaderboard").to respond_with_slack_message "There're no ranked players." end end end it_behaves_like 'leaderboard' context 'with another team' do let!(:team2) { Fabricate(:team) } let!(:user2_elo_42) { Fabricate(:user, team: team2, elo: 42, wins: 3, losses: 2) } let!(:user2_elo_48) { Fabricate(:user, team: team2, elo: 48, wins: 2, losses: 3) } it_behaves_like 'leaderboard' end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/cancel_spec.rb
spec/slack-gamebot/commands/cancel_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Cancel, vcr: { cassette_name: 'user_info' } do let!(:team) { Fabricate(:team) } let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } context 'challenger' do let(:challenger) { Fabricate(:user, user_name: 'username') } let!(:challenge) { Fabricate(:challenge, challengers: [challenger]) } it 'cancels a challenge' do expect(message: "#{SlackRubyBot.config.user} cancel", user: challenger.user_id, channel: challenge.channel).to respond_with_slack_message( "#{challenge.challengers.map(&:display_name).and} canceled a challenge against #{challenge.challenged.map(&:display_name).and}." ) expect(challenge.reload.state).to eq ChallengeState::CANCELED end end context 'challenged' do let(:challenged) { Fabricate(:user, user_name: 'username') } let!(:challenge) { Fabricate(:challenge, challenged: [challenged]) } it 'cancels a challenge' do expect(message: "#{SlackRubyBot.config.user} cancel", user: challenged.user_id, channel: challenge.channel).to respond_with_slack_message( "#{challenge.challenged.map(&:display_name).and} canceled a challenge against #{challenge.challengers.map(&:display_name).and}." ) expect(challenge.reload.state).to eq ChallengeState::CANCELED end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/set_spec.rb
spec/slack-gamebot/commands/set_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Set, vcr: { cassette_name: 'user_info' } do let!(:team) { Fabricate(:team) } let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } let(:captain) { Fabricate(:user, team:, user_name: 'username', captain: true) } let(:message_hook) { SlackRubyBot::Hooks::Message.new } context 'captain' do it 'gives help' do expect(message: "#{SlackRubyBot.config.user} set").to respond_with_slack_message( 'Missing setting, eg. _set gifs off_.' ) end context 'gifs' do it 'shows current value of GIFs on' do expect(message: "#{SlackRubyBot.config.user} set gifs").to respond_with_slack_message( "GIFs for team #{team.name} are on!" ) end it 'shows current value of GIFs off' do team.update_attributes!(gifs: false) expect(message: "#{SlackRubyBot.config.user} set gifs").to respond_with_slack_message( "GIFs for team #{team.name} are off." ) end it 'shows current value of GIFs on' do expect(message: "#{SlackRubyBot.config.user} set gifs").to respond_with_slack_message( "GIFs for team #{team.name} are on!" ) end it 'shows current value of GIFs off' do team.update_attributes!(gifs: false) expect(message: "#{SlackRubyBot.config.user} set gifs").to respond_with_slack_message( "GIFs for team #{team.name} are off." ) end it 'enables GIFs' do team.update_attributes!(gifs: false) expect(message: "#{SlackRubyBot.config.user} set gifs on").to respond_with_slack_message( "GIFs for team #{team.name} are on!" ) expect(team.reload.gifs).to be true expect(app.send(:client).send_gifs?).to be true end it 'disables GIFs with set' do team.update_attributes!(gifs: true) expect(message: "#{SlackRubyBot.config.user} set gifs off").to respond_with_slack_message( "GIFs for team #{team.name} are off." ) expect(team.reload.gifs).to be false expect(app.send(:client).send_gifs?).to be false end it 'disables GIFs with unset' do team.update_attributes!(gifs: true) expect(message: "#{SlackRubyBot.config.user} unset gifs").to respond_with_slack_message( "GIFs for team #{team.name} are off." ) expect(team.reload.gifs).to be false expect(app.send(:client).send_gifs?).to be false end end context 'unbalanced' do it 'shows current value of unbalanced off' do expect(message: "#{SlackRubyBot.config.user} set unbalanced").to respond_with_slack_message( "Unbalanced challenges for team #{team.name} are off." ) end it 'shows current value of unbalanced off' do team.update_attributes!(unbalanced: false) expect(message: "#{SlackRubyBot.config.user} set unbalanced").to respond_with_slack_message( "Unbalanced challenges for team #{team.name} are off." ) end it 'shows current value of unbalanced off' do expect(message: "#{SlackRubyBot.config.user} set unbalanced").to respond_with_slack_message( "Unbalanced challenges for team #{team.name} are off." ) end it 'shows current value of unbalanced off' do team.update_attributes!(unbalanced: false) expect(message: "#{SlackRubyBot.config.user} set unbalanced").to respond_with_slack_message( "Unbalanced challenges for team #{team.name} are off." ) end it 'enables unbalanced' do team.update_attributes!(unbalanced: false) expect(message: "#{SlackRubyBot.config.user} set unbalanced on").to respond_with_slack_message( "Unbalanced challenges for team #{team.name} are on!" ) expect(team.reload.unbalanced).to be true end it 'disables unbalanced with set' do team.update_attributes!(unbalanced: true) expect(message: "#{SlackRubyBot.config.user} set unbalanced off").to respond_with_slack_message( "Unbalanced challenges for team #{team.name} are off." ) expect(team.reload.unbalanced).to be false end it 'disables unbalanced with unset' do team.update_attributes!(unbalanced: true) expect(message: "#{SlackRubyBot.config.user} unset unbalanced").to respond_with_slack_message( "Unbalanced challenges for team #{team.name} are off." ) expect(team.reload.unbalanced).to be false end end context 'api' do it 'shows current value of API on' do team.update_attributes!(api: true) expect(message: "#{SlackRubyBot.config.user} set api").to respond_with_slack_message( "API for team #{team.name} is on!\n#{team.api_url}" ) end it 'shows current value of API off' do team.update_attributes!(api: false) expect(message: "#{SlackRubyBot.config.user} set api").to respond_with_slack_message( "API for team #{team.name} is off." ) end it 'shows current value of API on' do team.update_attributes!(api: true) expect(message: "#{SlackRubyBot.config.user} set api").to respond_with_slack_message( "API for team #{team.name} is on!\n#{team.api_url}" ) end it 'shows current value of API off' do team.update_attributes!(api: false) expect(message: "#{SlackRubyBot.config.user} set api").to respond_with_slack_message( "API for team #{team.name} is off." ) end it 'enables API' do expect(message: "#{SlackRubyBot.config.user} set api on").to respond_with_slack_message( "API for team #{team.name} is on!\n#{team.api_url}" ) expect(team.reload.api).to be true end it 'disables API with set' do team.update_attributes!(api: true) expect(message: "#{SlackRubyBot.config.user} set api off").to respond_with_slack_message( "API for team #{team.name} is off." ) expect(team.reload.api).to be false end it 'disables API with unset' do team.update_attributes!(api: true) expect(message: "#{SlackRubyBot.config.user} unset api").to respond_with_slack_message( "API for team #{team.name} is off." ) expect(team.reload.api).to be false end context 'with API_URL' do before do ENV['API_URL'] = 'http://local.api' end after do ENV.delete 'API_URL' end it 'shows current value of API on with API URL' do team.update_attributes!(api: true) expect(message: "#{SlackRubyBot.config.user} set api").to respond_with_slack_message( "API for team #{team.name} is on!\nhttp://local.api/teams/#{team.id}" ) end it 'shows current value of API off without API URL' do team.update_attributes!(api: false) expect(message: "#{SlackRubyBot.config.user} set api").to respond_with_slack_message( "API for team #{team.name} is off." ) end end end context 'aliases' do context 'with aliases' do before do team.update_attributes!(aliases: %w[foo bar]) end it 'shows current value of aliases' do expect(message: "#{SlackRubyBot.config.user} set aliases").to respond_with_slack_message( "Bot aliases for team #{team.name} are foo and bar." ) end end context 'with aliases' do before do team.update_attributes!(aliases: %w[foo bar]) end it 'shows current value of aliases' do expect(message: "#{SlackRubyBot.config.user} set aliases").to respond_with_slack_message( "Bot aliases for team #{team.name} are foo and bar." ) end it 'sets aliases' do expect(message: "#{SlackRubyBot.config.user} set aliases foo bar baz").to respond_with_slack_message( "Bot aliases for team #{team.name} are foo, bar and baz." ) expect(team.reload.aliases).to eq %w[foo bar baz] expect(app.send(:client).aliases).to eq %w[foo bar baz] end it 'sets comma-separated aliases' do expect(message: "#{SlackRubyBot.config.user} set aliases foo,bar").to respond_with_slack_message( "Bot aliases for team #{team.name} are foo and bar." ) expect(team.reload.aliases).to eq %w[foo bar] expect(app.send(:client).aliases).to eq %w[foo bar] end it 'sets comma-separated aliases with extra spaces' do expect(message: "#{SlackRubyBot.config.user} set aliases foo, bar").to respond_with_slack_message( "Bot aliases for team #{team.name} are foo and bar." ) expect(team.reload.aliases).to eq %w[foo bar] expect(app.send(:client).aliases).to eq %w[foo bar] end it 'sets emoji aliases' do expect(message: "#{SlackRubyBot.config.user} set aliases pp :pong:").to respond_with_slack_message( "Bot aliases for team #{team.name} are pp and :pong:." ) expect(team.reload.aliases).to eq ['pp', ':pong:'] end it 'removes aliases' do expect(message: "#{SlackRubyBot.config.user} unset aliases").to respond_with_slack_message( "Team #{team.name} no longer has bot aliases." ) expect(team.reload.aliases).to be_empty expect(app.send(:client).aliases).to be_empty end end context 'without aliases' do it 'shows no aliases' do expect(message: "#{SlackRubyBot.config.user} set aliases").to respond_with_slack_message( "Team #{team.name} does not have any bot aliases." ) end end end context 'elo' do context 'with a non-default base elo' do before do team.update_attributes!(elo: 1000) end it 'shows current value of elo' do expect(message: "#{SlackRubyBot.config.user} set elo").to respond_with_slack_message( "Base elo for team #{team.name} is 1000." ) end it 'sets elo' do expect(message: "#{SlackRubyBot.config.user} set elo 200").to respond_with_slack_message( "Base elo for team #{team.name} is 200." ) expect(team.reload.elo).to eq 200 end it 'handles errors' do expect(message: "#{SlackRubyBot.config.user} set elo invalid").to respond_with_slack_message( 'Sorry, invalid is not a valid number.' ) expect(team.reload.elo).to eq 1000 end it 'resets elo with set' do expect(message: "#{SlackRubyBot.config.user} set elo 0").to respond_with_slack_message( "Base elo for team #{team.name} is 0." ) expect(team.reload.elo).to eq 0 end it 'resets elo with unset' do expect(message: "#{SlackRubyBot.config.user} unset elo").to respond_with_slack_message( "Base elo for team #{team.name} has been unset." ) expect(team.reload.elo).to eq 0 end end end context 'leaderboard max' do context 'with a non-default leaderboard max' do before do team.update_attributes!(leaderboard_max: 5) end it 'shows current value of leaderboard max' do expect(message: "#{SlackRubyBot.config.user} set leaderboard max").to respond_with_slack_message( "Leaderboard max for team #{team.name} is 5." ) end it 'sets leaderboard max' do expect(message: "#{SlackRubyBot.config.user} set leaderboard max 12").to respond_with_slack_message( "Leaderboard max for team #{team.name} is 12." ) expect(team.leaderboard_max).to eq 12 end it 'sets leaderboard max to a negative number' do expect(message: "#{SlackRubyBot.config.user} set leaderboard max -12").to respond_with_slack_message( "Leaderboard max for team #{team.name} is -12." ) expect(team.leaderboard_max).to eq(-12) end it 'handles errors' do expect(message: "#{SlackRubyBot.config.user} set leaderboard max invalid").to respond_with_slack_message( 'Sorry, invalid is not a valid number.' ) expect(team.leaderboard_max).to eq 5 end it 'resets leaderboard max with set 0' do expect(message: "#{SlackRubyBot.config.user} set leaderboard max 0").to respond_with_slack_message( "Leaderboard max for team #{team.name} is not set." ) expect(team.leaderboard_max).to be_nil end it 'resets leaderboard max with set infinity' do expect(message: "#{SlackRubyBot.config.user} set leaderboard max infinity").to respond_with_slack_message( "Leaderboard max for team #{team.name} is not set." ) expect(team.leaderboard_max).to be_nil end it 'resets leaderboard max with unset' do expect(message: "#{SlackRubyBot.config.user} unset leaderboard max").to respond_with_slack_message( "Leaderboard max for team #{team.name} has been unset." ) expect(team.leaderboard_max).to be_nil end end end context 'invalid' do it 'errors set' do expect(message: "#{SlackRubyBot.config.user} set invalid on").to respond_with_slack_message( 'Invalid setting invalid, you can _set gifs on|off_, _set unbalanced on|off_, _api on|off_, _leaderboard max_, _elo_, _nickname_ and _aliases_.' ) end it 'errors unset' do expect(message: "#{SlackRubyBot.config.user} unset invalid").to respond_with_slack_message( 'Invalid setting invalid, you can _unset gifs_, _api_, _leaderboard max_, _elo_, _nickname_ and _aliases_.' ) end end end context 'not captain' do before do Fabricate(:user, team:, captain: true) captain.demote! end context 'gifs' do it 'cannot set GIFs' do expect(message: "#{SlackRubyBot.config.user} set gifs true").to respond_with_slack_message( "You're not a captain, sorry." ) end it 'can see GIFs value' do expect(message: "#{SlackRubyBot.config.user} set gifs").to respond_with_slack_message( "GIFs for team #{team.name} are on!" ) end end context 'aliases' do it 'cannot set aliases' do expect(message: "#{SlackRubyBot.config.user} set aliases foo bar").to respond_with_slack_message( "You're not a captain, sorry." ) end it 'can see aliases' do expect(message: "#{SlackRubyBot.config.user} set aliases").to respond_with_slack_message( "Team #{team.name} does not have any bot aliases." ) end end context 'elo' do it 'cannot set elo' do expect(message: "#{SlackRubyBot.config.user} set elo 1000").to respond_with_slack_message( "You're not a captain, sorry." ) end it 'can see elo' do expect(message: "#{SlackRubyBot.config.user} set elo").to respond_with_slack_message( "Base elo for team #{team.name} is 0." ) end end context 'leaderboard max' do it 'cannot set leaderboard max' do expect(message: "#{SlackRubyBot.config.user} set leaderboard max 3").to respond_with_slack_message( "You're not a captain, sorry." ) end it 'can see leaderboard max' do expect(message: "#{SlackRubyBot.config.user} set leaderboard max").to respond_with_slack_message( "Leaderboard max for team #{team.name} is not set." ) end end end context 'nickname' do let(:user) { Fabricate(:user, team:, user_name: 'username') } context 'with no nickname' do it 'shows that the user has no nickname' do expect(message: "#{SlackRubyBot.config.user} set nickname", user: user.user_id).to respond_with_slack_message( "You don't have a nickname set, #{user.user_name}." ) end end context 'without a nickname set' do it 'sets nickname' do expect(message: "#{SlackRubyBot.config.user} set nickname john doe", user: user.user_id).to respond_with_slack_message( "Your nickname is now *john doe*, #{user.slack_mention}." ) expect(user.reload.nickname).to eq 'john doe' end it 'does not unset nickname' do expect(message: "#{SlackRubyBot.config.user} unset nickname", user: user.user_id).to respond_with_slack_message( "You don't have a nickname set, #{user.slack_mention}." ) expect(user.reload.nickname).to be_nil end it 'sets emoji nickname' do expect(message: "#{SlackRubyBot.config.user} set nickname :dancer:", user: user.user_id).to respond_with_slack_message( "Your nickname is now *:dancer:*, #{user.slack_mention}." ) expect(user.reload.nickname).to eq ':dancer:' end end context 'with a nickname set' do before do user.update_attributes!(nickname: 'bob') end it 'shows current value of nickname' do expect(message: "#{SlackRubyBot.config.user} set nickname", user: user.user_id).to respond_with_slack_message( "Your nickname is *bob*, #{user.slack_mention}." ) end it 'sets nickname' do expect(message: "#{SlackRubyBot.config.user} set nickname john doe", user: user.user_id).to respond_with_slack_message( "Your nickname is now *john doe*, #{user.slack_mention}." ) expect(user.reload.nickname).to eq 'john doe' end it 'unsets nickname' do expect(message: "#{SlackRubyBot.config.user} unset nickname", user: user.user_id).to respond_with_slack_message( "You don't have a nickname set anymore, #{user.slack_mention}." ) expect(user.reload.nickname).to be_nil end it 'cannot set nickname unless captain' do expect(message: "#{SlackRubyBot.config.user} set nickname #{captain.slack_mention} :dancer:", user: user.user_id).to respond_with_slack_message( "You're not a captain, sorry." ) end it 'sets nickname for another user' do expect(message: "#{SlackRubyBot.config.user} set nickname #{user.slack_mention} john doe", user: captain.user_id).to respond_with_slack_message( "Your nickname is now *john doe*, #{user.slack_mention}." ) expect(user.reload.nickname).to eq 'john doe' end it 'unsets nickname for another user' do user.update_attributes!(nickname: 'bob') expect(message: "#{SlackRubyBot.config.user} unset nickname #{user.slack_mention}", user: captain.user_id).to respond_with_slack_message( "You don't have a nickname set anymore, #{user.slack_mention}." ) expect(user.reload.nickname).to be_nil end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/hi_spec.rb
spec/slack-gamebot/commands/hi_spec.rb
require 'spec_helper' describe SlackRubyBot::Commands::Hi do let!(:team) { Fabricate(:team) } let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } it 'says hi' do expect(message: "#{SlackRubyBot.config.user} hi").to respond_with_slack_message('Hi <@user>!') end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/matches_spec.rb
spec/slack-gamebot/commands/matches_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Matches, vcr: { cassette_name: 'user_info' } do let!(:team) { Fabricate(:team) } let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } shared_examples_for 'matches' do let!(:team) { Fabricate(:team) } let(:user) { Fabricate(:user, user_name: 'username') } let(:singles_challenge) { Fabricate(:challenge, challengers: [user]) } let(:doubles_challenge) { Fabricate(:doubles_challenge, challengers: [user, Fabricate(:user)]) } context 'with many matches' do let!(:match0) { Fabricate(:match) } let!(:match1) { Fabricate(:match, challenge: doubles_challenge) } let!(:match2) { Fabricate(:match, challenge: doubles_challenge) } let!(:match3) { Fabricate(:match, challenge: doubles_challenge) } it 'displays top 10 matches' do expect_any_instance_of(Array).to receive(:take).with(10).and_call_original expect(message: "#{SlackRubyBot.config.user} matches", user: user.user_id, channel: doubles_challenge.channel).to respond_with_slack_message([ "#{match1} 3 times", "#{match0} once" ].join("\n")) end it 'limits number of matches' do expect(message: "#{SlackRubyBot.config.user} matches 1", user: user.user_id, channel: doubles_challenge.channel).to respond_with_slack_message([ "#{match1} 3 times" ].join("\n")) end it 'displays only matches for requested users' do expect(message: "#{SlackRubyBot.config.user} matches #{doubles_challenge.challenged.first.user_name}", user: user.user_id, channel: doubles_challenge.channel).to respond_with_slack_message( "#{match1} 3 times" ) end it 'displays only matches for requested users with a limit' do another_challenge = Fabricate(:challenge, challengers: [doubles_challenge.challenged.first]) Fabricate(:match, challenge: another_challenge) expect(message: "#{SlackRubyBot.config.user} matches #{doubles_challenge.challenged.first.user_name} 1", user: user.user_id, channel: doubles_challenge.channel).to respond_with_slack_message( "#{match1} 3 times" ) end end context 'with a doubles match' do let!(:match) { Fabricate(:match, challenge: doubles_challenge) } it 'displays user matches' do expect(message: "#{SlackRubyBot.config.user} matches", user: user.user_id, channel: match.challenge.channel).to respond_with_slack_message( "#{match} once" ) end end context 'with a singles match' do let!(:match) { Fabricate(:match, challenge: singles_challenge) } it 'displays user matches' do expect(message: "#{SlackRubyBot.config.user} matches", user: user.user_id, channel: match.challenge.channel).to respond_with_slack_message( "#{match} once" ) end end context 'without matches' do it 'displays' do expect(message: "#{SlackRubyBot.config.user} matches", user: user.user_id, channel: 'channel').to respond_with_slack_message('No matches.') end end context 'matches in prior seasons' do let!(:match1) { Fabricate(:match, challenge: singles_challenge) } let!(:season) { Fabricate(:season) } let(:singles_challenge2) { Fabricate(:challenge, challengers: [user]) } let!(:match2) { Fabricate(:match, challenge: singles_challenge2) } it 'displays user matches in current season only' do expect(message: "#{SlackRubyBot.config.user} matches", user: user.user_id, channel: match2.challenge.channel).to respond_with_slack_message( "#{match2} once" ) end end context 'lost to' do let(:loser) { Fabricate(:user, user_name: 'username') } let(:winner) { Fabricate(:user) } it 'a player' do expect(message: "#{SlackRubyBot.config.user} lost to #{winner.user_name}", user: loser.user_id, channel: 'channel').to respond_with_slack_message( "Match has been recorded! #{winner.user_name} defeated #{loser.user_name}." ) expect(message: "#{SlackRubyBot.config.user} matches", user: loser.user_id, channel: 'channel').to respond_with_slack_message( "#{team.matches.first} once" ) end end end it_behaves_like 'matches' context 'with another team' do let!(:team2) { Fabricate(:team) } let!(:team2_match) { Fabricate(:match, team: team2) } it_behaves_like 'matches' end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/seasons_spec.rb
spec/slack-gamebot/commands/seasons_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Seasons, vcr: { cassette_name: 'user_info' } do let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } shared_examples_for 'seasons' do context 'no seasons' do it 'seasons' do expect(message: "#{SlackRubyBot.config.user} seasons").to respond_with_slack_message "There're no seasons." end end context 'one season' do before do Array.new(2) { Fabricate(:match, team:) } challenge = Fabricate(:challenge, challengers: [team.users.asc(:_id).first], challenged: [team.users.asc(:_id).last]) Fabricate(:match, challenge:) end let!(:season) { Fabricate(:season, team:) } it 'seasons' do expect(message: "#{SlackRubyBot.config.user} seasons").to respond_with_slack_message season.to_s end end context 'two seasons' do let!(:seasons) do Array.new(2) do |n| team.users.all.destroy Array.new(n + 1) { Fabricate(:match, team:) } challenge = Fabricate(:challenge, challengers: [team.users.asc(:_id).first], challenged: [team.users.asc(:_id).last]) Fabricate(:match, challenge:) Fabricate(:season) end end it 'returns past seasons and current season' do expect(message: "#{SlackRubyBot.config.user} seasons").to respond_with_slack_message seasons.reverse.map(&:to_s).join("\n") end end context 'current season' do before do Array.new(2) { Fabricate(:match) } end it 'returns past seasons and current season' do current_season = Season.new(team:) expect(message: "#{SlackRubyBot.config.user} seasons").to respond_with_slack_message current_season.to_s end end context 'current and past season' do let!(:season1) do Array.new(2) { Fabricate(:match) } challenge = Fabricate(:challenge, challengers: [team.users.asc(:_id).first], challenged: [team.users.asc(:_id).last]) Fabricate(:match, challenge:) Fabricate(:season) end let!(:current_season) do Array.new(2) { Fabricate(:match) } Season.new(team:) end it 'returns past seasons and current season' do expect(message: "#{SlackRubyBot.config.user} seasons").to respond_with_slack_message [current_season, season1].map(&:to_s).join("\n") end end end context 'subscribed team' do let!(:team) { Fabricate(:team, subscribed: true) } it_behaves_like 'seasons' context 'with another team' do let!(:team2) { Fabricate(:team) } let!(:match2) { Fabricate(:match, team: team2) } let!(:season2) { Fabricate(:season, team: team2) } it_behaves_like 'seasons' end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/help_spec.rb
spec/slack-gamebot/commands/help_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Help do let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } let(:message_hook) { SlackRubyBot::Hooks::Message.new } context 'subscribed team' do let!(:team) { Fabricate(:team, subscribed: true) } it 'help' do expect(client).to receive(:say).with(channel: 'channel', text: [SlackGamebot::Commands::Help::HELP].join("\n")) expect(client).to receive(:say).with(channel: 'channel', gif: 'help') message_hook.call(client, Hashie::Mash.new(channel: 'channel', text: "#{SlackRubyBot.config.user} help")) end end context 'non-subscribed team' do let!(:team) { Fabricate(:team) } it 'help' do expect(client).to receive(:say).with(channel: 'channel', text: [SlackGamebot::Commands::Help::HELP, team.trial_message].join("\n")) expect(client).to receive(:say).with(channel: 'channel', gif: 'help') message_hook.call(client, Hashie::Mash.new(channel: 'channel', text: "#{SlackRubyBot.config.user} help")) end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/decline_spec.rb
spec/slack-gamebot/commands/decline_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Decline, vcr: { cassette_name: 'user_info' } do let!(:team) { Fabricate(:team) } let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } let(:challenged) { Fabricate(:user, user_name: 'username') } let!(:challenge) { Fabricate(:challenge, challenged: [challenged]) } it 'declines a challenge' do expect(message: "#{SlackRubyBot.config.user} decline", user: challenged.user_id, channel: challenge.channel).to respond_with_slack_message( "#{challenge.challenged.map(&:display_name).and} declined #{challenge.challengers.map(&:display_name).and} challenge." ) expect(challenge.reload.state).to eq ChallengeState::DECLINED end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/sucks_spec.rb
spec/slack-gamebot/commands/sucks_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Sucks, vcr: { cassette_name: 'user_info' } do let!(:team) { Fabricate(:team) } let(:app) { SlackGamebot::Server.new(team:) } let(:user) { Fabricate(:user) } let(:client) { app.send(:client) } it 'sucks' do expect(message: "#{SlackRubyBot.config.user} sucks").to respond_with_slack_message( 'No <@user>, you suck!' ) end it 'suck' do expect(message: "#{SlackRubyBot.config.user} you suck").to respond_with_slack_message( 'No <@user>, you suck!' ) end it 'sucks!' do expect(message: "#{SlackRubyBot.config.user} sucks!").to respond_with_slack_message( 'No <@user>, you suck!' ) end it 'really sucks!' do expect(message: "#{SlackRubyBot.config.user} you suck!").to respond_with_slack_message( 'No <@user>, you suck!' ) end it 'does not conflict with a player name that contains suck' do allow(client.web_client).to receive(:users_info) expect(message: "#{SlackRubyBot.config.user} challenge suckarov", user: user.user_id, channel: 'pongbot').to respond_with_slack_message( "I don't know who suckarov is! Ask them to _register_." ) end it 'sucks for someone with many losses' do allow_any_instance_of(User).to receive(:losses).and_return(6) expect(message: "#{SlackRubyBot.config.user} sucks").to respond_with_slack_message( 'No <@user>, with 6 losses, you suck!' ) end it 'sucks for a poorly ranked user' do allow_any_instance_of(User).to receive(:rank).and_return(4) expect(message: "#{SlackRubyBot.config.user} sucks").to respond_with_slack_message( 'No <@user>, with a rank of 4, you suck!' ) end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/challenge_question_spec.rb
spec/slack-gamebot/commands/challenge_question_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::ChallengeQuestion, vcr: { cassette_name: 'user_info' } do let!(:team) { Fabricate(:team) } let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } let(:user) { Fabricate(:user, user_name: 'username') } let(:opponent) { Fabricate(:user) } it 'displays elo at stake for a singles challenge' do expect do expect(message: "#{SlackRubyBot.config.user} challenge? <@#{opponent.user_id}>", user: user.user_id, channel: 'pongbot').to respond_with_slack_message( "#{user.slack_mention} challenging #{opponent.slack_mention} to a match is worth 48 elo." ) end.not_to change(Challenge, :count) end it 'displays elo at stake for a doubles challenge' do opponent2 = Fabricate(:user, team:) teammate = Fabricate(:user, team:) expect do expect(message: "#{SlackRubyBot.config.user} challenge? #{opponent.slack_mention} #{opponent2.user_name} with #{teammate.user_name}", user: user.user_id, channel: 'pongbot').to respond_with_slack_message( "#{user.slack_mention} and #{teammate.slack_mention} challenging #{opponent.slack_mention} and #{opponent2.slack_mention} to a match is worth 48 elo." ) end.not_to change(Challenge, :count) end context 'with unbalanced option enabled' do before do team.update_attributes!(unbalanced: true) end it 'displays elo at stake with different number of opponents' do opponent1 = Fabricate(:user) opponent2 = Fabricate(:user) expect do expect(message: "#{SlackRubyBot.config.user} challenge? #{opponent1.slack_mention} #{opponent2.slack_mention}", user: user.user_id, channel: 'pongbot').to respond_with_slack_message( "#{user.slack_mention} challenging #{opponent1.slack_mention} and #{opponent2.slack_mention} to a match is worth 24 and 48 elo." ) end.not_to change(Challenge, :count) end end context 'subscription expiration' do before do team.update_attributes!(created_at: 3.weeks.ago) end it 'prevents new challenge questions' do expect(message: "#{SlackRubyBot.config.user} challenge? <@#{opponent.user_id}>", user: user.user_id, channel: 'pongbot').to respond_with_slack_message( "Your trial subscription has expired. Subscribe your team for $29.99 a year at https://www.playplay.io/subscribe?team_id=#{team.team_id}&game=#{team.game.name}." ) end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/taunt_spec.rb
spec/slack-gamebot/commands/taunt_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Taunt, vcr: { cassette_name: 'user_info' } do let!(:team) { Fabricate(:team) } let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } let(:user) { Fabricate(:user, user_name: 'username') } it 'taunts one person by user id' do victim = Fabricate(:user, team:) expect(message: "#{SlackRubyBot.config.user} taunt <@#{victim.user_id}>", user: user.user_id).to respond_with_slack_message( "#{user.user_name} says that #{victim.user_name} sucks at #{client.name}!" ) end it 'taunts one person by user name' do victim = Fabricate(:user, team:) expect(message: "#{SlackRubyBot.config.user} taunt #{victim.user_name}", user: user.user_id).to respond_with_slack_message( "#{user.user_name} says that #{victim.user_name} sucks at #{client.name}!" ) end it 'taunts multiple users by user id' do victim1 = Fabricate(:user, team:) victim2 = Fabricate(:user, team:) victim3 = Fabricate(:user, team:) expect(message: "#{SlackRubyBot.config.user} taunt <@#{victim1.user_id}> <@#{victim2.user_id}> <@#{victim3.user_id}>", user: user.user_id).to respond_with_slack_message( "#{user.user_name} says that #{victim1.user_name}, #{victim2.user_name} and #{victim3.user_name} suck at #{client.name}!" ) end it 'taunts multiple users by user name' do victim1 = Fabricate(:user, team:) victim2 = Fabricate(:user, team:) victim3 = Fabricate(:user, team:) expect(message: "#{SlackRubyBot.config.user} taunt #{victim1.user_name} #{victim2.user_name} #{victim3.user_name}", user: user.user_id).to respond_with_slack_message( "#{user.user_name} says that #{victim1.user_name}, #{victim2.user_name} and #{victim3.user_name} suck at #{client.name}!" ) end it 'no entered user to taunt' do expect(message: "#{SlackRubyBot.config.user} taunt", user: user.user_id).to respond_with_slack_message( 'Please provide a user name to taunt.' ) end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/info_spec.rb
spec/slack-gamebot/commands/info_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Info do let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } let(:message_hook) { SlackRubyBot::Hooks::Message.new } let(:team) { Fabricate(:team) } it 'info' do expect(client).to receive(:say).with(channel: 'channel', text: SlackGamebot::INFO) message_hook.call(client, Hashie::Mash.new(channel: 'channel', text: "#{SlackRubyBot.config.user} info")) end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/challenges_spec.rb
spec/slack-gamebot/commands/challenges_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Challenges, vcr: { cassette_name: 'user_info' } do let!(:team) { Fabricate(:team) } let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } let(:user) { Fabricate(:user, user_name: 'username') } context 'with challenges' do let!(:challenge_proposed) { Fabricate(:challenge) } let!(:challenge_canceled) { Fabricate(:canceled_challenge) } let!(:challenge_declined) { Fabricate(:declined_challenge) } let!(:challenge_accepted) { Fabricate(:accepted_challenge) } let!(:challenge_played) { Fabricate(:played_challenge) } it 'displays a proposed and accepted challenges' do expect(message: "#{SlackRubyBot.config.user} challenges", user: user.user_id, channel: challenge_proposed.channel).to respond_with_slack_message( "a challenge between #{challenge_proposed.challengers.map(&:display_name).and} and #{challenge_proposed.challenged.map(&:display_name).and} was proposed just now\n" \ "a challenge between #{challenge_accepted.challengers.map(&:display_name).and} and #{challenge_accepted.challenged.map(&:display_name).and} was accepted just now" ) end end context 'without challenges' do it 'displays all challenges have been played' do expect(message: "#{SlackRubyBot.config.user} challenges", user: user.user_id, channel: 'channel').to respond_with_slack_message( 'All the challenges have been played.' ) end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/unregister_spec.rb
spec/slack-gamebot/commands/unregister_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Unregister, vcr: { cassette_name: 'user_info' } do context 'team' do let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } let!(:team) { Fabricate(:team) } it 'requires a captain to unregister someone' do Fabricate(:user, captain: true, team:) user = Fabricate(:user) expect(message: "#{SlackRubyBot.config.user} unregister #{user.user_name}").to respond_with_slack_message("You're not a captain, sorry.") end it 'registers, then unregisters a previously unknown user' do expect do expect(message: "#{SlackRubyBot.config.user} unregister", user: 'user1').to respond_with_slack_message("I've removed <@user1> from the leaderboard.") end.to change(User, :count).by(1) expect(User.where(user_id: 'user1').first.registered).to be false end it 'cannot unregister an unknown user by name' do captain = Fabricate(:user, captain: true, team:) allow(client.web_client).to receive(:users_info) user = Fabricate(:user, team: Fabricate(:team)) # another user in another team expect(message: "#{SlackRubyBot.config.user} unregister #{user.user_name}", user: captain.user_id).to respond_with_slack_message("I don't know who #{user.user_name} is! Ask them to _register_.") end it 'unregisters self' do user = Fabricate(:user, user_id: 'user') expect(message: "#{SlackRubyBot.config.user} unregister", user: user.user_id).to respond_with_slack_message("I've removed <@user> from the leaderboard.") expect(user.reload.registered).to be false end it 'unregisters self via me' do user = Fabricate(:user, user_id: 'user') expect(message: "#{SlackRubyBot.config.user} unregister me", user: user.user_id).to respond_with_slack_message("I've removed <@user> from the leaderboard.") expect(user.reload.registered).to be false end it 'unregisters another user' do user = Fabricate(:user) expect(message: "#{SlackRubyBot.config.user} unregister #{user.user_name}", user: 'user').to respond_with_slack_message("I've removed <@#{user.user_id}> from the leaderboard.") expect(user.reload.registered).to be false end it 'unregisters multiple users' do user1 = Fabricate(:user) user2 = Fabricate(:user) expect(message: "#{SlackRubyBot.config.user} unregister #{user1.user_name} <@#{user2.user_id}>", user: 'user').to respond_with_slack_message( "I've removed <@#{user1.user_id}> and <@#{user2.user_id}> from the leaderboard." ) expect(user1.reload.registered).to be false expect(user2.reload.registered).to be false end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/slack-gamebot/commands/draw_spec.rb
spec/slack-gamebot/commands/draw_spec.rb
require 'spec_helper' describe SlackGamebot::Commands::Draw, vcr: { cassette_name: 'user_info' } do let!(:team) { Fabricate(:team) } let(:app) { SlackGamebot::Server.new(team:) } let(:client) { app.send(:client) } context 'with a challenge' do let(:challenged) { Fabricate(:user, user_name: 'username') } let!(:challenge) { Fabricate(:challenge, challenged: [challenged]) } before do challenge.accept!(challenged) end it 'draw' do expect(message: "#{SlackRubyBot.config.user} draw", user: challenged.user_id, channel: challenge.channel).to respond_with_slack_message( "Match is a draw, waiting to hear from #{challenge.challengers.map(&:display_name).and}." ) challenge.reload expect(challenge.state).to eq ChallengeState::DRAWN expect(challenge.draw).to eq challenge.challenged end it 'draw with a score' do expect(message: "#{SlackRubyBot.config.user} draw 2:2", user: challenged.user_id, channel: challenge.channel).to respond_with_slack_message( "Match is a draw, waiting to hear from #{challenge.challengers.map(&:display_name).and}. Recorded the score of 2:2." ) challenge.reload expect(challenge.state).to eq ChallengeState::DRAWN expect(challenge.draw).to eq challenge.challenged expect(challenge.draw_scores?).to be true expect(challenge.draw_scores).to eq [[2, 2]] end context 'confirmation' do before do challenge.draw!(challenge.challengers.first) end it 'confirmed' do expect(message: "#{SlackRubyBot.config.user} draw", user: challenged.user_id, channel: challenge.channel).to respond_with_slack_message( "Match has been recorded! #{challenge.challengers.map(&:display_name).and} tied with #{challenge.challenged.map(&:display_name).and}." ) challenge.reload expect(challenge.state).to eq ChallengeState::PLAYED expect(challenge.draw).to eq challenge.challenged + challenge.challengers end it 'with score' do expect(message: "#{SlackRubyBot.config.user} draw 3:3", user: challenged.user_id, channel: challenge.channel).to respond_with_slack_message( "Match has been recorded! #{challenge.challengers.map(&:display_name).and} tied with #{challenge.challenged.map(&:display_name).and} with the score of 3:3." ) challenge.reload expect(challenge.match.scores).to eq [[3, 3]] end it 'with invalid score' do expect(message: "#{SlackRubyBot.config.user} draw 21:15", user: challenged.user_id, channel: challenge.channel).to respond_with_slack_message( 'In a tie both sides must score the same number of points.' ) end it 'draw with scores' do expect(message: "#{SlackRubyBot.config.user} draw 21:15 15:21", user: challenged.user_id, channel: challenge.channel).to respond_with_slack_message( "Match has been recorded! #{challenge.challengers.map(&:display_name).and} tied with #{challenge.challenged.map(&:display_name).and} with the scores of 15:21 21:15." ) challenge.reload expect(challenge.match.scores).to eq [[21, 15], [15, 21]] end end it 'draw already confirmed' do challenge.draw!(challenge.challenged.first) expect(message: "#{SlackRubyBot.config.user} draw", user: challenged.user_id, channel: challenge.channel).to respond_with_slack_message( "Match is a draw, still waiting to hear from #{challenge.challengers.map(&:display_name).and}." ) end it 'does not update a previously lost match' do challenge.lose!(challenge.challenged.first) expect(message: "#{SlackRubyBot.config.user} draw", user: challenged.user_id, channel: challenge.channel).to respond_with_slack_message( 'No challenge to draw!' ) end it 'does not update a previously won match' do challenge.lose!(challenge.challengers.first) expect(message: "#{SlackRubyBot.config.user} draw", user: challenged.user_id, channel: challenge.channel).to respond_with_slack_message( 'No challenge to draw!' ) end end context 'without a challenge' do let(:winner) { Fabricate(:user) } let(:loser) { Fabricate(:user, user_name: 'username') } it 'draw to' do expect do expect do expect(message: "#{SlackRubyBot.config.user} draw to #{winner.user_name}", user: loser.user_id, channel: 'channel').to respond_with_slack_message( "Match is a draw, waiting to hear from #{winner.user_name}." ) end.to change(Challenge, :count).by(1) end.not_to change(Match, :count) challenge = Challenge.desc(:_id).first expect(challenge.state).to eq ChallengeState::DRAWN expect(challenge.draw).to eq [loser] end it 'draw with a score' do expect do expect do expect(message: "#{SlackRubyBot.config.user} draw to #{winner.user_name} 2:2", user: loser.user_id, channel: 'channel').to respond_with_slack_message( "Match is a draw, waiting to hear from #{winner.user_name}. Recorded the score of 2:2." ) end.to change(Challenge, :count).by(1) end.not_to change(Match, :count) challenge = Challenge.desc(:_id).first expect(challenge.state).to eq ChallengeState::DRAWN expect(challenge.draw).to eq [loser] expect(challenge.draw_scores?).to be true expect(challenge.draw_scores).to eq [[2, 2]] end context 'confirmation' do before do allow_any_instance_of(Slack::Web::Client).to receive(:users_info).and_return(nil) end let!(:challenge) do Challenge.create!( team: loser.team, channel: 'channel', created_by: loser, updated_by: loser, challengers: [loser], challenged: [winner], draw: [loser], draw_scores: [], state: ChallengeState::DRAWN ) end it 'still waiting' do expect(message: "#{SlackRubyBot.config.user} draw", user: loser.user_id, channel: 'channel').to respond_with_slack_message( "Match is a draw, still waiting to hear from #{winner.user_name}." ) end it 'confirmed' do expect(message: "#{SlackRubyBot.config.user} draw", user: winner.user_id, channel: 'channel').to respond_with_slack_message( "Match has been recorded! #{loser.user_name} tied with #{winner.user_name}." ) challenge.reload expect(challenge.state).to eq ChallengeState::PLAYED expect(challenge.draw).to eq [loser, winner] end it 'with score' do expect(message: "#{SlackRubyBot.config.user} draw 3:3", user: winner.user_id, channel: 'channel').to respond_with_slack_message( "Match has been recorded! #{loser.user_name} tied with #{winner.user_name} with the score of 3:3." ) challenge.reload expect(challenge.match.scores).to eq [[3, 3]] end it 'with invalid score' do expect(message: "#{SlackRubyBot.config.user} draw 21:15", user: winner.user_id, channel: 'channel').to respond_with_slack_message( 'In a tie both sides must score the same number of points.' ) end it 'draw with scores' do expect(message: "#{SlackRubyBot.config.user} draw 21:15 15:21", user: winner.user_id, channel: challenge.channel).to respond_with_slack_message( "Match has been recorded! #{loser.user_name} tied with #{winner.user_name} with the scores of 15:21 21:15." ) challenge.reload expect(challenge.match.scores).to eq [[21, 15], [15, 21]] end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/fabricators/season_fabricator.rb
spec/fabricators/season_fabricator.rb
Fabricator(:season) do team { Team.first || Fabricate(:team) } before_create do Fabricate(:match, team:) if Challenge.current.none? end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/fabricators/match_fabricator.rb
spec/fabricators/match_fabricator.rb
Fabricator(:match_lost_to, class_name: 'Match') do after_build do |match| match.scores = match.tied? ? [[3, 3]] : [[15, 21]] end end Fabricator(:match) do after_build do |match| match.challenge ||= Fabricate(:challenge, team: match.team || Team.first || Fabricate(:team)) match.team = challenge.team match.winners = match.challenge.challengers if match.winners.none? match.losers = match.challenge.challenged if match.losers.none? match.scores = match.tied? ? [[3, 3]] : [[15, 21]] end after_create do |match| challenge.update_attributes!(state: ChallengeState::PLAYED, updated_by: match.losers.first) end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/fabricators/team_fabricator.rb
spec/fabricators/team_fabricator.rb
Fabricator(:team) do token { Fabricate.sequence(:team_token) { |i| "abc-#{i}" } } team_id { Fabricate.sequence(:team_id) { |i| "T#{i}" } } activated_user_id { Fabricate.sequence(:activated_user_id) { |i| "U#{i}" } } game { Game.first || Fabricate(:game) } name { Faker::Lorem.word } api { true } end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/fabricators/challenge_fabricator.rb
spec/fabricators/challenge_fabricator.rb
Fabricator(:challenge) do channel 'gamebot' team { Team.first || Fabricate(:team) } before_create do |instance| instance.challengers << Fabricate(:user, team: instance.team) unless instance.challengers.any? instance.challenged << Fabricate(:user, team: instance.team) unless instance.challenged.any? instance.created_by = instance.challengers.first end end Fabricator(:doubles_challenge, from: :challenge) do after_build do |instance| instance.challengers = [Fabricate(:user, team: instance.team), Fabricate(:user, team: instance.team)] unless instance.challengers.any? instance.challenged = [Fabricate(:user, team: instance.team), Fabricate(:user, team: instance.team)] unless instance.challenged.any? end end Fabricator(:accepted_challenge, from: :challenge) do state ChallengeState::ACCEPTED before_create do |instance| instance.updated_by = instance.challenged.first end end Fabricator(:declined_challenge, from: :challenge) do state ChallengeState::DECLINED before_create do |instance| instance.updated_by = instance.challenged.first end end Fabricator(:canceled_challenge, from: :challenge) do state ChallengeState::CANCELED before_create do |instance| instance.updated_by = instance.challengers.first end end Fabricator(:played_challenge, from: :challenge) do state ChallengeState::PLAYED before_create do |instance| instance.updated_by = instance.challenged.first end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/fabricators/user_fabricator.rb
spec/fabricators/user_fabricator.rb
Fabricator(:user) do user_id { Fabricate.sequence(:user_id) { |i| "U#{i}" } } user_name { Faker::Internet.user_name } team { Team.first || Fabricate(:team) } end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/spec/fabricators/game_fabricator.rb
spec/fabricators/game_fabricator.rb
Fabricator(:game) do name { Faker::Lorem.word } client_id { Faker::Internet.password(min_length: 8) } client_secret { Faker::Internet.password(min_length: 16) } aliases { Faker::Lorem.words } after_build do |game| game.bot_name = game.name + 'bot' end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/version.rb
slack-gamebot/version.rb
module SlackGamebot VERSION = '0.4.0'.freeze end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/models.rb
slack-gamebot/models.rb
require 'slack-gamebot/models/game' require 'slack-gamebot/models/team' require 'slack-gamebot/models/elo' require 'slack-gamebot/models/user' require 'slack-gamebot/models/user_rank' require 'slack-gamebot/models/challenge_state' require 'slack-gamebot/models/challenge' require 'slack-gamebot/models/score' require 'slack-gamebot/models/match' require 'slack-gamebot/models/season'
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/api.rb
slack-gamebot/api.rb
require 'grape' require 'roar' require 'grape-roar' require 'slack-gamebot/api/helpers' require 'slack-gamebot/api/presenters' require 'slack-gamebot/api/endpoints' require 'slack-gamebot/api/middleware'
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/app.rb
slack-gamebot/app.rb
module SlackGamebot class App < SlackRubyBotServer::App DEAD_MESSAGE = <<~EOS.freeze This leaderboard has been dead for over a month, deactivating. Re-install the bot at https://www.playplay.io. Your data will be purged in 2 weeks. EOS def after_start! once_and_every 60 * 60 * 24 do check_trials! deactivate_dead_teams! inform_dead_teams! check_subscribed_teams! check_active_subscriptions_without_teams! end end private def once_and_every(tt) ::Async::Reactor.run do |task| loop do yield task.sleep tt end end end def inform_dead_teams! Team.where(active: false).each do |team| next if team.dead_at begin team.dead! DEAD_MESSAGE, 'dead' rescue StandardError => e logger.warn "Error informing dead team #{team}, #{e.message}." end end end def deactivate_dead_teams! Team.active.each do |team| next if team.subscribed? next unless team.dead? begin team.deactivate! rescue StandardError => e logger.warn "Error deactivating team #{team}, #{e.message}." end end end def check_trials! Team.active.where(subscribed: false).each do |team| logger.info "Team #{team} has #{team.remaining_trial_days} trial days left." next unless team.remaining_trial_days > 0 && team.remaining_trial_days <= 3 team.inform_trial! rescue StandardError => e logger.warn "Error checking team #{team} trial, #{e.message}." end end def check_subscribed_teams! Team.where(subscribed: true, :stripe_customer_id.ne => nil).each do |team| if team.subscribed? && team.stripe_customer.subscriptions.none? logger.info "No active subscriptions for #{team} (#{team.stripe_customer_id}), downgrading." team.inform_admin! 'Your subscription was canceled and your team has been downgraded. Thank you for being a customer!' team.update_attributes!(subscribed: false) else team.stripe_customer.subscriptions.each do |subscription| subscription_name = "#{subscription.plan.name} (#{ActiveSupport::NumberHelper.number_to_currency(subscription.plan.amount.to_f / 100)})" logger.info "Checking #{team} subscription to #{subscription_name}, #{subscription.status}." case subscription.status when 'past_due' logger.warn "Subscription for #{team} is #{subscription.status}, notifying." team.inform_admin! "Your subscription to #{subscription_name} is past due. #{team.update_cc_text}" when 'canceled', 'unpaid' logger.warn "Subscription for #{team} is #{subscription.status}, downgrading." team.inform_admin! "Your subscription to #{subscription.plan.name} (#{ActiveSupport::NumberHelper.number_to_currency(subscription.plan.amount.to_f / 100)}) was canceled and your team has been downgraded. Thank you for being a customer!" team.update_attributes!(subscribed: false) end end end rescue StandardError => e logger.warn "Error checking team #{team} subscription, #{e.message}." end end def check_active_subscriptions_without_teams! Stripe::Subscription.all(plan: 'slack-playplay-yearly').each do |subscription| next if subscription.cancel_at_period_end next if Team.where(stripe_customer_id: subscription.customer).exists? customer = Stripe::Customer.retrieve(subscription.customer) logger.warn "Customer #{customer.email}, team #{customer.metadata['name']} is #{subscription.status}, but customer no longer exists." end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/info.rb
slack-gamebot/info.rb
module SlackGamebot INFO = <<~EOS.freeze Gamebot #{SlackGamebot::VERSION} © Daniel Doubrovkine, Vestris LLC & Contributors, MIT License https://www.vestris.com Hosted at https://www.playplay.io Follow Us at https://twitter.com/playplayio Open-Source at https://github.com/dblock/slack-gamebot EOS end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands.rb
slack-gamebot/commands.rb
require 'slack-gamebot/commands/mixins' require 'slack-gamebot/commands/accept' require 'slack-gamebot/commands/cancel' require 'slack-gamebot/commands/challenge' require 'slack-gamebot/commands/challenge_question' require 'slack-gamebot/commands/challenges' require 'slack-gamebot/commands/decline' require 'slack-gamebot/commands/default' require 'slack-gamebot/commands/help' require 'slack-gamebot/commands/info' require 'slack-gamebot/commands/rank' require 'slack-gamebot/commands/leaderboard' require 'slack-gamebot/commands/lost' require 'slack-gamebot/commands/resigned' require 'slack-gamebot/commands/draw' require 'slack-gamebot/commands/register' require 'slack-gamebot/commands/unregister' require 'slack-gamebot/commands/reset' require 'slack-gamebot/commands/seasons' require 'slack-gamebot/commands/season' require 'slack-gamebot/commands/matches' require 'slack-gamebot/commands/promote' require 'slack-gamebot/commands/demote' require 'slack-gamebot/commands/taunt' require 'slack-gamebot/commands/team' require 'slack-gamebot/commands/set' require 'slack-gamebot/commands/sucks' require 'slack-gamebot/commands/subscription' require 'slack-gamebot/commands/unsubscribe'
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/server.rb
slack-gamebot/server.rb
module SlackGamebot class Server < SlackRubyBotServer::RealTime::Server def initialize(attrs = {}) attrs = attrs.dup attrs[:aliases] = ([attrs[:team].game.name] + [attrs[:team].aliases]).flatten.compact super end on :user_change do |client, data| user = User.where(team: client.owner, user_id: data.user.id).first next unless user && user.user_name != data.user.name logger.info "RENAME: #{user.user_id}, #{user.user_name} => #{data.user.name}" user.update_attributes!(user_name: data.user.name) end on :channel_joined do |client, data| logger.info "#{client.owner.name}: joined ##{data.channel['name']}." message = <<~EOS.freeze Hi! I am your friendly game bot. Register with `@#{client.self.name} register`. Challenge someone to a game of #{client.owner.game.name} with `@#{client.self.name} challenge @someone`. Type `@#{client.self.name} help` fore more commands and don't forget to have fun at work! EOS client.say(channel: data.channel['id'], text: message) end def client @client ||= begin client = super client.send_gifs = team.gifs client end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/service.rb
slack-gamebot/service.rb
module SlackRubyBotServer class Service def self.url ENV.fetch('URL') { (ENV['RACK_ENV'] == 'development' ? 'http://localhost:5000' : 'https://www.playplay.io') } end def self.api_url ENV.fetch('API_URL') { "#{url}/api" } end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/error.rb
slack-gamebot/error.rb
module SlackGamebot class Error < StandardError end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/subscription.rb
slack-gamebot/commands/subscription.rb
module SlackGamebot module Commands class Subscription < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription subscribed_command 'subscription' do |client, data, _match| user = ::User.find_create_or_update_by_slack_id!(client, data.user) team = ::Team.find(client.owner.id) subscription_info = [] if team.stripe_subcriptions&.any? subscription_info << team.stripe_customer_text subscription_info.concat(team.stripe_customer_subscriptions_info) if user.captain? subscription_info.concat(team.stripe_customer_invoices_info) subscription_info.concat(team.stripe_customer_sources_info) subscription_info << team.update_cc_text end elsif team.subscribed && team.subscribed_at subscription_info << team.subscriber_text else subscription_info << team.trial_message end client.say(channel: data.channel, text: subscription_info.compact.join("\n")) logger.info "SUBSCRIPTION: #{client.owner} - #{data.user}" end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/season.rb
slack-gamebot/commands/season.rb
module SlackGamebot module Commands class Season < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription subscribed_command 'season' do |client, data, _match| if client.owner.matches.current.any? || client.owner.challenges.current.any? current_season = ::Season.new(team: client.owner) client.say(channel: data.channel, text: current_season.to_s) elsif client.owner.seasons.count > 0 client.say(channel: data.channel, text: 'No matches have been recorded.', gif: 'history') else client.say(channel: data.channel, text: "There're no seasons.", gif: %w[winter summer fall spring].sample) end logger.info "SEASON: #{client.owner} - #{data.user}" end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/unregister.rb
slack-gamebot/commands/unregister.rb
module SlackGamebot module Commands class Unregister < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription subscribed_command 'unregister' do |client, data, match| if !match['expression'] || match['expression'] == 'me' user = ::User.find_create_or_update_by_slack_id!(client, data.user) user.unregister! client.say(channel: data.channel, text: "I've removed #{user.slack_mention} from the leaderboard.", gif: 'removed') logger.info "UNREGISTER ME: #{client.owner} - #{user.slack_mention}" elsif match['expression'] user = ::User.find_create_or_update_by_slack_id!(client, data.user) names = match['expression'].split.reject(&:blank?) if user.captain? users = names.map { |name| ::User.find_by_slack_mention!(client, name) } users.each(&:unregister!) slack_mentions = users.map(&:slack_mention) client.say(channel: data.channel, text: "I've removed #{slack_mentions.and} from the leaderboard.", gif: 'find') logger.info "UNREGISTER: #{client.owner} - #{names.and}" else client.say(channel: data.channel, text: "You're not a captain, sorry.", gif: 'sorry') logger.info "UNREGISTER: #{client.owner} - #{names.and}, failed, not captain" end end end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/demote.rb
slack-gamebot/commands/demote.rb
module SlackGamebot module Commands class Demote < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription subscribed_command 'demote' do |client, data, match| user = ::User.find_create_or_update_by_slack_id!(client, data.user) if !match['expression'] || match['expression'] != 'me' client.say(channel: data.channel, text: 'You can only demote yourself, try _demote me_.', gif: 'help') logger.info "DEMOTE: #{client.owner} - #{user.user_name}, failed, not me" elsif !user.captain? client.say(channel: data.channel, text: "You're not a captain, sorry.", gif: 'sorry') logger.info "DEMOTE: #{client.owner} - #{user.user_name}, failed, not captain" elsif client.owner.captains.count == 1 client.say(channel: data.channel, text: "You cannot demote yourself, you're the last captain. Promote someone else first.", gif: 'sorry') logger.info "DEMOTE: #{client.owner} - #{user.user_name}, failed, last captain" else user.demote! client.say(channel: data.channel, text: "#{user.user_name} is no longer captain.") logger.info "DEMOTED: #{client.owner} - #{user.user_name}" end end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/default.rb
slack-gamebot/commands/default.rb
module SlackGamebot module Commands class Default < SlackRubyBot::Commands::Base match(/^(?<bot>\w*)$/) def self.call(client, data, _match) client.say(channel: data.channel, text: SlackGamebot::INFO) client.say(channel: data.channel, gif: 'robot') end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/lost.rb
slack-gamebot/commands/lost.rb
module SlackGamebot module Commands class Lost < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription subscribed_command 'lost' do |client, data, match| challenger = ::User.find_create_or_update_by_slack_id!(client, data.user) expression = match['expression'] if match['expression'] arguments = expression.split.reject(&:blank?) if expression scores = nil opponents = [] teammates = [challenger] multi_player = expression&.include?(' with ') current = :scores while arguments&.any? argument = arguments.shift case argument when 'to' current = :opponents when 'with' current = :teammates else if current == :opponents opponents << ::User.find_by_slack_mention!(client, argument) current = :scores unless multi_player elsif current == :teammates teammates << ::User.find_by_slack_mention!(client, argument) current = :scores if opponents.count == teammates.count else scores ||= [] scores << Score.check(argument) end end end challenge = ::Challenge.find_by_user(client.owner, data.channel, challenger, [ChallengeState::PROPOSED, ChallengeState::ACCEPTED]) if !(teammates & opponents).empty? client.say(channel: data.channel, text: 'You cannot lose to yourself!', gif: 'loser') logger.info "Cannot lose to yourself: #{client.owner} - #{match}" elsif opponents.any? && (challenge.nil? || (challenge.challengers != opponents && challenge.challenged != opponents)) match = ::Match.lose!(team: client.owner, winners: opponents, losers: teammates, scores:) client.say(channel: data.channel, text: "Match has been recorded! #{match}.", gif: 'loser') logger.info "LOST TO: #{client.owner} - #{match}" elsif challenge challenge.lose!(challenger, scores) client.say(channel: data.channel, text: "Match has been recorded! #{challenge.match}.", gif: 'loser') logger.info "LOST: #{client.owner} - #{challenge}" else match = ::Match.where(loser_ids: challenger.id).desc(:_id).first if match match.update_attributes!(scores:) client.say(channel: data.channel, text: "Match scores have been updated! #{match}.", gif: 'score') logger.info "SCORED: #{client.owner} - #{match}" else client.say(channel: data.channel, text: 'No challenge to lose!') logger.info "LOST: #{client.owner} - #{data.user}, N/A" end end end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/taunt.rb
slack-gamebot/commands/taunt.rb
module SlackGamebot module Commands class Taunt < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription subscribed_command 'taunt' do |client, data, match| taunter = ::User.find_create_or_update_by_slack_id!(client, data.user) arguments = match['expression'] ? match['expression'].split.reject(&:blank?) : [] if arguments.empty? client.say(channel: data.channel, text: 'Please provide a user name to taunt.') else victim = ::User.find_many_by_slack_mention!(client, arguments) taunt = "#{victim.map(&:display_name).and} #{victim.count == 1 ? 'sucks' : 'suck'} at #{client.name}!" client.say(channel: data.channel, text: "#{taunter.user_name} says that #{taunt}") logger.info "TAUNT: #{client.owner} - #{taunter.user_name}" end end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/draw.rb
slack-gamebot/commands/draw.rb
module SlackGamebot module Commands class Draw < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription subscribed_command 'draw' do |client, data, match| challenger = ::User.find_create_or_update_by_slack_id!(client, data.user) expression = match['expression'] if match['expression'] arguments = expression.split.reject(&:blank?) if expression scores = nil opponents = [] teammates = [challenger] multi_player = expression&.include?(' with ') current = :scores while arguments&.any? argument = arguments.shift case argument when 'to' current = :opponents when 'with' current = :teammates else if current == :opponents opponents << ::User.find_by_slack_mention!(client, argument) current = :scores unless multi_player elsif current == :teammates teammates << ::User.find_by_slack_mention!(client, argument) current = :scores if opponents.count == teammates.count else scores ||= [] scores << Score.check(argument) end end end challenge = ::Challenge.find_by_user(client.owner, data.channel, challenger, [ ChallengeState::PROPOSED, ChallengeState::ACCEPTED, ChallengeState::DRAWN ]) if !(teammates & opponents).empty? client.say(channel: data.channel, text: 'You cannot draw to yourself!', gif: 'loser') logger.info "Cannot draw to yourself: #{client.owner} - #{match}" elsif opponents.any? && (challenge.nil? || (challenge.challengers != opponents && challenge.challenged != opponents)) challenge = ::Challenge.create!( team: client.owner, channel: data.channel, created_by: challenger, updated_by: challenger, challengers: teammates, challenged: opponents, draw: [challenger], draw_scores: scores, state: ChallengeState::DRAWN ) messages = [ "Match is a draw, waiting to hear from #{(challenge.challengers + challenge.challenged - challenge.draw).map(&:display_name).and}.", challenge.draw_scores? ? "Recorded #{Score.scores_to_string(challenge.draw_scores)}." : nil ].compact client.say(channel: data.channel, text: messages.join(' '), gif: 'tie') logger.info "DRAW TO: #{client.owner} - #{challenge}" elsif challenge if challenge.draw.include?(challenger) challenge.update_attributes!(draw_scores: scores) if scores messages = [ "Match is a draw, still waiting to hear from #{(challenge.challengers + challenge.challenged - challenge.draw).map(&:display_name).and}.", challenge.draw_scores? ? "Recorded #{Score.scores_to_string(challenge.draw_scores)}." : nil ].compact client.say(channel: data.channel, text: messages.join(' '), gif: 'tie') else challenge.draw!(challenger, scores) if challenge.state == ChallengeState::PLAYED client.say(channel: data.channel, text: "Match has been recorded! #{challenge.match}.", gif: 'tie') else messages = [ "Match is a draw, waiting to hear from #{(challenge.challengers + challenge.challenged - challenge.draw).map(&:display_name).and}.", challenge.draw_scores? ? "Recorded #{Score.scores_to_string(challenge.draw_scores)}." : nil ].compact client.say(channel: data.channel, text: messages.join(' '), gif: 'tie') end end logger.info "DRAW: #{client.owner} - #{challenge}" else match = ::Match.any_of({ winner_ids: challenger.id }, loser_ids: challenger.id).desc(:id).first if match&.tied? match.update_attributes!(scores:) client.say(channel: data.channel, text: "Match scores have been updated! #{match}.", gif: 'score') logger.info "SCORED: #{client.owner} - #{match}" else client.say(channel: data.channel, text: 'No challenge to draw!') logger.info "DRAW: #{client.owner} - #{data.user}, N/A" end end end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/decline.rb
slack-gamebot/commands/decline.rb
module SlackGamebot module Commands class Decline < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription subscribed_command 'decline' do |client, data, _match| challenger = ::User.find_create_or_update_by_slack_id!(client, data.user) challenge = ::Challenge.find_by_user(client.owner, data.channel, challenger) if challenge challenge.decline!(challenger) client.say(channel: data.channel, text: "#{challenge.challenged.map(&:display_name).and} declined #{challenge.challengers.map(&:display_name).and} challenge.", gif: 'no') logger.info "DECLINE: #{client.owner} - #{challenge}" else client.say(channel: data.channel, text: 'No challenge to decline!') logger.info "DECLINE: #{client.owner} - #{data.user}, N/A" end end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/challenge.rb
slack-gamebot/commands/challenge.rb
module SlackGamebot module Commands class Challenge < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription subscribed_command 'challenge' do |client, data, match| challenger = ::User.find_create_or_update_by_slack_id!(client, data.user) arguments = match['expression'].split.reject(&:blank?) if match['expression'] arguments ||= [] challenge = ::Challenge.create_from_teammates_and_opponents!(client, data.channel, challenger, arguments) client.say(channel: data.channel, text: "#{challenge.challengers.map(&:slack_mention).and} challenged #{challenge.challenged.map(&:slack_mention).and} to a match!", gif: 'challenge') logger.info "CHALLENGE: #{client.owner} - #{challenge}" end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/challenges.rb
slack-gamebot/commands/challenges.rb
module SlackGamebot module Commands class Challenges < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription subscribed_command 'challenges' do |client, data, _match| challenges = ::Challenge.where( channel: data.channel, :state.in => [ ChallengeState::PROPOSED, ChallengeState::ACCEPTED, ChallengeState::DRAWN ] ).asc(:created_at) if challenges.any? challenges_s = challenges.map do |challenge| "#{challenge} was #{challenge.state} #{(challenge.updated_at || challenge.created_at).ago_in_words}" end.join("\n") client.say(channel: data.channel, text: challenges_s, gif: 'memories') else client.say(channel: data.channel, text: 'All the challenges have been played.', gif: 'boring') end logger.info "CHALLENGES: #{client.owner} - #{data.user}" end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/set.rb
slack-gamebot/commands/set.rb
module SlackGamebot module Commands class Set < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription class << self def set_nickname(client, data, user, v) target_user = user slack_mention = v.split.first if v if v && User.slack_mention?(slack_mention) raise SlackGamebot::Error, "You're not a captain, sorry." unless user.captain? target_user = ::User.find_by_slack_mention!(client, slack_mention) v = v[slack_mention.length + 1..-1] end target_user.update_attributes!(nickname: v) unless v.nil? if target_user.nickname.blank? client.say(channel: data.channel, text: "You don't have a nickname set, #{target_user.user_name}.", gif: 'anonymous') logger.info "SET: #{client.owner} - #{user.user_name}: nickname #{' for ' + target_user.user_name unless target_user == user}is not set" else client.say(channel: data.channel, text: "Your nickname is #{'now ' unless v.nil?}*#{target_user.nickname}*, #{target_user.slack_mention}.", gif: 'name') logger.info "SET: #{client.owner} - #{user.user_name} nickname #{' for ' + target_user.user_name unless target_user == user}is #{target_user.nickname}" end end def unset_nickname(client, data, user, v) target_user = user slack_mention = v.split.first if v if User.slack_mention?(slack_mention) raise SlackGamebot::Error, "You're not a captain, sorry." unless user.captain? target_user = ::User.find_by_slack_mention!(client, slack_mention) end old_nickname = target_user.nickname target_user.update_attributes!(nickname: nil) client.say(channel: data.channel, text: "You don't have a nickname set#{' anymore' unless old_nickname.blank?}, #{target_user.slack_mention}.", gif: 'anonymous') logger.info "UNSET: #{client.owner} - #{user.user_name}: nickname #{' for ' + target_user.user_name unless target_user == user} was #{old_nickname.blank? ? 'not ' : 'un'}set" end def set_gifs(client, data, user, v) raise SlackGamebot::Error, "You're not a captain, sorry." unless v.nil? || user.captain? unless v.nil? client.owner.update_attributes!(gifs: v.to_b) client.send_gifs = client.owner.gifs end client.say(channel: data.channel, text: "GIFs for team #{client.owner.name} are #{client.owner.gifs? ? 'on!' : 'off.'}", gif: 'fun') logger.info "SET: #{client.owner} - #{user.user_name} GIFs are #{client.owner.gifs? ? 'on' : 'off'}" end def unset_gifs(client, data, user) raise SlackGamebot::Error, "You're not a captain, sorry." unless user.captain? client.owner.update_attributes!(gifs: false) client.send_gifs = client.owner.gifs client.say(channel: data.channel, text: "GIFs for team #{client.owner.name} are off.", gif: 'fun') logger.info "UNSET: #{client.owner} - #{user.user_name} GIFs are off" end def set_unbalanced(client, data, user, v) raise SlackGamebot::Error, "You're not a captain, sorry." unless v.nil? || user.captain? client.owner.update_attributes!(unbalanced: v.to_b) unless v.nil? client.say(channel: data.channel, text: "Unbalanced challenges for team #{client.owner.name} are #{client.owner.unbalanced? ? 'on!' : 'off.'}", gif: 'balance') logger.info "SET: #{client.owner} - #{user.user_name} unbalanced challenges are #{client.owner.unbalanced? ? 'on' : 'off'}" end def unset_unbalanced(client, data, user) raise SlackGamebot::Error, "You're not a captain, sorry." unless user.captain? client.owner.update_attributes!(unbalanced: false) client.say(channel: data.channel, text: "Unbalanced challenges for team #{client.owner.name} are off.", gif: 'balance') logger.info "UNSET: #{client.owner} - #{user.user_name} unbalanced challenges are off" end def set_api(client, data, user, v) raise SlackGamebot::Error, "You're not a captain, sorry." unless v.nil? || user.captain? client.owner.update_attributes!(api: v.to_b) unless v.nil? message = [ "API for team #{client.owner.name} is #{client.owner.api? ? 'on!' : 'off.'}", client.owner.api_url ].compact.join("\n") client.say(channel: data.channel, text: message, gif: 'programmer') logger.info "SET: #{client.owner} - #{user.user_name} API is #{client.owner.api? ? 'on' : 'off'}" end def unset_api(client, data, user) raise SlackGamebot::Error, "You're not a captain, sorry." unless user.captain? client.owner.update_attributes!(api: false) client.say(channel: data.channel, text: "API for team #{client.owner.name} is off.", gif: 'programmer') logger.info "UNSET: #{client.owner} - #{user.user_name} API is off" end def set_elo(client, data, user, v) raise SlackGamebot::Error, "You're not a captain, sorry." unless v.nil? || user.captain? client.owner.update_attributes!(elo: parse_int(v)) unless v.nil? message = "Base elo for team #{client.owner.name} is #{client.owner.elo}." client.say(channel: data.channel, text: message, gif: 'score') logger.info "SET: #{client.owner} - #{user.user_name} ELO is #{client.owner.elo}" end def unset_elo(client, data, user) raise SlackGamebot::Error, "You're not a captain, sorry." unless user.captain? client.owner.update_attributes!(elo: 0) client.say(channel: data.channel, text: "Base elo for team #{client.owner.name} has been unset.", gif: 'score') logger.info "UNSET: #{client.owner} - #{user.user_name} ELO has been unset" end def set_leaderboard_max(client, data, user, v) raise SlackGamebot::Error, "You're not a captain, sorry." unless v.nil? || user.captain? unless v.nil? v = parse_int_with_inifinity(v) client.owner.update_attributes!(leaderboard_max: v && v != 0 ? v : nil) end message = "Leaderboard max for team #{client.owner.name} is #{client.owner.leaderboard_max || 'not set'}." client.say(channel: data.channel, text: message, gif: 'count') logger.info "SET: #{client.owner} - #{user.user_name} LEADERBOARD MAX is #{client.owner.leaderboard_max}" end def unset_leaderboard_max(client, data, user) raise SlackGamebot::Error, "You're not a captain, sorry." unless user.captain? client.owner.update_attributes!(leaderboard_max: nil) client.say(channel: data.channel, text: "Leaderboard max for team #{client.owner.name} has been unset.", gif: 'score') logger.info "UNSET: #{client.owner} - #{user.user_name} LEADERBOARD MAX has been unset" end def set_aliases(client, data, user, v) raise SlackGamebot::Error, "You're not a captain, sorry." unless v.nil? || user.captain? unless v.nil? client.owner.update_attributes!(aliases: v.split(/[\s,;]+/)) client.aliases = client.owner.aliases end if client.owner.aliases.any? client.say(channel: data.channel, text: "Bot aliases for team #{client.owner.name} are #{client.owner.aliases.and}.", gif: 'name') logger.info "SET: #{client.owner} - #{user.user_name} Bot aliases are #{client.owner.aliases.and}" else client.say(channel: data.channel, text: "Team #{client.owner.name} does not have any bot aliases.", gif: 'name') logger.info "SET: #{client.owner} - #{user.user_name}, does not have any bot aliases" end end def unset_aliases(client, data, user) raise SlackGamebot::Error, "You're not a captain, sorry." unless user.captain? client.owner.update_attributes!(aliases: []) client.aliases = [] client.say(channel: data.channel, text: "Team #{client.owner.name} no longer has bot aliases.", gif: 'name') logger.info "UNSET: #{client.owner} - #{user.user_name} no longer has bot aliases" end def parse_int_with_inifinity(v) v == 'infinity' ? nil : parse_int(v) end def parse_int(v) Integer(v) rescue StandardError raise SlackGamebot::Error, "Sorry, #{v} is not a valid number." end def set(client, data, user, k, v) case k when 'nickname' set_nickname client, data, user, v when 'gifs' set_gifs client, data, user, v when 'leaderboard' k, v = v.split(/\s+/, 2) if v case k when 'max' set_leaderboard_max client, data, user, v else raise SlackGamebot::Error, "Invalid leaderboard setting #{k}, you can _set leaderboard max_." end when 'unbalanced' set_unbalanced client, data, user, v when 'api' set_api client, data, user, v when 'elo' set_elo client, data, user, v when 'aliases' set_aliases client, data, user, v else raise SlackGamebot::Error, "Invalid setting #{k}, you can _set gifs on|off_, _set unbalanced on|off_, _api on|off_, _leaderboard max_, _elo_, _nickname_ and _aliases_." end end def unset(client, data, user, k, v) case k when 'nickname' unset_nickname client, data, user, v when 'gifs' unset_gifs client, data, user when 'leaderboard' case v when 'max' unset_leaderboard_max client, data, user else raise SlackGamebot::Error, "Invalid leaderboard setting #{v}, you can _unset leaderboard max_." end when 'unbalanced' unset_unbalanced client, data, user when 'api' unset_api client, data, user when 'elo' unset_elo client, data, user when 'aliases' unset_aliases client, data, user else raise SlackGamebot::Error, "Invalid setting #{k}, you can _unset gifs_, _api_, _leaderboard max_, _elo_, _nickname_ and _aliases_." end end end subscribed_command 'set' do |client, data, match| user = ::User.find_create_or_update_by_slack_id!(client, data.user) if match['expression'] k, v = match['expression'].split(/\s+/, 2) set client, data, user, k, v else client.say(channel: data.channel, text: 'Missing setting, eg. _set gifs off_.', gif: 'help') logger.info "SET: #{client.owner} - #{user.user_name}, failed, missing setting" end end subscribed_command 'unset' do |client, data, match| user = ::User.find_create_or_update_by_slack_id!(client, data.user) if match['expression'] k, v = match['expression'].split(/\s+/, 2) unset client, data, user, k, v else client.say(channel: data.channel, text: 'Missing setting, eg. _unset gifs_.', gif: 'help') logger.info "UNSET: #{client.owner} - #{user.user_name}, failed, missing setting" end end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/resigned.rb
slack-gamebot/commands/resigned.rb
module SlackGamebot module Commands class Resigned < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription subscribed_command 'resigned' do |client, data, match| challenger = ::User.find_create_or_update_by_slack_id!(client, data.user) expression = match['expression'] if match['expression'] arguments = expression.split.reject(&:blank?) if expression scores = nil opponents = [] teammates = [challenger] multi_player = expression&.include?(' with ') current = :scores while arguments&.any? argument = arguments.shift case argument when 'to' current = :opponents when 'with' current = :teammates else if current == :opponents opponents << ::User.find_by_slack_mention!(client, argument) current = :scores unless multi_player elsif current == :teammates teammates << ::User.find_by_slack_mention!(client, argument) current = :scores if opponents.count == teammates.count else scores ||= [] scores << argument end end end challenge = ::Challenge.find_by_user(client.owner, data.channel, challenger, [ChallengeState::PROPOSED, ChallengeState::ACCEPTED]) if scores&.any? client.say(channel: data.channel, text: 'Cannot score when resigning.', gif: 'idiot') logger.info "RESIGNED: #{client.owner} - #{data.user}, cannot score." elsif opponents.any? && (challenge.nil? || (challenge.challengers != opponents && challenge.challenged != opponents)) match = ::Match.resign!(team: client.owner, winners: opponents, losers: teammates) client.say(channel: data.channel, text: "Match has been recorded! #{match}.", gif: 'loser') logger.info "RESIGNED TO: #{client.owner} - #{match}" elsif challenge challenge.resign!(challenger) client.say(channel: data.channel, text: "Match has been recorded! #{challenge.match}.", gif: 'loser') logger.info "RESIGNED: #{client.owner} - #{challenge}" else client.say(channel: data.channel, text: 'No challenge to resign!') logger.info "RESIGNED: #{client.owner} - #{data.user}, N/A" end end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/promote.rb
slack-gamebot/commands/promote.rb
module SlackGamebot module Commands class Promote < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription subscribed_command 'promote' do |client, data, match| user = ::User.find_create_or_update_by_slack_id!(client, data.user) arguments = match['expression'].split.reject(&:blank?) if match['expression'] users = User.find_many_by_slack_mention!(client, arguments) if arguments&.any? captains = users.select(&:captain) if users if !users client.say(channel: data.channel, text: 'Try _promote @someone_.', gif: 'help') logger.info "PROMOTE: #{client.owner} - #{user.user_name}, failed, no users" elsif !user.captain? client.say(channel: data.channel, text: "You're not a captain, sorry.", gif: 'sorry') logger.info "PROMOTE: #{client.owner} - #{user.user_name} promoting #{users.map(&:display_name).and}, failed, not captain" elsif captains && captains.count > 1 client.say(channel: data.channel, text: "#{captains.map(&:display_name).and} are already captains.") logger.info "PROMOTE: #{client.owner} - #{user.user_name} promoting #{users.map(&:display_name).and}, failed, #{captains.map(&:display_name).and} already captains" elsif captains && captains.count == 1 client.say(channel: data.channel, text: "#{captains.first.user_name} is already a captain.") logger.info "PROMOTE: #{client.owner} - #{user.user_name} promoting #{users.map(&:display_name).and}, failed, #{captains.first.user_name} already captain" else users.each(&:promote!) client.say(channel: data.channel, text: "#{users.map(&:display_name).and} #{users.count == 1 ? 'has' : 'have'} been promoted to captain.", gif: 'power') logger.info "PROMOTE: #{client.owner} - #{user.user_name} promoted #{users.map(&:display_name).and}" end end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/cancel.rb
slack-gamebot/commands/cancel.rb
module SlackGamebot module Commands class Cancel < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription subscribed_command 'cancel' do |client, data, _match| player = ::User.find_create_or_update_by_slack_id!(client, data.user) challenge = ::Challenge.find_by_user(client.owner, data.channel, player) if challenge challenge.cancel!(player) if challenge.challengers.include?(player) client.say(channel: data.channel, text: "#{challenge.challengers.map(&:display_name).and} canceled a challenge against #{challenge.challenged.map(&:display_name).and}.", gif: 'chicken') elsif challenge.challenged.include?(player) client.say(channel: data.channel, text: "#{challenge.challenged.map(&:display_name).and} canceled a challenge against #{challenge.challengers.map(&:display_name).and}.", gif: 'chicken') else client.say(channel: data.channel, text: "#{player.display_name} canceled #{challenge}.", gif: 'chicken') end logger.info "CANCEL: #{client.owner} - #{challenge}" else client.say(channel: data.channel, text: 'No challenge to cancel!') logger.info "CANCEL: #{client.owner} - #{data.user}, N/A" end end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/help.rb
slack-gamebot/commands/help.rb
module SlackGamebot module Commands class Help < SlackRubyBot::Commands::Base HELP = <<~EOS.freeze I am your friendly Gamebot, here to help. ``` General ------- hi: be nice, say hi to your bot team: show your team's info and captains register: re-register yourself as a player unregister: unregister yourself, removes you from leaderboards and challenges help: get this helpful message info: bot credits sucks: express some frustration Games ----- challenge <opponent> ... [with <teammate> ...]: challenge opponent(s) to a game challenge @here|@channel: challenge anyone to a game challenge? <opponent> ... [with <teammate> ...]: show elo at stake accept: accept a challenge decline: decline a previous challenge cancel: cancel a previous challenge lost [to <opponent>] [score, ...]: record your loss resigned [to <opponent>]: record a resignation draw [to <opponent>] [score, ...]: record a tie taunt <opponent> [<opponent> ...]: taunt players rank [<player> ...]: rank a player or a list of players matches [number|infinity]: show this season's matches Stats ----- leaderboard [number|infinity]: show the leaderboard, eg. leaderboard 10 season: show current season Settings -------- set nickname [name], unset nickname: set/unset your nickname displayed in leaderboards set leaderboard max [number|infinity], unset leaderboard max: set/unset leaderboard max set gifs [on|off]: enable/disable animated GIFs, default is on set aliases [<alias> ...], unset aliases: set/unset additional bot aliases set elo [number]: set base elo for the team set api [on|off]: enable/disable team data in the public API, default is off set unbalanced [on|off]: allow matches between different numbers of players, default is off Captains -------- promote <player>: promote a user to captain demote me: demote you from captain set nickname <player> [name], unset nickname <player>: set/unset someone's nickname seasons: show all seasons reset <team>: reset all stats, start a new season unregister <player>: remove a player from the leaderboard subscription: show subscription info (captains also see payment data) unsubscribe: do not auto-renew subscription ``` EOS def self.call(client, data, _match) client.say(channel: data.channel, text: [ HELP, client.owner.reload.subscribed? ? nil : client.owner.trial_message ].compact.join("\n")) client.say(channel: data.channel, gif: 'help') logger.info "HELP: #{client.owner} - #{data.user}" end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/info.rb
slack-gamebot/commands/info.rb
module SlackGamebot module Commands class Info < SlackRubyBot::Commands::Base def self.call(client, data, _match) client.say(channel: data.channel, text: SlackGamebot::INFO) logger.info "INFO: #{client.owner} - #{data.user}" end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/matches.rb
slack-gamebot/commands/matches.rb
module SlackGamebot module Commands class Matches < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription subscribed_command 'matches' do |client, data, match| totals = {} totals.default = 0 arguments = match['expression'].split.reject(&:blank?) if match['expression'] # limit max = 10 if arguments&.any? case arguments.last.downcase when 'infinity' max = nil else begin Integer(arguments.last).tap do |value| max = value arguments.pop end rescue ArgumentError # ignore end end end # users team = client.owner users = ::User.find_many_by_slack_mention!(client, arguments) if arguments&.any? user_ids = users.map(&:id) if users&.any? matches = team.matches.current matches = matches.any_of({ :winner_ids.in => user_ids }, :loser_ids.in => user_ids) if user_ids&.any? matches.each do |m| totals[m.to_s] += 1 end totals = totals.sort_by { |_, value| -value } totals = totals.take(max) if max message = totals.map do |s, count| case count when 1 "#{s} once" when 2 "#{s} twice" else "#{s} #{count} times" end end.join("\n") client.say(channel: data.channel, text: message.empty? ? 'No matches.' : message) logger.info "MATCHES: #{team} - #{data.user}" end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/seasons.rb
slack-gamebot/commands/seasons.rb
module SlackGamebot module Commands class Seasons < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription subscribed_command 'seasons' do |client, data, _match| current_season = ::Season.new(team: client.owner) if current_season.valid? message = [current_season, client.owner.seasons.desc(:_id)].flatten.map(&:to_s).join("\n") client.say(channel: data.channel, text: message) elsif ::Season.where(team: client.owner).any? # don't use client.owner.seasons, would include current_season message = client.owner.seasons.desc(:_id).map(&:to_s).join("\n") client.say(channel: data.channel, text: message) else client.say(channel: data.channel, text: "There're no seasons.", gif: %w[winter summer fall spring].sample) end logger.info "SEASONS: #{client.owner} - #{data.user}" end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/unsubscribe.rb
slack-gamebot/commands/unsubscribe.rb
module SlackGamebot module Commands class Unsubscribe < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription subscribed_command 'unsubscribe' do |client, data, match| user = ::User.find_create_or_update_by_slack_id!(client, data.user) team = ::Team.find(client.owner.id) if !team.stripe_customer_id client.say(channel: data.channel, text: "You don't have a paid subscription, all set.") logger.info "UNSUBSCRIBE: #{client.owner} - #{user.user_name} unsubscribe failed, no subscription" elsif user.captain? && team.active_stripe_subscription? subscription_info = [] subscription_id = match['expression'] active_subscription = team.active_stripe_subscription if active_subscription && active_subscription.id == subscription_id active_subscription.delete(at_period_end: true) amount = ActiveSupport::NumberHelper.number_to_currency(active_subscription.plan.amount.to_f / 100) subscription_info << "Successfully canceled auto-renew for #{active_subscription.plan.name} (#{amount})." logger.info "UNSUBSCRIBE: #{client.owner} - #{data.user}, canceled #{subscription_id}" elsif subscription_id subscription_info << "Sorry, I cannot find a subscription with \"#{subscription_id}\"." else subscription_info.concat(team.stripe_customer_subscriptions_info(true)) end client.say(channel: data.channel, text: subscription_info.compact.join("\n")) logger.info "UNSUBSCRIBE: #{client.owner} - #{data.user}" else client.say(channel: data.channel, text: "You're not a captain, sorry.", gif: 'sorry') logger.info "UNSUBSCRIBE: #{client.owner} - #{user.user_name} unsubscribe failed, not captain" end end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/team.rb
slack-gamebot/commands/team.rb
module SlackGamebot module Commands class Team < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription subscribed_command 'team' do |client, data, _match| ::User.find_create_or_update_by_slack_id!(client, data.user) captains = if client.owner.captains.count == 1 ", captain #{client.owner.captains.first.user_name}" elsif client.owner.captains.count > 1 ", captains #{client.owner.captains.map(&:display_name).and}" end client.say(channel: data.channel, text: "Team _#{client.owner.name}_ (#{client.owner.team_id})#{captains}.", gif: 'team') logger.info "TEAM: #{client.owner} - #{data.user}" end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/challenge_question.rb
slack-gamebot/commands/challenge_question.rb
module SlackGamebot module Commands class ChallengeQuestion < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription subscribed_command 'challenge?' do |client, data, match| challenger = ::User.find_create_or_update_by_slack_id!(client, data.user) arguments = match['expression'].split.reject(&:blank?) if match['expression'] arguments ||= [] challenge = ::Challenge.new_from_teammates_and_opponents(client, data.channel, challenger, arguments) match = ::Match.new(team: client.owner, winners: challenge.challengers, losers: challenge.challenged, scores: []) client.say(channel: data.channel, text: "#{challenge.challengers.map(&:slack_mention).and} challenging #{challenge.challenged.map(&:slack_mention).and} to a match is worth #{match.elo_s} elo.", gif: 'challenge') logger.info "CHALLENGE?: #{client.owner} - #{challenge}" end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/rank.rb
slack-gamebot/commands/rank.rb
module SlackGamebot module Commands class Rank < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription subscribed_command 'rank' do |client, data, match| arguments = match['expression'].split.reject(&:blank?) if match['expression'] users = arguments || [] if arguments&.any? users = User.find_many_by_slack_mention!(client, users) else users << ::User.find_create_or_update_by_slack_id!(client, data.user) end message = User.rank_section(client.owner, users).map do |user| user.rank ? "#{user.rank}. #{user}" : "#{user.user_name}: not ranked" end.join("\n") client.say(channel: data.channel, text: message) logger.info "RANK: #{client.owner} - #{users.map(&:display_name).and}" end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/sucks.rb
slack-gamebot/commands/sucks.rb
module SlackGamebot module Commands class Sucks < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription subscribed_command 'sucks', 'suck', 'you suck', 'sucks!', 'you suck!' do |client, data, _match| user = ::User.find_create_or_update_by_slack_id!(client, data.user) if user.losses && user.losses > 5 client.say(channel: data.channel, text: "No <@#{data.user}>, with #{user.losses} losses, you suck!", gif: 'loser') elsif user.rank && user.rank > 3 client.say(channel: data.channel, text: "No <@#{data.user}>, with a rank of #{user.rank}, you suck!", gif: 'loser') else client.say(channel: data.channel, text: "No <@#{data.user}>, you suck!", gif: 'rude') end logger.info "SUCKS: #{client.owner} - #{data.user}" end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/accept.rb
slack-gamebot/commands/accept.rb
module SlackGamebot module Commands class Accept < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription subscribed_command 'accept' do |client, data, _match| challenger = ::User.find_create_or_update_by_slack_id!(client, data.user) challenge = ::Challenge.find_by_user(client.owner, data.channel, challenger) challenge ||= ::Challenge.find_open_challenge(client.owner, data.channel) if challenge challenge.accept!(challenger) client.say(channel: data.channel, text: "#{challenge.challenged.map(&:display_name).and} accepted #{challenge.challengers.map(&:display_name).and}'s challenge.", gif: 'game') logger.info "ACCEPT: #{client.owner} - #{challenge}" else client.say(channel: data.channel, text: 'No challenge to accept!') logger.info "ACCEPT: #{client.owner} - #{data.user}, N/A" end end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/mixins.rb
slack-gamebot/commands/mixins.rb
require 'slack-gamebot/commands/mixins/subscription'
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/leaderboard.rb
slack-gamebot/commands/leaderboard.rb
module SlackGamebot module Commands class Leaderboard < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription subscribed_command 'leaderboard' do |client, data, match| max = client.owner.leaderboard_max reverse = false arguments = match['expression'].split.reject(&:blank?) if match['expression'] arguments ||= [] number = arguments.shift if number if number[0] == '-' reverse = true number = number[1..-1] end max = case number.downcase when 'infinity' nil else Integer(number) end end ranked_players = client.owner.users.ranked if ranked_players.any? ranked_players = ranked_players.send(reverse ? :desc : :asc, :rank) ranked_players = ranked_players.limit(max) if max && max >= 1 message = ranked_players.each_with_index.map do |user, index| "#{reverse ? index + 1 : user.rank}. #{user}" end.join("\n") client.say(channel: data.channel, text: message) else client.say(channel: data.channel, text: "There're no ranked players.", gif: 'empty') end logger.info "LEADERBOARD #{max || '∞'}: #{client.owner} - #{data.user}" end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/register.rb
slack-gamebot/commands/register.rb
module SlackGamebot module Commands class Register < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription subscribed_command 'register' do |client, data, _match| ts = Time.now.utc user = ::User.find_create_or_update_by_slack_id!(client, data.user) user.register! if user && !user.registered? message = if user.created_at >= ts "Welcome <@#{data.user}>! You're ready to play." elsif user.updated_at >= ts "Welcome back <@#{data.user}>, I've updated your registration." else "Welcome back <@#{data.user}>, you're already registered." end message += " You're also team captain." if user.captain? client.say(channel: data.channel, text: message, gif: 'welcome') logger.info "REGISTER: #{client.owner} - #{data.user}" user end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/reset.rb
slack-gamebot/commands/reset.rb
module SlackGamebot module Commands class Reset < SlackRubyBot::Commands::Base include SlackGamebot::Commands::Mixins::Subscription subscribed_command 'reset' do |client, data, match| user = ::User.find_create_or_update_by_slack_id!(client, data.user) if !user.captain? client.say(channel: data.channel, text: "You're not a captain, sorry.", gif: 'sorry') logger.info "RESET: #{client.owner} - #{user.user_name}, failed, not captain" elsif !match['expression'] client.say(channel: data.channel, text: "Missing team name or id, confirm with _reset #{user.team.name}_ or _reset #{user.team.team_id}_.", gif: 'help') logger.info "RESET: #{client.owner} - #{user.user_name}, failed, missing team name" elsif match['expression'] != user.team.name && match['expression'] != user.team.team_id client.say(channel: data.channel, text: "Invalid team name or id, confirm with _reset #{user.team.name}_ or _reset #{user.team.team_id}_.", gif: 'help') logger.info "RESET: #{client.owner} - #{user.user_name}, failed, invalid team name '#{match['expression']}'" else ::Season.create!(team: user.team, created_by: user) client.say(channel: data.channel, text: 'Welcome to the new season!', gif: 'season') logger.info "RESET: #{client.owner} - #{data.user}" end end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/commands/mixins/subscription.rb
slack-gamebot/commands/mixins/subscription.rb
module SlackGamebot module Commands module Mixins module Subscription extend ActiveSupport::Concern module ClassMethods def subscribed_command(*values, &) command(*values) do |client, data, match| if Stripe.api_key && client.owner.reload.subscription_expired? client.say channel: data.channel, text: client.owner.trial_message logger.info "#{client.owner}, user=#{data.user}, text=#{data.text}, subscribed feature required" else yield client, data, match end end end end end end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/models/season.rb
slack-gamebot/models/season.rb
class Season include Mongoid::Document include Mongoid::Timestamps::Created belongs_to :team, index: true belongs_to :created_by, class_name: 'User', inverse_of: nil, index: true, optional: true has_many :challenges has_many :matches embeds_many :user_ranks after_create :archive_challenges! after_create :reset_users! validate :validate_challenges validate :validate_teams validates_presence_of :team SORT_ORDERS = ['created_at', '-created_at'].freeze def initialize(attrs = {}) super create_user_ranks end def to_s [ "#{label}: #{winners ? winners.map(&:to_s).and : 'n/a'}", "#{team.matches.count} match#{'es' unless team.matches.count == 1}", "#{players.count} player#{'s' unless players.count == 1}" ].join(', ') end def winners min = user_ranks.min(:rank) user_ranks.asc(:id).where(rank: min) if min end def players user_ranks.where(:rank.ne => nil) end private def validate_teams teams = [team] teams.concat(challenges.map(&:team)) teams.uniq! errors.add(:team, 'Season can only be recorded for one team.') if teams.count != 1 end def played_challenges persisted? ? challenges.played : team.challenges.current.played end def label persisted? ? created_at.strftime('%F') : 'Current' end def validate_challenges return if team.matches.current.any? || team.challenges.current.any? errors.add(:challenges, 'No matches have been recorded.') end def create_user_ranks return if user_ranks.any? team.users.ranked.asc(:rank).asc(:_id).each do |user| user_ranks << UserRank.from_user(user) end end def archive_challenges! team.challenges.where( :state.in => [ ChallengeState::PROPOSED, ChallengeState::ACCEPTED, ChallengeState::DRAWN ] ).set( state: ChallengeState::CANCELED, updated_by_id: created_by&.id ) team.challenges.current.set(season_id: id) team.matches.current.set(season_id: id) end def reset_users! User.reset_all!(team) end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/models/elo.rb
slack-gamebot/models/elo.rb
module Elo DELTA_TAU = 0.94 MAX_TAU = 11 def self.team_elo(players) (players.sum(&:elo).to_f / players.count).round(2) end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/models/user_rank.rb
slack-gamebot/models/user_rank.rb
class UserRank include Mongoid::Document belongs_to :user field :user_name, type: String field :wins, type: Integer, default: 0 field :losses, type: Integer, default: 0 field :elo, type: Integer, default: 0 field :elo_history, type: Array, default: [] field :tau, type: Float, default: 0 field :rank, type: Integer scope :ranked, -> { where(:rank.ne => nil) } def self.from_user(user) UserRank.new.tap do |user_rank| user_rank.user = user user_rank.user_name = user.user_name user_rank.wins = user.wins user_rank.losses = user.losses user_rank.elo = user.elo user_rank.elo_history = user.elo_history user_rank.tau = user.tau user_rank.rank = user.rank end end def team_elo user&.team ? elo + user.team.elo : elo end def to_s "#{user_name}: #{wins} win#{'s' unless wins == 1}, #{losses} loss#{'es' unless losses == 1} (elo: #{team_elo})" end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/models/score.rb
slack-gamebot/models/score.rb
module Score # returns loser, winner points def self.points(scores) winning = 0 losing = 0 scores.each do |score| losing += score[0] winning += score[1] end [losing, winning] end # loser scores first def self.valid?(scores) scores.count { |score| score[0] < score[1] } > scores.count / 2 end # draw scores? def self.tie?(scores) points = Score.points(scores) points[0] == points[1] end # parse scores from a string def self.parse(expression) return unless expression scores = [] expression.split(/[\s,.]/).reject(&:blank?).each do |pair| scores << check(pair) end scores end def self.check(pair) pair_n = if pair.include?(':') pair.split(':') if pair.include?(':') elsif pair.include?('-') pair.split('-') elsif pair.include?(',') pair.split(',') end raise SlackGamebot::Error, "Invalid score: #{pair}." unless pair_n && pair_n.length == 2 pair_n.map do |points| points = Integer(points) raise SlackGamebot::Error, 'points must be greater or equal to zero' if points < 0 points rescue StandardError => e raise SlackGamebot::Error, "Invalid score: #{pair}, #{e}." end end def self.scores_to_string(scores) [ scores.count > 1 ? 'the scores of' : 'the score of', scores.map do |score| "#{score[1]}:#{score[0]}" end ].flatten.join(' ') end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/models/game.rb
slack-gamebot/models/game.rb
class Game include Mongoid::Document include Mongoid::Timestamps SORT_ORDERS = ['created_at', '-created_at', 'updated_at', '-updated_at'].freeze field :name, type: String index(name: 1) field :bot_name, type: String field :client_id, type: String field :client_secret, type: String field :aliases, type: Array, default: [] validates_uniqueness_of :client_id, message: 'already exists' has_many :teams before_destroy :check_teams! def users User.where(:team_id.in => teams.distinct(:_id)) end def matches Match.where(:team_id.in => teams.distinct(:_id)) end def challenges Challenge.where(:team_id.in => teams.distinct(:_id)) end def seasons Season.where(:team_id.in => teams.distinct(:_id)) end def to_s { name:, client_id:, aliases: }.map do |k, v| "#{k}=#{v}" if v end.compact.join(', ') end def self.find_or_create_from_env! client_id = ENV.fetch('SLACK_CLIENT_ID', nil) client_secret = ENV.fetch('SLACK_CLIENT_SECRET', nil) return unless client_id && client_secret game = Game.where(client_id:).first game ||= Game.new(client_id:) game.client_id = client_id game.client_secret = client_secret game.aliases = ENV['SLACK_RUBY_BOT_ALIASES'].split if ENV.key?('SLACK_RUBY_BOT_ALIASES') game.save! game end private def check_teams! raise SlackGamebot::Error, 'The game has teams and cannot be destroyed.' if teams.any? end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/models/challenge.rb
slack-gamebot/models/challenge.rb
class Challenge include Mongoid::Document include Mongoid::Timestamps index(state: 1, channel: 1) SORT_ORDERS = ['created_at', '-created_at', 'updated_at', '-updated_at', 'state', '-state', 'channel', '-channel'].freeze field :state, type: String, default: ChallengeState::PROPOSED field :channel, type: String belongs_to :team, index: true belongs_to :season, inverse_of: :challenges, index: true, optional: true belongs_to :created_by, class_name: 'User', inverse_of: nil, index: true, optional: true belongs_to :updated_by, class_name: 'User', inverse_of: nil, index: true, optional: true has_and_belongs_to_many :challengers, class_name: 'User', inverse_of: nil has_and_belongs_to_many :challenged, class_name: 'User', inverse_of: nil field :draw_scores, type: Array has_and_belongs_to_many :draw, class_name: 'User', inverse_of: nil has_one :match index({ challenger_ids: 1, state: 1 }, name: 'active_challenger_index') index({ challenged_ids: 1, state: 1 }, name: 'active_challenged_index') validate :validate_playing_against_themselves validate :validate_opponents_counts validate :validate_unique_challenge validate :validate_teams validate :validate_updated_by validate :validate_draw_scores validates_presence_of :updated_by, if: ->(challenge) { challenge.state != ChallengeState::PROPOSED } validates_presence_of :team # current challenges are not in an archived season scope :current, -> { where(season_id: nil) } # challenges scoped by state ChallengeState.values.each do |state| scope state.to_sym, -> { where(state:) } end # Given a challenger and a list of names splits into two groups, returns users. def self.split_teammates_and_opponents(client, challenger, names, separator = 'with') teammates = [challenger] opponents = [] current_side = opponents names.each do |name| if name == separator current_side = teammates else current_side << ::User.find_by_slack_mention!(client, name) end end [teammates, opponents] end def self.new_from_teammates_and_opponents(client, channel, challenger, names, separator = 'with') teammates, opponents = split_teammates_and_opponents(client, challenger, names, separator) Challenge.new( team: client.owner, channel:, created_by: challenger, challengers: teammates, challenged: opponents, state: ChallengeState::PROPOSED ) end def self.create_from_teammates_and_opponents!(client, channel, challenger, names, separator = 'with') new_from_teammates_and_opponents(client, channel, challenger, names, separator).tap(&:save!) end def accept!(challenger) raise SlackGamebot::Error, "Challenge has already been #{state}." unless state == ChallengeState::PROPOSED updates = { updated_by: challenger, state: ChallengeState::ACCEPTED } updates[:challenged_ids] = [challenger._id] if open_challenge? update_attributes!(updates) end def decline!(challenger) raise SlackGamebot::Error, "Challenge has already been #{state}." unless state == ChallengeState::PROPOSED update_attributes!(updated_by: challenger, state: ChallengeState::DECLINED) end def cancel!(challenger) raise SlackGamebot::Error, "Challenge has already been #{state}." unless [ChallengeState::PROPOSED, ChallengeState::ACCEPTED].include?(state) update_attributes!(updated_by: challenger, state: ChallengeState::CANCELED) end def lose!(loser, scores = nil) raise SlackGamebot::Error, 'Challenge must first be accepted.' if state == ChallengeState::PROPOSED raise SlackGamebot::Error, "Challenge has already been #{state}." unless state == ChallengeState::ACCEPTED winners, losers = winners_and_losers_for(loser) Match.lose!(team:, challenge: self, winners:, losers:, scores:) update_attributes!(state: ChallengeState::PLAYED) end def winners_and_losers_for(loser) if challenged.include?(loser) [challengers, challenged] elsif challengers.include?(loser) [challenged, challengers] else raise SlackGamebot::Error, "Only #{(challenged + challengers).map(&:user_name).or} can lose this challenge." end end def resign!(loser, scores = nil) raise SlackGamebot::Error, 'Challenge must first be accepted.' if state == ChallengeState::PROPOSED raise SlackGamebot::Error, "Challenge has already been #{state}." unless state == ChallengeState::ACCEPTED winners, losers = winners_and_losers_for_resigned(loser) Match.resign!(team:, challenge: self, winners:, losers:, scores:) update_attributes!(state: ChallengeState::PLAYED) end def winners_and_losers_for_resigned(loser) if challenged.include?(loser) [challengers, challenged] elsif challengers.include?(loser) [challenged, challengers] else raise SlackGamebot::Error, "Only #{(challenged + challengers).map(&:user_name).or} can resign this challenge." end end def draw!(player, scores = nil) raise SlackGamebot::Error, 'Challenge must first be accepted.' if state == ChallengeState::PROPOSED raise SlackGamebot::Error, "Challenge has already been #{state}." unless [ChallengeState::ACCEPTED, ChallengeState::DRAWN].include?(state) raise SlackGamebot::Error, "Already recorded a draw from #{player.user_name}." if draw.include?(player) draw << player update_attributes!(state: ChallengeState::DRAWN) update_attributes!(draw_scores: scores) if scores return if draw.count != (challenged.count + challengers.count) # in a draw, winners have a lower original elo winners, losers = winners_and_losers_for_draw(player) Match.draw!(team:, challenge: self, winners:, losers:, scores:) update_attributes!(state: ChallengeState::PLAYED) end def winners_and_losers_for_draw(player) raise SlackGamebot::Error, "Only #{(challenged + challengers).map(&:user_name).or} can draw this challenge." unless challenged.include?(player) || challengers.include?(player) if Elo.team_elo(challenged) < Elo.team_elo(challengers) [challenged, challengers] else [challengers, challenged] end end def to_s "a challenge between #{challengers.map(&:display_name).and} and #{challenged.map(&:display_name).and}" end def self.find_by_user(team, channel, player, states = [ChallengeState::PROPOSED, ChallengeState::ACCEPTED]) Challenge.any_of( { challenger_ids: player._id }, challenged_ids: player._id ).where( team:, channel:, :state.in => states ).first end def self.find_open_challenge(team, channel, states = [ChallengeState::PROPOSED]) Challenge.where( team:, challenged_ids: team.users.everyone.map(&:_id), channel:, :state.in => states ).first end def open_challenge? challenged.any?(&:anyone?) end def draw_scores? draw_scores&.any? end private def validate_playing_against_themselves intersection = challengers & challenged errors.add(:challengers, "Player #{intersection.first.user_name} cannot play against themselves.") if intersection.any? end def validate_opponents_counts return if challengers.any? && challenged.any? && (challengers.count == challenged.count || team.unbalanced) errors.add(:challenged, "Number of teammates (#{challengers.count}) and opponents (#{challenged.count}) must match.") end def validate_teams teams = [team] teams.concat(challengers.map(&:team)) teams.concat(challenged.map(&:team)) teams << match.team if match teams << season.team if season teams.uniq! errors.add(:team, 'Can only play others on the same team.') if teams.count != 1 end def validate_unique_challenge return unless [ChallengeState::PROPOSED, ChallengeState::ACCEPTED].include?(state) (challengers + challenged).each do |player| existing_challenge = ::Challenge.find_by_user(team, channel, player) next unless existing_challenge.present? next if existing_challenge == self errors.add(:challenge, "#{player.user_name} can't play. There's already #{existing_challenge}.") end end def validate_updated_by case state when ChallengeState::ACCEPTED return if updated_by && challenged.include?(updated_by) errors.add(:accepted_by, "Only #{challenged.map(&:display_name).and} can accept this challenge.") when ChallengeState::DECLINED return if updated_by && challenged.include?(updated_by) errors.add(:declined_by, "Only #{challenged.map(&:display_name).and} can decline this challenge.") when ChallengeState::CANCELED return if updated_by && (challengers.include?(updated_by) || challenged.include?(updated_by)) errors.add(:declined_by, "Only #{challengers.map(&:display_name).and} or #{challenged.map(&:display_name).and} can cancel this challenge.") end end def validate_draw_scores return unless draw_scores return if Score.tie?(draw_scores) errors.add(:scores, 'In a tie both sides must score the same number of points.') end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/models/match.rb
slack-gamebot/models/match.rb
class Match include Mongoid::Document include Mongoid::Timestamps SORT_ORDERS = ['created_at', '-created_at'].freeze belongs_to :team, index: true field :tied, type: Boolean, default: false field :resigned, type: Boolean, default: false field :scores, type: Array belongs_to :challenge, index: true, optional: true belongs_to :season, inverse_of: :matches, index: true, optional: true before_create :calculate_elo! after_create :update_users! validate :validate_scores, unless: :tied? validate :validate_tied_scores, if: :tied? validate :validate_resigned_scores, if: :resigned? validate :validate_tied_resigned validates_presence_of :team validate :validate_teams has_and_belongs_to_many :winners, class_name: 'User', inverse_of: nil has_and_belongs_to_many :losers, class_name: 'User', inverse_of: nil # current matches are not in an archived season scope :current, -> { where(season_id: nil) } def scores? scores&.any? end def to_s if resigned? "#{losers.map(&:display_name).and} resigned against #{winners.map(&:display_name).and}" else [ "#{winners.map(&:display_name).and} #{score_verb} #{losers.map(&:display_name).and}", scores ? "with #{Score.scores_to_string(scores)}" : nil ].compact.join(' ') end end def self.lose!(attrs) Match.create!(attrs) end def self.resign!(attrs) Match.create!(attrs.merge(resigned: true)) end def self.draw!(attrs) Match.create!(attrs.merge(tied: true)) end def update_users! if tied? winners.inc(ties: 1) losers.inc(ties: 1) else winners.inc(wins: 1) losers.inc(losses: 1) end winners.each(&:calculate_streaks!) losers.each(&:calculate_streaks!) User.rank!(team) end def elo_s winners_delta, losers_delta = calculated_elo if (winners_delta | losers_delta).same? winners_delta.first.to_i.to_s elsif winners_delta.same? && losers_delta.same? [winners_delta.first, losers_delta.first].map(&:to_i).and else (winners_delta | losers_delta).map(&:to_i).and end end private def validate_teams teams = [team] teams << challenge.team if challenge teams.uniq! errors.add(:team, 'Match can only be recorded for the same team.') if teams.count != 1 end def validate_scores return unless scores&.any? errors.add(:scores, 'Loser scores must come first.') unless Score.valid?(scores) end def validate_tied_scores return unless scores&.any? errors.add(:scores, 'In a tie both sides must have the same number of points.') unless Score.tie?(scores) end def validate_resigned_scores return unless scores&.any? errors.add(:scores, 'Cannot score when resigning.') end def validate_tied_resigned errors.add(:tied, 'Cannot be tied and resigned.') if tied? && resigned? end def score_verb if tied? 'tied with' elsif !scores 'defeated' else lose, win = Score.points(scores) ratio = lose.to_f / win if ratio > 0.9 'narrowly defeated' elsif ratio > 0.4 'defeated' else 'crushed' end end end def calculated_elo @calcualted_elo ||= begin winners_delta = [] losers_delta = [] winners_elo = Elo.team_elo(winners) losers_elo = Elo.team_elo(losers) losers_ratio = losers.any? ? [winners.size.to_f / losers.size, 1].min : 1 winners_ratio = winners.any? ? [losers.size.to_f / winners.size, 1].min : 1 ratio = if winners_elo == losers_elo && tied? 0 # no elo updates when tied and elo is equal elsif tied? 0.5 # half the elo in a tie else 1 # whole elo end winners.each do |winner| e = 100 - (1.0 / (1.0 + (10.0**((losers_elo - winner.elo) / 400.0))) * 100) winner.tau = [winner.tau + 0.5, Elo::MAX_TAU].min delta = e * ratio * (Elo::DELTA_TAU**winner.tau) * winners_ratio winners_delta << delta winner.elo += delta end losers.each do |loser| e = 100 - (1.0 / (1.0 + (10.0**((loser.elo - winners_elo) / 400.0))) * 100) loser.tau = [loser.tau + 0.5, Elo::MAX_TAU].min delta = e * ratio * (Elo::DELTA_TAU**loser.tau) * losers_ratio losers_delta << delta loser.elo -= delta end [losers_delta, winners_delta] end end def calculate_elo! calculated_elo winners.each(&:save!) losers.each(&:save!) end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/models/challenge_state.rb
slack-gamebot/models/challenge_state.rb
class ChallengeState include Ruby::Enum define :PROPOSED, 'proposed' define :ACCEPTED, 'accepted' define :DECLINED, 'declined' define :CANCELED, 'canceled' define :DRAWN, 'drawing' define :PLAYED, 'played' end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/models/team.rb
slack-gamebot/models/team.rb
class Team field :gifs, type: Boolean, default: true field :api, type: Boolean, default: false field :aliases, type: Array, default: [] field :dead_at, type: DateTime field :trial_informed_at, type: DateTime field :elo, type: Integer, default: 0 field :unbalanced, type: Boolean, default: false field :leaderboard_max, type: Integer field :stripe_customer_id, type: String field :subscribed, type: Boolean, default: false field :subscribed_at, type: DateTime scope :api, -> { where(api: true) } scope :subscribed, -> { where(subscribed: true) } validates_presence_of :game_id has_many :users, dependent: :destroy has_many :seasons, dependent: :destroy has_many :matches, dependent: :destroy has_many :challenges, dependent: :destroy belongs_to :game before_validation :update_subscribed_at after_update :subscribed! after_save :activated! def subscription_expired? return false if subscribed? time_limit = Time.now.utc - 2.weeks return false if created_at > time_limit true end def trial_ends_at raise 'Team is subscribed.' if subscribed? created_at + 2.weeks end def remaining_trial_days raise 'Team is subscribed.' if subscribed? [0, (trial_ends_at.to_date - Time.now.utc.to_date).to_i].max end def trial_message [ if remaining_trial_days.zero? 'Your trial subscription has expired.' else "Your trial subscription expires in #{remaining_trial_days} day#{'s' unless remaining_trial_days == 1}." end, subscribe_text ].join(' ') end def inform_trial! return if subscribed? || subscription_expired? return if trial_informed_at && (Time.now.utc < trial_informed_at + 7.days) inform! trial_message inform_admin! trial_message update_attributes!(trial_informed_at: Time.now.utc) end def subscribe_text "Subscribe your team for $29.99 a year at #{SlackRubyBotServer::Service.url}/subscribe?team_id=#{team_id}&game=#{game.name}." end def update_cc_text "Update your credit card info at #{SlackRubyBotServer::Service.url}/update_cc?team_id=#{team_id}&game=#{game.name}." end def captains users.captains end def to_s { game: game.name, name:, domain:, id: team_id }.map do |k, v| "#{k}=#{v}" if v end.compact.join(', ') end def asleep?(dt = 2.weeks) time_limit = Time.now.utc - dt return false if created_at > time_limit recent_match = matches.desc(:updated_at).limit(1).first return false if recent_match && recent_match.updated_at >= time_limit recent_challenge = challenges.desc(:updated_at).limit(1).first return false if recent_challenge && recent_challenge.updated_at >= time_limit true end def dead?(dt = 1.month) asleep?(dt) end def dead!(message, gif = nil) inform! message, gif inform_admin! message, gif ensure update_attributes!(dead_at: Time.now.utc) end def api_url return unless api? "#{SlackRubyBotServer::Service.api_url}/teams/#{id}" end def slack_client @slack_client ||= Slack::Web::Client.new(token:) end def slack_channels raise 'missing bot_user_id' unless bot_user_id channels = [] slack_client.users_conversations( user: bot_user_id, exclude_archived: true, types: 'public_channel,private_channel' ) do |response| channels.concat(response.channels) end channels end def inform!(message, gif_name = nil) slack_channels.each do |channel| logger.info "Sending '#{message}' to #{self} on ##{channel['name']}." slack_client.chat_postMessage(text: make_message(message, gif_name), channel: channel['id'], as_user: true) end end def inform_admin!(message, gif_name = nil) return unless activated_user_id channel = slack_client.conversations_open(users: activated_user_id.to_s) logger.info "Sending DM '#{message}' to #{activated_user_id}." slack_client.chat_postMessage(text: make_message(message, gif_name), channel: channel.channel.id, as_user: true) end def self.find_or_create_from_env! token = ENV.fetch('SLACK_API_TOKEN', nil) return unless token team = Team.where(token:).first team ||= Team.new(token:) info = Slack::Web::Client.new(token:).team_info team.team_id = info['team']['id'] team.name = info['team']['name'] team.domain = info['team']['domain'] team.game = Game.first || Game.create!(name: 'default') team.save! team end def stripe_customer return unless stripe_customer_id @stripe_customer ||= Stripe::Customer.retrieve(stripe_customer_id) end def stripe_customer_text "Customer since #{Time.at(stripe_customer.created).strftime('%B %d, %Y')}." end def subscriber_text return unless subscribed_at "Subscriber since #{subscribed_at.strftime('%B %d, %Y')}." end def stripe_subcriptions return unless stripe_customer stripe_customer.subscriptions end def stripe_customer_subscriptions_info(with_unsubscribe = false) stripe_customer.subscriptions.map do |subscription| amount = ActiveSupport::NumberHelper.number_to_currency(subscription.plan.amount.to_f / 100) current_period_end = Time.at(subscription.current_period_end).strftime('%B %d, %Y') if subscription.status == 'active' [ "Subscribed to #{subscription.plan.name} (#{amount}), will#{' not' if subscription.cancel_at_period_end} auto-renew on #{current_period_end}.", !subscription.cancel_at_period_end && with_unsubscribe ? "Send `unsubscribe #{subscription.id}` to unsubscribe." : nil ].compact.join("\n") else "#{subscription.status.titleize} subscription created #{Time.at(subscription.created).strftime('%B %d, %Y')} to #{subscription.plan.name} (#{amount})." end end end def stripe_customer_invoices_info stripe_customer.invoices.map do |invoice| amount = ActiveSupport::NumberHelper.number_to_currency(invoice.amount_due.to_f / 100) "Invoice for #{amount} on #{Time.at(invoice.date).strftime('%B %d, %Y')}, #{invoice.paid ? 'paid' : 'unpaid'}." end end def stripe_customer_sources_info stripe_customer.sources.map do |source| "On file #{source.brand} #{source.object}, #{source.name} ending with #{source.last4}, expires #{source.exp_month}/#{source.exp_year}." end end def active_stripe_subscription? !active_stripe_subscription.nil? end def active_stripe_subscription return unless stripe_customer stripe_customer.subscriptions.detect do |subscription| subscription.status == 'active' && !subscription.cancel_at_period_end end end def tags [ subscribed? ? 'subscribed' : 'trial', stripe_customer_id? ? 'paid' : nil ].compact end def ping_if_active! return unless active? ping! rescue Slack::Web::Api::Errors::SlackError => e logger.warn "Active team #{self} ping, #{e.message}." case e.message when 'account_inactive', 'invalid_auth' deactivate! end end private SUBSCRIBED_TEXT = <<~EOS.freeze Your team has been subscribed. Thank you! Follow https://twitter.com/playplayio for news and updates. EOS def make_message(message, gif_name = nil) gif = Giphy.random(gif_name) if gif_name && gifs? [message, gif].compact.join("\n") end def update_subscribed_at return unless subscribed? && (subscribed_changed? || saved_change_to_subscribed?) self.subscribed_at = subscribed? ? DateTime.now.utc : nil end def subscribed! return unless subscribed? && (subscribed_changed? || saved_change_to_subscribed?) inform! SUBSCRIBED_TEXT, 'thanks' end def bot_mention "<@#{bot_user_id || 'bot'}>" end def activated_text <<~EOS Welcome! Invite #{bot_mention} to a channel to get started. EOS end def activated! return unless active? && activated_user_id && bot_user_id return unless (active_changed? || saved_change_to_active?) || (activated_user_id_changed? || saved_change_to_activated_user_id?) inform_activated! end def inform_activated! im = slack_client.conversations_open(users: activated_user_id.to_s) slack_client.chat_postMessage( text: activated_text, channel: im['channel']['id'], as_user: true ) end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/models/user.rb
slack-gamebot/models/user.rb
class User include Mongoid::Document include Mongoid::Timestamps field :user_id, type: String field :user_name, type: String field :wins, type: Integer, default: 0 field :losses, type: Integer, default: 0 field :losing_streak, type: Integer, default: 0 field :winning_streak, type: Integer, default: 0 field :ties, type: Integer, default: 0 field :elo, type: Integer, default: 0 field :elo_history, type: Array, default: [] field :tau, type: Float, default: 0 field :rank, type: Integer field :captain, type: Boolean, default: false field :registered, type: Boolean, default: true field :nickname, type: String belongs_to :team, index: true validates_presence_of :team index({ user_id: 1, team_id: 1 }, unique: true) index(user_name: 1, team_id: 1) index(wins: 1, team_id: 1) index(losses: 1, team_id: 1) index(ties: 1, team_id: 1) index(elo: 1, team_id: 1) before_save :update_elo_history! after_save :rank! SORT_ORDERS = ['elo', '-elo', 'created_at', '-created_at', 'wins', '-wins', 'losses', '-losses', 'ties', '-ties', 'user_name', '-user_name', 'rank', '-rank'].freeze ANYONE = '*'.freeze EVERYONE = %w[here channel].freeze scope :ranked, -> { where(:rank.ne => nil) } scope :captains, -> { where(captain: true) } scope :everyone, -> { where(user_id: ANYONE) } def current_matches Match.current.where(team:).any_of({ winner_ids: _id }, loser_ids: _id) end def slack_mention anyone? ? 'anyone' : "<@#{user_id}>" end def display_name registered ? nickname || user_name : '<unregistered>' end def anyone? user_id == ANYONE end def self.slack_mention?(user_name) slack_id = ::Regexp.last_match[1] if user_name =~ /^<[@!](.*)>$/ slack_id = ANYONE if slack_id && EVERYONE.include?(slack_id) slack_id end def self.find_by_slack_mention!(client, user_name) team = client.owner slack_id = slack_mention?(user_name) user = if slack_id team.users.where(user_id: slack_id).first else regexp = ::Regexp.new("^#{user_name}$", 'i') query = User.where(team:).any_of({ user_name: regexp }, nickname: regexp) query.first end unless user case slack_id when ANYONE user = User.create!(team:, user_id: ANYONE, user_name: ANYONE, nickname: 'anyone', registered: true) else begin users_info = client.web_client.users_info(user: slack_id || "@#{user_name}") if users_info info = Hashie::Mash.new(users_info).user if info user = team.users.where(user_id: info.id).first user ||= User.create!(team:, user_id: info.id, user_name: info.name, registered: true) end end rescue Slack::Web::Api::Errors::SlackError => e raise e unless e.message == 'user_not_found' end end end raise SlackGamebot::Error, "I don't know who #{user_name} is! Ask them to _register_." unless user&.registered? raise SlackGamebot::Error, "I don't know who #{user_name} is!" unless user user end def self.find_many_by_slack_mention!(client, user_names) user_names.map { |user| find_by_slack_mention!(client, user) } end # Find an existing record, update the username if necessary, otherwise create a user record. def self.find_create_or_update_by_slack_id!(client, slack_id) instance = User.where(team: client.owner, user_id: slack_id).first users_info = client.web_client.users_info(user: slack_id) instance_info = Hashie::Mash.new(users_info).user if users_info if users_info && instance instance.update_attributes!(user_name: instance_info.name) if instance.user_name != instance_info.name elsif !instance && instance_info instance = User.create!(team: client.owner, user_id: slack_id, user_name: instance_info.name, registered: true) end if instance instance.register! unless instance.registered? instance.promote! unless instance.captain? || client.owner.captains.count > 0 end raise SlackGamebot::Error, "I don't know who <@#{slack_id}> is!" unless instance instance end def self.reset_all!(team) User.where(team:).set( wins: 0, losses: 0, ties: 0, elo: 0, elo_history: [], tau: 0, rank: nil, losing_streak: 0, winning_streak: 0 ) end def to_s wins_s = "#{wins} win#{'s' unless wins == 1}" losses_s = "#{losses} loss#{'es' unless losses == 1}" ties_s = "#{ties} tie#{'s' unless ties == 1}" if ties && ties > 0 elo_s = "elo: #{team_elo}" lws_s = "lws: #{winning_streak}" if winning_streak >= losing_streak && winning_streak >= 3 lls_s = "lls: #{losing_streak}" if losing_streak > winning_streak && losing_streak >= 3 "#{display_name}: #{[wins_s, losses_s, ties_s].compact.join(', ')} (#{[elo_s, lws_s, lls_s].compact.join(', ')})" end def team_elo elo + team.elo end def promote! update_attributes!(captain: true) end def demote! update_attributes!(captain: false) end def register! return if registered? update_attributes!(registered: true) User.rank!(team) end def unregister! return unless registered? update_attributes!(registered: false, rank: nil) User.rank!(team) end def rank! return unless elo_changed? || saved_change_to_elo? User.rank!(team) reload.rank end def update_elo_history! return unless elo_changed? || saved_change_to_elo? elo_history << elo end def self.rank!(team) rank = 1 players = any_of({ :wins.gt => 0 }, { :losses.gt => 0 }, :ties.gt => 0).where(team:, registered: true).desc(:elo).desc(:wins).asc(:losses).desc(:ties) players.each_with_index do |player, index| if player.registered? rank += 1 if index > 0 && %i[elo wins losses ties].any? { |property| players[index - 1].send(property) != player.send(property) } player.set(rank:) unless rank == player.rank end end end def calculate_streaks! longest_winning_streak = 0 longest_losing_streak = 0 current_winning_streak = 0 current_losing_streak = 0 current_matches.asc(:_id).each do |match| if match.tied? current_winning_streak = 0 current_losing_streak = 0 elsif match.winner_ids.include?(_id) current_losing_streak = 0 current_winning_streak += 1 else current_winning_streak = 0 current_losing_streak += 1 end longest_losing_streak = current_losing_streak if current_losing_streak > longest_losing_streak longest_winning_streak = current_winning_streak if current_winning_streak > longest_winning_streak end return if losing_streak == longest_losing_streak && winning_streak == longest_winning_streak update_attributes!(losing_streak: longest_losing_streak, winning_streak: longest_winning_streak) end def self.rank_section(team, users) ranks = users.map(&:rank) return users unless ranks.min && ranks.max where(team:, :rank.gte => ranks.min, :rank.lte => ranks.max).asc(:rank).asc(:wins).asc(:ties) end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/api/presenters.rb
slack-gamebot/api/presenters.rb
require 'roar/representer' require 'roar/json' require 'roar/json/hal' require 'slack-gamebot/api/presenters/paginated_presenter' require 'slack-gamebot/api/presenters/status_presenter' require 'slack-gamebot/api/presenters/challenge_presenter' require 'slack-gamebot/api/presenters/challenges_presenter' require 'slack-gamebot/api/presenters/user_presenter' require 'slack-gamebot/api/presenters/users_presenter' require 'slack-gamebot/api/presenters/match_presenter' require 'slack-gamebot/api/presenters/matches_presenter' require 'slack-gamebot/api/presenters/user_rank_presenter' require 'slack-gamebot/api/presenters/user_ranks_presenter' require 'slack-gamebot/api/presenters/season_presenter' require 'slack-gamebot/api/presenters/seasons_presenter' require 'slack-gamebot/api/presenters/team_presenter' require 'slack-gamebot/api/presenters/teams_presenter' require 'slack-gamebot/api/presenters/game_presenter' require 'slack-gamebot/api/presenters/games_presenter' require 'slack-gamebot/api/presenters/root_presenter'
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/api/middleware.rb
slack-gamebot/api/middleware.rb
module Api class Middleware def self.logger @logger ||= begin $stdout.sync = true Logger.new(STDOUT) end end def self.instance @instance ||= Rack::Builder.new do use Rack::Cors do allow do origins '*' resource '*', headers: :any, methods: %i[get post] end end # rewrite HAL links to make them clickable in a browser use Rack::Rewrite do r302 %r{(/[\w/]*/)(%7B|\{)?(.*)(%7D|\})}, '$1' end use Rack::Robotz, 'User-Agent' => '*', 'Disallow' => '/api' use Rack::ServerPages run Api::Middleware.new end.to_app end def call(env) Api::Endpoints::RootEndpoint.call(env) end end end
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false
dblock/slack-gamebot
https://github.com/dblock/slack-gamebot/blob/0af9dc9bf8c61523ed46c1007a96a3c9daa488c8/slack-gamebot/api/endpoints.rb
slack-gamebot/api/endpoints.rb
require 'slack-gamebot/api/endpoints/challenges_endpoint' require 'slack-gamebot/api/endpoints/matches_endpoint' require 'slack-gamebot/api/endpoints/users_endpoint' require 'slack-gamebot/api/endpoints/seasons_endpoint' require 'slack-gamebot/api/endpoints/subscriptions_endpoint' require 'slack-gamebot/api/endpoints/teams_endpoint' require 'slack-gamebot/api/endpoints/games_endpoint' require 'slack-gamebot/api/endpoints/status_endpoint' require 'slack-gamebot/api/endpoints/credit_cards_endpoint' require 'slack-gamebot/api/endpoints/root_endpoint'
ruby
MIT
0af9dc9bf8c61523ed46c1007a96a3c9daa488c8
2026-01-04T17:48:57.592423Z
false