示例#1
0
        public async Task RemoveCargoComONomeDoEmojiReactRoleAsync(CommandContext ctx, DiscordChannel canalReactRole = null, string emoji = null)
        {
            await ctx.TriggerTypingAsync();

            new Thread(async() =>
            {
                try
                {
                    CommandsNextExtension commandsNext = ctx.Client.GetCommandsNext();

                    Command ProcuraComando = commandsNext.FindCommand($"reactrole cargo.del {canalReactRole.Id} {Program.Bot.Utilities.FindEmoji(ctx, emoji)}", out string Args);
                    CommandContext Comando = commandsNext.CreateFakeContext(ctx.Member, ctx.Channel, "", "//", ProcuraComando, Args);

                    await commandsNext.ExecuteCommandAsync(Comando);
                }
                catch (ArgumentException)
                {
                    await ctx.RespondAsync($"{ctx.Member.Mention}, este emoji não foi encontrado!");
                }
                catch (Exception exception)
                {
                    await Program.Bot.Logger.Error(Log.TypeError.Commands, exception);
                }
            }).Start();
        }
        public async Task Sudo(CommandContext ctx,
                               [Description("user to execute as.")] DiscordMember member,
                               [Description("command text to execute."), RemainingText] string command)
        {
            if (ctx.Channel.IsPrivate)
            {
                await ctx.RespondAsync(":x: This command is only for server use.");

                return;
            }
            await ctx.TriggerTypingAsync();

            CommandsNextExtension cmds    = ctx.CommandsNext;
            CommandContext        fakectx = cmds.CreateFakeContext(member, ctx.Channel, command, ctx.Prefix, cmds.FindCommand(command, out _));
            await cmds.ExecuteCommandAsync(fakectx);
        }
示例#3
0
        public Task Commands(DiscordClient c, MessageCreateEventArgs e)
        {
            _ = Task.Run(async() =>
            {
                if (e.Author.IsBot || string.IsNullOrEmpty(e.Message.Content))
                {
                    return;
                }
                CommandsNextExtension cnext = c.GetCommandsNext();

                string prefix = _prefixCache.RetrievePrefix(e.Guild?.Id);

                int prefixLength =
                    e.Channel.IsPrivate ? 0 : // No prefix in DMs, else try to get the string prefix length. //
                    e.MentionedUsers.Any(u => u.Id == c.CurrentUser.Id) ?
                    e.Message.GetMentionPrefixLength(c.CurrentUser) :
                    e.Message.GetStringPrefixLength(prefix);

                if (prefixLength is - 1)
                {
                    return;
                }

                string commandString = e.Message.Content.Substring(prefixLength);

                Command?command = cnext.FindCommand(commandString, out string arguments);

                if (command is null)
                {
                    _logger.LogWarning($"Command not found: {e.Message.Content}");
                    return;
                }
                CommandContext context = cnext.CreateContext(e.Message, prefix, command, arguments);

                await cnext.ExecuteCommandAsync(context).ConfigureAwait(false);
            });
            return(Task.CompletedTask);
        }
