Learn to Code via Tutorials on Repl.it!

← Back to all posts
How to make a discord bot
h
GatewayDuckYT (31)

How to get started
Step 1: install discordrb
The discordrb gem (library) is required to make a discord bot in Ruby. You can install it by typing gem install discordrb or by using bundler. Then, in your code put require "discordrb" on the first line.

Step 2: setup your bot
Assuming that you have created your bot on Discord already, you need to create a bot by doing the following (of course, you can change the name):

@my_bot = Discordrb::Bot.new token: <my-token>, client_id: <my-id>
@my_bot.run true

commands go here!

@my_bot.join
And of course, <my-token> and <my-id> are replaced with your bot's token and id. @my_bot.run true and @my_bot.join help keep the bot running btw. If you want a predetermined prefix, add , prefix: "<my-prefix>" to the end of the first line (and "<my-token>" is replaced with your token).

Step 3: adding commands to your bot
If you have a prefix
Having a prefix makes things easier (though a bit limited). To add a simple command, use the command method on your bot, followed by the command name (as a string or symbol), any options (will be described later), and the event block (like an anonymous function that looks like a control structure). Here's an example of a command that takes 2 or more numbers, and adds them up:

@my_bot.command :sum, min_args: 2 do |event, *args|
numbers = args.collect &:to_i # turns each argument into a number
sum = numbers.collect &:+ # adds up everything in "numbers"
event.respond sum

# I could have just done `event.respond args.collect(&:to_i).collect(&:+)` btw

end
This would be used as <my-prefix> sum num1 num2 [... num].

If you don't have a prefix
Not having a prefix is not a bad thing, it just means that you want your bot to do more. You can get every message by using the message command on your bot. For each message, you can specify options like:

contains: "some text" (searching for text)
content: "some text" (to match entire message) or content: /some_regex/ (to match a pattern)
starts_with: "text" or ends_with: "text" (for matching the beginning or end of a message
...and other things. To create something like the previous example:
@my_bot.message content: /^<my-prefix>\s+sum\s+.+$/ do |event|
args = event.content.split " " # "event.content" is the message
numbers = args.collect &:to_i # turns each string in "args" into a number
sum = numbers.collect &:+ # adds up everything in "numbers"
event.respond sum

# I could have just done `event.respond event.content.split(" ").collect(&:to_i).collect(&:+)` btw

end
This would be used as <my-prefix> sum num1 num2 [... num].

This post has been locked
Comments
hotnewtop
GatewayDuckYT (31)

i did this to get content creator

GatewayDuckYT (31)

sorry i am bad at markup