【问题标题】:How to solve errors while compiling discord.py?编译 discord.py 时如何解决错误?
【发布时间】:2021-05-11 22:35:57
【问题描述】:

我使用 python 3.8 创建了一个不和谐的机器人,一切正常,但是当我发送消息时 ||添加对任何帖子的反应,我在编译器中收到错误cannot unpack non-iterable NoneType object,而机器人仍在工作和在线,并且机器人也在我手动设置的不和谐中执行错误异常An Error Occurred,我再次发送消息并且编译器再次记录相同的错误。 有什么办法解决吗?

代码:

class Exp(Cog):
    def __init__(self, bot):
        self.bot = bot

    async def process_xp(self, message):
        xp, lvl, xplock = db.record("SELECT XP, Level, XPLock FROM exp WHERE UserID = ?", message.author.id)

        if datetime.utcnow() > datetime.fromisoformat(xplock):
            await self.add_xp(message, xp, lvl)

    async def add_xp(self, message, xp, lvl):
        xp_to_add = randint(10, 20)
        new_lvl = int(((xp + xp_to_add) // 42) ** 0.55)

        db.execute("UPDATE exp SET XP = XP + ?, Level = ?, XPLock = ? WHERE UserID = ?",
                   xp_to_add, new_lvl, (datetime.utcnow() + timedelta(seconds=60)).isoformat(), message.author.id)

        if new_lvl > lvl:
            await self.levelup_channel.send(f"Congrats {message.author.mention} - you reached level {new_lvl:,}!")
            await self.check_lvl_rewards(message, new_lvl)

    async def check_lvl_rewards(self, message, lvl):
        if lvl >= 50:  # Red
            if (new_role := message.guild.get_role(841660969991195158)) not in message.author.roles:
                await message.author.add_roles(new_role)
                await message.author.remove_roles(message.guild.get_role(841661523859588840))

Code in db.sql

CREATE TABLE IF NOT EXISTS guilds (
    GuildID integer PRIMARY KEY,
    Prefix text DEFAULT "+"
);
CREATE TABLE IF NOT EXISTS exp (
    UserID integer PRIMARY KEY,
    XP integer DEFAULT 0,
    Level integer DEFAULT 0,
    XPLock text DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE IF NOT EXISTS mutes (
    UserID integer PRIMARY KEY,
    RoleIDs text,
    EndTime text
);

CREATE TABLE IF NOT EXISTS starboard (
    RootMessageID integer PRIMARY KEY,
    StarMessageID integer,
    Stars integer DEFAULT 1
);

Code db.py

    from os.path import isfile
from sqlite3 import connect

from apscheduler.triggers.cron import CronTrigger

DB_PATH = "./data/db/database.db"
BUILD_PATH = "./data/db/build.sql"

cxn = connect(DB_PATH, check_same_thread=False)
cur = cxn.cursor()

def with_commit(func):
    def inner(*args, **kwargs):
        func(*args, **kwargs)
        commit()

    return inner

@with_commit
def build():
    if isfile(BUILD_PATH):
        scriptexec(BUILD_PATH)

def commit():
    cxn.commit()

def autosave(sched):
    sched.add_job(commit, CronTrigger(second=0))

def close():
    cxn.close()

def field(command, *values):
    cur.execute(command, tuple(values))

    if (fetch := cur.fetchone()) is not None:
        return fetch[0]

def record(command, *values):
    cur.execute(command, tuple(values))

    return cur.fetchone()

def records(command, *values):
    cur.execute(command, tuple(values))

    return cur.fetchall()

def column(command, *values):
    cur.execute(command, tuple(values))

    return [item[0] for item in cur.fetchall()]

def execute(command, *values):
    cur.execute(command, tuple(values))

def multiexec(command, valueset):
    cur.executemany(command, valueset)

def scriptexec(path):
    with open(path, "r", encoding="utf-8") as script:
        cur.executescript(script.read())

【问题讨论】:

  • db 到底是什么?你用的是什么sql
  • @Ceres 我正在使用 SQLite
  • 实际上,如果您不使用 intellij Idea Commercial,则会出现插件错误,因为在 student-license.jar 上您不允许使用 SQLite,并且它总是会给出拒绝访问错误,只是为了解决这个问题安装外部 SQL Server 并连接到它。
  • @Саша 使用 VStudio + SQLite 解决了测试

标签: python discord bots


【解决方案1】:

当查询 SELECT XP, Level, XPLock FROM exp WHERE UserID = ? 返回 None 时,您可能会遇到错误,这可能是因为您的数据库为空或没有具有所选用户 ID 的行。

我建议换行:

xp, lvl, xplock = db.record("SELECT XP, Level, XPLock FROM exp WHERE UserID = ?", message.author.id)

类似于:

result = db.record("SELECT XP, Level, XPLock FROM exp WHERE UserID = ?", message.author.id)
if result is None:
    handle_new_user_id(message.author.id)
    return
xp, lvl, xplock = result

这样你只在查询返回某些行时解压值。 handle_new_user_id 应该为尚未在数据库中的用户 ID 做一些事情

【讨论】:

  • 它给出了同样的错误,我想我为频道和用户角色选择了错误的 ID。
  • 你能把错误贴在这里吗?现在第 51 行没有解包操作,所以错误不能相同。
  • AttributeError: 'Exp' 对象没有属性 'bot'
  • 所以和之前的错误不一样了,能不能把完整的traceback贴一下?
  • 我颠倒了代码,发现实际错误正在发生,因为数据库结构未初始化,可能访问被拒绝或其他什么...我正在从头开始编写基本机器人以使用数据库初始化程序进行测试
猜你喜欢
  • 2013-03-17
  • 1970-01-01
  • 1970-01-01
  • 2014-06-11
  • 1970-01-01
  • 1970-01-01
  • 2019-09-04
  • 2018-03-19
  • 1970-01-01
相关资源
最近更新 更多