Python DIscordbot using MongoDB



我尝试从json切换到MongoDB,大多数事情都成功了。然而,bancommand不起作用,因为python不会将用户ID存储到变量中更长时间,也不会从数据库中获取用户ID。所以每次我运行命令时,它都会打印出ID不在VAriable中,但ID和名称存储在数据库中。希望有人能帮我。这是我的完整代码:

import pymongo
import json
import discord
from discord.ext import commands
with open("mongosetup.json") as file:
setupfile = json.load(file)
# ==> DISCORDBOT SETUP <== #
botprefix = setupfile.get("Discordbot Prefix")
token = setupfile.get("Discordbot Token")
# ==> DATABASE SETUP <== #
url = setupfile.get("Database url")
databasename = setupfile.get("Database Name")
bot = commands.Bot(command_prefix=botprefix, case_insensitive=True, self_bot=False, Intents=discord.Intents.all())
myclient = pymongo.MongoClient(url)
mydb = myclient[databasename]
print(myclient.list_database_names())
dblist = myclient.list_database_names()
if databasename in dblist:
print("The database exists.")
collection = mydb["UserData"]
bannedusers = mydb["BannedUser"]

@bot.command(name="AddDB")
async def addtodb(ctx):
try:
userdata = {"_id": ctx.author.id, "Username": ctx.message.author.name}
if ctx.author.id not in userdata:
collection.insert_one(userdata)
await ctx.send("Your Username and your UserID where stored into our Datebase sucessfully! n"
f"Saved Data: {userdata}")
except pymongo.errors.DuplicateKeyError:
await ctx.send("You cant add yourself twice in our Database. This User alredy exist!")
@bot.command(name="ban")
@commands.has_permissions(ban_members=True)
async def banuser(ctx, member: discord.Member, *, reason=None):
userdata = {"_id": member.id, "Username": member.display_name}
data = collection.find_one({"_id": member.id})
if data is None:
post = {userdata}
collection.insert_one(post)
print(member.id)
if member.id not in userdata:
print("Not in userdata")
bannedusers.insert_one(userdata)
elif member.id in bannedusers:
await ctx.send(f"Trying to ban the User {member.display_name}...")
try:
await member.ban(reason=reason)
await ctx.send("Banned this user Sucessfully")
except:
await ctx.send("error")
@bot.event
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send("Please pass in all required Arguments :rolling_eyes:")
if isinstance(error, commands.MissingPermissions):
await ctx.send("You dont have all the required Permissions :angry:")

@bot.event
async def on_ready():
print(f'{bot.user} has connected to Discord!')

bot.run(token)

您不能在字典中查找变量(member.id(。此外,我不认为有if member.id not in userdata:的原因,因为member.id将始终在userdata中,因为您指定member.id应该在userdata内。

如果我理解正确,您希望禁止用户,然后将其存储在mongodb中。你可以这样做很容易做到这一点:

@bot.command(name="ban")
@commands.has_permissions(ban_members=True)
async def banuser(ctx, member: discord.Member, *, reason=None):
userdata = {"_id": member.id, "Username": member.display_name} #stores all values in a variable
data = collection.find_one({"_id": member.id}) #looks for the user in the collection db
if data is None: #if user doesnt exist in the user db
collection.insert_one(userdata) #add the user

await ctx.send(f"Trying to ban the User {member.display_name}...")
try:
await member.ban(reason=reason)
await ctx.send("Banned this user Sucessfully")
bannedusers.insert_one(userdata) #adds the user to the banned db
except:
await ctx.send("error")

希望这能有所帮助,如果你有任何问题,就直接问吧!

最新更新