|
| 1 | +# import necessary modules |
| 2 | +from discord.ext import commands |
| 3 | + |
| 4 | +# creates a bot instance with "$" as the command prefix |
| 5 | +bot = commands.Bot("$") |
| 6 | + |
| 7 | + |
| 8 | +TOKEN = "TOKEN" |
| 9 | +# ^^^^^^^ FILL IN THIS! This is the generated token for your bot from the Discord Developer Page |
| 10 | + |
| 11 | + |
| 12 | +# a command in discord.py is <command-prefix><command-name> |
| 13 | +# this creates a command that can be triggered by `$hello`, ie. "hello" is the command name |
| 14 | +@bot.command(pass_context=True) |
| 15 | +async def hello(ctx): # note: discord commands must be coroutines, so define the function with `async def` |
| 16 | + # the ctx argument is passed as the first positional argument when pass_context=True |
| 17 | + # this is required if you need to access the "context" of this command's origin |
| 18 | + |
| 19 | + # you can access the author (type discord.Member) and channel (type discord.Channel) of the command as followed: |
| 20 | + message_author = ctx.message.author # both .author and .channel can only be accessed from the message instance |
| 21 | + message_channel = ctx.message.channel |
| 22 | + |
| 23 | + # prints "<username> said hello" to the console |
| 24 | + print("{} said hello".format(message_author)) |
| 25 | + |
| 26 | + # bot.send_message(...) is a coroutine, so it must be awaited |
| 27 | + # this sends a message "Hello, <username>!" to the message channel |
| 28 | + await bot.send_message(message_channel, "Hello, {}!".format(message_author.name)) |
| 29 | + # bot.send_message takes the destination and content as the first and second positional arguments |
| 30 | + # more info on string formatting: https://pyformat.info |
| 31 | + |
| 32 | + |
| 33 | +# This is how you define a discord.py event |
| 34 | +@bot.event |
| 35 | +async def on_ready(): # the event `on_ready` is triggered when the bot is ready to function |
| 36 | + print("The bot is READY!") |
| 37 | + print("Logged in as: {}".format(bot.user.name)) |
| 38 | + |
| 39 | +# starts the bot with the corresponding token |
| 40 | +bot.run(TOKEN) |
0 commit comments