簡體   English   中英

如何定義帶參數的變量?

[英]How to define a variable with an argument?

我有一個 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。 我將如何 go 關於將 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 = $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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM