Guest User

Untitled

a guest
Dec 10th, 2020
619
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 8.36 KB | None | 0 0
  1. using Discord;
  2. using Discord.Commands;
  3. using Discord.WebSocket;
  4. using System;
  5. using System.Reflection;
  6. using System.Threading.Tasks;
  7.  
  8.  
  9. namespace DrunkBotCore
  10. {
  11.     public class Program
  12.     {
  13.         public static void Main(string[] args)
  14.             => new Program().MainAsync().GetAwaiter().GetResult();
  15.  
  16.         private DiscordSocketClient _client;
  17.  
  18.         public async Task MainAsync()
  19.         {
  20.             _client = new DiscordSocketClient();
  21.  
  22.             _client.Log += Log;
  23.  
  24.             //  You can assign your bot token to a string, and pass that in to connect.
  25.             //  This is, however, insecure, particularly if you plan to have your code hosted in a public repository.
  26.             var token = "Nzg2NDY3NjU4ODYxMjQ4NTQy.X9G1FQ.z6w74iCvCA9ce7ZbKmgXPOWXDkM";
  27.  
  28.             // Some alternative options would be to keep your token in an Environment Variable or a standalone file.
  29.             // var token = Environment.GetEnvironmentVariable("NameOfYourEnvironmentVariable");
  30.             // var token = File.ReadAllText("token.txt");
  31.             // var token = JsonConvert.DeserializeObject<AConfigurationClass>(File.ReadAllText("config.json")).Token;
  32.  
  33.             await _client.LoginAsync(TokenType.Bot, token);
  34.             await _client.StartAsync();
  35.  
  36.             // Block this task until the program is closed.
  37.             await Task.Delay(-1);
  38.         }
  39.  
  40.         private Task Log(LogMessage msg)
  41.         {
  42.             Console.WriteLine(msg.ToString());
  43.             return Task.CompletedTask;
  44.      
  45.            
  46.            
  47.         }
  48.  
  49.  
  50.         private async Task InitCommands()
  51.         {
  52.             // Either search the program and add all Module classes that can be found.
  53.             // Module classes MUST be marked 'public' or they will be ignored.
  54.             // You also need to pass your 'IServiceProvider' instance now,
  55.             // so make sure that's done before you get here.
  56.  
  57.  
  58.             await  _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
  59.             // Or add Modules manually if you prefer to be a little more explicit:
  60.             await _commands.AddModuleAsync<SampleModule>(_services);
  61.             // Note that the first one is 'Modules' (plural) and the second is 'Module' (singular).
  62.  
  63.             // Subscribe a handler to see if a message invokes a command.
  64.             _client.MessageReceived += HandleCommandAsync;
  65.         }
  66.  
  67.         private async Task HandleCommandAsync(SocketMessage arg)
  68.         {
  69.             // Bail out if it's a System Message.
  70.             var msg = arg as SocketUserMessage;
  71.             if (msg == null) return;
  72.  
  73.             // We don't want the bot to respond to itself or other bots.
  74.             if (msg.Author.Id == _client.CurrentUser.Id || msg.Author.IsBot) return;
  75.  
  76.             // Create a number to track where the prefix ends and the command begins
  77.             int pos = 0;
  78.             // Replace the '!' with whatever character
  79.             // you want to prefix your commands with.
  80.             // Uncomment the second half if you also want
  81.             // commands to be invoked by mentioning the bot instead.
  82.             if (msg.HasCharPrefix('!', ref pos) /* || msg.HasMentionPrefix(_client.CurrentUser, ref pos) */)
  83.             {
  84.                 // Create a Command Context.
  85.                 var context = new SocketCommandContext(_client, msg);
  86.  
  87.                 // Execute the command. (result does not indicate a return value,
  88.                 // rather an object stating if the command executed successfully).
  89.                 var result = await _commands.ExecuteAsync(context, pos, _services);
  90.  
  91.                 // Uncomment the following lines if you want the bot
  92.                 // to send a message if it failed.
  93.                 // This does not catch errors from commands with 'RunMode.Async',
  94.                 // subscribe a handler for '_commands.CommandExecuted' to see those.
  95.                 //if (!result.IsSuccess && result.Error != CommandError.UnknownCommand)
  96.                 //    await msg.Channel.SendMessageAsync(result.ErrorReason);
  97.             }
  98.  
  99.  
  100.         }
  101.  
  102.     }
  103. }
  104.  
  105. using Discord;
  106. using Discord.Commands;
  107. using Discord.WebSocket;
  108. using System;
  109. using System.Collections.Generic;
  110. using System.Reflection;
  111. using System.Text;
  112. using System.Threading.Tasks;
  113.  
  114. namespace DrunkBotCore
  115. {
  116.     public class CommandHandler
  117.     {
  118.         private readonly DiscordSocketClient _client;
  119.         private readonly CommandService _commands;
  120.  
  121.         // Retrieve client and CommandService instance via ctor
  122.         public CommandHandler(DiscordSocketClient client, CommandService commands)
  123.         {
  124.             _commands = commands;
  125.             _client = client;
  126.         }
  127.  
  128.         public async Task InstallCommandsAsync()
  129.         {
  130.             // Hook the MessageReceived event into our command handler
  131.             _client.MessageReceived += HandleCommandAsync;
  132.  
  133.             // Here we discover all of the command modules in the entry
  134.             // assembly and load them. Starting from Discord.NET 2.0, a
  135.             // service provider is required to be passed into the
  136.             // module registration method to inject the
  137.             // required dependencies.
  138.             //
  139.             // If you do not use Dependency Injection, pass null.
  140.             // See Dependency Injection guide for more information.
  141.             await _commands.AddModulesAsync(assembly: Assembly.GetEntryAssembly(),
  142.                                             services: null);
  143.         }
  144.  
  145.         private async Task HandleCommandAsync(SocketMessage messageParam)
  146.         {
  147.             // Don't process the command if it was a system message
  148.             var message = messageParam as SocketUserMessage;
  149.             if (message == null) return;
  150.  
  151.             // Create a number to track where the prefix ends and the command begins
  152.             int argPos = 0;
  153.  
  154.             // Determine if the message is a command based on the prefix and make sure no bots trigger commands
  155.             if (!(message.HasCharPrefix('!', ref argPos) ||
  156.                 message.HasMentionPrefix(_client.CurrentUser, ref argPos)) ||
  157.                 message.Author.IsBot)
  158.                 return;
  159.  
  160.             // Create a WebSocket-based command context based on the message
  161.             var context = new SocketCommandContext(_client, message);
  162.  
  163.             // Execute the command with the command context we just
  164.             // created, along with the service provider for precondition checks.
  165.             await _commands.ExecuteAsync(
  166.                 context: context,
  167.                 argPos: argPos,
  168.                 services: null);
  169.         }
  170.     }
  171.  
  172.     // Create a module with no prefix
  173.     public class InfoModule : ModuleBase<SocketCommandContext>
  174.     {
  175.         // ~say hello world -> hello world
  176.         [Command("say")]
  177.         [Summary("Echoes a message.")]
  178.         public Task SayAsync([Remainder][Summary("The text to echo")] string echo)
  179.             => ReplyAsync(echo);
  180.  
  181.         // ReplyAsync is a method on ModuleBase
  182.     }
  183.  
  184.     // Create a module with the 'sample' prefix
  185.     [Group("sample")]
  186.     public class SampleModule : ModuleBase<SocketCommandContext>
  187.     {
  188.         // ~sample square 20 -> 400
  189.         [Command("square")]
  190.         [Summary("Squares a number.")]
  191.         public async Task SquareAsync(
  192.             [Summary("The number to square.")]
  193.         int num)
  194.         {
  195.             // We can also access the channel from the Command Context.
  196.             await Context.Channel.SendMessageAsync($"{num}^2 = {Math.Pow(num, 2)}");
  197.         }
  198.  
  199.         // ~sample userinfo --> foxbot#0282
  200.         // ~sample userinfo @Khionu --> Khionu#8708
  201.         // ~sample userinfo Khionu#8708 --> Khionu#8708
  202.         // ~sample userinfo Khionu --> Khionu#8708
  203.         // ~sample userinfo 96642168176807936 --> Khionu#8708
  204.         // ~sample whois 96642168176807936 --> Khionu#8708
  205.         [Command("userinfo")]
  206.         [Summary
  207.         ("Returns info about the current user, or the user parameter, if one passed.")]
  208.         [Alias("user", "whois")]
  209.         public async Task UserInfoAsync(
  210.             [Summary("The (optional) user to get info from")]
  211.         SocketUser user = null)
  212.         {
  213.             var userInfo = user ?? Context.Client.CurrentUser;
  214.             await ReplyAsync($"{userInfo.Username}#{userInfo.Discriminator}");
  215.         }
  216.     }
  217.  
  218.  
  219.  
  220.  
  221.  
  222. }
  223.  
  224.    
  225.  
  226.  
  227.  
  228.  
Advertisement
Add Comment
Please, Sign In to add comment