コード例 #1
0
ファイル: Handler.cs プロジェクト: emre1702/BonusBot_Csharp
        private async Task RemoveLabelAddedOutput(Base o, ITextChannel channel)
        {
            var messages = await channel.GetMessagesAsync(1000).FlattenAsync();

            var msgId = messages.Where(m =>
            {
                if (m.Embeds.Count == 0)
                {
                    return(false);
                }
                var embed = m.Embeds.First();
                if (!embed.Footer.HasValue)
                {
                    return(false);
                }

                if (embed.Footer.Value.Text != o.Label.Name)
                {
                    return(false);
                }

                return(embed.Url == o.Issue.HtmlUrl);
            })
                        .FirstOrDefault();

            if (msgId == default)
            {
                return;
            }
            await channel.DeleteMessageAsync(msgId);
        }
コード例 #2
0
        public async Task DeleteOtherChannelMessages
        (
            [Summary("The channel on which the the messages to delete are contained.")]
            ITextChannel textChannel,
            [Summary("The ID of the first message that will be deleted, **inclusive**.")]
            ulong firstMessageID,
            [Summary("The ID of the last message that will be deleted, **inclusive**.")]
            ulong lastMessageID
        )
        {
            var contextChannel = Context.Channel;

            if (firstMessageID == 0 || lastMessageID == 0)
            {
                await contextChannel.SendMessageAsync("The provided message IDs are invalid.");

                return;
            }

            var originalProgressMessage = await contextChannel.SendMessageAsync($"Discovering messages to delete... 0 messages have been found so far.");

            var progressMessageTimestamp = originalProgressMessage.Timestamp;

            var persistentProgressMessage = new PersistentMessage(originalProgressMessage);

            var foundMessages = await textChannel.GetMessageRangeAsync(firstMessageID, lastMessageID, UpdateMessage);

            async Task UpdateMessage(int messages)
            {
                await persistentProgressMessage.SetContentAsync($"Discovering users to delete... {messages} messages have been found so far.");
            }

            // The progress message's timestamp is being used because it was used with Discord's clock
            // Avoiding clock difference issues
            var threshold = progressMessageTimestamp.UtcDateTime - TimeSpan.FromDays(14);

            foundMessages.Dissect(m => m.Timestamp.UtcDateTime < threshold, out var olderMessages, out var newerMessages);

            var newerMessageIDs = newerMessages.Select(m => m.Id).ToArray();

            int  currentlyDeletedMessages = 0;
            bool deletionComplete         = false;

            await persistentProgressMessage.SetContentAsync($"{foundMessages.Count} messages are being deleted...");

            await textChannel.DeleteMessagesAsync(newerMessageIDs);

            currentlyDeletedMessages += newerMessageIDs.Length;
            deletionComplete          = foundMessages.Count == newerMessageIDs.Length;

            if (!deletionComplete)
            {
                var progressMessageUpdatingTask = UpdateProgressMessage();

                foreach (var message in olderMessages)
                {
                    await textChannel.DeleteMessageAsync(message);

                    currentlyDeletedMessages++;
                }

                deletionComplete = true;

                await progressMessageUpdatingTask;

                async Task UpdateProgressMessage()
                {
                    while (!deletionComplete)
                    {
                        var progressMessageContent = $"{foundMessages.Count} messages are being deleted... {currentlyDeletedMessages} messages have been deleted.";

                        await persistentProgressMessage.SetContentAsync(progressMessageContent);

                        await Task.Delay(1000);
                    }
                }
            }

            await persistentProgressMessage.SetContentAsync($"{foundMessages.Count} messages have been deleted.");

            await Task.Delay(5000);

            await persistentProgressMessage.DeleteAsync();
        }
