iTranslated by AI
discord.py - Using MongoDB with discord.py
Introduction
This article aims to create a profile Bot using MongoDB with discord.py.
Please feel free to point out any mistakes you find.
Environment
- Python v3.9.2-final
- discord.py v1.7.1-final
- aiohttp v3.6.3
- system info: Windows 10 10.0.17134
(Information from python -m discord -v)
1. Create a MongoDB Account
If you have already created a Collection, please skip to 3. Installing Libraries.
Access
https://mongodb.com
and create an account.
This time, we will create it using a Google account.
Click Sign In,
Log in with your Google account from the Sign In with Google button here.
Agree to the terms, and if you see a screen like the one below, it is a success.
2. Create a Cluster
Create an Organization
Click Create an Organization to create a new organization.
Enter a name for the Organization Name and click Next.
You can leave MongoDB Atlas selected for Select Cloud Service.
You will be moved to a screen to invite members.
If there are other developers, invite them.
For this tutorial, we will ignore it and click Create Organization.
Create a Project
Once you reach this screen, create a new project with New Project.
Specify a name in Project Name.
Just like before, invite other developers if they exist.
For this tutorial, we will ignore it and click Create Project.
Create a Cluster
Create a Cluster with Build a Cluster.
Plans will appear; select Shared Clusters.
You can configure various settings here.
You can use servers in Japan by selecting Google Cloud > Tokyo.
Once configured, create the Cluster by clicking Create Cluster.
After clicking, the Cluster will be created, so please wait for about 1-3 minutes.
Configure Connection
Once the Cluster is ready, open the connection settings by clicking Connect.
You can restrict the IPs that can access it above. If you are hosting on Heroku or similar, the IP changes with each deployment, so use Allow Access from Anywhere.
In this case, we will not restrict the IP.
Create a user below.
This time, create a user with the username Bot. It is safer to use Autogenerate Secure Password for the password.
Once generated, click SHOW in the password field to display and copy the password.
Click Connect Your Application.
Copy the URL (Connection String) written at the bottom of the window.
mongodb+srv://<name>:<password>@hitoniyotte.kawaru.mongodb.net/<database_name>?retryWrites=true&w=majority
(This is an example.)
Please replace <name> and <password> with the values you set. You can choose any database name you like.
That's all for the preparation. Well done.
3. Installing Libraries
To use MongoDB, pymongo is generally used, but this causes blocking (freezing the entire bot in discord.py, see discord.py FAQ for details).
Therefore, we will use motor this time.
Also, dnspython is required, so please install it.
py -3 -m pip install motor dnspython
or
python3 -m pip install motor dnspython
4. Reading and Writing to the Database
Start with the following code:
import discord
from discord.ext import commands
intents = discord.Intents.default()
intents.members = True # Enable Member Intents
allowed_mentions = discord.AllowedMentions(replied_user=False) # Disable reply mentions by default
bot = commands.Bot(command_prefix="p ", intents=intents, allowed_mentions=allowed_mentions)
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
bot.run("Th1sIsN0tT0k3n.B3cause.1fiShowB0tWillG3tH4cked")
Creating a Client
Create a motor.motor_asyncio.AsyncIOMotorClient.
from discord.ext import commands
+ from motor import motor_asyncio as motor # Import motor_asyncio
================================================================
bot = commands.Bot(command_prefix="p ", intents=intents, allowed_mentions=allowed_mentions)
+ dbclient = motor.AsyncIOMotorClient("mongodb+srv://<name>:<password>@hitoniyotte.kawaru.mongodb.net/<database_name>?retryWrites=true&w=majority") # Create AsyncIOMotorClient
Please replace the Connection String.
Also, it is recommended to use dotenv or similar to prevent leaks.
Creating a Database Object
You can create a database object using client["database_name"] or client.database_name.
dbclient = motor.AsyncIOMotorClient("mongodb+srv://<name>:<password>@hitoniyotte.kawaru.mongodb.net/<database_name>?retryWrites=true&w=majority")
+ db = dbclient["ProfileBot"]
+ # Or: db = dbclient.ProfileBot
Creating a Collection Object
A collection is like a table, a place where data is stored.
You can create a collection object using database["collection_name"] or database.collection_name.
db = dbclient["ProfileBot"]
+ profiles_collection = db.profiles
+ # Or: profiles_collection = db["profiles"]
Reading and Writing to a Collection
Writing
You can write one piece of data with insert_one and multiple pieces with insert_many.
We will make it possible to set a profile with p set <profile>.
@bot.command(name="set")
async def set_profile(ctx, *, text): # Rename to avoid conflict with 'set', use *, to ignore spaces
await profiles_collection.insert_one({
"userid": ctx.author.id,
"text": text
})
await ctx.reply("Setup complete.")
Reading
You can search for one piece of data that matches a condition with find_one and multiple pieces with find.
We will make it possible to display it with p show <user>.
@bot.command(name="show")
async def show_profile(ctx, target: discord.User): # Specify a user
profile = await profiles_collection.find_one({
"userid": target.id
}, {
"_id": False # Do not retrieve the internal ID
})
if profile is None:
return await ctx.reply("Not found.")
embed = discord.Embed(title=f"Profile of `{target}`", description=profile["text"]) # Create an embed
return await ctx.reply(embed=embed) # Send the embed
Looks good.
Deleting
You can delete one piece of data that matches a condition with delete_one and all matches with delete_many.
Also, you can get the number of deleted items from the deleted_count of the return value pymongo.results.DeleteResult.
We will make it possible to delete with p delete or p del.
@bot.command(name="delete", aliases=["del"])
async def delete_profile(ctx): # Specify a user
result = await profiles_collection.delete_one({
"userid": ctx.author.id # Specify the condition by userid
})
if result.deleted_count == 0: # If nothing was deleted
return await ctx.reply("Not found.")
return await ctx.reply("Deleted successfully.")
It is correctly deleted.
Replacing
replace_one replaces one piece of data matching the condition with the specified object.
By setting upsert=True, it will perform a new insertion if no matching data is found (UPdate + inSERT).
async def set_profile(ctx, *, text):
+ new_data = {
+ "userid": ctx.author.id,
+ "text": text
+ }
+ await profiles_collection.replace_one({
+ "userid": ctx.author.id # Specify the condition by userid
+ }, new_data, upsert=True)
- await profiles_collection.insert_one({
- "userid": ctx.author.id,
- "text": text
- })
It is correctly replaced.
There are many other things you can do, so please read the reference for more details.
Final Code
import discord
from discord.ext import commands
from motor import motor_asyncio as motor
intents = discord.Intents.default()
intents.members = True
allowed_mentions = discord.AllowedMentions(replied_user=False)
bot = commands.Bot(command_prefix="p ", intents=intents, allowed_mentions=allowed_mentions)
dbclient = motor.AsyncIOMotorClient("mongodb+srv://<name>:<password>@hitoniyotte.kawaru.mongodb.net/<database_name>?retryWrites=true&w=majority")
db = dbclient["ProfileBot"]
profiles_collection = db.profiles
@bot.event
async def on_ready():
print(f"Logged in as {bot.user}")
@bot.command(name="set")
async def set_profile(ctx, *, text):
new_data = {
"userid": ctx.author.id,
"text": text
}
result = await profiles_collection.replace_one({
"userid": ctx.author.id
}, new_data)
if result.matched_count == 0:
await profiles_collection.insert_one(new_data)
await ctx.reply("Setup complete.")
@bot.command(name="show")
async def show_profile(ctx, target: discord.User):
profile = await profiles_collection.find_one({
"userid": target.id
}, {
"_id": False
})
if profile is None:
return await ctx.reply("Not found.")
embed = discord.Embed(title=f"Profile of `{target}`", description=profile["text"])
return await ctx.reply(embed=embed)
@bot.command(name="delete", aliases=["del"])
async def delete_profile(ctx):
result = await profiles_collection.delete_one({
"userid": ctx.author.id
})
if result.deleted_count == 0:
return await ctx.reply("Not found.")
return await ctx.reply("Deleted successfully.")
bot.run("Th1sIsN0tT0k3n.B3cause.1fiShowB0tWillG3tH4cked")
Conclusion
I hope this article is helpful.
Thank you for reading.
Discussion