Discord Bots - Python
This example uses the interactions.py framework, but you can use any Python framework of your choice.
Preresiquites
- Have a Discord Bot Token
- Install interactions.py
pip install -U discord-py-interactions
Project Structure
This example consists of two files: main.py
, where we create our Slash Commands, and whop.py
, where we add our Whop API code.
.
├── main.py
└── whop.py
Creating your first Slash Command
After obtaining your Discord Bot Token and installing the dependencies, you can begin creating your first Slash Command.
It is recommended that you make your bot token an environment variable and do not hardcode it into your code.
import interactions
bot = interactions.Client(token="your_secret_bot_token")
@bot.command(
name="my_first_command",
description="This is the first command I made!",
scope=the_id_of_your_guild,
)
async def my_first_command(ctx: interactions.CommandContext):
await ctx.send("Hi there!")
bot.start()
Adding the Whop API
For this step, you will need a Whop API key. If you haven’t done so already, you can find details on how to do that here.
In the whop.py
file, add the following code. This function will check if there are any memberships associated with the user’s Discord ID.
To check if they own a specific product, you can append &product_id=your_product_id
to the URL. This is useful if you have multiple products with different commands.
For more information on this endpoint, you can check it out here.
import requests
class WhopUtilities:
def checkUserAccess(discord_id):
url = f"https://api.whop.com/api/v2/memberships?page=1&per=10&discord_id={discord_id}&hide_metadata=false"
headers = {
"accept": "application/json",
"Authorization": f"Bearer {LICENSE_KEY}"
}
response = requests.get(url, headers=headers)
if response.status_code != 200:
return False # We couldn't find a membership
else:
return True # There is a valid membership
Integrating the Whop API with Your Slash Command
Now that you have a function that checks for user membership, connect it to your Slash Command.
First, we need to import the WhopUtilities
class from our whop.py
file.
Then, we can add an if statement to check if the user has a membership. If they do, we can send a message. If they don’t, we can send a different message.
The current import statement only works if your whop.py
file is in the same
directory as your main.py
file. If it is not, update the import statement
accordingly.
import interactions
from Whop import WhopUtilities
bot = interactions.Client(token="your_secret_bot_token")
@bot.command(
name="my_first_command",
description="This is the first command I made!",
scope=the_id_of_your_guild,
)
async def my_first_command(ctx: interactions.CommandContext):
if WhopUtilities.checkUserAccess(ctx.author.id):
await ctx.send("Hi there!")
else:
await ctx.send("You don't have access to this command!")
bot.start()