Skip to content

Instantly share code, notes, and snippets.

@vingkan
Last active January 9, 2022 01:19
Show Gist options
  • Save vingkan/ba9a0eba78d4986d3b4847f05887685f to your computer and use it in GitHub Desktop.
Save vingkan/ba9a0eba78d4986d3b4847f05887685f to your computer and use it in GitHub Desktop.
Example Discord bot to send you cat pictures.
import discord
import os
import requests
from discord.ext import commands
DISCORD_BOT_TOKEN = os.environ["DISCORD_BOT_TOKEN"]
RANDOM_CAT_URL = "https://cataas.com"
bot = commands.Bot(
command_prefix=commands.when_mentioned,
description="An example bot.",
intents=discord.Intents.default()
)
def get_random_cat():
req = requests.get(f"{RANDOM_CAT_URL}/cat?json=true")
res = req.json()
url = res["url"]
return f"{RANDOM_CAT_URL}{url}"
@bot.event
async def on_ready():
print(f"Hello, I am {bot.user}.")
@bot.event
async def on_message(message):
"""
Listener to reply with a random cat, as text.
Usage: Any message that contains "random cat"
"""
# Don't respond to your own messages
if message.author == bot.user:
return
# Get the text of the message
content = str(message.content).lower()
# Send a random cat
if "random cat" in content:
your_cat = get_random_cat()
await message.channel.send(your_cat)
await bot.process_commands(message)
return
@bot.command()
async def cat(ctx):
"""
Command to get a random cat, as an embed.
Usage: @Bot cat
"""
your_cat = get_random_cat()
embed = discord.Embed(
title="Here is your cat.",
description="Please react with pats."
)
embed.set_image(url=your_cat)
await ctx.send(embed=embed)
bot.run(DISCORD_BOT_TOKEN)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment