所以我试图使一个不和谐的机器人,只有注册用户可以使用机器人。你只能注册1次,否则机器人会给你一个错误信息。但不幸的是,机器人将相同的结果发送给注册用户。下面是我的代码:
import discord
from discord.ext import commands
import sqlite3 as sl
conn = sl.connect('my-test.db')
bot = commands.Bot(command_prefix='n.')
c.execute("""CREATE TABLE IF NOT EXISTS users (user_ID, gold, level)""")
c = conn.cursor()
@bot.command()
async def register(ctx):
GetUserId = ctx.author.id
c.execute("SELECT user_ID FROM users WHERE user_ID=?", (GetUserId,))
data = c.fetchall()
if(GetUserId in data):
embed = discord.Embed(title="Error!", description="You have been registered to the bot!")
await ctx.send(embed=embed)
else:
c.execute("INSERT INTO USERS (user_ID) VALUES (?)", (GetUserId,))
embed = discord.Embed(title="Welcome!", description="some description")
await ctx.send(embed=embed)
你能帮我解决这个问题吗,因为我已经搜索这个问题几个小时了,还没有找到解决方案。谢谢!
fetchall()
返回一个行列表,这意味着它看起来像
[(GetUserId_goes_here,)]
您试图检查ctx.author.id
是否在此列表中,但它从来没有,因为您正在检查int
是否在tuples
列表中,这显然是不匹配的。
你的SELECT
将只选择user_ID
匹配你给定id的行,所以没有必要检查它是否在那里。检查是否返回任何东西在这里就足够了:如果没有返回(空列表),那么没有行包含GetUserId
,这意味着用户还没有在您的数据库中。
GetUserId = ctx.author.id
c.execute("SELECT user_ID FROM users WHERE user_ID=?", (GetUserId,))
data = c.fetchall()
if not data:
# Nothing was found, add the user
else:
# User is already in the database
not data
与本if
中的len(data) == 0
相同,因为空列表为Falsy
。你可以用你喜欢的。
作为将来的参考,如果您返回数据库中的所有行,并希望检查是否有用户在那里,您应该使用any()
来检查是否有任何元组包含此id。
if any(row[0] == GetUserId for row in data):
# Found at least 1 matching row
else:
# No matches found