bankerbot-rb/coin.rb

83 lines
1.9 KiB
Ruby
Raw Normal View History

2022-10-07 15:12:06 +00:00
require 'dotenv/load'
require 'yaml'
require 'discordrb'
MAX_COINS_PER_DAY = 3
2022-10-07 15:12:06 +00:00
COIN_TIMEOUT = 15
SCOREBOARD = './scoreboard.yml'
coin_state_active = false
coins_offered_today = 0
2022-10-07 15:12:06 +00:00
bot = Discordrb::Bot.new token: ENV['DISCORD_TOKEN']
def get_seconds_to_midnight(time)
t2 = Time.new(time.year, time.month, time.day + 1)
return t2 - time
end
def get_random_hours(min, max)
min_hours = min * 60 * 60
max_hours = max * 60* 60
return rand(min_hours..max_hours)
2022-10-07 15:12:06 +00:00
end
def load_scoreboard()
YAML::load_file(SCOREBOARD) || {}
end
def get_coin_count(scoreboard, user)
scoreboard[user] || 0
end
def increment_coin(scoreboard, user)
coins = get_coin_count(scoreboard, user) + 1
scoreboard[user] = coins
File.write(SCOREBOARD, scoreboard.to_yaml)
end
def plural(string, count)
2022-10-07 18:50:01 +00:00
"#{count} #{string}#{count != 1 ? 's' : ''}"
2022-10-07 15:12:06 +00:00
end
bot.message(with_text: 'GET COIN' ) do |event|
# update score
if coin_state_active
scoreboard = load_scoreboard()
increment_coin(scoreboard, event.author.id)
coin_state_active = false
coins = get_coin_count(scoreboard, event.author.id)
2022-10-07 18:46:36 +00:00
event.respond "Nice catch, #{event.author.display_name}! You have #{plural('coin', coins)} now!"
2022-10-07 15:12:06 +00:00
else
2022-10-07 18:46:36 +00:00
event.respond "No coins for you, #{event.author.display_name}!"
2022-10-07 15:12:06 +00:00
end
end
bot.message(with_text: '/coins') do |event|
coins = get_coin_count(load_scoreboard(), event.author.id)
2022-10-07 18:46:36 +00:00
event.respond "#{event.author.display_name}, you have #{plural('coin', coins)}!"
2022-10-07 15:12:06 +00:00
end
bot.run(true)
loop do
# sleep random amount of time between 1 and 4 hours
sleep(get_random_hours(1, 4))
2022-10-10 19:47:09 +00:00
# activate coin state
coin_state_active = true
2022-10-07 15:12:06 +00:00
# send coin GIF
bot.send_file(ENV['BOT_CHANNEL'], File.open('./coin.gif', 'r'))
coins_offered_today += 1
2022-10-07 15:12:06 +00:00
# if max coins per day has reached, sleep until midnight
if coins_offered_today >= MAX_COINS_PER_DAY
sleep(get_seconds_to_midnight(Time.now))
coins_offered_today = 0
end
2022-10-07 15:12:06 +00:00
end
bot.join()