print(f"Starting bot...")



import time
startTime = time.time()



print(f"Importing modules...")



import os

import nextcord
from nextcord.ext import commands
from dotenv import load_dotenv
from nextcord import Interaction

import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request



print(f"Importing .env configuration...")



# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets']

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
SAMPLE_SPREADSHEET_ID = os.getenv('SAMPLE_SPREADSHEET_ID')
SAMPLE_RANGE1 = os.getenv('SAMPLE_RANGE1')
SAMPLE_RANGE2 = os.getenv('SAMPLE_RANGE2')

intents  = nextcord.Intents.all()

bot = commands.Bot(command_prefix='!',intents= intents)



print("Initializing Google Authentication...")



creds = None
if os.path.exists('token.pickle'):
    with open('token.pickle', 'rb') as token:
        creds = pickle.load(token)
if not creds or not creds.valid:
    if creds and creds.expired and creds.refresh_token:
        creds.refresh(Request())
    else:
        flow = InstalledAppFlow.from_client_secrets_file('credentials.json', SCOPES)
        creds = flow.run_local_server(port=0)
    with open('token.pickle', 'wb') as token:
        pickle.dump(creds, token)
service = build('sheets', 'v4', credentials=creds)
sheet = service.spreadsheets()



print(f"Startup complete!\t[ {(time.time()-startTime):.2f}s ]")


TSID = 932262476781875331




@bot.command(name='test')
async def testCommand(ctx, *args):
    if (len(args) == 0):
        await ctx.send("Please send some arguements!")
    else:
        valuesToWrite = [
            [ "C1","D1" ],
            [ "C2","D2" ],
            [ "C3","D3" ],
        ]
        body = {
            'values': valuesToWrite
        }
        result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID, range=SAMPLE_RANGE1).execute()
        result2 = sheet.values().update(spreadsheetId=SAMPLE_SPREADSHEET_ID, range=SAMPLE_RANGE2, valueInputOption='USER_ENTERED', body=body).execute()
        values = result.get('values', [])

        if not values:
            print('No data found.')
        else:
            print('Name, Major:')
            for row in values:
                # Print columns A and E, which correspond to indices 0 and 4.
                print('%s, %s' % (row[0], row[1]))
                await ctx.send(f"{row[0]} {row[1]}")
        print(f"Arg0: {args[0]}")

@bot.slash_command(name="addxp", description="Add some xp to your character.", guild_ids=[TSID])
async def addxp(self, interaction: Interaction , Cname:str, am:int, reason:str):
    try:

        Result = sheet.values().get(spreadsheetID = SAMPLE_SPREADSHEET_ID, range = SAMPLE_RANGE1).execute()
        rows = Result.get('values', [])
        for i in rows:
            if i == Cname:
                row = rows.index(i)+2
        RANGE = "B" + str(row)
        Result2 = sheet.values().update(SAMPLE_SPREADSHEET_ID, RANGE, "USER_ENTERED", int(am))
        await interaction.response.write("XP was added for " + reason)
    except Exception: print("error")

bot.run(TOKEN)

我得到了一个例外:

Traceback (most recent call last):
  File "C:\Users\Swadesh\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\client.py", line 490, in _run_event
    await coro(*args, **kwargs)
  File "C:\Users\Swadesh\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\client.py", line 2458, in on_connect
    self.add_all_application_commands()
  File "C:\Users\Swadesh\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\client.py", line 2473, in add_all_application_commands   
    self._add_decorated_application_commands()
  File "C:\Users\Swadesh\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\client.py", line 2537, in _add_decorated_application_commands
    command.from_callback(command.callback)
  File "C:\Users\Swadesh\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\application_command.py", line 2800, in from_callback     
    BaseApplicationCommand.from_callback(self, callback=callback, option_class=option_class)
  File "C:\Users\Swadesh\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\application_command.py", line 2390, in from_callback     
    super().from_callback(callback=callback, option_class=option_class)
  File "C:\Users\Swadesh\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\application_command.py", line 795, in from_callback      
    raise e
  File "C:\Users\Swadesh\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\application_command.py", line 785, in from_callback
    arg = option_class(param, self, parent_cog=self.parent_cog)  # type: ignore
  File "C:\Users\Swadesh\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\application_command.py", line 1480, in __init__
    found_type = self.get_type(anno)
  File "C:\Users\Swadesh\AppData\Local\Programs\Python\Python39\lib\site-packages\nextcord\application_command.py", line 1602, in get_type
    raise ValueError(
ValueError: SlashCommandOption interaction of command SlashApplicationCommand addxp <function addxp at 0x000002840C4BEA60> Type `<class 'nextcord.interactions.Interaction'>` isn't a supported typehint for Application Commands.

这是一个值错误,但根据文档交互应该是正确的值类型

我对API和文档都是新手,不是很直观,如果你能帮我,那就太好了,谢谢

推荐答案

您还有一个额外的self参数:

@bot.slash_command(name="addxp", description="Add some xp to your character.", guild_ids=[TSID])
async def addxp(self, interaction: Interaction , Cname:str, am:int, reason:str):
#               ^^^^ here

这是一个仅存在于类的方法中的参数.也许你把它放在了课堂上,然后转到了全球范围?

因此,NextCordetry 将Interaction值作为第一个参数(self)传递,然后不知道如何处理后面的interaction参数.

解决方案:删除self.

Python相关问答推荐

如何将桌子刮成带有Se的筷子/要求/Beautiful Soup ?

使文本输入中的文本与标签中的文本相同

Python plt.text中重叠,包adjust_text不起作用,如何修复?

如何使用symy打印方程?

仿制药的类型铸造

滚动和,句号来自Pandas列

计算组中唯一值的数量

Python键入协议默认值

将输入聚合到统一词典中

如何使Matplotlib标题以图形为中心,而图例框则以图形为中心

Pandas GroupBy可以分成两个盒子吗?

在代码执行后关闭ChromeDriver窗口

巨 Python :逆向猜谜游戏

如果有2个或3个,则从pandas列中删除空格

在Python中控制列表中的数据步长

如何重新组织我的Pandas DataFrame,使列名成为列值?

当输入是字典时,`pandas. concat`如何工作?

如何使用大量常量优化代码?

如何获得满足掩码条件的第一行的索引?

为什么Visual Studio Code说我的代码在使用Pandas concat函数后无法访问?