Discord Bots in Python

Ever wanted to create a Discord bot for your server? Now you can!

Python Code

import discord
from discord.ext import commands
import requests
import random
import io
bot = commands.Bot(command_prefix="!")
def get_total_comics():
    response = requests.get("https://xkcd.com/info.0.json").json()
    print(response["num"])
    return int(response["num"])
def get_url(total):
    url = "https://xkcd.com/" + str(random.randrange(1, total)) + "/info.0.json"
    return url 
def get_img(url):
    response = requests.get(url).json()
    img_url = response["img"]
    img_content = requests.get(img_url).content
    img = io.BytesIO(img_content)
    return img
@bot.command()
async def xkcd(ctx):
    total = get_total_comics()
    url = get_url(total)
    img = get_img(url)
    await ctx.send(file=discord.File(img, 'comic.png'))
bot.run("INSERT TOKEN HERE")

Terminal Commands

To run your discord bot,

pip install discord requests
python bot.py

You could also use a virtual environment to only install them in that folder:

python3 -m venv .venv
source .venv/bin/activate
pip install discord requests
python bot.py

The terminal commands for Windows will differ

Last updated