如何定义带参数的变量?

How to define a variable with an argument?

我有一个 discord.py 机器人试图根据命令中给出的参数读取 postgresql table 的不同条目。例如,如果要执行 $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 命令中给出的参数?

根据我在文档中看到的内容,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 = ;", 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