コード例 #3
0
        public async Task AcceptOfferAsync([Summary("The ID of the offer.")] string offerID)
        {
            Collection <string> IDs = await db.getIDs("transactions");

            string userMoneyt;
            string authorMoneyt;
            double userMoney;
            double authorMoney;

            if (IDs.Contains(offerID) == true)
            {
                if (offerID.Substring(0, 4) == "ind-")
                {
                    await ReplyAsync("You need to provide a ticker of the company which will get the industry.");

                    return;
                }
                Transaction transaction = new Transaction(await db.getJObjectAsync(offerID, "transactions"));

                if (transaction.author != Context.User.Id.ToString())
                {
                    // Gets money values of the command user and the transaction author
                    userMoneyt = (string)await db.GetFieldAsync(Context.User.Id.ToString(), "money", "users");

                    if (userMoneyt == null)
                    {
                        userMoney = 50000;
                    }
                    else
                    {
                        userMoney = double.Parse(userMoneyt);
                    }

                    authorMoneyt = (string)await db.GetFieldAsync(transaction.author, "money", "users");

                    if (authorMoneyt == null)
                    {
                        authorMoney = 50000;
                    }
                    else
                    {
                        authorMoney = double.Parse(authorMoneyt);
                    }

                    // Transfers the money
                    if (transaction.type == "buy")
                    {
                        userMoney   += (transaction.shares * transaction.price);
                        authorMoney -= (transaction.shares * transaction.price);
                    }
                    else
                    {
                        userMoney   -= (transaction.shares * transaction.price);
                        authorMoney += (transaction.shares * transaction.price);
                    }

                    // Transfers the shares
                    int _userShares = await MarketService.GetShares(Context.User.Id.ToString(), transaction.ticker);

                    int _authorShares = await MarketService.GetShares(transaction.author, transaction.ticker);

                    if (transaction.type == "buy")
                    {
                        _authorShares += transaction.shares;
                        _userShares   -= transaction.shares;
                    }
                    else
                    {
                        _authorShares -= transaction.shares;
                        _userShares   += transaction.shares;
                    }

                    if (_userShares < 0)
                    {
                        await ReplyAsync("You cannot complete this transaction as it would leave you with a negative amount of shares in the specified company.");
                    }
                    else if (userMoney < 0)
                    {
                        await ReplyAsync("You cannot complete this transaction as it would leave you with a negative amount on money.");
                    }
                    else
                    {
                        await MarketService.SetShares(Context.User.Id.ToString(), transaction.ticker, _userShares);

                        await MarketService.SetShares(transaction.author, transaction.ticker, _authorShares);

                        await MarketService.UpdateSharePrice(transaction);

                        await db.SetFieldAsync(Context.User.Id.ToString(), "money", userMoney, "users");

                        await db.SetFieldAsync(transaction.author, "money", authorMoney, "users");

                        await db.RemoveObjectAsync(offerID, "transactions");

                        ITextChannel chnl = (ITextChannel)await Context.Client.GetChannelAsync((UInt64)await db.GetFieldAsync("MarketChannel", "channel", "system"));

                        await chnl.DeleteMessageAsync(Convert.ToUInt64(transaction.messageID));

                        await ReplyAsync("Transaction complete!");

                        await CommandService.PostMessageTask((string)await db.GetFieldAsync("MarketChannel", "channel", "system"), $"<@{transaction.author}>'s Transaction with ID {transaction.id} has been accepted by <@{Context.User.Id}>!");

                        //await transaction.authorObj.SendMessageAsync($"Your transaction with the id {transaction.id} has been completed by {Context.User.Username.ToString()}");
                    }
                }
                else
                {
                    await ReplyAsync("You cannot accept your own transaction!");
                }
            }
            else
            {
                await ReplyAsync("That is not a valid transaction ID");
            }
        }
コード例 #4
0
        protected async static Task CleanDiscordChannel(ITextChannel chan, int HistoryHours, bool forceempty)
        {
            long nowunix = DateTimeOffset.Now.ToUnixTimeSeconds();
            IEnumerable <IMessage> messages;
            bool empty = false;

            while (empty == false)
            {
                empty    = true;
                messages = await chan.GetMessagesAsync(50).FlattenAsync();

                List <ulong>    deleteMessages     = new List <ulong>();
                List <IMessage> slowDeleteMessages = new List <IMessage>();

                foreach (IMessage mess in messages)
                {
                    long messageunix = mess.Timestamp.ToUnixTimeSeconds();
                    long dif         = nowunix - messageunix;
                    var  hours       = (dif / 60) / 60;
                    bool slowdel     = false;

                    if (hours > (24 * 13))
                    {
                        slowdel = true;
                    }
                    if ((hours > HistoryHours) || (forceempty == true))
                    {
                        empty = false;
                        if (slowdel == false)
                        {
                            deleteMessages.Add(mess.Id);
                        }
                        else
                        {
                            slowDeleteMessages.Add(mess);
                        }
                    }
                }
                if ((deleteMessages.Count > 0) || (slowDeleteMessages.Count > 0))
                {
                    try
                    {
                        if (deleteMessages.Count > 0)
                        {
                            await chan.DeleteMessagesAsync(deleteMessages).ConfigureAwait(true);
                        }
                        if (slowDeleteMessages.Count > 0)
                        {
                            foreach (IMessage slowdelmessage in slowDeleteMessages)
                            {
                                await chan.DeleteMessageAsync(slowdelmessage).ConfigureAwait(true);
                            }
                        }
                    }
                    catch
                    {
                    }
                    empty = false;
                }
            }
        }
