【发布时间】:2021-09-06 00:29:42
【问题描述】:
我是数据库和日期时间之类的新手。
我实际上想创建一个使用 MongoDB 作为数据库的提醒命令。我正在使用 Motor,因为我想与它一起使用 asyncio。请告诉我我是否在正确的道路上,如果我不是,那我该怎么办?
我已经使用电机设置了与 MongoDB 的基本连接。
这是我的代码。
import discord
from discord.ext import commands
import pymongo
from pymongo import MongoClient
import os
import asyncio
import motor
import motor.motor_asyncio
class Reminder(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_ready(self):
print('Reminder is Ready.')
### MongoDB Variables ###
@commands.command()
async def remind(self, ctx, time, *, msg):
### MongoDB Variables ###
mongo_url = os.environ['Mongodb_url']
cluster = motor.motor_asyncio.AsyncIOMotorClient(str(mongo_url))
db = cluster['Database']
collection = db['reminder']
### Discord Variables ###
author_id = ctx.author.id
guild_id = ctx.guild.id
### Time Variables ###
time_conversion = {"s": 1, "m": 60, "h": 3600, "d": 86400}
remindertime = int(time[0]) * time_conversion[time[-1]]
if ctx.author.bot:
return
if (await collection.count_documents({}) == 0):
rem_info = {"_id": author_id, "GuildID": guild_id, "time": remindertime, "msg": msg}
await collection.insert_one(rem_info)
await ctx.send('Logged In')
def setup(bot):
bot.add_cog(Reminder(bot))
什么是提醒命令,我想做什么?
基本上,该命令将需要提醒的时间量和需要提醒的主题作为参数。 在命令中指定的一定时间后,它会 DM 用户说“你让我提醒你关于 {topic}”。
我希望这是所有需要的信息。
【问题讨论】:
-
代码是否将预期数据存储在数据库中?那么你在正确的轨道上???您可以使用
discord.ext.tasks循环进行提醒 -
是的,数据已存储。但是,仅当我的集合中没有文档时才会存储数据。我可以在不和谐中执行该命令时这样做,提醒将在数据库中注册吗?
-
我猜是因为这个原因:
if (await collection.count_documents({}) == 0):只需删除它,或者您可以像count_documents({'_id': author_id})一样添加过滤器,同样当_id是作者ID 时,每个用户只能有一个同时提醒 -
你能告诉我在我的提醒命令中使用
@tasks.loop()的代码吗(请不要告诉我像我一样只看文档,但我不知道该怎么做)。 -
我的整个命令应该在
@task.loop()下吗?我真的不知道
标签: mongodb discord discord.py tornado-motor