Class: Bitbot::Bot
- Inherits:
-
Cinch::Bot
- Object
- Cinch::Bot
- Bitbot::Bot
- Defined in:
- lib/bitbot/bot.rb
Instance Method Summary collapse
- #command_balance(msg) ⇒ Object
- #command_deposit(msg, create = true) ⇒ Object
- #command_help(msg) ⇒ Object
- #command_history(msg) ⇒ Object
- #command_tip(msg, recipient, amount, message) ⇒ Object
- #command_tipstats(msg) ⇒ Object
- #command_withdraw(msg, amount, address) ⇒ Object
- #get_blockchain ⇒ Object
- #get_db ⇒ Object
-
#initialize(config = {}) ⇒ Bot
constructor
A new instance of Bot.
- #process_new_transactions_for_address(address, user_id, all_addresses) ⇒ Object
- #satoshi_to_str(satoshi) ⇒ Object
- #satoshi_to_usd(satoshi) ⇒ Object
- #satoshi_with_usd(satoshi) ⇒ Object
-
#update_addresses ⇒ Object
This method needs to be called periodically, like every minute in order to process new transactions.
-
#update_exchange_rates ⇒ Object
This should be called periodically to keep exchange rates up to date.
- #user_with_username(username) ⇒ Object
Constructor Details
#initialize(config = {}) ⇒ Bot
Returns a new instance of Bot.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/bitbot/bot.rb', line 10 def initialize(config = {}) @bot_config = config @cached_addresses = nil @cached_exchange_rates = nil super() do configure do |c| c.server = config['irc']['server'] c.port = config['irc']['port'] c.ssl.use = config['irc']['ssl'] c.channels = config['irc']['channels'] c.nick = config['irc']['nick'] || 'bitbot' c.user = config['irc']['username'] || 'bitbot' c.password = config['irc']['password'] c.verbose = config['irc']['verbose'] end on :private, /^help$/ do |m| self.bot.command_help(m) end on :private, /^balance/ do |m| self.bot.command_balance(m) end on :private, /^history/ do |m| self.bot.command_history(m) end on :private, /^withdraw$/ do |m| m.reply "Usage: withdraw <amount in BTC> <address>" end on :private, /^withdraw\s+([\d.]+)\s+([13][0-9a-zA-Z]{26,35})/ do |m, amount, address| self.bot.command_withdraw(m, amount, address) end on :private, /^deposit/ do |m| self.bot.command_deposit(m) end on :channel, /^\+tipstats$/ do |m| self.bot.command_tipstats(m) end on :channel, /^\+tip\s+(\w+)\s+([\d.]+)\s+?(.*)/ do |m, recipient, amount, | self.bot.command_tip(m, recipient, amount, ) end end end |
Instance Method Details
#command_balance(msg) ⇒ Object
226 227 228 229 230 231 |
# File 'lib/bitbot/bot.rb', line 226 def command_balance(msg) db = get_db() user_id = db.get_or_create_user_id_for_username(msg.user.user) msg.reply "Balance is #{satoshi_with_usd(db.get_balance_for_user_id(user_id))}" end |
#command_deposit(msg, create = true) ⇒ Object
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 |
# File 'lib/bitbot/bot.rb', line 233 def command_deposit(msg, create = true) db = get_db() user_id = db.get_or_create_user_id_for_username(msg.user.user) unless @cached_addresses msg.reply "Bitbot is not initialized yet. Please try again later." return end if address = @cached_addresses[user_id] msg.reply "Send deposits to #{address["address"].irc(:bold)}. " + "This address is specific to you, and any funds delivered " + "to it will be added to your account after confirmation." return end unless create msg.reply "There was a problem getting your deposit address. " + "Please contact your friends Bitbot admin." return end # Attempt to create an address. blockchain = get_blockchain() blockchain.create_deposit_address_for_user_id(user_id) # Force a refresh of the cached address list... self.update_addresses() self.command_deposit(msg, false) end |
#command_help(msg) ⇒ Object
222 223 224 |
# File 'lib/bitbot/bot.rb', line 222 def command_help(msg) msg.reply "Commands: balance, history, withdraw, deposit, +tip, +tipstats" end |
#command_history(msg) ⇒ Object
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 |
# File 'lib/bitbot/bot.rb', line 265 def command_history(msg) db = get_db() user_id = db.get_or_create_user_id_for_username(msg.user.user) command_balance(msg) n = 0 db.get_transactions_for_user_id(user_id).each do |tx| time = Time.at(tx[:created_at].to_i).strftime("%Y-%m-%d") amount = satoshi_with_usd(tx[:amount]) action = if tx[:amount] < 0 && tx[:other_user_id] "to #{tx[:other_username]}" elsif tx[:amount] > 0 && tx[:other_user_id] "from #{tx[:other_username]}" elsif tx[:withdrawal_address] "withdrawal to #{tx[:withdrawal_address]}" elsif tx[:incoming_transaction] "deposit from tx #{tx[:incoming_transaction]}" end msg.reply "#{time.irc(:grey)}: #{amount} #{action} #{"(#{tx[:note]})".irc(:grey) if tx[:note]}" n += 1 break if n >= 10 end end |
#command_tip(msg, recipient, amount, message) ⇒ Object
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 |
# File 'lib/bitbot/bot.rb', line 346 def command_tip(msg, recipient, amount, ) db = get_db() # Look up sender user_id = db.get_or_create_user_id_for_username(msg.user.user) # Look up recipient recipient_ircuser = msg.channel.users.keys.find {|u| u.name == recipient } unless recipient_ircuser msg.user.msg("Could not find #{recipient} in the channel list.") return end recipient_user_id = db.get_or_create_user_id_for_username(recipient_ircuser.user) # Convert amount to satoshi satoshi = (amount.to_f * 10**8).to_i if satoshi <= 0 msg.user.msg("Cannot send a negative amount.") return end # Attempt the transaction (will raise on InsufficientFunds) begin db.create_transaction_from_tip(user_id, recipient_user_id, satoshi, ) rescue InsufficientFundsError msg.reply "Insufficient funds! It's the thought that counts.", true return end # Success! Let the room know... msg.reply "[✔] Verified: ".irc(:grey).irc(:bold) + msg.user.user.irc(:bold) + " ➜ ".irc(:grey) + satoshi_with_usd(satoshi) + " ➜ ".irc(:grey) + recipient_ircuser.user.irc(:bold) # ... and let the sender know privately ... msg.user.msg "You just sent " + recipient_ircuser.user.irc(:bold) + " " + satoshi_with_usd(satoshi) + " in " + msg.channel.name.irc(:bold) + " bringing your balance to " + satoshi_with_usd(db.get_balance_for_user_id(user_id)) + "." # ... and let the recipient know privately. recipient_ircuser.msg msg.user.user.irc(:bold) + " just sent you " + satoshi_with_usd(satoshi) + " in " + msg.channel.name.irc(:bold) + " bringing your balance to " + satoshi_with_usd(db.get_balance_for_user_id(recipient_user_id)) + ". Type 'help' to list bitbot commands." end |
#command_tipstats(msg) ⇒ Object
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 |
# File 'lib/bitbot/bot.rb', line 322 def command_tipstats(msg) db = get_db() stats = db.get_tipping_stats str = "Stats: ".irc(:grey) + "tips today: " + satoshi_with_usd(0 - stats[:total_tipped]) + " " + "#{stats[:total_tips]} tips " if stats[:tippers].length > 0 str += "biggest tipper: ".irc(:black) + stats[:tippers][0][0].irc(:bold) + " (#{satoshi_with_usd(0 - stats[:tippers][0][1])}) " end if stats[:tippees].length > 0 str += "biggest recipient: ".irc(:black) + stats[:tippees][0][0].irc(:bold) + " (#{satoshi_with_usd(stats[:tippees][0][1])}) " end msg.reply str end |
#command_withdraw(msg, amount, address) ⇒ Object
292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 |
# File 'lib/bitbot/bot.rb', line 292 def command_withdraw(msg, amount, address) db = get_db() user_id = db.get_or_create_user_id_for_username(msg.user.user) satoshi = (amount.to_f * 10**8).to_i # Perform the local transaction in the database. Note that we # don't do the blockchain update in the transaction, because we # don't want to roll back the transaction if the blockchain update # *appears* to fail. It might look like it failed, but really # succeed, letting someone withdraw money twice. # TODO: don't hardcode fee begin db.create_transaction_from_withdrawal(user_id, satoshi, 500000, address) rescue InsufficientFundsError msg.reply "You don't have enough to withdraw #{satoshi_to_str(satoshi)} + 0.0005 fee" return end blockchain = get_blockchain() response = blockchain.create_payment(address, satoshi, 500000) if response["tx_hash"] msg.reply "Sent #{satoshi_with_usd(satoshi)} to #{address.irc(:bold)} " + "in transaction #{response["tx_hash"].irc(:grey)}." else msg.reply "Something may have gone wrong with your withdrawal. Please contact " + "your friendly Bitbot administrator to investigate where your money is." end end |
#get_blockchain ⇒ Object
65 66 67 68 69 |
# File 'lib/bitbot/bot.rb', line 65 def get_blockchain Bitbot::Blockchain.new(@bot_config['blockchain']['wallet_id'], @bot_config['blockchain']['password1'], @bot_config['blockchain']['password2']) end |
#get_db ⇒ Object
61 62 63 |
# File 'lib/bitbot/bot.rb', line 61 def get_db Bitbot::Database.new(File.join(@bot_config['data']['path'], "bitbot.db")) end |
#process_new_transactions_for_address(address, user_id, all_addresses) ⇒ Object
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 |
# File 'lib/bitbot/bot.rb', line 162 def process_new_transactions_for_address(address, user_id, all_addresses) db = get_db() blockchain = get_blockchain() existing_transactions = {} db.get_incoming_transaction_ids().each do |txid| existing_transactions[txid] = true end response = blockchain.get_details_for_address(address["address"]) username = db.get_username_for_user_id(user_id) ircuser = self.user_with_username(username) response["txs"].each do |tx| # Skip ones we already have in the database next if existing_transactions[tx["hash"]] # Skip any transactions that have an existing bitbot address # as an input if tx["inputs"].any? {|input| all_addresses.include? input["prev_out"]["addr"] } debug "Skipping tx with bitbot input address: #{tx["hash"]}" next end # find the total amount for this address amount = 0 tx["out"].each do |out| if out["addr"] == address["address"] amount += out["value"] end end # Skip unless it's in a block (>=1 confirmation) if !tx["block_height"] || tx["block_height"] == 0 ircuser.msg "Waiting for confirmation of transaction of " + satoshi_with_usd(amount) + " in transaction #{tx["hash"].irc(:grey)}" next end # There is a unique constraint on incoming_transaction, so this # will fail if for some reason we try to add it again. if db.create_transaction_from_deposit(user_id, amount, tx["hash"]) # Notify the depositor if ircuser ircuser.msg "Received deposit of " + satoshi_with_usd(amount) + ". Current balance is " + satoshi_with_usd(db.get_balance_for_user_id(user_id)) + "." end end end end |
#satoshi_to_str(satoshi) ⇒ Object
71 72 73 74 75 |
# File 'lib/bitbot/bot.rb', line 71 def satoshi_to_str(satoshi) str = "฿%.8f" % (satoshi.to_f / 10**8) # strip trailing 0s str.gsub(/0*$/, '') end |
#satoshi_to_usd(satoshi) ⇒ Object
77 78 79 80 81 82 83 |
# File 'lib/bitbot/bot.rb', line 77 def satoshi_to_usd(satoshi) if @cached_exchange_rates && @cached_exchange_rates["USD"] "$%.2f" % (satoshi.to_f / 10**8 * @cached_exchange_rates["USD"]["15m"]) else "$?" end end |
#satoshi_with_usd(satoshi) ⇒ Object
85 86 87 88 89 90 91 92 93 94 95 96 |
# File 'lib/bitbot/bot.rb', line 85 def satoshi_with_usd(satoshi) btc_str = satoshi_to_str(satoshi) if satoshi < 0 btc_str = btc_str.irc(:red) else btc_str = btc_str.irc(:green) end usd_str = "[".irc(:grey) + satoshi_to_usd(satoshi).irc(:blue) + "]".irc(:grey) "#{btc_str} #{usd_str}" end |
#update_addresses ⇒ Object
This method needs to be called periodically, like every minute in order to process new transactions.
106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
# File 'lib/bitbot/bot.rb', line 106 def update_addresses cache_file = File.join(@bot_config['data']['path'], "cached_addresses.yml") if @cached_addresses.nil? # Load from the cache, if available, on first load @cached_addresses = YAML.load(File.read(cache_file)) rescue nil end blockchain = get_blockchain() # Updates the cached map of depositing addresses. new_addresses = {} all_addresses = [] addresses = blockchain.get_addresses_in_wallet() addresses.each do |address| all_addresses << address["address"] next unless address["label"] =~ /^\d+$/ user_id = address["label"].to_i new_addresses[user_id] = address # We set a flag on the address saying we need to get the # confirmed balance IF the previous entry has the flag, OR # the address is new OR if the balance does not equal the # previous balance. We only clear the field when the balance # equals the confirmed balance. address["need_confirmed_balance"] = @cached_addresses[user_id]["need_confirmed_balance"] rescue true if address["balance"] != (@cached_addresses[user_id]["balance"] rescue nil) address["need_confirmed_balance"] = true end end # Now go through new addresses, performing any confirmation checks # for flagged ones. new_addresses.each do |user_id, address| if address["need_confirmed_balance"] balance = blockchain.get_balance_for_address(address["address"]) address["confirmed_balance"] = balance if address["confirmed_balance"] == address["balance"] address["need_confirmed_balance"] = false end # Process any transactions for this address self.process_new_transactions_for_address(address, user_id, all_addresses) end end # Thread-safe? Sure, why not. @cached_addresses = new_addresses # Cache them on disk for faster startups File.write(cache_file, YAML.dump(@cached_addresses)) end |
#update_exchange_rates ⇒ Object
This should be called periodically to keep exchange rates up to date.
100 101 102 |
# File 'lib/bitbot/bot.rb', line 100 def update_exchange_rates @cached_exchange_rates = get_blockchain().get_exchange_rates() end |
#user_with_username(username) ⇒ Object
216 217 218 219 220 |
# File 'lib/bitbot/bot.rb', line 216 def user_with_username(username) self.bot.user_list.each do |user| return user if user.user == username end end |