コード例 #5
0
        public async Task AcceptOfferAsync([Summary("Company Ticker")] string ticker, [Summary("The ID of the offer.")] string offerID)
        {
            Collection <string> IDs = await _dataBaseService.getIDs("transactions");

            string userMoneyt;
            string authorMoneyt;
            double userMoney;
            double authorMoney;

            if (IDs.Contains(offerID) == true)
            {
                IndustryTransaction transaction = new IndustryTransaction(await _dataBaseService.getJObjectAsync(offerID, "transactions"));
                JObject             obj         = await _dataBaseService.getJObjectAsync(transaction.industryID, "industries");

                Industry ind    = new Industry(obj);
                Company  exeCom = await _companyService.getCompany(ticker);

                Company transCom = null;
                if (transaction.type == "auction")
                {
                    await ReplyAsync("You must bid for auctions.");
                }
                if (transaction.type == "buy")
                {
                    transCom = await _companyService.getCompany(ind.CompanyId);

                    if (!exeCom.employee.Keys.Contains(Context.User.Id.ToString()))
                    {
                        await ReplyAsync("You cannot sell industries for corps you are not an employee of.");

                        return;
                    }
                    if (!new List <int> {
                        1, 3, 5, 7
                    }.Contains(exeCom.employee[Context.User.Id.ToString()].position.manages))
                    {
                        await ReplyAsync($"You do not have the permission to sell industry in {exeCom.name}");
                    }
                }
                if (!exeCom.employee.Keys.Contains(Context.User.Id.ToString()))
                {
                    await ReplyAsync("You cannot buy industries for corps you are not an employee of.");

                    return;
                }
                if (!new List <int> {
                    1, 3, 5, 7
                }.Contains(exeCom.employee[Context.User.Id.ToString()].position.manages))
                {
                    await ReplyAsync($"You do not have the permission to buy industry in {exeCom.name}");
                }
                if (transaction.author != Context.User.Id.ToString())
                {
                    // Gets money values of the command user and the transaction author
                    userMoneyt = (string)await _dataBaseService.GetFieldAsync(Context.User.Id.ToString(), "money", "users");

                    if (userMoneyt == null)
                    {
                        userMoney = 50000;
                    }
                    else
                    {
                        userMoney = double.Parse(userMoneyt);
                    }

                    authorMoneyt = (string)await _dataBaseService.GetFieldAsync(transaction.author, "money", "users");

                    if (authorMoneyt == null)
                    {
                        authorMoney = 50000;
                    }
                    else
                    {
                        authorMoney = double.Parse(authorMoneyt);
                    }

                    // Transfers the money
                    if (transaction.type == "buy")
                    {
                        userMoney   += transaction.price;
                        authorMoney -= transaction.price;
                    }
                    else
                    {
                        userMoney   -= transaction.price;
                        authorMoney += transaction.price;
                    }

                    if (transaction.type == "sell")
                    {
                        ind.CompanyId = ticker;
                        await _dataBaseService.SetJObjectAsync(ind.SerializeIntoJObject(), "industries");
                    }
                    else
                    {
                        ind.CompanyId = transCom.id;
                        await _dataBaseService.SetJObjectAsync(ind.SerializeIntoJObject(), "industries");
                    }

                    if (userMoney < 0)
                    {
                        await ReplyAsync("You cannot complete this transaction as it would leave you with a negative amount on money.");
                    }
                    else
                    {
                        await _dataBaseService.SetFieldAsync(Context.User.Id.ToString(), "money", userMoney, "users");

                        await _dataBaseService.SetFieldAsync(transaction.author, "money", authorMoney, "users");

                        await _dataBaseService.RemoveObjectAsync(offerID, "transactions");

                        ITextChannel chnl = (ITextChannel)await Context.Client.GetChannelAsync((UInt64)await _dataBaseService.GetFieldAsync("MarketChannel", "channel", "system"));

                        await chnl.DeleteMessageAsync(Convert.ToUInt64(transaction.messageID));

                        await ReplyAsync("Transaction complete!");

                        await _commandService.PostMessageTask((string)await _dataBaseService.GetFieldAsync("MarketChannel", "channel", "system"), $"<@{transaction.author}>'s Transaction with ID {transaction.id} has been accepted by <@{Context.User.Id}>!");

                        //await transaction.authorObj.SendMessageAsync($"Your transaction with the id {transaction.id} has been completed by {Context.User.Username.ToString()}");
                    }
                }
                else
                {
                    await ReplyAsync("You cannot accept your own transaction!");
                }
            }
            else
            {
                await ReplyAsync("That is not a valid transaction ID");
            }
        }