示例#4
0
        static async Task MainAsync()
        {
            discord = new DiscordClient(new DiscordConfiguration
            {
                Token           = Environment.GetEnvironmentVariable("Bot_Token"),
                TokenType       = TokenType.Bot,
                MinimumLogLevel = Microsoft.Extensions.Logging.LogLevel.Debug
            });
            commands = discord.UseCommandsNext(new CommandsNextConfiguration
            {
                CaseSensitive  = false,
                EnableDms      = false,
                StringPrefixes = new string[] { "#", "$" }
            });
            commands.RegisterCommands <MedicCommands>();
            commands.CommandErrored  += Commands_CommandErrored;
            commands.CommandExecuted += Commands_CommandExecuted;
            interactivity             = discord.UseInteractivity(new InteractivityConfiguration
            {
                Timeout = TimeSpan.FromMinutes(1)
            });
            // EnableIncoming = true increases CPU usage and is not being used until Speech Recognition can be handled easily.
            voice = discord.UseVoiceNext(new VoiceNextConfiguration
            {
                AudioFormat    = new AudioFormat(48000, 2, VoiceApplication.LowLatency),
                EnableIncoming = false
            });

            AudioHelper.Load();
            AudioHelper.CheckForErrors();


            System.Timers.Timer timer = new System.Timers.Timer(900000); // change this to a larger value later: 900000
            timer.Elapsed += Timer_ElapsedAsync;
            timer.Enabled  = true;

            if (!File.Exists("safe-guilds.txt"))
            {
                File.WriteAllText("safe-guilds.txt", "386570547267502080");
            }

            discord.VoiceStateUpdated += async(client, e) =>
            {
                if (voice.GetConnection(e.Guild) != null) //Remove(d) second check so bot can play audio for itself??   (&& e.User != discord.CurrentUser)
                {
                    if (e.Channel == voice.GetConnection(e.Guild).TargetChannel&& !alreadyPlayedForUsers.Contains(e.User.Id))
                    { // If the user who triggered the event is in the same voice channel as the bot; AND the intro hasn't been played for the user yet
                        List <AudioEntry> intros     = AudioHelper.GetUniversalIntros();
                        List <AudioEntry> userIntros = AudioHelper.GetUserIntros(e.After.User.Id);
                        if (userIntros != null || userIntros.Count != 0) // Exception here
                        {
                            intros.AddRange(userIntros);
                        }

                        AudioEntry introEntry = intros.OrderBy(e => new Random().Next()).First();

                        await Task.Delay(1000);

                        await commands.ExecuteCommandAsync(commands.CreateFakeContext(e.User, e.Guild.Channels[505103389537992704], "#play " + introEntry.Name, "#", commands.RegisteredCommands["play"], introEntry.Name));

                        alreadyPlayedForUsers.Add(e.User.Id);
                    }
                    else if (e.Channel == null)
                    { // Someone left
                        alreadyPlayedForUsers.Remove(e.User.Id);
                        if (e.Before.Channel.Users.Count() == 1)
                        {
                            await commands.ExecuteCommandAsync(commands.CreateFakeContext(e.User, e.Guild.Channels[505103389537992704], "#leave", "#", commands.RegisteredCommands["leave"]));
                        }
                    }
                }
                else if (e.User.Id == client.CurrentUser.Id)
                {     // Bot did something
                    if ((e.Before == null || e.Before.Channel == null) && (e.After != null && e.After.Channel != null))
                    { // Bot joined
                        alreadyPlayedForUsers.AddRange(e.After.Channel.Users.Where(u => u.Id != client.CurrentUser.Id).Select(u => u.Id));
                    }
                    else
                    {
                        // Bot left
                    }
                }
            };

            discord.MessageCreated += async(client, e) =>
            {
                if (e.Author.Equals(discord.CurrentUser))
                {
                    return;
                }
                string messageContent = e.Message.Content.ToLower();
                if (e.Author.Id == 477504775907311619 && e.Message.Content == "wrong" && discord.GetVoiceNext().GetConnection(e.Guild) != null)
                {
                    DiscordUser medicUser = await discord.GetUserAsync(134336937224830977);

                    //await commands.SudoAsync(medicUser, e.Channel, "#play wrong");
                    await commands.ExecuteCommandAsync(commands.CreateFakeContext(medicUser, e.Channel, "#play wrong", "#", commands.RegisteredCommands.Where(c => c.Key == "play").FirstOrDefault().Value, "wrong"));
                }
                else if (messageContent.StartsWith("creeper"))
                {
                    await e.Channel.SendMessageAsync("Aww man!");

                    if (discord.GetVoiceNext().GetConnection(e.Guild) != null)
                    {
                        DiscordUser medicUser = await discord.GetUserAsync(134336937224830977);

                        await commands.ExecuteCommandAsync(commands.CreateFakeContext(medicUser, e.Channel, "#play aw man", "#", commands.RegisteredCommands.Where(c => c.Key == "play").FirstOrDefault().Value, "aw man"));
                    }
                }
                else if (messageContent.Contains("iftara") || messageContent.Contains("akşam ezanına"))
                {
                    DateTime iftarTime = GetIftarTime(cityScheduleLinks.Keys.Where(s => messageContent.ToLower().Contains(s)).FirstOrDefault());
                    TimeSpan timeLeft  = iftarTime.Subtract(DateTime.UtcNow.AddHours(3));
                    await e.Channel.SendMessageAsync("Akşam ezanı " + iftarTime.ToString("HH:mm") + " saatinde okunuyor, yani " + (timeLeft.Hours == 0 ? "" : timeLeft.Hours + " saat ") + timeLeft.Minutes + " dakika kaldı.");
                }
                else if (messageContent.Contains("sahura"))
                {
                    DateTime imsakTime = GetImsakTime(cityScheduleLinks.Keys.Where(s => messageContent.ToLower().Contains(s)).FirstOrDefault());
                    TimeSpan timeLeft  = imsakTime.Subtract(DateTime.UtcNow.AddHours(3));
                    await e.Channel.SendMessageAsync("İmsak " + imsakTime.ToString("HH:mm") + " saatinde, yani " + (timeLeft.Hours == 0 ? "" : timeLeft.Hours + " saat ") + timeLeft.Minutes + " dakika kaldı.");
                }
                else if (messageContent.Contains("okundu mu") || messageContent.Contains("kaçta oku"))
                {
                    DateTime iftarTime = GetIftarTime(cityScheduleLinks.Keys.Where(s => messageContent.ToLower().Contains(s)).FirstOrDefault());
                    if (iftarTime.Day == DateTime.Today.Day)
                    {
                        TimeSpan timeLeft = iftarTime.Subtract(DateTime.UtcNow.AddHours(3));
                        await e.Channel.SendMessageAsync("Akşam ezanı " + iftarTime.ToString("HH:mm") + " saatinde okunuyor, yani " + (timeLeft.Hours == 0 ? "" : timeLeft.Hours + " saat ") + timeLeft.Minutes + " dakika kaldı.");
                    }
                    else
                    {
                        DateTime imsakTime = GetImsakTime(cityScheduleLinks.Keys.Where(s => messageContent.ToLower().Contains(s)).FirstOrDefault());
                        TimeSpan timeLeft  = imsakTime.Subtract(DateTime.UtcNow.AddHours(3));
                        await e.Channel.SendMessageAsync("Okundu! Sahura " + (timeLeft.Hours == 0 ? "" : timeLeft.Hours + " saat ") + timeLeft.Minutes + " dakika kaldı.");
                    }
                }
                else if (e.Message.Content.ToUpper().StartsWith("HOFFMAN"))
                {
                    await e.Channel.SendMessageAsync("Yeah?");

                    var userReply = await interactivity.WaitForMessageAsync(m => m.Author.Id == e.Author.Id && m.Content.Contains(" call this"), TimeSpan.FromSeconds(5));

                    await e.Channel.SendMessageAsync("Uh, uhh...");

                    // TODO: Think of functionality for this HOFFMAN
                }
            };

            HttpListener listener = new HttpListener();

            if (!Debugger.IsAttached)
            {   // In production
                listener.Prefixes.Add("http://*:3131/medicbotapi/");
            }
            else
            {   // Debugging
                listener.Prefixes.Add("http://127.0.0.1:3131/medicbotapi/");
            }
            listener.Start();
            _ = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);

            await discord.ConnectAsync();

            await Task.Delay(-1);
        }
