2023-06-27 02:07:14 +00:00
import { CacheType , ChatInputCommandInteraction } from 'discord.js' ;
2023-07-15 18:44:20 +00:00
import { Region } from '../../constants/regions' ;
2023-06-27 02:13:57 +00:00
import listPlayers , {
2023-06-27 02:07:14 +00:00
usernamePatternWithoutPosition ,
2023-07-11 19:54:57 +00:00
} from '../blitz/listPlayers' ;
import throwError from '../node/throwError' ;
2023-06-27 02:07:14 +00:00
export const serverAndIdPattern = /(com|eu|asia)\/[0-9]+/ ;
export interface ResolvedPlayer {
2023-07-15 18:44:20 +00:00
region : Region ;
2023-06-27 02:07:14 +00:00
id : number ;
}
export default async function resolvePlayerFromCommand (
interaction : ChatInputCommandInteraction < CacheType >,
) {
const commandUsername = interaction . options . getString ( 'username' );
const displayName = interaction . guild ? . members . cache
. get ( interaction . user . id )
? . displayName . match ( usernamePatternWithoutPosition ) ? .[ 0 ];
2023-08-11 18:01:31 +00:00
const username = commandUsername ?? displayName ;
2023-06-27 02:07:14 +00:00
if ( username === undefined ) {
2023-06-27 17:22:27 +00:00
throw throwError (
2023-06-27 02:07:14 +00:00
'Username could not be inferred' ,
"You didn't provide me a username in the command nor was I able to infer your Blitz username from your Discord nickname. Try providing a username manually in the command or using the `/verify` command to set your Discord nickname to your Blitz username." ,
);
}
if ( serverAndIdPattern . test ( username )) {
const [ server , accountId ] = username . split ( '/' );
return {
2023-07-15 18:44:20 +00:00
region : server as Region ,
2023-06-27 02:07:14 +00:00
id : Number ( accountId ),
} satisfies ResolvedPlayer ;
} else {
2023-06-27 02:13:57 +00:00
const accounts = await listPlayers ( username );
2023-06-27 02:07:14 +00:00
if ( accounts [ 0 ]) {
return {
2023-09-18 23:05:19 +00:00
region : accounts [ 0 ]. region ,
2023-06-27 02:07:14 +00:00
id : accounts [ 0 ]. account_id ,
} satisfies ResolvedPlayer ;
} else {
2023-06-27 17:22:27 +00:00
throw throwError (
2023-06-27 02:07:14 +00:00
'Could not find user' ,
`I couldn't find user \` ${ username } \`. Try providing a valid username manually or using the \`/verify\` command to set your Discord nickname to your Blitz username.` ,
);
}
}
}