【问题标题】:Reminder Command using MongoDB discord.py使用 MongoDB discord.py 的提醒命令
【发布时间】: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


【解决方案1】:

附上问题下方的cmets:

检查是否该提醒用户您可以使用datetime 模块

import discord
from discord.ext import commands, tasks
import pymongo
from pymongo import MongoClient
import os
import asyncio
import motor
import motor.motor_asyncio

import datetime
from datetime import datetime, timedelta

### MongoDB Variables ###
mongo_url = os.environ['Mongodb_url']
cluster = motor.motor_asyncio.AsyncIOMotorClient(str(mongo_url))
db = cluster['Database']
collection = db['reminder']

class Reminder(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self.reminder_task.start()

    def cog_unload(self):
        self.reminder_task.cancel()

    @tasks.loop(minutes=1.0)
    async def reminder_task(self):
        reminders = collection.find({})
        for reminder in reminders:
            # reminder should look like this: {"_id": 1234, "GuildID": 1234, "time": datetime_objekt, "msg": "some text"}
            now = datetime.now()
            if now >= reminder:
                # remind the user 
                guild = self.client.get_guild(reminder['GuildID'])
                member = guild.get_member(reminder['_id'])
                await member.send(f"reminder for {reminder['msg']}")
            



    @commands.Cog.listener()
    async def on_ready(self):
        print('Reminder is Ready.')


    @commands.command()
    async def remind(self, ctx, time, *, msg):
        """Reminder Command"""
        # like above
        
        # just change this
        ### Time Variables ###
        time_conversion = {"s": 1, "m": 60, "h": 3600, "d": 86400}
        remindseconds = int(time[0]) * time_conversion[time[-1]]
        remindertime = datetime.now() + timedelta(seconds=remindseconds)


        


def setup(bot):
    bot.add_cog(Reminder(bot))

【讨论】:

  • 不确定这个reminders = collection.find({}) 是否与motor 一样,但我想你知道我的意思,找到所有文件
  • 由于某种原因这不起作用。我想 dm 用户。我尝试使用ctx.author.send('message')。我确实在@tasks.loop 中添加了ctx 作为参数。 Here is the link 我的代码。检查文件rem_cmd.py。你会在那里找到代码。
  • 我在控制台中没有收到任何错误,也没有收到任何 DM。没有数据进入我的数据库。
  • 你不能在任务上这样做,你必须得到会员 - 我会为此编辑我的答案
  • 我有一个问题,可能没有必要,只是为了确认,
猜你喜欢
  • 1970-01-01
  • 2022-01-05
  • 2020-12-18
  • 2021-07-11
  • 2021-03-06
  • 1970-01-01
  • 2022-01-21
  • 1970-01-01
  • 2021-09-05
相关资源
最近更新 更多