示例#5
0
        public static void ListenerCallback(IAsyncResult result)
        {
            HttpListener listener = (HttpListener)result.AsyncState;
            // Call EndGetContext to complete the asynchronous operation.
            HttpListenerContext context = listener.EndGetContext(result);
            HttpListenerRequest request = context.Request;
            // Read request body
            StreamReader bodyStream = new StreamReader(request.InputStream);
            string       bodyString = bodyStream.ReadToEnd();

            // Log the request
            Console.WriteLine("INCOMING API REQUEST: " + request.RemoteEndPoint.ToString());
            Console.WriteLine("||" + bodyString + "||");

            // Obtain a response object.
            HttpListenerResponse response = context.Response;

            // """security"""
            bodyString = bodyString.Trim();
            var    splitString = bodyString.Split('\n');
            string playString  = splitString[0];

            playString = playString.Trim();
            ulong guildId = 0;

            try
            {
                guildId = Convert.ToUInt64(splitString[1]);
            }
            catch (Exception)
            {
                response.StatusCode = 400;
            }
            if (response.StatusCode != 400) // If we haven't already set the response code, indicating an error..
            {
                if (!playString.StartsWith("#play"))
                {
                    response.StatusCode = 400; // Bad request, no commands except play are to be accepted through the API yet.
                }
                else
                {
                    DiscordUser medicUser = discord.GetUserAsync(134336937224830977).Result;
                    if (playString.Length >= 6)
                    {
                        commands.ExecuteCommandAsync(commands.CreateFakeContext(medicUser, discord.GetGuildAsync(guildId).Result.Channels.FirstOrDefault().Value, playString, "#", commands.RegisteredCommands.Where(c => c.Key == "play").FirstOrDefault().Value, playString.Substring(6)));
                    }
                    else
                    {
                        commands.ExecuteCommandAsync(commands.CreateFakeContext(medicUser, discord.GetGuildAsync(guildId).Result.Channels.FirstOrDefault().Value, playString, "#", commands.RegisteredCommands.Where(c => c.Key == "play").FirstOrDefault().Value));
                    }
                }
            }
            // Construct a response.
            response.ContentType = "application/json";
            string responseString = $"{{\"time\": \"{DateTime.Now}\"}}";

            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
            // Get a response stream and write the response to it.
            response.ContentLength64 = buffer.Length;
            Stream output = response.OutputStream;

            output.Write(buffer, 0, buffer.Length);
            output.Close();
            _ = listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
        }
