Пример #1
0
 static void JoinChannel(BotCommandContext ctx, string data)
 {
     foreach (var chan in Utils.SimpleParse(data))
     {
         ctx.IRC.JoinChannel(chan);
     }
 }
Пример #2
0
        private async Task OnMessageReceivedAsync(SocketMessage s)
        {
            if (!(s is SocketUserMessage msg))
            {
                return;                     // Ensure the message is from a user/bot
            }
            if (s.Author.IsBot)
            {
                return;                                     // Ignore bots and self when checking commands
            }
            var context = new BotCommandContext(this, msg); // Create the command context

            string prefix     = Config["prefix"];
            int    argPos     = 0;          // Check if the message has a valid command prefix
            bool   hasPrefix  = msg.HasStringPrefix(prefix, ref argPos, StringComparison.OrdinalIgnoreCase);
            bool   hasMention = msg.HasMentionPrefix(Client.CurrentUser, ref argPos);

            if (hasPrefix || hasMention)
            {
                var result = await Commands.ExecuteAsync(context, argPos, Services);                     // Execute the command

                if (!result.IsSuccess)
                {
                    if (result.Error.HasValue && result.Error == CommandError.UnknownCommand)
                    {
                        await msg.AddReactionAsync(new Emoji("❓"));
                    }
                }
            }
        }
Пример #3
0
 public ReactionMessage(BotCommandContext context, IUserMessage message, CustomReactionAction defaultAction, bool allowMultipleReactions = false)
 {
     Context                = context;
     Message                = message;
     DefaultAction          = defaultAction;
     AllowMultipleReactions = allowMultipleReactions;
     AcceptsAllReactions    = true;
 }
Пример #4
0
        public static void CreateCustomReactionMessage(BotCommandContext context, IUserMessage message, CustomReactionAction defaultAction, bool allowMultipleReactions = false, int timeout = 300000, Action onTimeout = null)
        {
            var reactionMessage = new ReactionMessage(context, message, defaultAction, allowMultipleReactions);

            ReactionMessageCache.Add(message.Id.ToString(), reactionMessage, new CacheItemPolicy {
                SlidingExpiration = TimeSpan.FromMilliseconds(timeout), RemovedCallback = onTimeout == null ? null : (CacheEntryRemovedCallback)(_ => onTimeout())
            });
        }
Пример #5
0
 public ReactionMessage(BotCommandContext context, IUserMessage message, Dictionary <string, ReactionAction> actions, bool allowMultipleReactions = false)
 {
     Context = context;
     Message = message;
     Actions = actions;
     AllowMultipleReactions = allowMultipleReactions;
     AcceptsAllReactions    = false;
 }
Пример #6
0
 public static void CreateConfirmReactionMessage(BotCommandContext context, IUserMessage message, ReactionAction onPositiveResponse, ReactionAction onNegativeResponse, bool allowMultipleReactions = false, int timeout = 300000, Action onTimeout = null)
 {
     CreateReactionMessage(context, message, new Dictionary <string, ReactionAction>
     {
         ["✅"] = onPositiveResponse,
         ["❌"] = onNegativeResponse
     }, allowMultipleReactions, timeout, onTimeout);
 }
Пример #7
0
 // Lets a user buy a listing, transfering ownership of the emoji from the market to the buyer
 public static void BuyListing(BotCommandContext context, ulong marketId, string emojiUnicode, ulong buyer)
 {
     context.Bot.Clerk.Queue(new Purchase
     {
         Context  = context,
         MarketId = marketId,
         BuyerId  = buyer,
         Emoji    = emojiUnicode,
     }
                             );
 }
Пример #8
0
        public static void CreateReactionMessage(BotCommandContext context, IUserMessage message, Dictionary <string, ReactionAction> actions, bool allowMultipleReactions = false, int timeout = 300000, Action onTimeout = null)
        {
            foreach (string e in actions.Keys)
            {
                message.AddReactionAsync(Emote.TryParse(e, out Emote emote) ? emote : (IEmote) new Emoji(e));
            }

            var reactionMessage = new ReactionMessage(context, message, actions, allowMultipleReactions);

            ReactionMessageCache.Add(message.Id.ToString(), reactionMessage, new CacheItemPolicy {
                SlidingExpiration = TimeSpan.FromMilliseconds(timeout), RemovedCallback = onTimeout == null ? null : (CacheEntryRemovedCallback)(_ => onTimeout())
            });
        }