コード例 #6
0
        private async Task CheckImageArtChannelAsync(SocketUserMessage message)
        {
            //init channels
            ITextChannel galleryChannel     = (ITextChannel)_client.GetChannel(galleryId);
            ITextChannel galleryTalkChannel = (ITextChannel)_client.GetChannel(galleryTalkId);

            // Delete if message is empty

            List <string> urlList = GetAllUrlFromString(message.Content);

            if ((message.Attachments.Count == 0) && (urlList.Count == 0))
            {
                Console.WriteLine($"deleted {message.Attachments.Count} attachment and {urlList.Count} URLs");
                Embed embedMessage = PostEmbedText(message.Author.Username, message.Author.GetAvatarUrl(), "Deleted message content:", message.Content);
                await galleryTalkChannel.SendMessageAsync(
                    $"{message.Author.Username} No posting in the gallery <#{message.Channel.Id}>"
                    , embed : embedMessage
                    );

                await galleryChannel.DeleteMessageAsync(message);

                return;
            }

            // Post if message has image
            string[] extensionList = { ".png", ".jpeg", ".gif", ".jpg" };
            Console.WriteLine($"{message.Attachments.Count} attachment and {urlList.Count} URLs");
            // if the message has no attachments and no url
            if ((message.Attachments.Count == 0 && urlList.Count == 0))
            {
                return;
            }
            // post every attachment as an embed
            foreach (var attachment in message.Attachments)
            {
                if (attachment.IsSpoiler())
                {
                    string messageContent = $"{message.Author.Username} posted: {Regex.Replace(message.Content, @"http[^\s]+", "")}\nUrl link: ||{attachment.Url} ||\nDiscord link: https://discord.com/channels/{serverId}/{galleryId}/{message.Id}";
                    await MessageChannel(_client, messageContent, galleryTalkId);
                }
                else
                {
                    bool isEmbedable = false;
                    foreach (var extensionItem in extensionList)
                    {
                        if (isEmbedable = attachment.Url.EndsWith(extensionItem))
                        {
                            break;
                        }
                    }
                    // if the attachment is an image
                    if (isEmbedable)
                    {
                        await galleryTalkChannel.SendMessageAsync(embed :
                                                                  PostEmbedImage(message.Author.Username, message.Author.Id, Regex.Replace(message.Content, @"http[^\s]+", ""), message.Author.GetAvatarUrl(), attachment.Url, message.Id));
                    }
                    // if it's something else (like a video)
                    else
                    {
                        string messageContent = $"{message.Author.Username} posted: {Regex.Replace(message.Content, @"http[^\s]+", "")}\nUrl link: {attachment.Url}\nDiscord link: https://discord.com/channels/{serverId}/{galleryId}/{message.Id}";
                        await MessageChannel(_client, messageContent, galleryTalkId);
                    }
                }
            }
            // post every attachment as an embed
            foreach (var url in urlList)
            {
                if (message.Content.Contains("||"))
                {
                    string messageString  = message.Content.Replace("|", "");
                    string messageContent = $"{message.Author.Username} posted: {Regex.Replace(messageString, @"http[^\s]+", "")}\nUrl link: ||{url} ||\nDiscord link: https://discord.com/channels/{serverId}/{galleryId}/{message.Id}";
                    await MessageChannel(_client, messageContent, galleryTalkId);
                }
                else
                {
                    bool isEmbedable = false;
                    foreach (var extensionItem in extensionList)
                    {
                        if (isEmbedable = url.EndsWith(extensionItem))
                        {
                            break;
                        }
                    }
                    // if the attachment is an image
                    if (isEmbedable)
                    {
                        await galleryTalkChannel.SendMessageAsync(embed :
                                                                  PostEmbedImage(message.Author.Username, message.Author.Id, Regex.Replace(message.Content, @"http[^\s]+", ""), message.Author.GetAvatarUrl(), url, message.Id));
                    }
                    // if it's something else (like a video)
                    else
                    {
                        string messageContent = $"{message.Author.Username} posted: {Regex.Replace(message.Content, @"http[^\s]+", "")}\nUrl link: {url}\nDiscord link: https://discord.com/channels/{serverId}/{galleryId}/{message.Id}";
                        await MessageChannel(_client, messageContent, galleryTalkId);
                    }
                }
            }
            ;
        }
コード例 #7
0
        public async Task Say(ITextChannel channel, string message, ulong prevMessageId)
        {
            await channel.DeleteMessageAsync(prevMessageId);

            await channel.SendMessageAsync(message);
        }