Skip to content

Basic bot creation

Matthew Carey edited this page Nov 15, 2020 · 1 revision

Creating a bot is amazingly simple. There are three steps to it; creating the bot object, adding event handlers and running the bot.

Creating the bot object

Simply create a new object of the Discordrb::Bot class:

require 'discordrb'

bot = Discordrb::Bot.new token: 'TOKEN HERE'

The initializer requires a token. If you're unsure how to get a token, look here - create an application (you don't need to set any redirect URIs), create a bot account for it and use that token. That's all for initialization, now you can start adding event handlers.

Adding event handlers

To add an event handler, call the respective method with a list of filter attributes and a block:

bot.message(with_text: "Hey Bot!") do |event|
  event.respond "Hi, #{event.user.name}!"
end

Events and filter attributes are explained in more detail here.

Running your bot

bot.run

Note that bot.run runs synchronously by default, blocking all further execution. If you need to do stuff after starting the bot (such as listening to external events) run bot.run by passing true to the background argument.

# Run the bot in another thread in the background:
bot.run(true)

loop do
  # looped code goes here:
  message = ExternalService.last_queued_message
  bot.send_message(channel_id, message)
end

If the code you want to execute runs for a finite amount of time, run bot.join afterwards so the script execution doesn't end prematurely:

# Run the bot in another thread in the background:
bot.run(true)

bot.send_message(channel_id, 'Bot is now active!')

# Join the bot's thread back with the main thread:
bot.join

Shutting down your bot

If your bot exits, it will appear to remain connected until the connection times out. To avoid this, call bot.stop. This will gracefully disconnect the bot. Calling it inside at_exit means your bot will always gracefully disconnect.

at_exit { bot.stop }
bot.run

That's it! You made a bot using discordrb.