Beispiel #1
0
    public async Task Run()
    {
        client = new DiscordSocketClient();

        // Place the token of your bot account here
        string token = "aaabbbccc";

        // Hook into the MessageReceived event on DiscordSocketClient
        client.MessageReceived += async(message) =>
        {   // Check to see if the Message Content is "!ping"
            if (message.Content == "!ping")
            {
                // Send 'pong' back to the channel the message was sent in
                await message.Channel.SendMessageAsync("pong");
            }
        };

        // Configure the client to use a Bot token, and use our token
        await client.LoginAsync(TokenType.Bot, token);

        // Connect the client to Discord's gateway
        await client.ConnectAsync();

        // Block this task until the program is exited.
        await Task.Delay(-1);
    }
Beispiel #2
0
        /// <summary>
        /// Stars Disbott Running
        /// </summary>
        /// <returns></returns>
        public async Task Start()
        {
            _client   = new DiscordSocketClient();
            _commands = new CommandService();

            #if DEBUG
            var envpath = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.FullName + "/../variables.env";
            if (File.Exists(envpath))
            {
                Dictionary <string, string> variables = DotEnvFile.DotEnvFile.LoadFile(envpath);
                DotEnvFile.DotEnvFile.InjectIntoEnvironment(variables);
            }
            #endif

            var token = Environment.GetEnvironmentVariable("token");

            await InstallCommands();

            await _client.LoginAsync(TokenType.Bot, token);

            await _client.ConnectAsync();

            await ModifyStatus();

            await Task.Delay(-1);
        }
Beispiel #3
0
        public async Task Start()
        {
            _client = new DiscordSocketClient(new DiscordSocketConfig()
            {
                LogLevel = LogSeverity.Info
            });
            _client.Log += (message) => {
                Console.WriteLine($"[{message.Severity}] {message.Source}: {message.Exception?.ToString() ?? message.Message}");
                return(Task.CompletedTask);
            };

            handler = new CommandHandler();
            await handler.Load(_client);

            // Configure the client to use a Bot token, and use our token
            await _client.LoginAsync(TokenType.Bot, token);

            // Connect the client to Discord's gateway
            await _client.ConnectAsync();

            foreach (SocketGuild guild in _client.Guilds)
            {
                Configuration.Load(guild.Id);
                await _client.SetGame(Configuration.activeServers[guild.Id].Game);
            }

            // Block this task until the program is exited.
            await Task.Delay(-1);
        }
Beispiel #4
0
        public async Task Start()
        {
            EnsureConfigExists();

            // Define the DiscordSocketClient
            client = new DiscordSocketClient(new DiscordSocketConfig
            {
                WebSocketProvider = Discord.Net.Providers.WS4Net.WS4NetProvider.Instance
            });

            // Login and connect to Discord.
            await client.LoginAsync(TokenType.Bot, Configuration.Load().Token);

            await client.ConnectAsync();

            var map = new DependencyMap();

            map.Add(client);

            handler = new CommandHandler();
            await handler.Install(map);


            // Block this program until it is closed.
            await Task.Delay(-1);
        }
Beispiel #5
0
        public async Task Start()
        {
            client = new DiscordSocketClient(new DiscordSocketConfig
            {
                MessageCacheSize = 1000,
            });

            string token = Environment.GetEnvironmentVariable("discord-foxboat-token");

            client.Log += (msg) =>
            {
                Console.WriteLine(msg.ToString());
                return(Task.CompletedTask);
            };

            await client.LoginAsync(TokenType.Bot, token);

            await client.ConnectAsync();

            var map = new DependencyMap();

            ConfigureServices(map);
            await new CommandHandler().Install(map);

            await Task.Delay(-1);
        }
