Search code examples
c#botsdiscorduserinfo

Discord bot c# get userinfo (without parameter)and send back message


Hi I'm doing a Discord bot in c# and I'm trying to get the userinfo (preferably username) of the person who uses the command so ex: user types in command- ?response (username is hammerhead) bot reads username and outputs : "HammerHead" in a message along with other stuff

do I use a parameter or can that be avoided I basically don't want the user to type in their name I want the bot to do that automatically.

    [Command("response")]
  
    public async Task Response(CommandContext ctx, string first, String last, string email, string 
    affiliation)
    {

       
       //would something like this work I don't really know
        var username = Context.user;


        await ctx.Channel.SendMessageAsync(first + " " + last + " " + email + " " + affiliation+" 
        "+user ).ConfigureAwait(false);


        }

Solution

  • As you didn't specify which library you're using I'll just tell you for both.

    DSharpPlus:

    Your CommandContext has 2 properties called User and Member. Both of these is the user who called your command, and as the parameter is named ctx you just need to use ctx.User or ctx.Member. The difference is the user type. User gives you DiscordUser whereas Member gives you DiscordMember.

    Docs: https://dsharpplus.emzi0767.com/api/DSharpPlus.CommandsNext.CommandContext.html

    Discord.Net:

    DNet CommandContext has a User property as well. It'll give you IUser type. Call it using ctx.User.

    Docs: https://discord.foxbot.me/docs/api/Discord.Commands.CommandContext.html#Discord_Commands_CommandContext_User

    Tldr;

    Either way you have the idea. Just need to put ctx not Context as ctx is the name of your CommandContext parameter

    Side Note: You might want to look into using String Interpolation. MS Docs: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated