Skip to content
This repository has been archived by the owner on Aug 1, 2021. It is now read-only.

Commit

Permalink
Added more documentation in the bot tutorial directory (#56)
Browse files Browse the repository at this point in the history
* Added tutorial on how to create an embed

Had some spare time and figured I'd help out by creating a tutorial. Tried to follow the format in the rest of the bot tutorial, but if there are things that needs changing, please let me know!

* Added some comments

* Fix typo

* Fix another typo

* Update building_block_commands.md

* Update building_block_commands.md

* Update building_block_commands.md

* Update building_block_commands.md

* Update building_block_commands.md

* Added listeners docs

* Capitalize Discord

* Fix accidental double paste of content

* Update building_block_commands.md

* Update building_block_listeners.md

* Update message_embeds.md
  • Loading branch information
MrLotU authored and b1naryth1ef committed Feb 15, 2018
1 parent c86824a commit f5b4221
Show file tree
Hide file tree
Showing 3 changed files with 225 additions and 0 deletions.
113 changes: 113 additions & 0 deletions docs/bot_tutorial/building_block_commands.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
# Commands

Commands are a big part of the Discord bot usage. A command can be defined as an order you give to a bot. Basic examples of commands are:
`!help` or `!info`, most bots have either of the two.
In the case of these examples, when you send `!help` or `!info` the bot will reply with a help or info message.

## Basic commands

Creating commands in Disco is really easy because of the [Plugins](https://b1naryth1ef.github.io/disco/bot_tutorial/building_block_plugins.html) that are a core fundamential of Disco. For more info on them, read back in the [Plugins](https://b1naryth1ef.github.io/disco/bot_tutorial/building_block_plugins.html) section of this tutorial. Creating a basic command is done as follows:
First, create a Plugin class:
```py
class myPlugin(Plugin):
```
Now, we can add a command to it. The command will be named ping, and it will simply reply with `pong!`
```py
@Plugin.command('ping')
def on_ping_command(self, event):
event.msg.reply('Pong!')
```
And there we go! Our very first command!

## Command arguments

Next, lets go on to some more advanced commands. Wye'll create an echo command that will respond with whatever we put in to it.
```py
@Plugin.command('echo', '<content:str...>')
def on_echo_command(self, event, content):
event.msg.reply(content)
```
What we did here, was add an argument to our command. The argument we created here, content, is required. This means the command won't work if you don't pass in data for the `content` argument.
You can also add optional arguments to a command. Instead of surrounding the name and type in angle brackets, you'd surround them in square brackets like this: `[content:str...]`
Keep in mind that arguments that are optional might not be there. You'll have to create some checks so that your program doesn't crash on unexpected null values.

## Command groups

Now that we have 2 basic commands and we know to create basic commands and add some arguments to it. Let's create a more advanced command utilizing what we just learned.
The command will take 2 numbers (integers) and simply adds them together. It will work like this: `!math add 1 4` and it would return 5. Instead of passing `'math add'` as the command name, we'll be using command groups here.
Using command groups you can easily group commands together and create sub commands. Now, here comes our math command:
```py
@Plugin.command('add', '<a:int> <b:int>', group='math')
def on_add_command(self, event, a, b):
event.msg.reply('{}'.format(a+b))
```
Here, we added multiple arguments to our command. Namely, number a and number b, that we add together and return back. Of course, you can do loads more fun things with the Disco command handler.

## Optional arguments

Lets create a tag system, that can either store a tag if you'd use it like this: `!tag name value` or retrieve a tag if you'd use it like this: `!tag name`

We'll need 2 arguments. A name argument that's required, and an optional value argument. Inside the command we'll check if a `value` is provided. If there is, we'll store the tag. Otherwise, we'll try to retrieve the previously set value for that tag and return it.
For the sake of this example, we'll asume that the `tags` dict gets stored somewhere so it doesn't get removed after a restart.
```py
tags = {}

@Plugin.command('tag', '<name:str> [value:str...]')
def on_tag_command(self, event, name, value=None):

if value:
tags[name] = value
event.msg.reply(':ok_hand: created tag `{}`'.format(name))
else:
if name in tags.keys():
return event.msg.reply(tags[name])
else:
return event.msg.reply('Unknown tag: `{}`'.format(name))
```

## ArgumentParser

A different way of adding arguments to a command is by using `argparse.ArgumentParser`. With `argparser` it's easier to create more complicated commands with many options or flags.
Let's put this into practice by recreating our math add command, but using `argparser`. More info on `argparser` and the `add_argument()` method can be found [here](https://docs.python.org/2/library/argparse.html#the-add-argument-method)
```py
@Plugin.command('add', parser=True, group='math')
@Plugin.parser.add_argument('a', type=int)
@Plugin.parser.add_argument('b', type=int)
def on_add_command(self, event, args):
event.msg.reply('{}'.format(args.a + args.b)
```

These are all the commands we created in this tutorial:
```py
class myPlugin(Plugin):
@Plugin.command('ping')
def on_ping_command(self, event):
event.msg.reply('Pong!')

@Plugin.command('echo', '<content:str...>')
def on_echo_command(self, event, content):
event.msg.reply(content)

@Plugin.command('add', '<a:int> <b:int>', group='math')
def on_add_command(self, event, a, b):
event.msg.reply('{}'.format(a+b))

tags = {}
@Plugin.command('tag', '<name:str> [value:str...]')
def on_tag_command(self, event, name, value=None):

if value:
tags[name] = value
event.msg.reply(':ok_hand: created tag `{}`'.format(name))
else:
if name in tags.keys():
return event.msg.reply(tags[name])
else:
return event.msg.reply('Unknown tag: `{}`'.format(name))

@Plugin.command('add', parser=True, group='math')
@Plugin.parser.add_argument('a', type=int)
@Plugin.parser.add_argument('b', type=int)
def on_add_command(self, event, args):
event.msg.reply('{}'.format(args.a + args.b)
```
51 changes: 51 additions & 0 deletions docs/bot_tutorial/building_block_listeners.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Listeners
Listeners are a way to execute custom actions when a certain Discord event happens. For example, on message creation, when a member joins or leaves a guild, or when someone changes their username or nickname.

## Listeners in disco
Listeners are easy to use and implement in Disco. First of all, we'll create a [Plugin](https://b1naryth1ef.github.io/disco/bot_tutorial/building_block_plugins.html) like so:
```py
class MyPlugin(Plugin):
```
Now, inside this plugin, we'll create our first listener. A listener is built up following this syntax:
```py
@Plugin.listen('EventName')
def on_event_name(self, event):
# Do something with the event
```
Change the `'EventName'` in the `.listen()` method to the event name you want to listen to, and give the `on_event_name` method a more descriptive name.

This listener will listen for a new message and will reply with the exact same message every time.
```py
@Plugin.listen('MesageCreate')
def on_message_create(self, event):
event.reply(event.message.content)
```
Let's create another listener, this time one that listens for a member that's added to the guild, when this happens, it will send a welcome message in a welcome channel:
```py
WELCOME_CHANNEL = 381890676654080001

@Plugin.listen('GuildMemberAdd')
def on_member_add(self, event):
self.bot.client.state.channels.get(WELCOME_CHANNEL).send_message(
'Welcome to the server {}'.format(event.member.user.mention())
)
```

A list of all Discord events supported by disco can be found [here](https://b1naryth1ef.github.io/disco/api/disco_gateway_events.html) including event attributes and functions you can use on the event property.

These are all the listeners we created in this tutorial:

```py
class MyPlugin(Plugin):
@Plugin.listen('MesageCreate')
def on_message_create(self, event):
event.reply(event.message.content)

WELCOME_CHANNEL = 381890676654080001

@Plugin.listen('GuildMemberAdd')
def on_member_add(self, event):
self.bot.client.state.channels.get(WELCOME_CHANNEL).send_message(
'Welcome to the server {}'.format(event.member.user.mention())
)
```
61 changes: 61 additions & 0 deletions docs/bot_tutorial/message_embeds.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
# Message Embeds

A [Message Embed](https://b1naryth1ef.github.io/disco/api/disco_types_message.html#messageembed) represents a Discord Embed object. An Embed object is another component of Discord messages that can be used to present data with special formatting and structure.

An example of a message embed:

![A discord embed](https://i.stack.imgur.com/HRWHk.png "A discord embed")

An embed can contain the following components:
* Author, including link and avatar
* Title
* Description
* Field(s)
* Thumbnail image
* Image
* Footer, including text and icon
* Timestamp
* Color (sets the color of the left sidebar of the embed)

## Creating an embed
Creating an embed is simple, and can be done like this:
```py
from disco.types.message import MessageEmbed #We need this to create the embed
from datetime import datetime #We need this to set the timestamp

embed = MessageEmbed()
```
This will create a default, empty, Discord Embed object. Now that we have that, let's assign some values to it. First, lets set the author and the title, with a link that leads to this page. This can be done as follows:
```py
embed.set_author(name='b1nzy#1337', url='https://b1naryth1ef.github.com/disco', icon_url='http://i.imgur.com/1tjdUId.jpg')
embed.title = 'How to create an embed'
embed.url = 'https://b1naryth1ef.github.io/disco/bot_tutorial/message_embeds.html' #This URL will be hooked up to the title of the embed
```
Now, we can add a description and a few fields:
```py
embed.add_field(name='Inline field 1', value='Some value for this field', inline=True)
embed.add_field(name='Inline field 2', value='Another value for another field', inline=True)
embed.add_field(name='Inline field 3', value='Third value for the third field', inline=True)
embed.add_field(name='A non-inline field', value='You can only have a max of 3 inline field on 1 line', inline=False)
embed.description = 'This is the general description of the embed, you can use the Discord supported MD in here too, to make it look extra fancy. For example, creating some **bold** or ~~strikethrough~~ text.'
```
Last up, let's set a footer, color and add a timestamp:
```py
embed.timestamp = datetime.utcnow().isoformat()
embed.set_footer(text='Disco Message Embeds tutorial')
embed.color = '10038562' #This can be any color, but I chose a nice dark red tint
```

Once your embed is finshed, you can send it using the `channel.send_message()` message or the `event.msg.reply()` function.
With `channel.send_message()`:
```py
self.bot.state.channels.get(<ChannelID>).send_message('[optional text]', embed=embed)
```
with the `event.msg.reply()` function:
```py
event.msg.reply('[optional text]', embed=embed)
```

The final embed we created in this tutorial would look like this:

![alt text](http://i.imgur.com/G1sUcTm.png "The final embed")

0 comments on commit f5b4221

Please sign in to comment.