【问题标题】:Custom prefix command with MongoDB使用 MongoDB 自定义前缀命令
【发布时间】:2021-09-11 18:20:22
【问题描述】:

我正在尝试创建一个setprefix 命令,它会更改服务器前缀。但是,我收到以下错误:

    raise TypeError("command_prefix must be plain string, iterable of strings, or callable "
TypeError: command_prefix must be plain string, iterable of strings, or callable returning either of these, not coroutine

我的代码:

main.py

#------importing packages

import keep_alive
import os
import discord
from discord.ext import commands
import pymongo
from pymongo import MongoClient
import asyncio
import motor
import motor.motor_asyncio
import prefixes
from prefixes import Prefixes

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


bot = commands.Bot(command_prefix = Prefixes.setprefix(), case_insensitive=True)

bot.remove_command('help')
my_token = os.environ['Token']

#------When bot is online


@bot.event
async def on_ready():

    #status
    #playing game status

    await bot.change_presence(activity=discord.Game(
        name=f'On {len(bot.guilds)} Servers | -help'))

    print('Bot is Ready')


initial_extensions = ['help', 'math1', 'mod', 'anime', 'prefixes']

if __name__ == '__main__':
    for extension in initial_extensions:
        bot.load_extension(extension)


#ping latency....
@bot.command()
async def ping(ctx):
    await ctx.send(f'Pong\n{round(bot.latency * 1000)}ms')




#------Running the bot
keep_alive.keep_alive()
bot.run(my_token)

为 cog 文件添加前缀

import discord
from discord.ext import commands
import asyncio
import motor
import motor.motor_asyncio
import os


class Prefixes(commands.Cog):
    def __init__(self, bot):
        self.bot = bot


    #custom prefix
    @commands.command()
    @commands.has_permissions(administrator = True)
    async def setprefix(self, ctx, prefix):

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

        guild_id = ctx.guild.id
        server_prefix = prefix

        if (await collection.count_documents({})) == 0:

            prefix_info = {'GuildId': guild_id, 'Prefix': server_prefix}
            await collection.insert_one(prefix_info)

        else:
            prefix_info = {'GuildId': guild_id, 'Prefix': server_prefix}
            await collection.update_one({'GuildId': guild_id}, {'$set': {'Prefix': prefix}})

        await ctx.send(f'My prefix is now {prefix}')

        finding_prefix = await collection.find_one({'Prefix': {'$eq': prefix}})

        view_finding_prefix = finding_prefix.values()
        iterate_view = iter(view_finding_prefix)
        first_value = next(iterate_view)

        self.bot(command_prefix = str(first_value), case_insesitive = True)



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

我不明白为什么会有TypeError。我正在使用motor,因为它支持异步。在motor documentation 中,它说当使用find_one() 它作为字典给出。这就是我这样做的原因,正如您在上面的代码中看到的那样:

        finding_prefix = await collection.find_one({'Prefix': {'$eq': prefix}})

        view_finding_prefix = finding_prefix.values()
        iterate_view = iter(view_finding_prefix)
        first_value = next(iterate_view)

        self.bot(command_prefix = str(first_value), case_insesitive = True)

我这样做是为了获得键 Prefix 的第一个值。如果有其他人可以这样做,请告诉我。

【问题讨论】:

    标签: python mongodb discord discord.py motorengine


    【解决方案1】:

    如果你理解逻辑,这很简单,首先代码 虽然

    import os
    
    import discord
    import motor.motor_asyncio
    import nest_asyncio
    from discord.ext import commands
    from discord.ext.commands import BucketType, cooldown
    from pymongo import MongoClient
    
    nest_asyncio.apply()
    
    mongo_url = os.environ.get("MONGO_URL")
    
    cluster = motor.motor_asyncio.AsyncIOMotorClient(mongo_url)
    
    predb = cluster["discord"]["prefix"]
    
    
    class Prefix(commands.Cog):
        def __init__(self, client):
            self.client = client
    
        @commands.Cog.listener()
        async def on_ready(self):
            print("Prefix cog loaded successfully")
    
        @commands.command(
            cooldown_after_parsing=True, description="Changes Bot prefix for this server"
        )
        @cooldown(1, 10, BucketType.user)
        @commands.has_permissions(administrator=True)
        async def setprefix(self, ctx, new_prefix):
            if len(new_prefix) > 3:
                embed = discord.Embed(
                    timestamp=ctx.message.created_at,
                    title="Error",
                    description="Looks like the prefix is very big ",
                    color=0xFF0000,
                )
                await ctx.send(embed=embed)
            else:
    
                new_prefix = str(new_prefix)
                stats = await predb.find_one({"guild": ctx.guild.id})
    
                if stats is None:
                    updated = {"guild": ctx.guild.id, "prefix": new_prefix}
                    await predb.insert_one(updated)
                    embed = discord.Embed(
                        title="Prefix",
                        description=f"This server prefix is now {new_prefix}",
                        color=0xFF0000,
                    )
                    await ctx.send(embed=embed)
    
                else:
                    await predb.update_one(
                        {"guild": ctx.guild.id}, {"$set": {"prefix": new_prefix}}
                    )
    
                    embed = discord.Embed(
                        timestamp=ctx.message.created_at,
                        title="Prefix",
                        description=f"This server prefix is now {new_prefix}",
                        color=0xFF0000,
                    )
                    await ctx.send(embed=embed)
    
    
    def setup(client):
        client.add_cog(Prefix(client))
    

    它的作用和工作原理是什么?

    1. 首先检查前缀是否太长,因为没有人希望人们搞砸并忘记了长前缀发生的前缀,如果你不想要它可以删除它 如果服务器已经注册,则在第一个 else 条件下,即如果在更新之前更改了前缀,否则会创建一个新条目,希望这会有所帮助,如果它对您有用并且您很高兴,请将此标记为答案:)

    【讨论】:

      【解决方案2】:

      我认为您需要一个数据库来制作自定义前缀代码,因为您需要为机器人所在的每个服务器自定义前缀。

      【讨论】:

      • 你能给我一些提示或代码吗?
      • 我无法完全理解您的评论。你能提供更多关于这方面的信息,或者告诉我一些我可以使用的代码吗?
      • 我不认为我可以给你一个例子,但是,我会解释我的意思。因此,您希望每台服务器都有一个自定义前缀。正确的?因此,您需要将每个服务器的前缀存储在某处。所以你可以做一个数据库什么的。我不知道如何创建数据库,但我知道你可以将 MySQL 用于 python,但我不确定它是否适用于 discord.py。
      • 我确实使用数据库。如我的代码中所述,我使用 mongodb 和电机。我想做的是,在一个集合中,我想制作不同的文档。每台服务器都会有自己的文档,每次有人使用 setprefix 命令时,都会更新文档并更新密钥Prefix。我想访问Prefix 的值,然后将其设置为机器人的前缀。这就是我想做的。如果有其他方法可以使用 mongodb 执行此操作,请随时分享。我制作了一个名为prefixes.py 的 cog 文件,然后我想访问该 cog 文件的功能。
      • Mongodb 确实以 json 格式存储东西,但它不是 json。它实际上是 Bson。
      猜你喜欢
      • 2021-09-20
      • 2021-05-31
      • 1970-01-01
      • 2021-03-31
      • 2018-01-05
      • 1970-01-01
      • 2019-11-09
      • 2016-10-26
      • 2015-02-01
      相关资源
      最近更新 更多