I have a discord.py bot that is trying to read a different entry to a postgresql table depending on what argument is given in the command. For example, if one was to do $playtime penguin then it would give the entry in minutes_played for the account 'penguin'. Here is what I have so far.
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}')
This however, does not work as it does not define name(). I want name() to be defined as the argument the discord user gave on the command, eg penguin. How would I go about defining name() as the argument given in the discord command?
From what I see in the documentation the arg
should contain the name provided as the first argument for the command. Also make sure to use parametrized queries to avoid sql injections . The following code should work:
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}')
You probably also want to add some error handling code if wrong name is passed to the command.
References:
[1] https://discordpy.readthedocs.io/en/latest/ext/commands/commands.html
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.