Пример #9
0
        public static void CreatePaginatedMessage(BotCommandContext context, IUserMessage message, int pageCount, int initialPage, PageAction action, int timeout = 300000, Action onTimeout = null)
        {
            if (pageCount == 1)
            {
                return;
            }
            message.AddReactionsAsync(new[] { new Emoji(PaginatedMessage.FirstPage), new Emoji(PaginatedMessage.PreviousPage), new Emoji(PaginatedMessage.NextPage), new Emoji(PaginatedMessage.LastPage) });

            var paginatedMessage = new PaginatedMessage(context, message, pageCount, initialPage, action);

            ReactionMessageCache.Add(message.Id.ToString(), paginatedMessage, new CacheItemPolicy {
                SlidingExpiration = TimeSpan.FromMilliseconds(timeout), RemovedCallback = onTimeout == null ? null : (CacheEntryRemovedCallback)(_ => onTimeout())
            });
        }
Пример #10
0
        public PaginatedMessage(BotCommandContext context, IUserMessage message, int count, int initial, PageAction action) : base(context, message, new Dictionary <string, ReactionAction>(), true)
        {
            if (count < 1)
            {
                throw new ArgumentOutOfRangeException(nameof(count));
            }
            if (initial < 1 || initial > count)
            {
                throw new ArgumentOutOfRangeException(nameof(initial));
            }

            PageCount   = count;
            CurrentPage = initial;
            OnChage     = action;
        }
Пример #11
0
        // Adds a listing to the market, transfering ownership of the emoji from the seller to the market
        // Returns the added listing
        public static Listing AddListing(BotCommandContext context, ulong marketId, Emoji emoji, long price)
        {
            if (emoji.EmojiId == Guid.Empty)
            {
                throw new ArgumentException("Error: cannot sell emoji without id");
            }

            Listing toAdd = new Listing
            {
                SellerId = context.User.Id,
                EmojiId  = emoji.EmojiId,
                Price    = price,
            };

            context.Bot.Clerk.Queue(PostListing.InMarket(emoji.Unicode, marketId, toAdd, true));

            return(toAdd);
        }
Пример #12
0
        static void SendMsg(BotCommandContext ctx, string data)
        {
            var args = Utils.SimpleParse(data);
            var text = string.Join(" ", args.Skip(1)).Trim();
            var msg  = $"<{Fmt.Colorize(Fmt.Colors.Teal)}{ctx.User.Nick}{Fmt.Reset}> {text}";

            switch (args[0])
            {
            case "ALL": {
                var chans = ctx.IRC.Channels.Select(w => w.Name).ToArray();
                ctx.IRC.SendMessage(msg, chans);
                break;
            }

            default: {
                var chans = args[0].Split(',', ' ');
                ctx.IRC.SendMessage(msg, chans);
                break;
            }
            }
        }
Пример #13
0
        private async Task OnMessageReceivedAsync(SocketMessage s)
        {
            if (!(s is SocketUserMessage msg))
            {
                return;
            }
            if (!(s.Channel is SocketGuildChannel))
            {
                return;
            }

            int argPos  = 0;
            var context = new BotCommandContext(_discord, msg);

            if (msg.HasMentionPrefix(_discord.CurrentUser, ref argPos))
            {
                var result = await _commandService.ExecuteAsync(context, argPos, _serviceProvider);

                if (result.IsSuccess)
                {
                    return;
                }

                switch (result)
                {
                case ExecuteResult execute:
                    _logger.LogError(execute.Exception?.ToString());
                    return;

                case ParseResult parse when parse.Error == CommandError.BadArgCount:
                    // Send Help Text
                    return;

                default:
                    await context.Channel.SendMessageAsync(result.ErrorReason);

                    return;
                }
            }
        }