Beispiel #6
0
        public async void InitAsync()
        {
            //_responders.Add(DiscordEvent.UserJoined, new UserUpdatedResponder());
            //_responders.Add(DiscordEvent.UserLeft, new UserUpdatedResponder());
            _responders.Add(DiscordEvent.MessageReceived, new MessageReceivedResponder());
            _responders.Add(DiscordEvent.UserUpdated, new UserUpdatedResponder());

            await Client.LoginAsync(TokenType.Bot, "");

            await Client.ConnectAsync();

            StartUpTime = DateTime.Now;

            Guild = Client.GetGuild(91374358932496384);

            //Client.UserJoined += _responders[DiscordEvent.UserJoined].RespondAsync;
            Client.MessageReceived += _responders[DiscordEvent.MessageReceived].RespondAsync;
            //Client.UserLeft += _responders[DiscordEvent.UserLeft].RespondAsync;
            //Client.UserUpdated += _responders[DiscordEvent.UserUpdated].RespondAsync;
            Client.UserUpdated         += Client_UserUpdated;
            Client.UserPresenceUpdated += new UserPresenceUpdatedResponder().RespondAsync;

            SpeakTextChannel = await Guild.GetTextChannelAsync(91374358932496384);

            //await SpeakTextChannel.SendMessageAsync(":robot: BEEP BOOP. THE FATMAN HAS ARRIVED. :robot:");
        }
        /// <summary>
        /// Sets up a connection to the voice connection.
        /// </summary>
        /// <param name="url">The url of the voice connection.</param>
        public async Task ConnectAsync(string url)
        {
            VoiceConnectionStatus = VoiceConnectionStatus == VoiceConnectionStatus.Initialized ? VoiceConnectionStatus.Connecting : VoiceConnectionStatus.Reconnecting;

            _connectionUrl = url;
            _socket        = new DiscordSocketClient <VoiceSocketFrame>(_serializeOptions, _deserializeOptions, HandleMessage, HandleError, UnhandledMessageEncountered);
            await _socket.ConnectAsync(url);
        }
Beispiel #8
0
        public async Task Connect()
        {
            if (IsConnected)
            {
                throw new InvalidOperationException();
            }

            await _discordClient.LoginAsync(TokenType.Bot, DISCORD_BOT_KEY);

            await _discordClient.ConnectAsync();

            IsConnected = true;

            _discordClient.MessageReceived += DiscordClientOnMessageReceived;
        }
Beispiel #9
0
    public async Task Start()
    {
        client   = new DiscordSocketClient();
        commands = new CommandService();

        string token = "bot token here";

        await InstallCommands();

        await client.LoginAsync(TokenType.Bot, token);

        await client.ConnectAsync();

        await Task.Delay(-1);
    }
Beispiel #10
0
        public async Task Start()
        {
            // As we are not using 4.6 we must include the Discord.Net WebSocketProvider.
            client = new DiscordSocketClient(new DiscordSocketConfig {
                WebSocketProvider = Discord.Net.Providers.WS4Net.WS4NetProvider.Instance,
                LogLevel          = LogSeverity.Verbose
            });
            // Writes detailed log to the console
            client.Log += (l)
                          => Task.Run(()
                                      => Console.WriteLine($"[{l.Severity}] {l.Source}: {l.Exception?.ToString() ?? l.Message}"));

            // Variable for token
            var token = "MjY0MjAwODI2NDI2MzU5ODA4.C3NZWg.hLb2Z8U66zcef7fgC43yAra6Ydo";

            // Use token to login, and then use asyncconnect to connect to discord
            await client.LoginAsync(TokenType.Bot, token);

            await client.ConnectAsync();

            // Create a new dependency map
            var map = new DependencyMap();

            map.Add(client);

            // Recall command handler and add the dependency map to it
            handler = new CommandHandler();
            await handler.Install(map);

            // Hooking into events

            client.UserJoined += async(e) =>
            {
                try
                {
                    ulong channelid = 266188297339011082;
                    e.Discord.GetChannel(channelid);
                    Console.WriteLine("Channel Found");
                }
                catch
                {
                    Console.WriteLine("Channel not found, or error with code");
                }
            };

            // Block the closing of the program until it is closed
            await Task.Delay(-1);
        }
        public async Task Start()
        {
            client = new DiscordSocketClient();

            await client.LoginAsync(TokenType.Bot, "TOKEN HERE");

            await client.ConnectAsync();

            var map = new DependencyMap();

            map.Add(client);

            handler = new CommandHandler();
            await handler.Install(map);

            await Task.Delay(-1);
        }
