static void Main(string[] args) { var client = new DiscordClient(); //Display all log messages in the console client.LogMessage += (s, e) => Console.WriteLine($"[{e.Severity}] {e.Source}: {e.Message}"); //Echo back any message received, provided it didn't come from the bot itself client.MessageReceived += async (s, e) => { if (!e.Message.IsAuthor) await client.SendMessage(e.Channel, e.Message.Text); }; //Convert our sync method to an async one and block the Main function until the bot disconnects client.Run(async () => { //Connect to the Discord server using our email and password await client.Connect("*****@*****.**", "Password123"); //If we are not a member of any server, use our invite code (made beforehand in the official Discord Client) if (!client.AllServers.Any()) await client.AcceptInvite(client.GetInvite("aaabbbcccdddeee")); }); }
public void Install(ModuleManager manager) { _client = manager.Client; manager.CreateCommands("", group => { //group.MinPermissions((int)PermissionLevel.User); group.CreateCommand("who") .Description("picks a random online member") .Do(async e => { var onlineMembers = e.Channel.Members.Where(m => m.Status != UserStatus.Offline); var random = new Random().Next(0, onlineMembers.Count()); var randomUser = onlineMembers.ElementAt(random); var message = string.Format("{0}!", Mention.User(randomUser)); await _client.SendMessage(e.Message.Channel, message); }); group.CreateCommand("help") .Description("sends a list of commands") .Do(async e => { await _client.SendMessage(e.Message.Channel, _client.Commands().AllCommands.ToDiscordMessage()); }); group.CreateCommand("uptime") .Description("shows how long the bot has been online for") .Do(async e => { var difference = DateTime.Now.Subtract(_botServices.Ticker.ConnectedOn); var message = string.Format("I've been online for **{0}** days, **{1}** hours & **{2}** minutes.", difference.Days, difference.Hours, difference.Minutes); await _client.SendMessage(e.Message.Channel, message); }); // https://discordapp.com/invite/0LOWyaMvOUdtZuYL VK group.CreateCommand("join") .Description("requests the bot to join another server.") .Parameter("invite url") .Do(async e => { var invite = await _client.GetInvite(e.Args[0]); if (invite.IsRevoked) { return; } await _client.AcceptInvite(invite); }); group.CreateCommand("leave") .Description("instructs the bot to leave this server.") .Do(async e => { await _client.SendMessage(e.Channel, $"Leaving~"); //await _client.LeaveServer(e.Server); }); }); _client.MessageReceived += (s, e) => { if (e.Message.IsAuthor) return; if (!e.Message.Text.StartsWith("!")) { _botServices.Events.AddEvent(e.Message.Server, e.Message.Channel, e.Message.User, EventType.Message); } if (e.Message.MentionedUsers.Any()) { foreach(var mentionedUser in e.Message.MentionedUsers) { if (!Equals(mentionedUser, e.Message.User)) { _botServices.Events.AddEvent(e.Message.Server, e.Message.Channel, mentionedUser, EventType.Mention); } } } }; }
void IModule.Install(ModuleManager manager) { _manager = manager; _client = manager.Client; manager.CreateCommands("", group => { group.CreateCommand("whoami") .Description("Returns the user's ID") .Do(async e => { await WhoIs(e, e.User); }); group.CreateCommand("whereami") .Description("Returns the channel and server's ID") .Do(async e => { await _client.SendMessage(e.Channel, $"You are currently in: {e.Server.Id}/{e.Channel.Id}"); }); group.CreateCommand("whois") .Description("Returns the user's ID") .Parameter("The user's Name") .Do(async e => { List<User> user = e.Channel.Members.Where(m => m.Name == e.Args[0]).ToList(); if (user.Any()) await WhoIs(e, user.First()); }); group.CreateCommand("join") .Description("Requests the bot to join a channel.") .Parameter("Instant Invite") .Do(async e => { var invite = await _client.GetInvite(e.Args[0]); if (invite == null) { await _client.SendMessage(e.Channel, $"Invite not found."); return; } else if (invite.IsRevoked) { await _client.SendMessage(e.Channel, $"The invite has expired or the bot is banned."); return; } await _client.AcceptInvite(invite); await _client.SendMessage(e.Channel, $"Joined the server."); }); group.CreateCommand("leave") .Description("Requests the bot to get the f**k out.") .MinPermissions((int)PermissionLevel.ServerMod) .Do(async e => { await _client.SendMessage(e.Channel, $"Leaving channel."); await _client.LeaveServer(e.Server); }); group.CreateCommand("Clean up") .Description("Requests the bot to purge all his messages since the last reboot in the channel.") .MinPermissions((int)PermissionLevel.ServerAdmin) .Do(async e => { List<Message> myMessages = e.Channel.Messages.Where(m => m.User.Id == _client.CurrentUser.Id).ToList(); await _client.DeleteMessages(myMessages); }); group.CreateCommand("Undo") .Description("Requests the bot to remove his last message.") .Do(async e => { Message lastMessage = e.Channel.Messages.Where(m => m.User.Id == _client.CurrentUser.Id).OrderByDescending(m => m.Timestamp).First(); await _client.DeleteMessage(lastMessage); }); }); }
private static void Start() { SettingsManager.Load(); _client = new DiscordClient(); _client.LogMessage += (s, e) => { Console.WriteLine($"[{e.Severity}] {e.Source} => {e.Message}"); }; //Set up permissions _client.AddService(new BlacklistService()); _client.AddService(new WhitelistService()); _client.AddService(new PermissionLevelService((u, c) => { if (u.Id == long.Parse(SettingsManager.OwnerID)) return (int)PermissionLevel.BotOwner; if (!u.IsPrivate) { if (u == c.Server.Owner) return (int)PermissionLevel.ServerOwner; var serverPerms = u.GetServerPermissions(); if (serverPerms.ManageRoles) return (int)PermissionLevel.ServerAdmin; if (serverPerms.ManageMessages && serverPerms.KickMembers && serverPerms.BanMembers) return (int)PermissionLevel.ServerMod; var channelPerms = u.GetPermissions(c); if (channelPerms.ManagePermissions) return (int)PermissionLevel.ChannelAdmin; if (channelPerms.ManageMessages) return (int)PermissionLevel.ChannelMod; } return (int)PermissionLevel.User; })); //Set up commands var commands = _client.AddService(new CommandService(new CommandServiceConfig { CommandChar = '!', HelpMode = HelpMode.Private })); commands.RanCommand += (s, e) => Console.WriteLine($"[Command] {(e.Server == null ? "[Private]" : e.Server.ToString()) + "/" + e.Channel} => {e.Message}"); commands.CommandError += (s, e) => { string msg = e.Exception?.GetBaseException().Message; if (msg == null) { { switch (e.ErrorType) { case CommandErrorType.Exception: msg = "Unknown error."; break; case CommandErrorType.BadPermissions: msg = "You do not have permission to run this command."; break; case CommandErrorType.BadArgCount: msg = "You provided the incorrect number of arguments for this command."; break; case CommandErrorType.InvalidInput: msg = "Unable to parse your command, please check your input."; break; case CommandErrorType.UnknownCommand: msg = "Unknown command."; break; } } } if (msg != null) { _client.SendMessage(e.Channel, $"Failed to complete command: {msg}"); Console.WriteLine($"[Error] Failed to complete command: {e.Command?.Text} for {e.User?.Name}"); Console.WriteLine($"Command failure: {msg}"); } }; //Set up modules var modules = _client.AddService(new ModuleService()); //Boot up _client.Run(async () => { while (true) { try { await _client.Connect(SettingsManager.Email, SettingsManager.Password); if (!_client.AllServers.Any()) await _client.AcceptInvite(_client.GetInvite("0nwaapOqh2LPqDL9").Result); modules.Install(new Modules.SimpleCommands(), "Simple Commands", FilterType.Unrestricted); modules.Install(new Modules.Chance(), "Dice Rolling", FilterType.Unrestricted); break; } catch (Exception ex) { Console.WriteLine("Login failed" + ex.ToString()); } } }); }
static void Main(string[] args) { // Load up the DB, or create it if it doesn't exist SQL.LoadDB(); // Load up the config file LoadConfig(); Console.Title = $"Nekobot v{version}"; // Load the stream channels Music.LoadStreams(); // Initialize rest client RCInit(); client = new DiscordClient(new DiscordClientConfig { AckMessages = true, LogLevel = LogMessageSeverity.Verbose, TrackActivity = true, UseMessageQueue = false, UseLargeThreshold = true, EnableVoiceMultiserver = true, VoiceMode = DiscordVoiceMode.Outgoing, }); // Set up the events and enforce use of the command prefix commands.CommandError += CommandError; client.Connected += Connected; client.Disconnected += Disconnected; client.UserJoined += UserJoined; client.LogMessage += LogMessage; client.AddService(commands); client.AddService(new PermissionLevelService(GetPermissions)); commands.CreateGroup("", group => GenerateCommands(group)); commands.NonCommands += Chatbot.Do; // Load the chatbots Chatbot.Load(); // Keep the window open in case of crashes elsewhere... (hopefully) Thread input = new Thread(InputThread); input.Start(); // Connection, join server if there is one in config, and start music streams try { client.Run(async() => { await client.Connect(config["email"].ToString(), config["password"].ToString()); if (config["server"].ToString() != "") { await client.AcceptInvite(client.GetInvite(config["server"].ToString()).Result); } await Music.StartStreams(); }); } catch (Exception e) { Console.WriteLine($"Error: {e.GetBaseException().Message}"); } }