«TUTORIAL/FREE» Discord Bot Development «TUTORIAL/FREE»

Status
This thread has been locked.

Infamous

Banned
Feedback score
7
Posts
146
Reactions
35
Resources
0
This will be a basic tutorial although I hope to go over some more advanced things in the future.

If you don't already have a server, create one free one at https://discordapp.com. Simply log in, and then click the plus sign on the left side of the main window to create a new server.

https://discordapp.com/developers/applications/me and create a new app. On your app detail page, save the Client ID. You will need it later to authorize your bot for your server.

https://discordapp.com/oauth2/authorize?client_id=XXXXXXXXXXXX&scope=bot but replace XXXX with your app client ID. Choose the server you want to add it to and select authorize.

Install the python package discord.py
Run pip install from your system terminal/shell/command prompt.

Code:
python -m pip install discord.py==0.16.12
Run the sample code
Replace the token value with the token from your bot that you saved earlier.

Code:
# Work with Python 3.6
import discord

TOKEN = 'XXXXXXXXXX'

client = discord.Client()

@client.event
async def on_message(message):
    # we do not want the bot to reply to itself
    if message.author == client.user:
        return

    if message.content.startswith('!hello'):
        msg = 'Hello {0.author.mention}'.format(message)
        await client.send_message(message.channel, msg)

@client.event
async def on_ready():
    print('Logged in as')
    print(client.user.name)
    print(client.user.id)
    print('------')

client.run(TOKEN)
After running the Python script, your bot should appear online in the server. You can go type !hello to the bot on Discord and it should respond.

Run pip install from your system terminal/shell/command prompt. Make sure to install the correct version of the package. If you are using PyCharm you can open the terminal from View -> Tool Windows -> Terminal

Code:
python -m pip install discord.py==0.16.12
Bot Code
Code:
# Work with Python 3.6
import random
import asyncio
import aiohttp
import json
from discord import Game
from discord.ext.commands import Bot

BOT_PREFIX = ("?", "!")
TOKEN = "XXXXSECRET_TOKENXXXXXXX"  # Get at discordapp.com/developers/applications/me

client = Bot(command_prefix=BOT_PREFIX)

@client.command(name='8ball',
                description="Answers a yes/no question.",
                brief="Answers from the beyond.",
                aliases=['eight_ball', 'eightball', '8-ball'],
                pass_context=True)
async def eight_ball(context):
    possible_responses = [
        'That is a resounding no',
        'It is not looking likely',
        'Too hard to tell',
        'It is quite possible',
        'Definitely',
    ]
    await client.say(random.choice(possible_responses) + ", " + context.message.author.mention)


@client.command()
async def square(number):
    squared_value = int(number) * int(number)
    await client.say(str(number) + " squared is " + str(squared_value))


@client.event
async def on_ready():
    await client.change_presence(game=Game(name="with humans"))
    print("Logged in as " + client.user.name)


@client.command()
async def bitcoin():
    url = 'https://api.coindesk.com/v1/bpi/currentprice/BTC.json'
    async with aiohttp.ClientSession() as session:  # Async HTTP request
        raw_response = await session.get(url)
        response = await raw_response.text()
        response = json.loads(response)
        await client.say("Bitcoin price is: $" + response['bpi']['USD']['rate'])


async def list_servers():
    await client.wait_until_ready()
    while not client.is_closed:
        print("Current servers:")
        for server in client.servers:
            print(server.name)
        await asyncio.sleep(600)


client.loop.create_task(list_servers())
client.run(TOKEN)

I hope you learnt something from this! (A lot of people are requesting this on the forums so I decided to make a post. If you want personal lessons open a pm with me.)​
 
PebbleHost
High performance, consistent uptime and fast support. Minecraft hosting that just works.

toxic13d

Python & Java Developer
Premium
Feedback score
12
Posts
212
Reactions
50
Resources
0
So you just give everyone a bunch of code and expect beginners to know what that means? Also why are you using async, should really be using rewrite as async is a little outdated now.
 

Infamous

Banned
Feedback score
7
Posts
146
Reactions
35
Resources
0
So you just give everyone a bunch of code and expect beginners to know what that means? Also why are you using async, should really be using rewrite as async is a little outdated now.
I guess...
 
Banned forever. Reason: Attempted scamming (https://gyazo.com/d4d2b377e0ad1dae3f2569edb7cbd307)
Status
This thread has been locked.
Top