Beispiel #12
0
        /// <summary>
        ///     Runs the bot, Exceptions are send to the callback.ExceptionNotifier
        /// </summary>
        /// <see cref="LoginForm" />
        public async void Run()
        {
            try
            {
                // Configure the client to use a Bot token, and use our token
                await _client.LoginAsync(TokenType.User, _token);

                // Connect the client to Discord's gateway
                await _client.ConnectAsync();

                //activate commands
                await InstallCommands();
            }
            catch (Exception e)
            {
                _callback.ExceptionNotifier(e);
            }
        }
Beispiel #13
0
        public async Task Start()
        {
            client = new DiscordSocketClient();
            map    = new DependencyMap();

            map.Add(client);
            map.Add <ICommands>(new Commands(map));

            string token = Environment.GetEnvironmentVariable("token");

            await map.Get <ICommands>().Install();

            await client.LoginAsync(TokenType.Bot, token);

            await client.ConnectAsync();

            await client.SetStatusAsync(UserStatus.Idle);

            await client.SetGameAsync("Message !help for help");
        }
Beispiel #14
0
        public async Task Start()
        {
            // Define the DiscordSocketClient
            client = new DiscordSocketClient();

            var token = "token here";

            // Login and connect to Discord.
            await client.LoginAsync(TokenType.Bot, token);

            await client.ConnectAsync();

            var map = new DependencyMap();

            map.Add(client);

            handler = new CommandHandler();
            await handler.Install(map);

            // Block this program until it is closed.
            await Task.Delay(-1);
        }
        public async Task Run()
        {
            var client = new DiscordSocketClient(new DiscordSocketConfig
            {
                WebSocketProvider = new WebSocketProvider(() => new WS4NetProvider()),
                LogLevel          = LogSeverity.Debug
            });

            var token = Environment.GetEnvironmentVariable("discord-foxboat-token");

            client.Log += msg =>
            {
                Console.WriteLine(msg.ToString());
                return(Task.CompletedTask);
            };

            await client.LoginAsync(TokenType.Bot, token);

            await client.ConnectAsync();

            await Task.Delay(-1);
        }
Beispiel #16
0
        public async Task RunAsync()
        {
            client   = new DiscordSocketClient();
            commands = new CommandService();

            string token = "MjUxNDAzODcyMDM4Mjg5NDA5.CxvZLg.D4qdH8YZnhqOoW5z-kWnYUPLpLo";

            map = new DependencyMap();

            await InstallCommandsAsync();

            await client.LoginAsync(TokenType.Bot, token);

            await client.ConnectAsync();

            StatusService.SetMinecraftStatusAsync(client);

            // TODO: Set avatar
            //await SetAvatarAsync();

            await Task.Delay(-1);
        }
Beispiel #17
0
        private async Task RunAsync(StatsContext stats)
        {
            _stats    = stats;
            _client   = new DiscordSocketClient();
            _commands = new CommandService();
            await _commands.AddModules(Assembly.GetEntryAssembly());

            _map = new DependencyMap();
            _map.Add(_client);
            _map.Add(_stats);

            _client.MessageReceived += HandleCommand;
            _client.MessageReceived += HandleMessage;

            Console.WriteLine("Logging in...");
            await _client.LoginAsync(TokenType.Bot, config["Token"]);

            await _client.ConnectAsync();

            Console.WriteLine("Bot is ready.");
            await Task.Delay(-1);
        }
Beispiel #18
0
    public async Task RunBot()
    {
        if (!File.Exists("config.json"))
        {
            Console.Write("Please enter a bot token: ");
            string token = Console.ReadLine();
            config = BotConfiguration.CreateBotConfigWithToken("config.json", token);
        }
        else
        {
            config = BotConfiguration.ProcessBotConfig("config.json");
        }

        _client = new DiscordSocketClient(new DiscordSocketConfig
        {
            AudioMode = Discord.Audio.AudioMode.Disabled,
            LogLevel  = Discord.LogSeverity.Debug
        });
        _commands = new CommandService();

        await ApplyCommands();

        _client.Log             += _client_Log;             // console info
        _client.MessageReceived += _client_MessageReceived; // filtering and commands

        await _client.LoginAsync(Discord.TokenType.Bot, config.Token);

        await _client.ConnectAsync();

        await _client.CurrentUser.ModifyAsync((ModifyCurrentUserParams mod) =>
        {
            mod.Avatar = new Image(new FileStream("Assets/contacts.png", FileMode.Open));
        });

        await _client.SetGame("Helping you C#");

        await Task.Delay(-1);
    }
Beispiel #19
0
        private CommandService commands;                                                                                    //  Stores a CommandService

        public async Task Run()
        {
            client = new DiscordSocketClient(new DiscordSocketConfig()                                                      //  Sets the client variable to be a new socketconfig with certain properties
            {
                LogLevel          = LogSeverity.Debug,                                                                      //  Sets the loglevel to be debug
                WebSocketProvider = () => new WS4NetProvider()                                                              //  This is done so the program works on windows 7
            });

            client.Log += Log;                                                                                      //  Makes a new event handler called Log

            commands = new CommandService();                                                                        //  Instantiates the commands

            string token = "";                                                                                      //  Our token gets stored

            await InstallCommands();                                                                                //  Call the InstallCommands function

            await client.LoginAsync(TokenType.Bot, token);                                                          //  Tells the program to login the bot

            await client.ConnectAsync();                                                                            //  Tells the program to connect

            var map = new DependencyMap();                                                                          //  Stores a new dependency map, that is used for our commands

            map.Add(client);                                                                                        //  adds the client to the map

            client.UserJoined += async(user) =>                                                                     //  Makes an event handler for when a user joins
            {
                SocketRole welcomeRole = user.Guild.GetRole(248434734240104459);                                    //  Stores the welcome role
                await user.AddRolesAsync(welcomeRole);                                                              //  Assigns the welcome role to the user who joined

                Discord.Rest.RestDMChannel dmchannel = await user.CreateDMChannelAsync();                           //  Makes a dmchannel with the newly joined user

                await dmchannel.SendMessageAsync($"Welcome to {user.Guild.ToString()}, {user.Mention.ToString()}"); //  Writes a message in the dmchannel
            };

            await Task.Delay(-1);                                                                                           //  Delays the task for minus 1 milisecond
        }
Beispiel #20
0
        public async Task RunBot()
        {
            if (!File.Exists("config.json"))
            {
                Console.Write("Please enter a bot token: ");
                string token = Console.ReadLine();
                _config = BotConfiguration.CreateBotConfigWithToken("config.json", token);
            }
            else
            {
                _config = BotConfiguration.ProcessBotConfig("config.json");
                _config.SaveBotConfig("config.json");
            }
#if DEV
            if (string.IsNullOrWhiteSpace(_config.DevToken))
            {
                Console.Write("Please enter a dev token: ");
                string token = Console.ReadLine();
                _config.DevToken = token;
                Console.WriteLine("Please enter a dev channel name (commands sent to the bot will be restricted to this channel): ");
                string channel = Console.ReadLine();
                _config.DevChannel = channel;
                _config.SaveBotConfig("config.json");
            }
#endif

            _client = new DiscordSocketClient(new DiscordSocketConfig
            {
                AudioMode = Discord.Audio.AudioMode.Disabled,
                LogLevel  = LogSeverity.Debug
            });

            // Create the dependency map and inject the client and config into it
            _map = new DependencyMap();
            _map.Add(_client);
            _map.Add(_config);
            _map.Add(this);

            _handler = new CommandHandler();
            await _handler.Install(_map);

            AddAssemblyActions(_map);

            _client.Log += _client_Log; // console info
            _client.Log += FileLog;     // file logs

            // handle logging to channel
            _client.UserJoined     += ChannelLog_UserJoin;
            _client.UserLeft       += ChannelLog_UserLeave;
            _client.UserBanned     += ChannelLog_UserBanned;
            _client.UserUnbanned   += ChannelLog_UserUnbanned;
            _client.MessageDeleted += ChannelLog_MessageDeleted;

#if DEV
            await _client.LoginAsync(TokenType.Bot, _config.DevToken);
#else
            await _client.LoginAsync(Discord.TokenType.Bot, _config.Token);
#endif
            await _client.ConnectAsync();

            await _client.SetGame("Helping you C#");

            await Task.Delay(-1);
        }
Beispiel #21
0
Datei: Rem.cs Projekt: lofdat/Rem
        public static async Task Start()
        {
            Console.WriteLine("Handover success.");
            Console.Write("Attempting to initialize client and service... ");
            RemClient  = new DiscordSocketClient(RemSocketConfig);
            RemService = new CommandService(RemServiceConfig);
            Console.Write("Done.");
            Console.WriteLine();
            try
            {
                // Import JSON
                StreamReader RawOpen            = File.OpenText(@"./rem_config.json");
                StreamReader RawCredentialsOpen = File.OpenText(@"./credentials.json");
            }
            catch (FileNotFoundException)
            {
                Console.WriteLine("==== CRITICAL ISSUE ====");
                Console.WriteLine("Failed to access credentials or config.");
                Console.WriteLine($"Cannot read rem_config.json or credentials.json.");
                Console.WriteLine("Follow this guide and try again: https://github.com/iloverem/Rem/blob/master/README.md");
                await Task.Delay(-1);
            }
            Console.Write("Attempting to deserialize configuration and credential files.... ");
            StreamReader   Raw            = File.OpenText(@"./rem_config.json");
            StreamReader   RawCredentials = File.OpenText(@"./credentials.json");
            JsonTextReader TextReader     = new JsonTextReader(Raw);
            JsonTextReader CredTextReader = new JsonTextReader(RawCredentials);
            JObject        MidoriJConfig  = (JObject)JToken.ReadFrom(TextReader);
            JObject        MidoriCred     = (JObject)JToken.ReadFrom(CredTextReader);

            RemConfig      = JsonConvert.DeserializeObject <Dictionary <string, object> >(MidoriJConfig.ToString());
            RemCredentials = JsonConvert.DeserializeObject <Dictionary <string, object> >(MidoriCred.ToString());
            Console.Write("Done.");
            Console.WriteLine();

            // Setup dependencies
            Console.Write("Creating dependency library... ");
            IDependencyMap RemDeps = new DependencyMap();

            RemDeps.Add(RemClient);
            RemDeps.Add(RemService);
            RemDeps.Add(MidoriJConfig);
            Console.Write("Done.");
            Console.WriteLine();

            // Events handler
            Console.Write("Installing events handler.... ");
            RemEvents.Setup();
            Console.Write("Done.");
            Console.WriteLine();

            // Login and connect
            Console.Write("Logging in... ");
            await RemClient.LoginAsync(TokenType.Bot, (string)RemCredentials["Connection_Token"]);

            Console.Write("Done.");
            Console.WriteLine();
            Console.Write("Connecting.... ");
            await RemClient.ConnectAsync();

            Console.Write("Done.");
            Console.WriteLine();
            Console.Write("Downloading users.... ");
            await RemClient.DownloadAllUsersAsync();

            Console.Write("Done.");
            Console.WriteLine();

            // Install command handling
            Console.Write("Installing commands handler... ");
            await RemHandler.Setup(RemDeps);

            Console.Write("Done.");
            Console.WriteLine();

            // Ready
            Console.WriteLine("=====");
            Console.WriteLine((Rem.RemClient.GetApplicationInfoAsync().GetAwaiter().GetResult()).Description);
            Console.WriteLine("Active token: " + Rem.RemCredentials["Connection_Token"]);
            Console.WriteLine("Active command prefix: " + Rem.RemConfig["Command_Prefix"]);
            Console.WriteLine("Accepting bot commands: " + ((bool)Rem.RemConfig["AcceptBotCommands"] ? "Yes." : "No."));
            Console.WriteLine("Alerting on unknown command: " + ((bool)Rem.RemConfig["AlertOnUnknownCommands"] ? "Yes." : "No."));
            Console.WriteLine("=====");

            // Keep the bot running
            await Task.Delay(-1);
        }