示例#6
0
        private Task Event_MessageCreated(DiscordClient d, MessageCreateEventArgs e)
        {
            d.Logger.LogDebug(BotEventId, "Event_MessageCreated.");

            CommandsNextExtension cnext = d.GetCommandsNext();
            DiscordMessage        msg   = e.Message;

            // Check if message has valid prefix.
            // json file loaded...
            int cmdStart = msg.GetStringPrefixLength("!");

            string        gId      = e.Guild.Id.ToString();
            List <string> prefixes = BotSettings.GuildSettings["default"].Prefixes;

            // Check to see if the guild has settings.
            if (BotSettings.GuildSettings.ContainsKey(gId))
            {
                // see if the guild wants global prefixes.
                if (BotSettings.GuildSettings[gId].UseGlobalPrefix)
                {
                    prefixes = prefixes.Concat(BotSettings.GuildSettings[gId].Prefixes).ToList();
                }
                else
                {
                    prefixes = BotSettings.GuildSettings[gId].Prefixes;
                }
            }

            // check each prefix. break on the one that is evoked.
            foreach (string item in prefixes)
            {
                cmdStart = msg.GetStringPrefixLength(item);
                if (cmdStart != -1)
                {
                    break;
                }
            }
            // we didn't find a command prefix... Break.
            if (cmdStart == -1)
            {
                return(Task.CompletedTask);
            }

            // Retrieve prefix.
            var prefix    = msg.Content.Substring(0, cmdStart);
            var cmdString = msg.Content.Substring(cmdStart);

            // Retrieve full command string.
            var command = cnext.FindCommand(cmdString, out var args);

            if (command == null)
            {
                return(Task.CompletedTask);
            }

            var ctx = cnext.CreateContext(msg, prefix, command, args);

            Task.Run(async() => await cnext.ExecuteCommandAsync(ctx));

            return(Task.CompletedTask);
        }
示例#7
0
        // TODO: Update to save guild config state. This will run as is, but will not hold any saved data between sessions.
        public async Task MessageReceivedAsync(CommandsNextExtension cnext, DiscordMessage msg, CancellationToken cancellationToken = new CancellationToken())
        {
            try
            {
                cancellationToken.ThrowIfCancellationRequested();

                if (this._commands is null)
                {
                    return;
                }

                var model = cnext.Services.GetRequiredService <ShatterDatabaseContext>();

                var guildConfig = await model.Configs.FindAsync(msg.Channel.GuildId);

                if (guildConfig is null)
                {
                    guildConfig = new GuildConfig
                    {
                        GuildId = msg.Channel.GuildId.Value,
                        Prefix  = this._config.Prefix
                    };

                    model.Configs.Add(guildConfig);

                    await model.SaveChangesAsync();
                }

                cancellationToken.ThrowIfCancellationRequested();

                int prefixPos = await PrefixResolver(msg, guildConfig);

                if (prefixPos == -1)
                {
                    return;                     // Prefix is wrong, dont respond to this message.
                }

                var    prefix        = msg.Content.Substring(0, prefixPos);
                string commandString = msg.Content.Replace(prefix, string.Empty);

                var command = cnext.FindCommand(commandString, out string args);

                cancellationToken.ThrowIfCancellationRequested();

                if (command is null)
                { // Looks like that command does not exsist!
                    await CommandResponder.RespondCommandNotFoundAsync(msg.Channel, prefix);
                }
                else
                {   // We found a command, lets deal with it.
                    if (guildConfig.DisabledCommands.Contains(command.Name))
                    {
                        return;                         // Command is disabled. Dont do a thing.
                    }

                    var moduleAttribute = command.CustomAttributes.FirstOrDefault(x => x is ExecutionModuleAttribute);

                    if (moduleAttribute != default)
                    {
                        var m = moduleAttribute as ExecutionModuleAttribute;
                        if (m is not null && m.GroupName != "config" &&
                            !guildConfig.ActivatedCommands.Contains(command.Name) &&
                            guildConfig.DisabledModules.Contains(m.GroupName))
                        {
                            await CommandResponder.RespondCommandDisabledAsync(msg.Channel, prefix);

                            return; // Command is disabled, dont do a thing.
                        }
                    }

                    var ctx = cnext.CreateContext(msg, prefix, command, args);
                    // We are done here, its up to CommandsNext now.

                    cancellationToken.ThrowIfCancellationRequested();

                    await cnext.ExecuteCommandAsync(ctx);
                }
            }
            finally
            {
                if (!(DiscordBot.CommandsInProgress is null))
                {
                    if (DiscordBot.CommandsInProgress.TryRemove(this, out var taskData))
                    {
                        taskData.Item2.Dispose();
                        taskData.Item1.Dispose();
                    }
                }
            }
        }