【发布时间】:2021-09-22 11:29:04
【问题描述】:
我正在制作一个不和谐的机器人,我希望它具有自定义前缀功能。它有点工作,但每次我重新启动它 - 数据库都消失了。
我尝试将 try - except 语句替换为 """CREATE TABLE IF NOT EXISTS"""。但它似乎也不能正常工作。 我认为我在数据库初始化中做错了。
这是我与此功能相关的代码:
import sqlite3
import discord
from discord.ext import commands
from discord.utils import get
connection = sqlite3.connect('Server_Settings.db')
cursor = connection.cursor()
try:
cursor.execute( """CREATE TABLE Settings (_id INTEGER, MD STRING, AR STRING, TC INTEGER,
AC INTEGER, WC INTEGER, IACS INTEGER, ITCS INTEGER, IWCS INTEGER,Prefix STRING )""")
except:
print("no need")
def get_prefix(client, message):
global Prefix
TechChannel1 = int
IsTChannelSet1 = int
AnnouncementChannel1 = int
IsAChannelSet1 = int
WelcomeChannel1 = int
IsWChannelSet1 = int
_id = message.guild.id
check = cursor.execute("SELECT _id FROM Settings WHERE _id = _id")
result = cursor.fetchone()
if result != None:
check = cursor.execute("SELECT Prefix FROM Settings WHERE _id = _id")
result = cursor.fetchone()
if result[0] != None:
Prefix = result[0]
print(Prefix)
else:
cursor.execute("UPDATE Settings SET Prefix = '!' WHERE _id = ?", (_id))
else:
if IsTChannelSet == False:
TechChannel1 = 0
IsTChannelSet1 = 0
else:
IsTChannelSet1 = 1
if IsAChannelSet == False:
AnnouncementChannel1 = 0
IsAChannelSet1 = 0
else:
IsAChannelSet1 = 1
if IsWChannelSet == False:
WelcomeChannel1 = 0
IsWChannelSet1 = 0
else:
IsWChannelSet1 = 1
cursor.execute("INSERT INTO Settings (_id,MD,AR,TC,AC,WC,IACS,ITCS,IWCS,Prefix) VALUES (?,?,?,?,?,?,?,?,?,?)",(_id, ModRole, AnnouncementRole, TechChannel1, AnnouncementChannel1, WelcomeChannel1, IsAChannelSet1,
IsTChannelSet1, IsWChannelSet1, '!'))
return Prefix
# prefix
bot = commands.Bot(command_prefix=get_prefix)
client = discord.Client
bot.remove_command("help")
@bot.command(name="set.prefix")
@commands.has_role(ModRole)
async def set_prefix(ctx, prefix):
global Prefix
mention = ctx.author.mention
_id = ctx.guild.id
if len(prefix) > 1:
embed = discord.Embed(
title="Attention",
description="It is not recommended to use prefix with length more than 1 character",
color= discord.Color.dark_magenta()
)
await ctx.channel.send(embed=embed)
else:
pass
cursor.execute("UPDATE Settings SET Prefix = ? WHERE _id = ?", (prefix, _id))
embed = discord.Embed(title=f"Updating prefix...", description=f"It might take a while", colour=discord.Color.green())
mes = await ctx.channel.send(embed=embed)
newmes = await ctx.fetch_message(mes.id)
cursor.execute("SELECT Prefix FROM Settings WHERE _id = _id")
result = cursor.fetchone()
print(result[0], prefix)
if result[0] == prefix:
embed = discord.Embed(title=f"@everyone", description=f"My new prefix is {prefix}", colour=discord.Color.green())
await newmes.edit(embed=embed)
else:
embed = discord.Embed(title=f"Oops! Something went wrong", description=f"Try again later", colour=discord.Color.red())
await newmes.edit(embed=embed)
运行代码:
重启代码后:
提前致谢!
【问题讨论】:
标签: python sqlite discord discord.py