Beispiel #22
0
        private async Task Run()
        {
            client = new DiscordSocketClient();

            // Place the token of your account here
            string token = "<insert token here>";

            client.ApiClient.ReceivedGatewayEvent += (code, i, arg3, arg4) =>
            {
                if (code != GatewayOpCode.Dispatch)
                {
                    return(Task.CompletedTask);
                }

                if (arg3 == "READY")
                {
                    JObject readyPacket = (JObject)arg4;
                    userGuildSettings = readyPacket["user_guild_settings"].ToObject <List <UserGuildSettings> >();
                }

                return(Task.CompletedTask);
            };

            // Hook into the MessageReceived event on DiscordSocketClient
            client.MessageReceived += message =>
            {
                if (message.Author.Id == this.client.CurrentUser.Id)
                {
                    return(Task.CompletedTask);
                }

                bool shouldSendMessage = false;
                if (message.Channel is IGuildChannel)
                {
                    var channel = (IGuildChannel)message.Channel;
                    var guild   = userGuildSettings.Where(x => x.IsMobilePushEnabled && !x.IsMuted && x.GuildId != null).FirstOrDefault(y => y.GuildId == channel.GuildId);
                    if (guild != null)
                    {
                        var channelOverride = guild.ChannelOverrides?.FirstOrDefault(x => x.ChannelId == channel.Id);
                        if (channelOverride != null)
                        {
                            switch (channelOverride.NotificationLevel)
                            {
                            case NotificationSettingLevel.AllMessages:
                                if (!channelOverride.IsMuted)
                                {
                                    shouldSendMessage = true;
                                }
                                break;

                            case NotificationSettingLevel.Mentions:
                                if (message.MentionedUsers.Any(x => x.Id == client.CurrentUser.Id) && !channelOverride.IsMuted)
                                {
                                    shouldSendMessage = true;
                                }
                                break;

                            case NotificationSettingLevel.Parent:
                                shouldSendMessage = ShouldNotifyGuild(guild, message);
                                break;
                            }
                        }
                        else
                        {
                            shouldSendMessage = ShouldNotifyGuild(guild, message);
                        }
                    }
                }

                if (shouldSendMessage)
                {
                    // Just use a random default URL for the moment
                    SendNotificationAsync(message.Author.Username + " (#" + message.Channel.Name + ")", message.Author.AvatarUrl ?? "https://discordapp.com/assets/1cbd08c76f8af6dddce02c5138971129.png", message.Content, client.CurrentUser.Id);
                }

                return(Task.CompletedTask);
            };

            await client.LoginAsync(TokenType.User, token);

            await client.ConnectAsync();

            // Block this task until the program is exited.
            await Task.Delay(-1);
        }
Beispiel #23
0
 public async Task ConnectAsync(string url)
 {
     _connectionUrl = url;
     _socket        = new DiscordSocketClient <GatewaySocketFrame>(_serializeOptions, _deserializeOptions, HandleMessage, HandleError, UnhandledMessageEncountered);
     await _socket.ConnectAsync(url);
 }
Beispiel #24
0
        private async Task Bot()
        {
            await _client.LoginAsync(TokenType.User, tbToken.Text);

            await _client.ConnectAsync();
        }