Advertisement
Guest User

Untitled

a guest
Apr 26th, 2017
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 7.55 KB | None | 0 0
  1. using Discord;
  2. using Discord.Commands;
  3. using Discord.Net.Providers.UDPClient;
  4. using Discord.Net.Providers.WS4Net;
  5. using Discord.WebSocket;
  6. using System;
  7. using System.Configuration;
  8. using System.Reflection;
  9. using System.Runtime.Remoting.Contexts;
  10. using System.Threading.Tasks;
  11.  
  12. namespace discBot
  13. {
  14.     class Program
  15.     {
  16.         private readonly DiscordSocketClient _client;
  17.         private readonly IDependencyMap _map = new DependencyMap();
  18.         private readonly CommandService _commands = new CommandService();
  19.  
  20.         /// <summary>
  21.         /// Program entry point
  22.         /// </summary>
  23.         /// <param name="args"></param>
  24.         static void Main(string[] args)
  25.         {
  26.             // Call the Program constructor, followed by the
  27.             // MainAsync method and wait until it finishes (which should be never).
  28.             new Program().MainAsync().GetAwaiter().GetResult();
  29.         }
  30.  
  31.         /// <summary>
  32.         /// Construct all the thigns
  33.         /// </summary>
  34.         private Program()
  35.         {
  36.             _client = new DiscordSocketClient(new DiscordSocketConfig
  37.             {
  38.                 // How much logging do you want to see?
  39.                 LogLevel = LogSeverity.Info,
  40.  
  41.                 // If you or another service needs to do anything with messages
  42.                 // (eg. checking Reactions), you should probably
  43.                 // set the MessageCacheSize here.
  44.                 //MessageCacheSize = 50,
  45.  
  46.                 // If your platform doesn't have native websockets,
  47.                 // add Discord.Net.Providers.WS4Net from NuGet,
  48.                 // add the `using` at the top, and uncomment this line:
  49.                 WebSocketProvider = WS4NetProvider.Instance
  50.             });
  51.         }
  52.        
  53.         /// <summary>
  54.         /// Start up the engines
  55.         /// </summary>
  56.         /// <returns></returns>
  57.         private async Task MainAsync()
  58.         {
  59.             // Subscribe the logging handler.
  60.             _client.Log += Logger;
  61.  
  62.             // Centralize the logic for commands into a seperate method.
  63.             await InitCommands();
  64.  
  65.             // Login and connect.
  66.             await _client.LoginAsync(TokenType.Bot, ConfigurationManager.AppSettings["token"]);
  67.             await _client.StartAsync();
  68.            
  69.             // Wait infinitely so your bot actually stays connected.
  70.             await Task.Delay(-1);
  71.         }
  72.  
  73.         /// <summary>
  74.         /// Init all commands and handle them
  75.         /// </summary>
  76.         /// <returns></returns>
  77.         private async Task InitCommands()
  78.         {
  79.             // Repeat this for all the service classes
  80.             // and other dependencies that your commands might need.
  81.             //_map.Add(new SomeServiceClass());
  82.  
  83.             // Either search the program and add all Module classes that can be found:
  84.             await _commands.AddModulesAsync(Assembly.GetEntryAssembly());
  85.  
  86.             // Or add Modules manually if you prefer to be a little more explicit:
  87.             //await _commands.AddModuleAsync<PublicModule>();
  88.  
  89.             // Subscribe a handler to see if a message invokes a command.
  90.             _client.MessageReceived += HandleCommandAsync;
  91.         }
  92.        
  93.         /// <summary>
  94.         /// Handle commands if they match the expected prfix
  95.         /// </summary>
  96.         /// <param name="arg"></param>
  97.         /// <returns></returns>
  98.         private async Task HandleCommandAsync(SocketMessage arg)
  99.         {
  100.             // Bail out if it's a System Message.
  101.             var msg = arg as SocketUserMessage;
  102.             if (msg == null) return;
  103.  
  104.             // Create a number to track where the prefix ends and the command begins
  105.             int pos = 0;
  106.             // Replace the '!' with whatever character you want to prefix your commands with.
  107.             // Uncomment the second half if you also want commands to be invoked by mentioning the bot instead.
  108.             if (msg.HasCharPrefix(ConfigurationManager.AppSettings["messagePrefix"][0], ref pos) /* || msg.HasMentionPrefix(msg.Discord.CurrentUser, ref pos) */)
  109.             {
  110.                 // Create a Command Context
  111.                 var context = new CommandContext(msg.Discord, msg);
  112.  
  113.                 // Execute the command. (result does not indicate a return value,
  114.                 // rather an object stating if the command executed succesfully).
  115.                 IResult result = await _commands.ExecuteAsync(context, pos, _map);
  116.  
  117.                 // Uncomment the following lines if you want the bot
  118.                 // to send a message if it failed (not advised for most situations).
  119.                 if (!result.IsSuccess && result.Error != CommandError.UnknownCommand)
  120.                     await msg.Channel.SendMessageAsync(result.ErrorReason);
  121.             }
  122.         }
  123.        
  124.         /// <summary>
  125.         /// Create a named logging handler, so it can be re-used by addons
  126.         /// that ask for a Func<LogMessage, Task>.
  127.         /// </summary>
  128.         /// <param name="message"></param>
  129.         /// <returns></returns>
  130.         private static Task Logger(LogMessage message)
  131.         {
  132.             var cc = Console.ForegroundColor;
  133.             switch (message.Severity)
  134.             {
  135.                 case LogSeverity.Critical:
  136.                 case LogSeverity.Error:
  137.                     Console.ForegroundColor = ConsoleColor.Red;
  138.                     break;
  139.                 case LogSeverity.Warning:
  140.                     Console.ForegroundColor = ConsoleColor.Yellow;
  141.                     break;
  142.                 case LogSeverity.Info:
  143.                     Console.ForegroundColor = ConsoleColor.White;
  144.                     break;
  145.                 case LogSeverity.Verbose:
  146.                 case LogSeverity.Debug:
  147.                     Console.ForegroundColor = ConsoleColor.DarkGray;
  148.                     break;
  149.             }
  150.             Console.WriteLine($"{DateTime.Now,-19} [{message.Severity,8}] {message.Source}: {message.Message}");
  151.             Console.ForegroundColor = cc;
  152.             return Task.CompletedTask;
  153.         }
  154.     }
  155. }
  156.  
  157.  
  158. using Discord.Commands;
  159. using Discord.WebSocket;
  160. using System.Reflection;
  161. using System.Threading.Tasks;
  162.  
  163. namespace discBot
  164. {
  165.     public class PublicModule : ModuleBase
  166.     {
  167.         /// <summary>
  168.         /// Say what
  169.         /// </summary>
  170.         /// <param name="echo"></param>
  171.         /// <returns></returns>
  172.         [Command("say"), Summary("Echos a message.")]
  173.         public async Task Say([Remainder, Summary("The text to echo")] string echo)
  174.         {
  175.             // ReplyAsync is a method on ModuleBase
  176.             await ReplyAsync(echo);
  177.         }
  178.  
  179.         /// <summary>
  180.         /// Super gay
  181.         /// </summary>
  182.         /// <param name="echo"></param>
  183.         /// <returns></returns>
  184.         [Command("isgingergay"), Summary("Echos a message.")]
  185.         public async Task WhatAreYou([Remainder, Summary("The text to echo")] string echo)
  186.         {
  187.             // ReplyAsync is a method on ModuleBase
  188.             await ReplyAsync(echo);
  189.         }
  190.  
  191.         /// <summary>
  192.         /// Invite
  193.         /// </summary>
  194.         /// <returns></returns>
  195.         [Command("invite")]
  196.         [Summary("Returns the OAuth2 Invite URL of the bot")]
  197.         public async Task Invite()
  198.         {
  199.             var application = await Context.Client.GetApplicationInfoAsync();
  200.             await ReplyAsync(
  201.                 $"A user with `MANAGE_SERVER` can invite me to your server here: <https://discordapp.com/oauth2/authorize?client_id={application.Id}&scope=bot>");
  202.         }
  203.     }
  204. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement