【问题标题】:How to make a reminder command with MongoDB? discord.py如何使用 MongoDB 制作提醒命令?不和谐.py
【发布时间】:2021-09-05 07:18:14
【问题描述】:

我实际上是 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))

这是起始代码。之后我不知道该去哪里。

【问题讨论】:

    标签: python discord discord.py pymongo


    【解决方案1】:

    您可以先使用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
    

    【讨论】:

    猜你喜欢
    • 2022-01-26
    • 2021-09-27
    • 2019-01-29
    • 2021-06-11
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多