如何使用 MongoDB 制作提醒命令?不和谐.py

时间:2021-06-21 15:48:11

标签: python discord discord.py pymongo

我实际上是 datetime 和 discord.py 以及数据库的新手。

我想在我的 discord.py 机器人中创建一个提醒命令。但是我想使用 mongodb 作为数据库,而不是使用 asyncio,因为万一我的机器人由于某种原因离线,所有提醒都会消失。

我不知道从哪里开始,我也找不到任何有关这样做的 YouTube 教程。

这是我的代码:

import pymongo
import discord
from discord.ext import commands
import os


Mongo_url = os.environ['Mongodb_url']


client = pymongo.MongoClient(str(Mongo_url))

这是入门代码。之后我不知道该去哪里。

1 个答案:

答案 0 :(得分:0)

您可以先使用此 example 作为如何将 pymongo 与 discord.py 结合使用的一个很好的示例。 Pymongo 适用于小型机器人,但您应该使用 motor 之类的东西而不是普通的 pymongo,因为它支持 async/await。

您可以像这样设置数据库/集合:

client = pymongo.MongoClient(str(Mongo_url))
database = client.bot
collection = database.reminders

然后在您的命令中,您可以插入它,您可以使用任务检查提醒是否超过显示时间然后显示它。 (将其添加到集合中,如果不到 15 分钟,则使用 asyncio.sleep,但如果时间更长,则让它去执行任务)

使用它来添加/插入到集合中,存储公会/服务器 ID、创建者 ID 和发布时间、应该何时完成、消息和 ID 以帮助识别提醒。

collection.insert_one(
                {"guild_id": ctx.guild.id, "user_id": ctx.author.id, "issued": datetime.datetime.now(),"requested_time": "datetime of the time when it's needed", "message": "Reminder message here", "id":"some random id for it, you could use a flake id or the ctx.message.id for this"})

然后在你的任务中你会有

for reminder in collection.find({}):
   # Your code here that goes through each reminder in the collection