Search code examples
pythonnextcord

Nextcord error while making a discord bot that stores info in a Google sheet


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 arguments!")
    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)

and I'm getting the exception :

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.

which is a valueerror, but according to the documentaion Interaction should be the correct valuetype

I'm fairly new at using both API's and the documentation isn't very intuitive, if you could help me that'd be great, thank you


Solution

  • You have an extra self parameter:

    @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
    

    This is a parameter that's only present in methods of a class. Maybe you had it in a class and moved to the global scope?

    So nextcord is trying to pass the Interaction value as the first parameter (self), then gets confused on what to do with the following interaction parameter.

    Solution: delete self.