首页 > 解决方案 > Discord.py:只能将元组(不是“int”)连接到元组

问题描述

我正在尝试为我的不和谐机器人创建一个警告命令,该命令将以下 4 个值输入数据库、成员 ID、服务器 ID、原因和警告 ID。警告 ID 是最后一次提取到表中的结果加 1。但是,当我尝试添加到警告 ID 时,我收到以下错误。

Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 333, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 47, in on_command_error
    raise error
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 903, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 1325, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: can only concatenate tuple (not "int") to tuple

这是我的代码:

  @commands.group()
  @commands.has_permissions(manage_roles = True)
  @commands.bot_has_permissions(manage_roles = True)
  async def warn(self, ctx, member: discord.Member, *, reason = 'No reason provided'):

    if ctx.invoked_subcommand is not None:
        return

    db = sqlite3.connect('warns.sqlite')
    cursor = db.cursor()
    cursor.execute(f'SELECT warn_id FROM warns WHERE guild_id = {ctx.guild.id} AND member_id = {member.id}')
    result = cursor.fetchone()

    if result is None:
      sql = ('INSERT INTO warns(guild_id, member_id, reason, warn_id) VALUES(?,?,?,?)')
      val = (ctx.guild.id, member.id, reason, 1)
    elif result is not None:
      sql = ('INSERT INTO warns(guild_id, member_id, reason, warn_id) VALUES(?,?,?,?)')
      val = (ctx.guild.id, member.id, reason, result + 1) # FAILS HERE

    await ctx.send(f'{check_mark} **{member.name}** has been warned.')

    cursor.execute(sql, val)
    db.commit()
    cursor.close()
    db.close()

我尝试将结果转换为整数,但没有奏效。我不知道为什么现在会发生这种情况。

标签: pythondatabasesqlitediscord.pydiscord.py-rewrite

解决方案


试试这个:

int(result[0]) + 1

您的打印输出表明它result('1',)一个tuple长度为 1 的包含字符串的 a。[0]获取元组中的第一个元素,并将int()字符串转换为数字,因此您可以向其添加数字。

您也可以+在 Python 中的字符串或元组上使用,但两个操作数必须是相同的类型。(它将它们连接起来。)这就是错误消息抱怨操作数而不是+运算符的原因。


推荐阅读