Send Random Cat Images Discord Python Bot
(I assume you already have your discord bot's token. If not, then get a key and come back later)
We are going to need "requests" and "discord.py" modules, so let's install them:
$ python3 -m pip install -U discord.py requests
For Windows:
py -3 -m pip install -U discord.py
Open up your bot's python file and import all the necessary modules and set your bot's token
import discord, requests from discord.ext import commandsTOKEN = "your-token-number"
Now, let's make the function that will get a random cat's image/gif URL and send that in a nice discord embed.
@client.command() async def catto(ctx): r = requests.get("https://api.thecatapi.com/v1/images/search").json() cat_embed = discord.Embed() cat_embed.set_image(url=f"{r[0]['url']}") await ctx.send(embed=cat_embed)
requests.get() will fetch the response from the API.
discord.Embed() is a discord's class which is used to created discord embed.
After initializing the embed we grabbed the URL part from the response and simply set that URL
as the image of the embed.
Finally we sent the embed as the bot's response.
To run our bot, we need to call the run() function and pass in the bot's token.
client.run(TOKEN)
Complete Code:
import discord, requests from discord.ext import commands TOKEN = "your-token-number" @client.command() async def catto(ctx): r = requests.get("https://api.thecatapi.com/v1/images/search").json() cat_em = discord.Embed() cat_em.set_image(url=f'{r[0]["url"]}') await ctx.send(embed=cat_em) client.run(TOKEN)
Comments
Post a Comment