Student Summer Sprint
  • Welcome to Hackathons for Schools Student Summer Sprint!
  • Event Information
  • What is the Student Summer Sprint?
  • Useful Event Information and Links
  • Schedule
  • Our Organisers, Panelists and Mentors
    • Organisers
    • Panelists and Speakers
    • Mentors
  • Project Details
    • Themes
    • Judging Criteria and Winning Teams
    • Presentation Advice
    • Submission Checklist and FAQs
  • Coding Platform and GitLab
  • Technical Workshops
    • How to Use Git
      • Git and the Terminal
      • How to use Git - The Basics
      • Branching, Merging and Other Useful Commands
      • How to use Git - Further Resources
    • Web Development
      • HTML
      • CSS
      • JavaScript
      • Web Development - Resources
    • Introduction to Python
      • Variables
      • Data Types and String Formatting
      • Input and Output
      • Conditional Statements
      • Functions
      • Libraries
      • CHALLENGES
        • Solutions
      • Learning Python - Resources
    • Discord Bots in Python
      • Discord Bots - Resources
    • Web Scraping in Python
  • Careers Advice and Opportunities
    • University Advice
      • University Advice - Further Resources
    • CV, Applications and Interviews
      • Creating a Great CV
      • UCAS Personal Statement Advice
      • Interview Hints and Tips
      • Ultimate LinkedIn Guide
      • Applications - Further Resources
    • Different routes into a tech career
      • Different Routes into Tech - Further Resources
    • What Now?
      • More Opportunities!
Powered by GitBook
On this page
  • Python Code
  • Terminal Commands

Was this helpful?

  1. Technical Workshops

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

PreviousLearning Python - ResourcesNextDiscord Bots - Resources

Last updated 4 years ago

Was this helpful?