Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using Discord;
- using Discord.Commands;
- using Discord.WebSocket;
- using System;
- using System.Reflection;
- using System.Threading.Tasks;
- namespace DrunkBotCore
- {
- public class Program
- {
- public static void Main(string[] args)
- => new Program().MainAsync().GetAwaiter().GetResult();
- private DiscordSocketClient _client;
- public async Task MainAsync()
- {
- _client = new DiscordSocketClient();
- _client.Log += Log;
- // You can assign your bot token to a string, and pass that in to connect.
- // This is, however, insecure, particularly if you plan to have your code hosted in a public repository.
- var token = "Nzg2NDY3NjU4ODYxMjQ4NTQy.X9G1FQ.z6w74iCvCA9ce7ZbKmgXPOWXDkM";
- // Some alternative options would be to keep your token in an Environment Variable or a standalone file.
- // var token = Environment.GetEnvironmentVariable("NameOfYourEnvironmentVariable");
- // var token = File.ReadAllText("token.txt");
- // var token = JsonConvert.DeserializeObject<AConfigurationClass>(File.ReadAllText("config.json")).Token;
- await _client.LoginAsync(TokenType.Bot, token);
- await _client.StartAsync();
- // Block this task until the program is closed.
- await Task.Delay(-1);
- }
- private Task Log(LogMessage msg)
- {
- Console.WriteLine(msg.ToString());
- return Task.CompletedTask;
- }
- private async Task InitCommands()
- {
- // Either search the program and add all Module classes that can be found.
- // Module classes MUST be marked 'public' or they will be ignored.
- // You also need to pass your 'IServiceProvider' instance now,
- // so make sure that's done before you get here.
- await _commands.AddModulesAsync(Assembly.GetEntryAssembly(), _services);
- // Or add Modules manually if you prefer to be a little more explicit:
- await _commands.AddModuleAsync<SampleModule>(_services);
- // Note that the first one is 'Modules' (plural) and the second is 'Module' (singular).
- // Subscribe a handler to see if a message invokes a command.
- _client.MessageReceived += HandleCommandAsync;
- }
- private async Task HandleCommandAsync(SocketMessage arg)
- {
- // Bail out if it's a System Message.
- var msg = arg as SocketUserMessage;
- if (msg == null) return;
- // We don't want the bot to respond to itself or other bots.
- if (msg.Author.Id == _client.CurrentUser.Id || msg.Author.IsBot) return;
- // Create a number to track where the prefix ends and the command begins
- int pos = 0;
- // Replace the '!' with whatever character
- // you want to prefix your commands with.
- // Uncomment the second half if you also want
- // commands to be invoked by mentioning the bot instead.
- if (msg.HasCharPrefix('!', ref pos) /* || msg.HasMentionPrefix(_client.CurrentUser, ref pos) */)
- {
- // Create a Command Context.
- var context = new SocketCommandContext(_client, msg);
- // Execute the command. (result does not indicate a return value,
- // rather an object stating if the command executed successfully).
- var result = await _commands.ExecuteAsync(context, pos, _services);
- // Uncomment the following lines if you want the bot
- // to send a message if it failed.
- // This does not catch errors from commands with 'RunMode.Async',
- // subscribe a handler for '_commands.CommandExecuted' to see those.
- //if (!result.IsSuccess && result.Error != CommandError.UnknownCommand)
- // await msg.Channel.SendMessageAsync(result.ErrorReason);
- }
- }
- }
- }
- using Discord;
- using Discord.Commands;
- using Discord.WebSocket;
- using System;
- using System.Collections.Generic;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
- namespace DrunkBotCore
- {
- public class CommandHandler
- {
- private readonly DiscordSocketClient _client;
- private readonly CommandService _commands;
- // Retrieve client and CommandService instance via ctor
- public CommandHandler(DiscordSocketClient client, CommandService commands)
- {
- _commands = commands;
- _client = client;
- }
- public async Task InstallCommandsAsync()
- {
- // Hook the MessageReceived event into our command handler
- _client.MessageReceived += HandleCommandAsync;
- // Here we discover all of the command modules in the entry
- // assembly and load them. Starting from Discord.NET 2.0, a
- // service provider is required to be passed into the
- // module registration method to inject the
- // required dependencies.
- //
- // If you do not use Dependency Injection, pass null.
- // See Dependency Injection guide for more information.
- await _commands.AddModulesAsync(assembly: Assembly.GetEntryAssembly(),
- services: null);
- }
- private async Task HandleCommandAsync(SocketMessage messageParam)
- {
- // Don't process the command if it was a system message
- var message = messageParam as SocketUserMessage;
- if (message == null) return;
- // Create a number to track where the prefix ends and the command begins
- int argPos = 0;
- // Determine if the message is a command based on the prefix and make sure no bots trigger commands
- if (!(message.HasCharPrefix('!', ref argPos) ||
- message.HasMentionPrefix(_client.CurrentUser, ref argPos)) ||
- message.Author.IsBot)
- return;
- // Create a WebSocket-based command context based on the message
- var context = new SocketCommandContext(_client, message);
- // Execute the command with the command context we just
- // created, along with the service provider for precondition checks.
- await _commands.ExecuteAsync(
- context: context,
- argPos: argPos,
- services: null);
- }
- }
- // Create a module with no prefix
- public class InfoModule : ModuleBase<SocketCommandContext>
- {
- // ~say hello world -> hello world
- [Command("say")]
- [Summary("Echoes a message.")]
- public Task SayAsync([Remainder][Summary("The text to echo")] string echo)
- => ReplyAsync(echo);
- // ReplyAsync is a method on ModuleBase
- }
- // Create a module with the 'sample' prefix
- [Group("sample")]
- public class SampleModule : ModuleBase<SocketCommandContext>
- {
- // ~sample square 20 -> 400
- [Command("square")]
- [Summary("Squares a number.")]
- public async Task SquareAsync(
- [Summary("The number to square.")]
- int num)
- {
- // We can also access the channel from the Command Context.
- await Context.Channel.SendMessageAsync($"{num}^2 = {Math.Pow(num, 2)}");
- }
- // ~sample userinfo --> foxbot#0282
- // ~sample userinfo @Khionu --> Khionu#8708
- // ~sample userinfo Khionu#8708 --> Khionu#8708
- // ~sample userinfo Khionu --> Khionu#8708
- // ~sample userinfo 96642168176807936 --> Khionu#8708
- // ~sample whois 96642168176807936 --> Khionu#8708
- [Command("userinfo")]
- [Summary
- ("Returns info about the current user, or the user parameter, if one passed.")]
- [Alias("user", "whois")]
- public async Task UserInfoAsync(
- [Summary("The (optional) user to get info from")]
- SocketUser user = null)
- {
- var userInfo = user ?? Context.Client.CurrentUser;
- await ReplyAsync($"{userInfo.Username}#{userInfo.Discriminator}");
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment