static void Main(string[] args) { bot.MessageReceived += Bot_MessageReceived; bot.ExecuteAndWait( async () => { //Connect to the Discord server using our email and password await bot.Connect("MjE4ODE4NTc2NzI1OTY2ODUx.CqM59Q.f_Hp2-_NVF0KVq2kBu2_dEezpvo"); }); }
public MyBot() { discord = new DiscordClient(x => { x.LogLevel = LogSeverity.Info; x.LogHandler = Log; }); discord.UsingCommands(x => { x.PrefixChar = '!'; x.AllowMentionPrefix = true; }); var commands = discord.GetService <CommandService>(); commands.CreateCommand("hello") .Do(async(e) => { await e.Channel.SendMessage("Hi I am a bot"); }); commands.CreateCommand("info") .Do(async(e) => { await e.Channel.SendMessage("I am written in C#"); }); commands.CreateCommand("anime") .Do(async(e) => { await e.Channel.SendMessage("F**K ANIME"); }); /*commands.CreateCommand("sound") * .Do((e) => * { * Console.WriteLine("Some Audio"); * SendAudio(AppDomain.CurrentDomain.BaseDirectory + "\\test.mp3"); * }); */ //var voiceChannel = discord.FindServers("4Head Kappa EleGiggle").FirstOrDefault().VoiceChannels.FirstOrDefault(); //IAudioClient.Join(Channel); discord.ExecuteAndWait(async() => { await discord.Connect("MjgyNjE2NDMyODY3NjcyMDc0.C4t_5Q.mRorqG7vzxAITKEsAMQV7lSn1Fw", TokenType.Bot); }); }
public void startBot() { bot.MessageReceived += Bot_MessageReceived; bot.ExecuteAndWait( async () => { //Connect to the Discord server using our email and password await bot.Connect("Bot MjE4ODE4NTc2NzI1OTY2ODUx.CsU4Zw.upIHYCw7ARcSCwtDE1AYLFsjA38"); // Serene BOT //await bot.Connect("Bot MjE4ODE4NTc2NzI1OTY2ODUx.CsU4Zw.upIHYCw7ARcSCwtDE1AYLFsjA38"); // DEBUG: Test BOT }); }
void Start() { bot = new DiscordClient(x => { x.AppName = "SharkBot"; x.AppUrl = "http://sharkbound.weebly.com/"; x.LogLevel = LogSeverity.Info; x.LogHandler = log; }); bot.UsingCommands(x => { x.PrefixChar = cfg.CommandPrefix; x.AllowMentionPrefix = true; }); CreateCommands(); bot.MessageReceived += async(s, e) => { if (bot.Status == UserStatus.Offline || !e.Message.IsAuthor || e.Message.Text[0] == cfg.CommandPrefix) { return; } var msg = $"{e.User.Name}: {e.Message.Text}"; Logger.Log(msg, ConsoleColor.Red); await e.Channel.SendMessage(msg); await e.User.SendMessage($"You have posted \n\t'{e.Message.Text}' \nin channel \n\t{e.Channel.Name} \nat \n\t{DateTime.Now.ToString()}"); }; bot.ExecuteAndWait(async() => { await bot.Connect(cfg.Token, TokenType.Bot); }); }
public DiscordBot() { bot = new DiscordClient(); bot.MessageReceived += Bot_MessageReceived; alice.Initialize(); bot.ExecuteAndWait(async() => { while (true) { try { await bot.Connect(""); break; } catch { await Task.Delay(3000); } } }); }
public MyBot() { discord = new DiscordClient(x => { x.LogLevel = LogSeverity.Info; x.LogHandler = Log; }); discord.UsingCommands(x => { x.PrefixChar = '>'; }); var commands = discord.GetService <CommandService>(); commands.CreateCommand("Hello") .Do(async(e) => { await e.Channel.SendMessage("Different floats for different boats"); }); discord.MessageReceived += Discord_MessageReceived; discord.ExecuteAndWait(async() => { await discord.Connect("MjUyNjc1NDA5MjI3ODA4NzY4.CyJ8UA.Z9rAh5aO2jeMjhwNQt_T3q8RGWM", TokenType.Bot); }); }
private void Start(string[] args) { #if !DNXCORE50 Console.Title = $"{AppName} (Discord.Net v{DiscordConfig.LibVersion})"; #endif GlobalSettings.Load(); _client = new DiscordClient(x => { x.AppName = AppName; x.AppUrl = AppUrl; x.MessageCacheSize = 0; x.UsePermissionsCache = true; x.EnablePreUpdateEvents = true; x.LogLevel = LogSeverity.Verbose; x.LogHandler = OnLogMessage; }) .UsingCommands(x => { x.AllowMentionPrefix = true; x.HelpMode = HelpMode.Public; x.ExecuteHandler = OnCommandExecuted; x.ErrorHandler = OnCommandError; }) .UsingModules() //.UsingAudio(x => //{ // x.Mode = AudioMode.Outgoing; // x.EnableMultiserver = true; // x.EnableEncryption = true; // x.Bitrate = AudioServiceConfig.MaxBitrate; // x.BufferLength = 10000; //}) .UsingPermissionLevels(PermissionResolver); _client.AddService <SettingsService>(); _client.AddService <HttpService>(); _client.AddModule <AdminModule>("Admin", ModuleFilter.None); //_client.AddModule<ColorsModule>("Colors", ModuleFilter.None); _client.AddModule <FeedModule>("Feeds", ModuleFilter.None); _client.AddModule <GithubModule>("Repos", ModuleFilter.None); _client.AddModule <GImagesModule>("GImages", ModuleFilter.None); _client.AddModule <ModulesModule>("Modules", ModuleFilter.None); _client.AddModule <PublicModule>("Public", ModuleFilter.None); _client.AddModule <TwitchModule>("Twitch", ModuleFilter.None); _client.AddModule <SedModule>("SedModule", ModuleFilter.None); _client.AddModule <StatusModule>("Status", ModuleFilter.None); _client.AddModule <TwitchEmotesModule>("TwitchEmotes", ModuleFilter.None); _client.AddModule <TwitterModule>("TwitterModule", ModuleFilter.None); _client.AddModule <Waifu2xModule>("Waifu2xModule", ModuleFilter.None); //_client.AddModule(new ExecuteModule(env, exporter), "Execute", ModuleFilter.ServerWhitelist); #if PRIVATE PrivateModules.Install(_client); #endif //Convert this method to an async function and connect to the server //DiscordClient will automatically reconnect once we've established a connection, until then we loop on our end //Note: ExecuteAndWait is only needed for Console projects as Main can't be declared as async. UI/Web applications should *not* use this function. _client.ExecuteAndWait(async() => { while (true) { try { if (GlobalSettings.Discord.Token != null) { await _client.Connect(GlobalSettings.Discord.Token); } else { await _client.Connect(GlobalSettings.Discord.Email, GlobalSettings.Discord.Password); } //await _client.ClientAPI.Send(new Discord.API.Client.Rest.HealthRequest()); break; } catch (Exception ex) { _client.Log.Error($"Login Failed", ex); await Task.Delay(_client.Config.FailedReconnectDelay); } } }); }
private void Start(string[] args) { GlobalSettings.Load(); //Set up the base client itself with no voice and small message queues _client = new DiscordClient(new DiscordConfig { AppName = "VoltBot", AppUrl = "https://github.com/RogueException/DiscordBot", AppVersion = DiscordConfig.LibVersion, LogLevel = LogSeverity.Info, MessageCacheSize = 0, UsePermissionsCache = false }) //** Core Services **// //These are services adding functionality from other Discord.Net.XXX packages //Enable commands on this bot and activate the built-in help command .UsingCommands(new CommandServiceConfig { CommandChar = '~', HelpMode = HelpMode.Public }) //Enable command modules .UsingModules() //Enable audio support .UsingAudio(new AudioServiceConfig { Mode = AudioMode.Outgoing, EnableMultiserver = false, EnableEncryption = true, Bitrate = 512, BufferLength = 10000 }) //** Command Permission Services **// // These allow you to use permission checks on commands or command groups, or apply a permission globally (such as a blacklist) //Add a blacklist service so we can add people that can't run any commands. We have used a whitelist instead to restrict it to just us. .UsingGlobalBlacklist() //.EnableGlobalWhitelist(GlobalSettings.Users.DevId)) //Assign users to our own role system based on their permissions in the server/channel a command is run in. .UsingPermissionLevels((u, c) => { if (u.Id == GlobalSettings.Users.DevId) { return((int)PermissionLevel.BotOwner); } if (u.Server != null) { if (u == c.Server.Owner) { return((int)PermissionLevel.ServerOwner); } var serverPerms = u.ServerPermissions; if (serverPerms.ManageRoles) { return((int)PermissionLevel.ServerAdmin); } if (serverPerms.ManageMessages && serverPerms.KickMembers && serverPerms.BanMembers) { return((int)PermissionLevel.ServerModerator); } var channelPerms = u.GetPermissions(c); if (channelPerms.ManagePermissions) { return((int)PermissionLevel.ChannelAdmin); } if (channelPerms.ManageMessages) { return((int)PermissionLevel.ChannelModerator); } } return((int)PermissionLevel.User); }) //** Helper Services**// //These are used by the modules below, and will likely be removed in the future .AddService <SettingsService>() .AddService <HttpService>() //** Command Modules **// //Modules allow for events such as commands run or user joins to be filtered to certain servers/channels, as well as provide a grouping mechanism for commands .AddModule <AdminModule>("Admin", ModuleFilter.ServerWhitelist) .AddModule <ColorsModule>("Colors", ModuleFilter.ServerWhitelist) .AddModule <FeedModule>("Feeds", ModuleFilter.ServerWhitelist) .AddModule <GithubModule>("Repos", ModuleFilter.ServerWhitelist) .AddModule <ModulesModule>("Modules", ModuleFilter.None) .AddModule <PublicModule>("Public", ModuleFilter.None) .AddModule <TwitchModule>("Twitch", ModuleFilter.ServerWhitelist); //.AddModule(new ExecuteModule(env, exporter), "Execute", ModuleFilter.ServerWhitelist); //** Events **// _client.Log.Message += (s, e) => WriteLog(e); //Display errors that occur when a user tries to run a command //(In this case, we hide argcount, parsing and unknown command errors to reduce spam in servers with multiple bots) _client.Commands().CommandErrored += (s, e) => { string msg = e.Exception?.GetBaseException().Message; if (msg == null) //No exception - show a generic message { 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.ReplyError(e, msg); _client.Log.Error("Command", msg); } }; //Log to the console whenever someone uses a command _client.Commands().CommandExecuted += (s, e) => _client.Log.Info("Command", $"{e.Command.Text} ({e.User.Name})"); //Used to load private modules outside of this repo #if PRIVATE PrivateModules.Install(_client); #endif //** Run **// #if !DNXCORE50 Console.Title = $"{_client.Config.AppName} v{_client.Config.AppVersion} (Discord.Net v{DiscordConfig.LibVersion})"; #endif //Convert this method to an async function and connect to the server //DiscordClient will automatically reconnect once we've established a connection, until then we loop on our end //Note: Run is only needed for Console projects as Main can't be declared as async. UI/Web applications should *not* use this function. _client.Run(async() => { while (true) { try { await _client.Connect(GlobalSettings.Discord.Email, GlobalSettings.Discord.Password); _client.SetGame("Discord.Net"); break; } catch (Exception ex) { _client.Log.Error($"Login Failed", ex); await Task.Delay(_client.Config.FailedReconnectDelay); } } }); }
public MyBot() { /* init */ client = new DiscordClient(x => { x.LogLevel = LogSeverity.Info; x.LogHandler = Log; }); client.UsingCommands(input => { input.PrefixChar = '!'; input.AllowMentionPrefix = true; }); commands = client.GetService <CommandService>(); /* init */ /* * Default info */ commands.CreateCommand("hello").Do(async(e) => { await e.Channel.SendMessage("こんにちは " + e.User.NicknameMention); }); commands.CreateCommand("千川ちひろ").Alias("help").Do(async(e) => { await help(e); //await e.Channel.SendMessage("rockon590が大好き^_^"); }); commands.CreateCommand("admin").Parameter("message", ParameterType.Multiple).Do(async(e) => { string jsonstr = ""; try { jsonstr = File.ReadAllText("../../../Certificate.json"); } catch { Console.WriteLine("ERROR: 沒有找到" + "Certificate.json"); Console.ReadKey(); } /* discordBot Token */ JObject jsonobj = JObject.Parse(jsonstr); string owner = jsonobj.GetValue("owner").ToString(); if (owner != null && owner.Equals(e.User.NicknameMention)) { if (e.Args.Length == 1) { if (e.Args[0].Equals("晚安")) { var eu_channel = client.GetServer(293706623652724736).GetChannel(299934136448057365); // eu testlab var nmw_channel = client.GetServer(257033414576701442).GetChannel(295057576020934656); // nmw gambling var lika_channel = client.GetServer(308898984200765450).GetChannel(308908235413389314); // lika gambling await eu_channel.SendMessage("みなさん、おやすみなさい"); await nmw_channel.SendMessage("みなさん、おやすみなさい"); await lika_channel.SendMessage("みなさん、おやすみなさい"); Console.WriteLine("SUCCESS!"); Environment.Exit(0); } } } }); /* * End Default info */ /* * Add feature */ UserInfo(); Draw.DrawCardCommand(); Instrucions.SetInstrucions(); Lots.DrawLotsCommand(); DrawRank.DrawCardRankCommand(); ; ; ; ; /* * End feature */ /* * Discord bot login. * Need to put last line. */ client.ExecuteAndWait(async() => { // Get discordBot Token from json string jsonstr = ""; try { jsonstr = File.ReadAllText("../../../Certificate.json"); } catch { Console.WriteLine("ERROR: 沒有找到" + "Certificate.json"); Console.ReadLine(); return; } /* discordBot Token */ JObject jsonobj = JObject.Parse(jsonstr); string discordbotToken = jsonobj.GetValue("token").ToString(); if (discordbotToken == "") { Console.WriteLine("Please check your token from \"Certificate.json\" file"); Console.WriteLine("URL : https://discordapp.com/developers/applications/me"); Console.ReadLine(); //Pause return; } await client.Connect(discordbotToken, TokenType.Bot); client.SetGame(new Game(jsonobj.GetValue("game").ToString())); }); }
private void Start(string[] args) { #if !DNXCORE50 Console.Title = $"{AppName} (Discord.Net v{DiscordConfig.LibVersion})"; #endif GlobalSettings.Load(); _client = new DiscordClient(x => { x.AppName = AppName; x.AppUrl = AppUrl; x.MessageCacheSize = 0; x.UsePermissionsCache = false; x.EnablePreUpdateEvents = true; x.LogLevel = LogSeverity.Info; x.LogHandler = OnLogMessage; }) .UsingCommands(x => { x.PrefixChar = '!'; x.AllowMentionPrefix = false; x.HelpMode = HelpMode.Public; x.ExecuteHandler = OnCommandExecuted; x.ErrorHandler = OnCommandError; }) .UsingModules() .UsingAudio(x => { x.Mode = AudioMode.Outgoing; x.EnableMultiserver = true; x.EnableEncryption = true; x.Bitrate = AudioServiceConfig.MaxBitrate; x.BufferLength = 10000; }) .UsingPermissionLevels(PermissionResolver) .AddService <SettingsService>() .AddService <HttpService>() .AddModule <AdminModule>("Admin", ModuleFilter.ServerWhitelist) .AddModule <ColorsModule>("Colors", ModuleFilter.ServerWhitelist) //.AddModule<FeedModule>("Feeds", ModuleFilter.ServerWhitelist) //.AddModule<GithubModule>("Repos", ModuleFilter.ServerWhitelist) .AddModule <ModulesModule>("Modules", ModuleFilter.None) .AddModule <PublicModule>("Public", ModuleFilter.None) .AddModule <TwitchModule>("Twitch", ModuleFilter.None) .AddModule <StatusModule>("Status", ModuleFilter.ServerWhitelist) .AddModule <Music>("Music", ModuleFilter.ServerWhitelist) .AddModule <DiscordBot.Modules.Sql.sql>("sql", ModuleFilter.None); PublicModule.loadgods(); //.AddModule(new ExecuteModule(env, exporter), "Execute", ModuleFilter.ServerWhitelist); #if PRIVATE PrivateModules.Install(_client); #endif /* IAudioClient test = new IAudioClient(); * test.*/ //Convert this method to an async function and connect to the server //DiscordClient will automatically reconnect once we've established a connection, until then we loop on our end //Note: ExecuteAndWait is only needed for Console projects as Main can't be declared as async. UI/Web applications should *not* use this function. _client.UserJoined += async(s, e) => { DiscordBot.Modules.Sql.sql sqll = new Modules.Sql.sql(); string message = sqll.getsinglevalue("servers", "server = " + e.Server.Id, "welcome"); if (message != "" && message != null && message.Length > 0) { Channel pm = await _client.CreatePrivateChannel(e.User.Id); await pm.SendMessage(message); } }; _client.ExecuteAndWait(async() => { while (true) { try { await _client.Connect(GlobalSettings.Discord.Email, GlobalSettings.Discord.Password); _client.SetGame("O Bot"); break; } catch (Exception ex) { _client.Log.Error($"Login Failed", ex); await Task.Delay(_client.Config.FailedReconnectDelay); } } }); }
static void Main(string[] args) { Console.Title = "Loading.."; int Width = 93; int Height = 23; Console.SetWindowSize(Width, Height); Console.SetBufferSize(Width, 512); Console.BackgroundColor = ConsoleColor.White; Console.ForegroundColor = ConsoleColor.Black; Console.Write(string.Empty.PadLeft(Width - 1, '-') + "\n [<< Kuriyama Mirai Bot for Discord created by Amir Zaidi, built on the Discord.Net API >>] \n" + string.Empty.PadLeft(Width - 1, '-')); Console.BackgroundColor = ConsoleColor.Black; Console.ForegroundColor = ConsoleColor.White; Console.WriteLine(); if (!File.Exists(CredentialsFile)) { "Create a new bot account at https://discordapp.com/developers/applications/me".Log(); Console.Write("[Text] Bot Token: "); Token = Console.ReadLine(); Console.Write("[Number] Application Id: "); while (!ulong.TryParse(Console.ReadLine(), out AppId)) { ; } "You can find your id (the bot owner's id) by typing \\@YourName in a server".Log(); Console.Write("[Number] Owner Id: "); while (!ulong.TryParse(Console.ReadLine(), out Owner)) { ; } File.WriteAllText(CredentialsFile, Token + "\r\n" + AppId + "\r\n" + Owner); } var Credentials = File.ReadAllText(CredentialsFile).Replace("\r", string.Empty).Split('\n'); Token = Credentials[0]; if (ulong.TryParse(Credentials[1], out AppId)) { InviteLink.Log(); } if (Credentials.Length <= 2 || !ulong.TryParse(Credentials[2], out Owner)) { "Couldn't load owner id from credentials".Log(); } if (Credentials.Length > 3) { MainDir = Credentials[3]; } Client = new DiscordClient(); Client.UsingAudio(new AudioServiceConfigBuilder() { Channels = 2, EnableEncryption = false, EnableMultiserver = true, Bitrate = AudioServiceConfig.MaxBitrate, BufferLength = 1000, Mode = AudioMode.Outgoing }.Build()); MusicHandler.Buffers = new ByteBuffer(1920 * 2, (int)Math.Pow(2, 16)); InitCommands(); Client.Log.Message += ClientEvents.LogMessage; Client.MessageReceived += ClientEvents.MessageReceived; Client.UserJoined += ClientEvents.UserJoined; Client.UserLeft += ClientEvents.UserLeft; Client.JoinedServer += ClientEvents.JoinedServer; Client.ServerAvailable += ClientEvents.ServerAvailable; Client.LeftServer += ClientEvents.LeftServer; try { new Func <Task>(async delegate { await Client.Connect(Token); }).UntilNoExceptionAsync <Discord.Net.WebSocketException>(3).Wait(); } catch (AggregateException) { } if (Client.State != ConnectionState.Connected) { Console.WriteLine("Could not connect to Discord. Type 'delete' to delete the current credentials file"); if (Console.ReadLine() == "delete") { File.Delete(CredentialsFile); } return; } Updater = new Timer(1000); Updater.Elapsed += UpdateTitle; Updater.AutoReset = true; Start = DateTime.Now; Updater.Start(); "The Discord functions have successfully booted".Log(); handler = new ConsoleEventDelegate(ConsoleEventCallback); SetConsoleCtrlHandler(handler, true); AppDomain.CurrentDomain.UnhandledException += (s, e) => { var StartInfo = Process.GetCurrentProcess().StartInfo; StartInfo.FileName = Process.GetCurrentProcess().MainModule.FileName; Process.Start(StartInfo); Shutdown(); }; if (File.Exists(TelegramFile)) { TelegramIntegration.Start(File.ReadAllText(TelegramFile).Trim()).Forget(); } Client.Wait(); }
public DiscordBot() { client = new DiscordClient(input => { input.LogLevel = LogSeverity.Info; input.LogHandler = Log; }); client.UsingCommands(input => { input.PrefixChar = '!'; input.AllowMentionPrefix = true; input.HelpMode = HelpMode.Public; }); commands = client.GetService <CommandService>(); commands.CreateCommand("Hello").Alias(new string[] { "hi", "sup" }).Do(async(e) => { await e.Channel.SendMessage("World"); }); commands.CreateCommand("Niggah").Alias(new string[] { "yo", "homie" }).Do(async(e) => { await e.Channel.SendMessage("N***a, please!"); }); commands.CreateCommand("announce").Parameter("message", ParameterType.Unparsed).Do(async(e) => { await DoAnnouncement(e); }); client.UserJoined += async(s, e) => { var channel = e.Server.FindChannels("gay-mers", ChannelType.Text).FirstOrDefault(); var user = e.User; await channel.SendTTSMessage(string.Format("{0} has joined the channel!", user.Name)); }; client.UserLeft += async(s, e) => { var channel = e.Server.FindChannels("gay-mers", ChannelType.Text).FirstOrDefault(); var user = e.User; await channel.SendTTSMessage(string.Format("{0} has left the channel", user.Name)); }; client.ExecuteAndWait(async() => { await client.Connect("MTk3NDUzODUwNDY5MzM1MDUx.C2g1eg.SJtbmHXDhsIbxorIXjkxQV2VDLs", TokenType.Bot); }); /* MULTITHREADED ADMIN PANEL*/ commands.CreateCommand("adminpanel").Do((e) => { AdminPanel = new Adminpanel(client, e); var thread = new Thread(OpenAdminPanel); thread.SetApartmentState(ApartmentState.STA); thread.Start(); }); }
public MyBot() { discord = new DiscordClient(x => { x.LogLevel = Discord.LogSeverity.Info; x.LogHandler = Log; }); discord.UsingCommands(x => { x.PrefixChar = '.'; x.AllowMentionPrefix = true; }); var commands = discord.GetService <CommandService>(); commands.CreateCommand("type") .Do(async(e) => { await e.Channel.SendIsTyping(); // await e.Channel.DeleteMessages(); }); commands.CreateCommand("poop") .Do(async(e) => { await e.Channel.SendMessage("POOP"); }); commands.CreateCommand("del") .Do(async(e) => { Message[] messagestoDelete; messagestoDelete = await e.Channel.DownloadMessages(2); await e.Channel.DeleteMessages(messagestoDelete); }); commands.CreateCommand("triggered") .Do(async(e) => { await e.Channel.SendIsTyping(); await e.Channel.SendFile("gif/trig.webp"); }); commands.CreateCommand("eg") .Do(async(e) => { await e.Channel.SendIsTyping(); await e.Channel.SendFile("gif/bear.png"); }); commands.CreateCommand("stocks") .Do(async(e) => { //Create the quote service var quote_service = new QuoteService(); //Get a quote var quotes = quote_service.Quote("COST", "").Return(QuoteReturnParameter.Symbol, QuoteReturnParameter.Name, QuoteReturnParameter.LatestTradePrice, QuoteReturnParameter.ChangeAsPercent, QuoteReturnParameter.LatestTradeTime); //Get info from the quotes foreach (var quote in quotes) { //Console.WriteLine("{0} - {1} - {2} - {3}", quote.Symbol, quote.Name, quote.LatestTradePrice, quote.LatestTradeTime); await e.Channel.SendMessage(quote.Name); await e.Channel.SendMessage(quote.ChangeAsPercent); } }); //Audio Portion// discord.UsingAudio(x => { x.Mode = AudioMode.Outgoing; }); commands.CreateCommand("joinc") .Do(async(e) => { var voiceChannel = discord.FindServers("C++").FirstOrDefault().VoiceChannels.FirstOrDefault(); // Finds the first VoiceChannel on the server 'Music Bot Server' var _vClient = await discord.GetService <AudioService>() // We use GetService to find the AudioService that we installed earlier. In previous versions, this was equivelent to _client.Audio() .Join(voiceChannel); // Join the Voice Channel, and return the IAudioClient. }); commands.CreateCommand("joine") .Do(async(e) => { var voiceChannel = discord.FindServers("The Great Eagle Bear").FirstOrDefault().VoiceChannels.FirstOrDefault(); // Finds the first VoiceChannel on the server 'Music Bot Server' var _vClient = await discord.GetService <AudioService>() // We use GetService to find the AudioService that we installed earlier. In previous versions, this was equivelent to _client.Audio() .Join(voiceChannel); // Join the Voice Channel, and return the IAudioClient. }); commands.CreateCommand("join") .Do(async(e) => { Channel voiceChan = e.User.VoiceChannel; // await voiceChan.JoinAudio(); var _vClient = await discord.GetService <AudioService>() // We use GetService to find the AudioService that we installed earlier. In previous versions, this was equivelent to _client.Audio() .Join(voiceChan); // Join the Voice Channel, and return the IAudioClient. }); commands.CreateCommand("leave") .Do(async(e) => { Channel voiceChan = e.User.VoiceChannel; await voiceChan.LeaveAudio(); }); commands.CreateCommand("kys") .Do(async(e) => { await discord.Disconnect(); }); /////Audio Portion/// //GREETING discord.GetService <CommandService>().CreateCommand("greet") //create command greet .Alias(new string[] { "gr", "hi" }) //add 2 aliases, so it can be run with ~gr and ~hi .Description("Greets a person.") //add description, it will be shown when ~help is used .Parameter("GreetedPerson", ParameterType.Required) //as an argument, we have a person we want to greet .Do(async e => { await e.Channel.SendMessage($"{e.User.Name} greets {e.GetArg("GreetedPerson")}"); //sends a message to channel with the given text }); //GREETING //Stocks/////////////////////////////////////////// discord.GetService <CommandService>().CreateCommand("price") //create command greet .Alias(new string[] { "p", "quote" }) //add 2 aliases, so it can be run with ~gr and ~hi .Description("Shows stock price.") //add description, it will be shown when ~help is used .Parameter("TickerSymbol", ParameterType.Required) //as an argument, we have a person we want to greet .Do(async e => { //Create the quote service var quote_service = new QuoteService(); //Get a quote var quotes = quote_service.Quote($"{e.GetArg("TickerSymbol")}", "").Return(QuoteReturnParameter.Symbol, QuoteReturnParameter.Name, QuoteReturnParameter.LatestTradePrice, QuoteReturnParameter.LatestTradeTime); //Get info from the quotes foreach (var quote in quotes) { //Console.WriteLine("{0} - {1} - {2} - {3}", quote.Symbol, quote.Name, quote.LatestTradePrice, quote.LatestTradeTime); await e.Channel.SendMessage(quote.Name); await e.Channel.SendMessage("$" + quote.LatestTradePrice); } //await e.Channel.SendMessage($"{e.User.Name} greets {e.GetArg("GreetedPerson")}"); //sends a message to channel with the given text }) ; //STOCKS^///////////////////////////////////// //FLIP// commands.CreateCommand("flipcoin") .Do(async(e) => { Random random = new Random(); int randomNumber = random.Next(1, 3); if (randomNumber == 1) { await e.Channel.SendMessage("HEADS"); } else if (randomNumber == 2) { await e.Channel.SendMessage("TAILS"); } }); commands.CreateCommand("flipdie") .Do(async(e) => { Random random = new Random(); int randomNumber = random.Next(1, 7); await e.Channel.SendMessage("" + randomNumber); }); //CONNECT BOT discord.ExecuteAndWait(async() => { await discord.Connect("MzM1MjM1NjU2NjAxMDQyOTQ1.DEnZhw.ANvKVSPmrLfEaEwdzhmjdTbVdtE", TokenType.Bot); }); }
static Task ClientTask(DiscordClient client) { return(Task.Run(() => { Console.WriteLine("WELCOME TO DISCORD BOT" + "\n============================="); // voice messages client.MessageReceived += (sender, e) => { // Joining a voice channel if (e.message.content.StartsWith("!joinvoice")) { string[] split = e.message.content.Split(new char[] { ' ' }, 2); if (!String.IsNullOrEmpty(split[1])) { DiscordChannel toJoin = e.Channel.parent.channels.Find(x => (x.Name.ToLower() == split[1].ToLower()) && (x.Type == ChannelType.Voice)); if (toJoin != null) { DiscordVoiceConfig voiceCfg = new DiscordVoiceConfig() { Bitrate = null, Channels = 1, FrameLengthMs = 60, OpusMode = Discord.Audio.Opus.OpusApplication.LowLatency, SendOnly = false }; audio = new AudioPlayer(voiceCfg); client.ConnectToVoiceChannel(toJoin); } } } else if (e.message.content.StartsWith("!addsong")) { string[] split = e.message.content.Split(new char[] { ' ' }, 3); if (split.Count() >= 3 && !String.IsNullOrEmpty(split[1]) && !String.IsNullOrEmpty(split[2])) { DoVoiceURL(client.GetVoiceClient(), split[1], split[2]); } else { client.SendMessageToChannel("Incorrect add song syntax.", e.Channel); } } else if (e.message.content.StartsWith("!play")) { string[] split = e.message.content.Split(new char[] { ' ' }, 2); if (File.Exists(split[1])) { DoVoiceMP3(client.GetVoiceClient(), split[1]); } else { client.SendMessageToChannel("Song does not exist.", e.Channel); } } else if (e.message.content.StartsWith("!disconnect")) { client.DisconnectFromVoice(); } }; // other messages client.MessageReceived += (sender, e) => { Console.WriteLine($"[" + e.Channel.Name.ToString() + "] " + e.message.author.Username + ": " + e.message.content.ToString()); if (e.Channel.Name == "thatbelikeitis" || e.Channel.Name == "newtestchannel") { mainText = e.Channel; quoteMuseum = client.GetChannelByName("quotes"); } if (e.message.content.StartsWith("!help")) { string helpMsg = "Welcome to DiscordBot! The following commands are available:\n" + "help, hello, joinvoice [channelname], play [mp3 path], addsong [youtube url] [song name], roll [XdX] [+/-] [mod]"; client.SendMessageToChannel(helpMsg, e.Channel); } // Text detection if (e.message.content.Contains("Kappa") || e.message.content.Contains("kappa")) { client.SendMessageToChannel("We don't use that word here.", e.Channel); } else if (e.message.content.Contains("I'm back") || e.message.content.Contains("im back")) { client.SendMessageToChannel("I'm front", e.Channel); } else if (e.message.content.Contains("ryan") || e.message.content.Contains("Ryan") || e.message.content.Contains("jimmy")) { client.AttachFile(e.Channel, "", "jimmyneukong.jpg"); //client.SendMessageToChannel("ryan", e.Channel); } else if (e.message.content.Contains("f14")) { client.AttachFile(e.Channel, "", "f14.jpg"); } // Commands! if (e.message.content.StartsWith("!hello")) { client.SendMessageToChannel("Hello World!", e.Channel); } else if (e.message.content.StartsWith("!quote")) { string quote = GetRandomQuote(client); client.SendMessageToChannel(quote, e.Channel); } else if (e.message.content.StartsWith("!addquote")) { char[] newQuote = e.message.content.Skip(9).ToArray(); client.SendMessageToChannel(new string(newQuote), quoteMuseum); } else if (e.message.content.StartsWith("!roll")) { string[] split = e.message.content.Split(new char[] { ' ' }, 4); if (split.Count() >= 2 && !String.IsNullOrEmpty(split[1])) { string[] split2 = split[1].Split(new char[] { 'd' }, 2); int roll = 0; if (split.Count() >= 4 && !String.IsNullOrEmpty(split[2]) && !String.IsNullOrEmpty(split[3])) { if (split[2] == "+") { roll = Roll(Int32.Parse(split2[0]), Int32.Parse(split2[1]), Int32.Parse(split[3])); } else if (split[2] == "-") { roll = Roll(Int32.Parse(split2[0]), Int32.Parse(split2[1]), Int32.Parse(split[3]) * -1); } else { client.SendMessageToChannel("Can only mod by + or -! Result invalid.", e.Channel); } } else { roll = Roll(Int32.Parse(split2[0]), Int32.Parse(split2[1]), 0); } string msg = split2[0] + "d" + split2[1] + ": " + roll; client.SendMessageToChannel(msg, e.Channel); } else { client.SendMessageToChannel("Missing arguments!", e.Channel); } } else if (e.message.content.StartsWith("!chat")) { char[] chatMsg = e.message.content.Skip(6).ToArray(); string reply = chatBot.Think(new string(chatMsg)); Console.WriteLine(new string(chatMsg)); Console.WriteLine(reply); client.SendMessageToChannel(reply, e.Channel); } else if (e.message.content.StartsWith("!supersecretshutdowncommand")) { System.Environment.Exit(0); } }; client.Connected += (sender, e) => { Console.WriteLine($"Connected! User: {e.user.Username}"); }; client.Connect(); })); }
public void Start() { _client = new DiscordClient(); _client.MessageReceived += async(s, e) => { if (!e.Message.IsAuthor) { await e.Channel.SendMessage(e.Message.Text); } }; _client.ExecuteAndWait(async() => { await _client.Connect("NDk5NzkzMzc5NTg5MzU3NTY4.DqBdxg.4YYspJPKqoHgYYeiyt7CoxXpv-E", TokenType.Bot); }); //set bot prefix _client.UsingCommands(x => { x.PrefixChar = !; //find how to set 2 character as prefix ";/" x.HelpMode = HelpMode.Public; }); _client.GetService <CommandService>().CreateCommand("name") //Create a command .Alias(new string[] { "cmd", "command" }) //add 2 aliases, so it can be run with ~cmd and ~command .Description("Command description.") //add description, it will be shown when ~help is used .Parameter("ParameterName", ParameterType.Required) //as an argument, we have a person we want to greet .Do(async e => { await e.Channel.SendMessage($"{e.User.Name} Command reply {e.GetArg("ParameterName")}"); //sends a message to channel with the given text }); //TODO: Find how to create a Channel, learn more about Parameters and make this work! _client.GetService <CommandService>().CreateGroup("make", make => { make.CreateCommand("textch") //~make textch .Alias(new string[] { "textch" }) .Description("Creates a new Text Channel.") // Not work yet .Parameter("???", ParameterType.Required) .Do(async e => { await e.Channel.SendMessage($"{e.User.Name} i donno wtf i'm doing {e.GetArg("???")}"); }); make.CreateCommand("voicech") //~make voicech .Alias(new string[] { "voicech" }) .Description("Creates a new Voice Channel.") // not work yet .Parameter("????", ParameterType.Required) .Do(async e => { await e.Channel.SendMessage($"{e.User.Name} change it later {e.GetArg("???")}"); }); }); //exemple//we would run our commands with ~do greet X and ~do bye X _client.GetService <CommandService>().CreateGroup("do", cgb => { cgb.CreateCommand("greet") .Alias(new string[] { "gr", "hi" }) .Description("Greets a person.") .Parameter("GreetedPerson", ParameterType.Required) .Do(async e => { await e.Channel.SendMessage($"{e.User.Name} greets {e.GetArg("GreetedPerson")}"); }); cgb.CreateCommand("bye") .Alias(new string[] { "bb", "gb" }) .Description("Greets a person.") .Parameter("GreetedPerson", ParameterType.Required) .Do(async e => { await e.Channel.SendMessage($"{e.User.Name} says goodbye to {e.GetArg("GreetedPerson")}"); }); }); }
public EvilBot() { discord = new DiscordClient(x => { x.LogLevel = LogSeverity.Info; x.LogHandler = Log; }); discord.UsingCommands(x => { x.PrefixChar = '`'; x.AllowMentionPrefix = true; }); CommandService commands; commands = discord.GetService <CommandService>(); //---------------------------------------Show me what you got--------------------------------- freshestMemes = new string[] { "mem/test.jpg", "mem/GetInBich.jpg", "mem/rompers.jpg", "mem/dwk.jpg", "mem/abortion.jpg", "mem/prayer.jpg", "mem/sasuke_patrick.jpg" }; commands.CreateCommand("show me what you got") .Do(async(e) => { Random rand = new Random(); int temp = rand.Next(0, freshestMemes.Length); await e.Channel.SendMessage("Here is meme #" + temp + "/" + freshestMemes.Length); await e.Channel.SendFile(freshestMemes[temp]); }); //----------------------------------Text Commands------------------------------ commands.CreateCommand("hello") .Do(async(e) => { await e.Channel.SendMessage("Hi Bitch!"); }); commands.CreateCommand("help") .Do(async(e) => { await e.Channel.SendMessage("Do I look like the kind of bot that gives help?"); }); commands.CreateCommand("help") .Do(async(e) => { await e.Channel.SendMessage("Do I look like the kind of bot that gives help?"); }); discord.ExecuteAndWait(async() => { await discord.Connect("MzE4NTk4NzE4MTYzMjU1Mjk4.DDISOw.s3-TBtxlDop7KUMx3N7O6s2rMAY", TokenType.Bot); }); }