【问题标题】:How to define a variable with an argument?如何定义带参数的变量?
【发布时间】:2021-06-26 22:14:26
【问题描述】:

我有一个 discord.py 机器人,它试图根据命令中给出的参数来读取 postgresql 表的不同条目。例如,如果要执行 $playtime penguin,那么它会在 minutes_played 中为帐户“penguin”提供条目。这是我目前所拥有的。

import discord
from discord.ext import commands
import asyncio
import asyncpg

bot = commands.Bot(command_prefix='$')

@bot.event
async def on_ready():
    print('Logged in as')
    print(bot.user.name)
    print(bot.user.id)
    print('------')

@bot.command()
async def playtime(ctx, arg):

    arg = name()

    conn = await asyncpg.connect('postgresql://{POSTGRES USERNAME/PASSWORD}@localhost/postgres')
    playtime = await conn.fetchrow(
        "SELECT minutes_played FROM public.penguin WHERE username = name();")
    await ctx.send(playtime)

bot.run('{BOT TOKEN}')

然而,这不起作用,因为它没有定义 name()。我希望将 name() 定义为 discord 用户在命令中给出的参数,例如 penguin。我将如何将 name() 定义为 discord 命令中给出的参数?

【问题讨论】:

    标签: python python-3.x discord discord.py python-asyncio


    【解决方案1】:

    根据我在文档中看到的,arg 应该包含作为命令的第一个参数提供的名称。还要确保使用参数化查询来避免sql injections。以下代码应该可以工作:

    import discord
    from discord.ext import commands
    import asyncio
    import asyncpg
    
    bot = commands.Bot(command_prefix='$')
    
    @bot.event
    async def on_ready():
        print('Logged in as')
        print(bot.user.name)
        print(bot.user.id)
        print('------')
    
    @bot.command()
    async def playtime(ctx, arg):
        conn = await asyncpg.connect('postgresql://{POSTGRES USERNAME/PASSWORD}@localhost/postgres')
        playtime = await conn.fetchrow(
            "SELECT minutes_played FROM public.penguin WHERE username = $1;", arg)
        await ctx.send(playtime)
    
    bot.run('{BOT TOKEN}')
    

    如果将错误的名称传递给命令,您可能还想添加一些错误处理代码。


    参考资料:

    [1]https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html

    [2]https://magicstack.github.io/asyncpg/current/usage.html

    【讨论】:

      猜你喜欢
      • 2011-04-08
      • 2011-12-17
      • 2013-02-09
      • 1970-01-01
      • 2019-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多