Пример #14
0
        public static List <EmbedBuilder> MakeEmbeds(BotCommandContext context, List <string> contents, string label, int maxLines)
        {
            List <EmbedBuilder> res = new List <EmbedBuilder>();

            if (contents.Count == 0)
            {
                return(res);
            }

            int           count   = 0;
            StringBuilder builder = new StringBuilder();

            foreach (string line in contents)
            {
                builder.Append(line + "\n");
                count++;
                if (count == maxLines)
                {
                    var embed = context.EmbedFromUser(context.User);
                    embed.AddField($"{label}", builder.ToString(), true);
                    res.Add(embed);
                    builder.Clear();
                    count = 0;
                }
            }
            var embedd = context.EmbedFromUser(context.User);

            if (builder.Length != 0)
            {
                embedd.AddField($"{label}", builder.ToString(), true);
                res.Add(embedd);
            }

            for (int i = 0; i < res.Count; i++)
            {
                res[i].WithFooter($"Page {i + 1} of {res.Count}");
            }

            return(res);
        }
        public async Task MessageReceivedAsync(SocketMessage rawMessage)
        {
            // Ignore system messages, or messages from other bots
            if (!(rawMessage is SocketUserMessage message))
            {
                return;
            }
            if (message.Source != MessageSource.User)
            {
                return;
            }

            // This value holds the offset where the prefix ends
            var argPos = 0;

            if (!message.HasCharPrefix(Program.Prefix, ref argPos))
            {
                return;
            }

            var context = new BotCommandContext(_discord, message);
            await _commands.ExecuteAsync(context, argPos, _services);
        }
Пример #16
0
 static void ShowHelp(BotCommandContext ctx, string data)
 {
     if (data.Length > 0)
     {
         BotCommandInfo info;
         if (ctx.Core.GetCommand(data, out info))
         {
             var helpStr = info.ExtHelp ?? info.Help;
             ctx.IRC.SendMultilineNotice(helpStr, false, ctx.User.Nick);
         }
         else
         {
             ctx.IRC.SendNotice($"No help available for {Fmt.Bold}{data}{Fmt.Reset}", ctx.User.Nick);
         }
     }
     else
     {
         ctx.IRC.SendNotice("Available commands:", ctx.User.Nick);
         foreach (var cmd in ctx.Core.GetCommands())
         {
             ctx.IRC.SendNotice($"    {Fmt.Bold}{cmd.Name,-15}{Fmt.Reset} {cmd.Help}", ctx.User.Nick);
         }
     }
 }
Пример #17
0
        // Gets the emoji price. Returns float.NaN if there are none for sale
        public static (long, bool valid) GetEmojiPrice(BotCommandContext context, ulong marketId, string emojiUnicode)
        {
            // Make sure market exists
            var marketsDB = context.MarketCollection;
            var market    = marketsDB.GetById(marketId);

            if (market == null)
            {
                // Market does not exist
                return(0, false);
            }

            if (market.Listings.ContainsKey(emojiUnicode))
            {
                Listing cheapest = CheapestListing(market.Listings[emojiUnicode]);
                if (cheapest != null)
                {
                    // There is a valid listing for sale
                    return(cheapest.Price, true);
                }
            }

            return(0, false);
        }
Пример #18
0
 static void QuitBot(BotCommandContext ctx, string data)
 {
     ctx.Core.Disconnect(data);
 }
Пример #19
0
 public static IReadOnlyCollection <string> GetAllLootBoxNames(BotCommandContext ctx) => GetAllLootBoxNames(ctx.Guild.Id);
Пример #20
0
 public static IReadOnlyCollection <string> GetAllLootBoxNames(ulong localMarket) => LootBoxVarieties.Keys;          // TODO: add custom varieties
 public static Dictionary <string, LootBox> GetAllLootBoxes(BotCommandContext ctx) => GetAllLootBoxes(ctx.Guild.Id); // TODO: add custom varieties
Пример #21
0
 public BaseCommandBotRequest(string userWmid, string commandName, TRequestBody context, string lng, string token, BotCommandContext ctx)
     : base(context, token, lng, BotRequestType.BotCommand)
 {
     this.commandName = commandName;
     this.userWmid    = userWmid;
     this.ctx         = ctx;
 }
Пример #22
0
 public InventoryWrapper(BotCommandContext ctx, ulong userId)
 {
     Context = ctx;
     UserId  = userId;
 }
Пример #23
0
 public InventoryWrapper(BotCommandContext ctx, User user)
 {
     Context   = ctx;
     UserId    = user.UserId;
     this.user = user;
 }
Пример #24
0
 static void SendRaw(BotCommandContext ctx, string data)
 {
     ctx.IRC.SendRawMessage("{0}", data);
 }