Ejemplo n.º 1
0
        /// <summary>
        /// Replies to a command context.
        /// </summary>
        /// <param name="ctx"></param>
        /// <param name="content"></param>
        /// <param name="embed"></param>
        /// <returns></returns>
        public async Task <DiscordMessage> ReplyAsync(CommandContext ctx, string content = null, DiscordEmbed embed = null)
        {
            //Prepare the response
            DiscordMessage response = null;

            //This is a command, so lets make sure we have a response
            var reply = await GetReplyFromMessageAsync(ctx.Message);

            if (reply != null && reply.CommandMsg == ctx.Message.Id)
            {
                //We are a reaction. We cannot create a new reaction, but we will remove our old one
                if (reply.ResponseType == Reply.SnowflakeType.Reaction)
                {
                    await ctx.Message.DeleteOwnReactionAsync(DiscordEmoji.FromName(ctx.Client, reply.ResponseEmote));
                }

                //We are just a message, so we will edit it
                if (reply.ResponseType == Reply.SnowflakeType.Message)
                {
                    //Get the response message and load it into our memory cache
                    // then modify the contents of the message
                    var msg = await ctx.Channel.GetMessageAsync(reply.ResponseMsg);

                    if (msg != null)
                    {
                        response = await msg.ModifyAsync(content, embed);
                    }
                }

                //Remove ourself from the cache, not longer required.
                //_memcache.Remove(ctx.Message.Id);
            }

            //We do not have a response, so just create a new one
            if (response == null)
            {
                response = await ctx.RespondAsync(content : content, embed : embed);
            }

            //Store the reply
            await StoreReplyAsync(ctx, response);

            return(response);
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Creates a new instance of a help message.
 /// </summary>
 /// <param name="content">Contents of the message.</param>
 /// <param name="embed">Embed to attach to the message.</param>
 public CommandHelpMessage(string content = null, DiscordEmbed embed = null)
 {
     this.Content = content;
     this.Embed   = embed;
 }
Ejemplo n.º 3
0
        public static async Task <DiscordMessage> SendDirectMessage(this DiscordClient client, DiscordUser user, DiscordEmbed embed)
        {
            if (embed == null)
            {
                return(null);
            }

            return(await client.SendDirectMessage(user, string.Empty, embed));
        }
Ejemplo n.º 4
0
 public static Task <DiscordMessage> ElevatedMessageAsync(this DiscordMember m, DiscordEmbed embed)
 => m.SendMessageAsync(embed: embed);
Ejemplo n.º 5
0
        /// <summary>
        /// DM this user.
        /// </summary>
        /// <param name="message">The string message to send.</param>
        /// <param name="embed">An optional embed to send.</param>
        /// <returns></returns>
        public async Task SendDMAsync(string message = null, DiscordEmbed embed = null)
        {
            DiscordChannel dm = await Member.CreateDmChannelAsync();

            await dm.SendMessageAsync(message, false, embed);
        }
Ejemplo n.º 6
0
        private async Task SendWelcomeMessage(DiscordMember member, DiscordEmbed embed)
        {
            var channel = await member.CreateDmChannelAsync();

            await channel.SendMessageAsync(embed : embed);
        }
Ejemplo n.º 7
0
 public static Task <DiscordMessage> ElevatedRespondAsync(this CommandContext ctx, DiscordEmbed embed)
 => ctx.RespondAsync(embed: embed);
Ejemplo n.º 8
0
        public static async Task <DiscordMessage> SendAsync(DiscordChannel channel, string textContent, DiscordEmbed embedContent = null)
        {
            try
            {
                if (!ChannelHasPermission(channel, Permissions.SendMessages))
                {
                    return(null);
                }

                if (embedContent == null)
                {
                    return(await channel.SendMessageAsync(textContent, false));
                }
                else
                {
                    // Either make sure we have permission to use embeds or convert the embed to text
                    if (ChannelHasPermission(channel, Permissions.EmbedLinks))
                    {
                        return(await channel.SendMessageAsync(textContent, false, embedContent));
                    }
                    else
                    {
                        return(await channel.SendMessageAsync(MessageBuilder.EmbedToText(textContent, embedContent)));
                    }
                }
            }
            catch (Newtonsoft.Json.JsonReaderException e)
            {
                Logger.Debug(e.ToString());
                return(null);
            }
            catch (Exception e)
            {
                Logger.Error("Error occurred while attempting to send Discord message. Error message: " + e);
                return(null);
            }
        }
Ejemplo n.º 9
0
        public static async Task <DiscordMessage> ModifyAsync(DiscordMessage message, string textContent, DiscordEmbed embedContent = null)
        {
            try
            {
                if (!ChannelHasPermission(message.Channel, Permissions.ManageMessages))
                {
                    return(null);
                }

                if (embedContent == null)
                {
                    return(await message.ModifyAsync(textContent));
                }
                else
                {
                    // Either make sure we have permission to use embeds or convert the embed to text
                    if (ChannelHasPermission(message.Channel, Permissions.EmbedLinks))
                    {
                        return(await message.ModifyAsync(textContent, embedContent));
                    }
                    else
                    {
                        await message.ModifyEmbedSuppressionAsync(true); // Remove existing embeds

                        return(await message.ModifyAsync(MessageBuilder.EmbedToText(textContent, embedContent)));
                    }
                }
            }
            catch (DSharpPlus.Exceptions.ServerErrorException e)
            {
                Logger.Debug(e.ToString());
                return(null);
            }
            catch (Newtonsoft.Json.JsonReaderException e)
            {
                Logger.Debug(e.ToString());
                return(null);
            }
            catch (DSharpPlus.Exceptions.NotFoundException e)
            {
                Logger.Debug(e.ToString());
                return(null);
            }
            catch (Exception e)
            {
                Logger.Error("Error occurred while attempting to modify Discord message. Error message: " + e);
                return(null);
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Sends a message through the webhook
        /// </summary>
        /// <param name="webhookId">ID of the webhook</param>
        /// <param name="webhookToken">The webhook's token</param>
        /// <param name="content">The message to send</param>
        /// <param name="embed">Embed to include in the message</param>
        /// <param name="profile">Custom Username and Avatar url (both are optional)</param>
        public static void SendWebhookMessage(this DiscordClient client, ulong webhookId, string webhookToken, string content, DiscordEmbed embed = null, DiscordWebhookProfile profile = null)
        {
            var properties = new WebhookMessageProperties()
            {
                Content = content, Embed = embed
            };

            if (profile != null)
            {
                if (profile.NameProperty.Set)
                {
                    properties.Username = profile.Username;
                }
                if (profile.AvatarProperty.Set)
                {
                    properties.AvatarUrl = profile.AvatarUrl;
                }
            }

            client.HttpClient.Post($"/webhooks/{webhookId}/{webhookToken}", properties);
        }
Ejemplo n.º 11
0
        private List <DiscordEmbedBuilder> GeneratePageText(List <string> cards, string rarity, DiscordEmbed parentEmbed)
        {
            List <DiscordEmbedBuilder> embeds = new List <DiscordEmbedBuilder>();

            for (int i = 0; i < cards.Count; i += 13)
            {
                DiscordEmbedBuilder embed = new DiscordEmbedBuilder(parentEmbed);

                embed.AddField($"{rarity}", string.Join("\n", cards.GetRange(i, Math.Min(13, cards.Count - i))), false);

                embeds.Add(embed);
            }

            return(embeds);
        }
Ejemplo n.º 12
0
 /// <summary>
 /// Quickly respond with a file to the message that triggered the command.
 /// </summary>
 /// <param name="fileName">Name of the file to send.</param>
 /// <param name="fileData">Stream containing the data to attach as a file.</param>
 /// <param name="content">Message to respond with.</param>
 /// <param name="isTTS">Whether the message is to be spoken aloud.</param>
 /// <param name="embed">Embed to attach to the message.</param>
 /// <returns>Message that was sent.</returns>
 public Task <DiscordMessage> RespondWithFileAsync(string fileName, Stream fileData, string content = null, bool isTTS = false, DiscordEmbed embed = null)
 => this.Message.RespondWithFileAsync(fileData, fileName, content, isTTS, embed);
Ejemplo n.º 13
0
 /// <summary>
 /// Quickly respond to the message that triggered the command.
 /// </summary>
 /// <param name="content">Message to respond with.</param>
 /// <param name="isTTS">Whether the message is to be spoken aloud.</param>
 /// <param name="embed">Embed to attach.</param>
 /// <returns></returns>
 public Task <DiscordMessage> RespondAsync(string content = null, bool isTTS = false, DiscordEmbed embed = null)
 => this.Message.RespondAsync(content, isTTS, embed);
Ejemplo n.º 14
0
 public EmbedViewer(DiscordMessage m, DiscordEmbed embed)
 {
     Embed = embed;
     InitializeComponent();
 }
Ejemplo n.º 15
0
 /// <summary>
 /// Quickly respond with multiple files to the message that triggered the command.
 /// </summary>
 /// <param name="content">Message to respond with.</param>
 /// <param name="files">Files to send.</param>
 /// <param name="is_tts">Whether the message is to be spoken aloud.</param>
 /// <param name="embed">Embed to attach to the message.</param>
 /// <returns>Message that was sent.</returns>
 public Task <DiscordMessage> RespondWithFilesAsync(Dictionary <string, Stream> files, string content = null, bool is_tts = false, DiscordEmbed embed = null) =>
 this.Message.RespondWithFilesAsync(files, content, is_tts, embed);
Ejemplo n.º 16
0
        public async static Task PardonWarns()
        {
            WarnRepository repo   = new WarnRepository(ReadConfig.Config.ConnectionString);
            UserRepository urepo  = new UserRepository(ReadConfig.Config.ConnectionString);
            bool           result = repo.GetAll(out List <Warn> list);

            if (!result)
            {
                _ = DiscordObjectService.Instance.ErrorLogChannel.SendMessageAsync("Error getting all warns in TimerTick.");
                return;
            }
            int pardoned = 0;

            foreach (var item in list)
            {
                if ((item.Level > 0 && item.Level < 6 && item.Time <= DateTime.Now - TimeSpan.FromDays(14) ||
                     item.Level > 5 && item.Level < 11 && item.Time <= DateTime.Now - TimeSpan.FromDays(56)) &&
                    !item.Persistent)
                {
                    pardoned++;
                    result = repo.Delete(item.ID);
                    if (!result)
                    {
                        _ = DiscordObjectService.Instance.ErrorLogChannel.SendMessageAsync($"Error deleting warn {item.ID} from {item.Time}, level {item.Level}.");
                    }
                    result = repo.GetAllByUser(item.User, out List <Warn> others);
                    if (!result)
                    {
                        _ = DiscordObjectService.Instance.ErrorLogChannel.SendMessageAsync("Error reading other warns from the database.");
                    }

                    int counter = 0;
                    foreach (var warn in others)
                    {
                        counter++;
                        warn.Number = counter;
                        result      = repo.Update(warn);
                        if (!result)
                        {
                            _ = DiscordObjectService.Instance.ErrorLogChannel.SendMessageAsync("Error updating the database.");
                            break;
                        }
                    }

                    result = urepo.Read(item.User, out User entity);
                    if (!result)
                    {
                        _ = DiscordObjectService.Instance.ErrorLogChannel.SendMessageAsync("Error reading a user from the database");
                        continue;
                    }
                    result = urepo.Read(item.Mod, out User modEntity);
                    if (!result)
                    {
                        _ = DiscordObjectService.Instance.ErrorLogChannel.SendMessageAsync("Error reading a user from the database");
                        continue;
                    }
                    try
                    {
                        DiscordMember member = await DiscordObjectService.Instance.Lathland.GetMemberAsync(entity.DcID);

                        DiscordMember moderator = await DiscordObjectService.Instance.Lathland.GetMemberAsync(modEntity.DcID);

                        DiscordEmbedBuilder embedBuilder = new DiscordEmbedBuilder
                        {
                            Color     = DiscordColor.Green,
                            Thumbnail = new DiscordEmbedBuilder.EmbedThumbnail {
                                Url = member.AvatarUrl
                            },
                            Title       = $"Pardoned warn number {item.Number} of {member.DisplayName}#{member.Discriminator} ({member.Id})",
                            Description = $"Warn from {item.Time}.",
                            Footer      = new DiscordEmbedBuilder.EmbedFooter {
                                IconUrl = moderator.AvatarUrl, Text = moderator.DisplayName
                            }
                        };
                        DiscordEmbed embed = embedBuilder.Build();

                        _ = DiscordObjectService.Instance.WarnsChannel.SendMessageAsync(embed);
                    }
                    catch
                    {
                        DiscordEmbedBuilder embedBuilder = new DiscordEmbedBuilder
                        {
                            Color       = DiscordColor.Green,
                            Title       = $"Pardoned warn of {entity.DcID}",
                            Description = $"Warn from {item.Time}.",
                            Footer      = new DiscordEmbedBuilder.EmbedFooter {
                                Text = modEntity.DcID.ToString()
                            }
                        };
                        DiscordEmbed embed = embedBuilder.Build();

                        _ = DiscordObjectService.Instance.WarnsChannel.SendMessageAsync(embed);
                    }
                }
            }
            if (pardoned >= 0)
            {
                _ = DiscordObjectService.Instance.TimerChannel.SendMessageAsync($"Timer ticked, {pardoned} warns pardoned.");
            }
            else
            {
                _ = DiscordObjectService.Instance.TimerChannel.SendMessageAsync("Timer ticked, no warns pardoned.");
            }
        }
Ejemplo n.º 17
0
 public Task <DiscordMessage> RespondAsync(string message = "", bool tts = false, DiscordEmbed embed = default)
 {
     return(Context.RespondAsync(message, tts, embed));
 }
Ejemplo n.º 18
0
 public static async Task DM(CommandContext ctx, DiscordMember member, DiscordEmbed message) =>
 await member.SendMessageAsync(embed : message);
Ejemplo n.º 19
0
        public static async Task <IDiscordMessage> SendToUser(this DiscordEmbed embed, IDiscordUser user)
        {
            await Task.Yield();

            return(await(await user.GetDMChannel()).SendMessageAsync("", false, embed));
        }
Ejemplo n.º 20
0
        public override async Task OperateCommand(CommandContext ctx, params string[] args)
        {
            await base.OperateCommand(ctx, args);

            string    subCommand = args[0];
            guildData data       = Utils.returnGuildData(ctx.Guild.Id);

            switch (subCommand.ToLower())
            {
            case "play":
                //Play the tunes!
                await VoiceJoin(ctx);

                //We need to download the spotify song or whatever
                if (args[1] != null)
                {
                    //Start to play the song
                    if (args[1].Contains("youtube") || args[1].Contains("youtu.be"))
                    {
                    }
                    else if (args[1].Contains("spotify"))
                    {
                        //Initialise the spotify bot if has not done yet!
                        if (api == null)
                        {
                            CredentialsAuth auth  = new CredentialsAuth("7c09a36e2ef84c2abc068c8979103d17", "d21bc05a3f604089b176e3b3e5975e0b");
                            Token           token = await auth.GetToken();

                            api = new SpotifyWebAPI
                            {
                                AccessToken = token.AccessToken,
                                TokenType   = token.TokenType
                            };
                        }

                        string uriCode = null;
                        Uri    uri     = new UriBuilder(args[1]).Uri;

                        if (args[1] != null)
                        {
                            //Get the spotify track from url or the uri code
                            uriCode = uri.Segments[2];
                        }

                        if (uriCode != null)
                        {
                            if (uri.Segments[1] == "track")
                            {
                                FullTrack track = await api.GetTrackAsync(uriCode);

                                if (track.Artists != null)
                                {
                                    List <string> artists = new List <string>();
                                    foreach (SimpleArtist artist in track.Artists)
                                    {
                                        artists.Add(artist.Name);
                                    }
                                    string connectArtist = string.Join(",", artists.ToArray());
                                    await ctx.RespondAsync("Playing: " + track.Name + " By: " + connectArtist);
                                }
                                if (track.HasError())
                                {
                                    await ctx.RespondAsync("The track when playing had an issue!");
                                }
                            }
                            else if (uri.Segments[1] == "playlist")
                            {
                                //Playlist
                                FullPlaylist list = await api.GetPlaylistAsync(uriCode);

                                await ctx.RespondAsync("Playing: " + list.Name);

                                if (list.HasError())
                                {
                                    await ctx.RespondAsync("The playlist had and issue");
                                }
                            }
                        }
                        else
                        {
                            await ctx.RespondAsync("Invalid url or uri code");
                        }
                    }
                }
                else
                {
                    await ctx.RespondAsync("No song link was defined!");
                }
                break;

            case "stop":
                //Stop the tunes!

                break;

            case "leave":
            case "fuckoff":
                //Leave the channel forcefully!
                await VoiceLeave(ctx);

                break;

            case "autoleave":
                //Set if the bot should automatically leave the voice channel when no one is in the voice channel
                if (data.autoSongLeave == false)
                {
                    data.autoSongLeave = true;
                    await ctx.RespondAsync("This bot will leave the party when everyone else has finished!");
                }
                else if (data.autoSongLeave == true)
                {
                    data.autoSongLeave = false;
                    await ctx.RespondAsync("This bot will keep on partying!");
                }
                break;

            case "loop":
                //loop the song that is currently playing
                if (data.loopSong == false)
                {
                    data.loopSong = true;
                    await ctx.RespondAsync("Looping Song !");
                }
                else if (data.loopSong == true)
                {
                    data.loopSong = false;
                    await ctx.RespondAsync("Not Looping Song!");
                }
                break;

            default:
            case "help":
                //Show the help on it.
                Dictionary <string, string> argumentsHelp = new System.Collections.Generic.Dictionary <string, string>();
                argumentsHelp.Add(";;song play", "specify a song right after play with a space then this bot will play or specify a link (overrides queue)");
                argumentsHelp.Add(";;song stop", "stop whatever is playing");
                argumentsHelp.Add(";;song leave", "forces the bot to leave the current voice channel");
                argumentsHelp.Add(";;song autoleave", "turns on auto leave the bot will leave the channel when no one is present");
                argumentsHelp.Add(";;song loop", "loops the current song and disables queue");
                DiscordEmbed embedHelp = JosephineEmbedBuilder.CreateEmbedMessage(ctx, "Sub-Commands", "for ';;announce set'", null, JosephineBot.defaultColor, argumentsHelp, false);
                await ctx.RespondAsync("Go to http://discord.rickasheye.xyz/ for all sub-commands", false, embedHelp);

                break;
            }
        }
Ejemplo n.º 21
0
 public static Task <DiscordMessage> ElevatedMessageAsync(this DiscordChannel channel, string s, DiscordEmbed embed)
 => channel.SendMessageAsync(s, embed: embed);
Ejemplo n.º 22
0
        public async Task OsuProfile(InteractionContext ctx,
                                     [Option("nickname", "Никнейм юзера")] string nickname,
                                     [Choice("Bancho server", "bancho")]
                                     [Choice("Gatari server", "gatari")]
                                     [Option("server", "Возможные параметры: bancho, gatari")] string args)
        {
            if (!(ctx.Channel.Name.Contains("-bot") || ctx.Channel.Name.Contains("dev-announce")))
            {
                await ctx.CreateResponseAsync(DSharpPlus.InteractionResponseType.ChannelMessageWithSource,
                                              new DiscordInteractionResponseBuilder().WithContent("Использование данной команды запрещено в этом текстовом канале. Используйте специально отведенный канал для ботов, связанных с osu!.")
                                              .AsEphemeral(true));

                return;
            }

            if (string.IsNullOrEmpty(nickname))
            {
                await ctx.CreateResponseAsync(DSharpPlus.InteractionResponseType.ChannelMessageWithSource,
                                              new DiscordInteractionResponseBuilder().WithContent("Вы ввели пустой никнейм..")
                                              .AsEphemeral(true));

                return;
            }

            if (args.Contains("gatari"))
            {
                GUser guser = null;
                if (!gapi.TryGetUser(nickname, ref guser))
                {
                    await ctx.CreateResponseAsync(DSharpPlus.InteractionResponseType.ChannelMessageWithSource,
                                                  new DiscordInteractionResponseBuilder().WithContent($"Не удалось получить информацию о пользователе `{nickname}`.")
                                                  .AsEphemeral(true));;
                    return;
                }

                List <GScore> gscores = gapi.GetUserBestScores(guser.id, 5);
                if (gscores is null || gscores.Count == 0)
                {
                    await ctx.CreateResponseAsync(DSharpPlus.InteractionResponseType.ChannelMessageWithSource,
                                                  new DiscordInteractionResponseBuilder().WithContent($"Не удалось получить информацию о лучших скорах пользователя `{nickname}`.")
                                                  .AsEphemeral(true));

                    return;
                }

                GStatistics gstats = gapi.GetUserStats(guser.username);
                if (gstats is null)
                {
                    await ctx.CreateResponseAsync(DSharpPlus.InteractionResponseType.ChannelMessageWithSource,
                                                  new DiscordInteractionResponseBuilder().WithContent($"Не удалось получить статистику пользователя `{nickname}`.")
                                                  .AsEphemeral(true));

                    return;
                }

                DiscordEmbed gembed = utils.UserToEmbed(guser, gstats, gscores);
                await ctx.CreateResponseAsync(DSharpPlus.InteractionResponseType.ChannelMessageWithSource,
                                              new DiscordInteractionResponseBuilder().AddEmbed(gembed));

                return;
            }

            if (args.Contains("bancho"))
            {
                User user = null;
                if (!api.TryGetUser(nickname, ref user))
                {
                    await ctx.CreateResponseAsync(DSharpPlus.InteractionResponseType.ChannelMessageWithSource,
                                                  new DiscordInteractionResponseBuilder().WithContent($"Не удалось получить информацию о пользователе `{nickname}`.")
                                                  .AsEphemeral(true));

                    return;
                }

                List <Score> scores = api.GetUserBestScores(user.id, 5);

                if (scores is null || scores.Count == 0)
                {
                    await ctx.CreateResponseAsync(DSharpPlus.InteractionResponseType.ChannelMessageWithSource,
                                                  new DiscordInteractionResponseBuilder().WithContent($"Не удалось получить информацию о лучших скорах пользователя `{nickname}`.")
                                                  .AsEphemeral(true));

                    return;
                }

                DiscordEmbed embed = utils.UserToEmbed(user, scores);
                await ctx.CreateResponseAsync(DSharpPlus.InteractionResponseType.ChannelMessageWithSource,
                                              new DiscordInteractionResponseBuilder().AddEmbed(embed));
            }

            await ctx.CreateResponseAsync(DSharpPlus.InteractionResponseType.ChannelMessageWithSource,
                                          new DiscordInteractionResponseBuilder().WithContent("Введенный сервер не поддерживается или не существует.")
                                          .AsEphemeral(true));
        }
Ejemplo n.º 23
0
 // Ignore timestamps
 private static bool IdenticalEmbed(DiscordEmbed a, DiscordEmbed b)
 {
     return(a.Title == b.Title &&
            a.Description == b.Description &&
            a.Color == b.Color);
 }
Ejemplo n.º 24
0
 public Page(string content = "", DiscordEmbedBuilder embed = null)
 {
     this.Content = content;
     this.Embed   = embed?.Build();
 }
Ejemplo n.º 25
0
        [Description("Manage the announcer everytime someone joins")]                       // this will be displayed to tell users what this command does when they invoke help
        public override async Task OperateCommand(CommandContext ctx, params string[] args) // this command takes no arguments
        {
            await base.OperateCommand(ctx);

            string    argumentType  = args[0];
            guildData specificGuild = Utils.returnGuildData(ctx.Guild.Id);

            List <DiscordEmoji> emojis = new List <DiscordEmoji>();

            emojis.Add(DiscordEmoji.FromName(ctx.Client, ":100:"));
            emojis.Add(DiscordEmoji.FromName(ctx.Client, ":ok_hand:"));
            List <DiscordEmoji> emojisFiltered = Utils.GetRandomPoggersEmoji(emojis);
            Random rnd   = new Random();
            var    emoji = emojisFiltered[rnd.Next(emojisFiltered.Count)];

            switch (argumentType.ToLower())
            {
            case "demo":
                //Bring up a version of the put command
                await ctx.RespondAsync("Here are the demo embed messages");

                string announcerMessage      = specificGuild.AnnounceFormatDesc;
                string finalannouncerMessage = announcerMessage.Replace("{guildname}", ctx.Guild.Name);

                string       announceTitle       = specificGuild.AnnounceFormatBot;
                string       finalAnnouncerTitle = announceTitle.Replace("{bot}", ctx.Client.CurrentUser.Username);
                DiscordEmbed embedMessageUser    = JosephineEmbedBuilder.CreateEmbedMessage(ctx, finalAnnouncerTitle, finalannouncerMessage);
                await ctx.RespondAsync("", false, embedMessageUser);

                string       announceTitleUser       = specificGuild.AnnounceFormatUser;
                string       finalAnnouncerTitleUser = announceTitleUser.Replace("{user}", ctx.Member.Username);
                DiscordEmbed embedMessageBot         = JosephineEmbedBuilder.CreateEmbedMessage(ctx, finalAnnouncerTitleUser, finalannouncerMessage);
                await ctx.RespondAsync("", false, embedMessageBot);

                break;

            case "set":
                switch (args[1].ToLower())
                {
                case "user":
                    //Set the user join message
                    if (args[2] != null || !args[2].Contains(string.Empty))
                    {
                        //string afterwardsMessage = string.Join()
                        specificGuild.AnnounceFormatUser = string.Join(" ", args).Substring(args[1].Length + args[2].Length);
                        await ctx.RespondAsync("Changed the announcer message for the user. TO see what it looks like try ';;announce demo'");
                    }
                    else
                    {
                        await ctx.RespondAsync("No message was defined!");
                    }
                    break;

                case "bot":
                    if (args[2] != null || !args[2].Contains(string.Empty))
                    {
                        specificGuild.AnnounceFormatBot = string.Join(" ", args).Substring(args[1].Length + args[2].Length);
                        await ctx.RespondAsync("Changed the announcer message for the bot. To see what it looks like try ';;announce demo'");
                    }
                    else
                    {
                        await ctx.RespondAsync("No message was defined!");
                    }
                    break;

                case "description":
                    if (args[2] != null || !args[2].Contains(string.Empty))
                    {
                        specificGuild.AnnounceFormatDesc = string.Join(" ", args).Substring(args[1].Length + args[2].Length);
                        await ctx.RespondAsync("Changed the description message for the bot. To see what it looks like try ';;announce demo'");
                    }
                    else
                    {
                        await ctx.RespondAsync("No message was defined!");
                    }
                    break;

                default:
                case "help":
                    if (!args[1].ToLower().Contains("help"))
                    {
                        await ctx.RespondAsync("Unable to change as there is either an incorrect command argument(s) or no arguments at all!");
                    }
                    Dictionary <string, string> arguments = new System.Collections.Generic.Dictionary <string, string>();
                    arguments.Add(";;announce set user <message>", "sets the user greeting (use {user} to be replaced with thier username)");
                    arguments.Add(";;announce set bot <message>", "sets the bot greeting (use {bot} to be replaced with the bot username)");
                    arguments.Add(";;announce set description <message>", "sets the greeting for both messages (use {guildname} to be replaced with the guild name)");
                    DiscordEmbed embed = JosephineEmbedBuilder.CreateEmbedMessage(ctx, "Sub-Commands", "for ';;announce set'", null, JosephineBot.defaultColor, arguments);
                    await ctx.RespondAsync("Go to http://discord.rickasheye.xyz/ for all sub-commands", false, embed);

                    break;
                }
                break;

            case "off":
                if (specificGuild.announceJoin == false)
                {
                    await ctx.RespondAsync("Announcer is already off run the on sub-command");
                }
                else
                {
                    specificGuild.announceJoin = false;
                    await ctx.Message.CreateReactionAsync(emoji);
                }
                break;

            case "on":
                if (specificGuild.announceJoin == true)
                {
                    await ctx.RespondAsync("Announcer is already on run the off sub-command");
                }
                else
                {
                    specificGuild.announceJoin = true;
                    await ctx.Message.CreateReactionAsync(emoji);
                }
                break;

            default:
            case "help":
                Dictionary <string, string> argumentsHelp = new System.Collections.Generic.Dictionary <string, string>();
                argumentsHelp.Add(";;announce demo", "shows the greeting messages for the user and the bots on this server");
                argumentsHelp.Add(";;announce set", "utility to set the greeting messages on this server");
                argumentsHelp.Add(";;announce off", "turns the announcer off");
                argumentsHelp.Add(";;announce on", "turns the announcer on");
                DiscordEmbed embedHelp = JosephineEmbedBuilder.CreateEmbedMessage(ctx, "Sub-Commands", "for ';;announce set'", null, JosephineBot.defaultColor, argumentsHelp);
                await ctx.RespondAsync("Go to http://discord.rickasheye.xyz/ for all sub-commands", false, embedHelp);

                break;
            }
        }
Ejemplo n.º 26
0
 /// <summary>
 /// Quickly respond with a file to the message that triggered the command.
 /// </summary>
 /// <param name="file_data">Stream containing the data to attach as a file.</param>
 /// <param name="content">Message to respond with.</param>
 /// <param name="is_tts">Whether the message is to be spoken aloud.</param>
 /// <param name="embed">Embed to attach to the message.</param>
 /// <returns>Message that was sent.</returns>
 public Task <DiscordMessage> RespondWithFileAsync(FileStream file_data, string content = null, bool is_tts = false, DiscordEmbed embed = null) =>
 this.Message.RespondWithFileAsync(file_data, content, is_tts, embed);
Ejemplo n.º 27
0
 /// <summary>
 /// Sends a message through the webhook
 /// </summary>
 /// <param name="content">The message to send</param>
 /// <param name="embed">Embed to include in the message</param>
 /// <param name="profile">Custom Username and Avatar url (both are optional)</param>
 public void SendMessage(string content, DiscordEmbed embed = null, DiscordWebhookProfile profile = null)
 {
     Client.SendWebhookMessage(Id, Token, content, embed, profile);
 }
Ejemplo n.º 28
0
 /// <summary>
 /// Quickly respond with a file to the message that triggered the command.
 /// </summary>
 /// <param name="file_path">Path to the file to be attached to the message.</param>
 /// <param name="content">Message to respond with.</param>
 /// <param name="is_tts">Whether the message is to be spoken aloud.</param>
 /// <param name="embed">Embed to attach to the message.</param>
 /// <returns>Message that was sent.</returns>
 public Task <DiscordMessage> RespondWithFileAsync(string file_path, string content = null, bool is_tts = false, DiscordEmbed embed = null)
 {
     return(this.Message.RespondWithFileAsync(file_path, content, is_tts, embed));
 }
Ejemplo n.º 29
0
        public static async Task <DiscordMessage> SendDirectMessage(this DiscordClient client, DiscordUser user, string message, DiscordEmbed embed)
        {
            try
            {
                var dm = await client.CreateDmAsync(user);

                if (dm != null)
                {
                    var msg = await dm.SendMessageAsync(message, false, embed);

                    return(msg);
                }
            }
            catch (Exception)
            {
                //_logger.Error(ex);
                _logger.Error($"Failed to send DM to user {user.Username}.");
            }

            return(null);
        }
Ejemplo n.º 30
0
        public static EmbedJson ReverseEmbed(DiscordMessage message)
        {
            if (message == null)
            {
                return(null);
            }

            DiscordEmbed embed = message.Embeds.ElementAt(0);

            Thumbnail thumbnail = null;
            Image     image     = null;

            Author author = null;
            Footer footer = null;

            if (embed.Thumbnail != null)
            {
                thumbnail = new Thumbnail()
                {
                    Url = embed.Thumbnail.Url.ToString()
                }
            }
            ;

            if (embed.Image != null)
            {
                image = new Image()
                {
                    Url = embed.Image.Url.ToString()
                }
            }
            ;

            if (embed.Author != null)
            {
                author = new Author()
                {
                    Url     = embed.Author.Url.ToString(),
                    IconUrl = embed.Author.IconUrl.ToString(),
                    Name    = embed.Author.Name
                }
            }
            ;

            if (embed.Footer != null)
            {
                footer = new Footer()
                {
                    IconUrl = embed.Footer.IconUrl?.ToString() ?? null,
                    Text    = embed.Footer.Text
                }
            }
            ;

            List <Field> fields = null;

            if (embed.Fields != null)
            {
                fields = new List <Field>();

                foreach (DiscordEmbedField f in embed.Fields)
                {
                    fields.Add(new Field()
                    {
                        Inline = f.Inline,
                        Value  = f.Value,
                        Name   = f.Name
                    });
                }
            }

            EmbedJson result = new EmbedJson()
            {
                Content = message.Content,
                Embed   = new Embed()
                {
                    Author      = author,
                    Thumbnail   = thumbnail,
                    Image       = image,
                    Footer      = footer,
                    Color       = embed.Color.Value,
                    Description = embed.Description,
                    Fields      = fields?.ToArray() ?? null,
                    Timestamp   = embed.Timestamp?.DateTime ?? DateTime.MinValue,
                    Title       = embed.Title,
                    Url         = embed.Url?.ToString() ?? null
                }
            };

            return(result);
        }