/// <summary>
        /// Set the bot's statuses to backup in process.
        /// </summary>
        /// <param name="client">The Discord client</param>
        /// <param name="channel">The channel that is being backed up.</param>
        /// <returns>The IDisposable for typing status.</returns>
        public static async Task <IDisposable> SetBackupBusyStatus(DiscordSocketClient client, IMessageChannel channel)
        {
            await client.SetStatusAsync(UserStatus.DoNotDisturb);

            await client.SetGameAsync($"#{channel.Name}", type : ActivityType.Playing);

            return(channel.EnterTypingState());
        }
示例#2
0
 private async Task SendPhoto(string breed, IMessageChannel channel, CancellationToken token)
 {
     using (channel.EnterTypingState(token.ToRequestOptions()))
     {
         var dog = JObject.Parse(await httpClient.GetStringAsync($"https://dog.ceo/api/breed/{breed}/images/random"));
         await channel.SendMessageAsync(System.Uri.EscapeUriString(dog.Value <string>("message")));
     }
 }
        public static async Task <IUserMessage> TypingReplyAsync([NotNull] this IMessageChannel channel, [NotNull] string message, bool isTTS = false, [CanBeNull] Embed embed = null, [CanBeNull] RequestOptions options = null)
        {
            using (channel.EnterTypingState())
            {
                await Task.Delay(Delay(message));

                return(await channel.SendMessageAsync(message, isTTS, embed, options).ConfigureAwait(false));
            }
        }
 private async Task SendPhoto(string breed, IMessageChannel channel, CancellationToken token)
 {
     using (channel.EnterTypingState(token.ToRequestOptions()))
         using (var httpClient = _httpClientFactory.CreateClient(DiscordHttpClientConstants.RESPONDER_CLIENT))
         {
             var dog = JObject.Parse(await httpClient.GetStringAsync($"https://dog.ceo/api/breed/{breed}/images/random"));
             await channel.SendMessageAsync(Uri.EscapeUriString(dog.Value <string>("message")));
         }
 }
示例#5
0
        public async Task TalkAsync(IMessageChannel c, string text)
        {
            if (!IsReady())
            {
                await c.SendMessageAsync("Loading...");

                return;
            }
            using (c.EnterTypingState())
            {
                await c.SendMessageAsync(await ThinkAsync(text));
            }
        }
示例#6
0
        async Task SendAutoReplyAsync(IMessageChannel channel, CharacterInfo characterInfo)
        {
            if (_config.ClaimReplies.Count == 0)
            {
                return;
            }

            var random  = new Random();
            var replies = new[] { _config.ClaimReplies[random.Next(_config.ClaimReplies.Count)] };

            // split into separate messages with "\n"
            replies = replies[0]
                      .Split(new[] { "\\n" }, StringSplitOptions.None)
                      .Select(s =>
            {
                var character = _bracketRegex.Replace(characterInfo.Name, "").Trim();
                var anime     = _bracketRegex.Replace(characterInfo.Anime, "").Trim();

                // character
                s = s.Replace("*character*", character.Split(' ')[0].ToLowerInvariant())
                    .Replace("*character_full*", character.ToLowerInvariant())
                    .Replace("*Character*", character.Split(' ')[0])
                    .Replace("*Character_full*", character);

                // anime
                s = s.Replace("*anime*", anime.ToLowerInvariant())
                    .Replace("*Anime*", anime);

                return(s.Trim());
            })
                      .Where(s => !string.IsNullOrEmpty(s) && s != ".")
                      .ToArray();

            foreach (var reply in replies)
            {
                await Task.Delay(TimeSpan.FromMilliseconds(200 + random.NextDouble() * 800));

                using (channel.EnterTypingState())
                {
                    // type for the length of the reply
                    await Task.Delay(TimeSpan.FromMilliseconds(reply.Length * 100));

                    await channel.SendMessageAsync(reply);
                }
            }
        }
示例#7
0
        private async Task Work(ulong guildId, IMessageChannel invokedChannel, CancellationToken token)
        {
            IUserMessage message = null;

            if (progress.ContainsKey(guildId))
            {
                message = progress[guildId];
            }

            if (createQueues.TryGetValue(guildId, out Queue <string> queue))
            {
                if (_settings[guildId].PNavChannel != null)
                {
                    IMessageChannel channel = _client.GetChannel((ulong)_settings[guildId].PNavChannel) as IMessageChannel;

                    if (channel == null)
                    {
                        await _logger.Log(new LogMessage(LogSeverity.Error, nameof(Work), $"Mod-Channel was no Message Channel for Guild {guildId}!"));

                        await invokedChannel.SendMessageAsync($"There was a problem with the mod-channel! try to run `{_settings[guildId].Prefix}set mod-channel` and then `{_settings[guildId].Prefix}resume` to try again!");

                        return;
                    }

                    while (queue.Count > 0)
                    {
                        if (token.IsCancellationRequested)
                        {
                            //workers.Remove(guildId);
                            tokens.Remove(guildId, out CancellationTokenSource s);
                            s.Dispose();
                            token.ThrowIfCancellationRequested();
                        }
                        string      current = queue.Dequeue();
                        IDisposable typing  = null;
                        try
                        {
                            typing = channel.EnterTypingState(typingOptions);
                        }
                        catch (Exception e)
                        {
                            await _logger.Log(new LogMessage(LogSeverity.Error, nameof(Work), $"Error while entering typing state in Guild {guildId}: {e.Message}", e));
                        }
                        Task t = Task.CompletedTask;
                        try
                        {
                            t = channel.SendMessageAsync($"{prefix}{current}", false, null, options);
                        }
                        catch (Exception e)
                        {
                            await _logger.Log(new LogMessage(LogSeverity.Error, nameof(Work), $"Error while sending Create Message in Guild {guildId}: {e.Message}", e));
                        }
                        // wait for PokeNav to respond...
                        var Result = await _inter.NextMessageAsync(x => x.Author.Id == 428187007965986826 && x.Channel.Id == channel.Id && x.Embeds.Count == 1 && (x.Content == "The following poi has been created for use in your community:" || x.Embeds.First().Title == "Error"), null, TimeSpan.FromSeconds(10));

                        await t;
                        if (typing != null)
                        {
                            typing.Dispose();
                        }
                        if (Result.IsSuccess == false)
                        {
                            try
                            {
                                await channel.SendMessageAsync($"PokeNav did not respond in time! Please try again by Hand!", false, null, options);
                            }
                            catch (Exception e)
                            {
                                await _logger.Log(new LogMessage(LogSeverity.Error, nameof(Work), $"Error while sending Error Message in Guild {guildId}: {e.Message}", e));
                            }
                            await _logger.Log(new LogMessage(LogSeverity.Info, nameof(Work), $"PokeNav did not respond within 10 seconds in Guild {guildId}."));
                        }
                        if (message != null && queue.Count % 5 == 0) // do not edit every time because of rate limits
                        {
                            try
                            {
                                await message.ModifyAsync((x) =>
                                {
                                    EmbedBuilder embed = message.Embeds.First().ToEmbedBuilder();
                                    embed.Fields.Find((x) => x.Name == "Creations").Value = queue.Count;
                                    x.Embed = embed.Build();
                                }, options);
                            }
                            catch (Exception e)
                            {
                                await _logger.Log(new LogMessage(LogSeverity.Error, nameof(Work), $"Error while editing progress message in Guild {guildId}: {e.Message}", e));
                            }
                        }
                    }
                }
                else
                {
                    try
                    {
                        await invokedChannel.SendMessageAsync($"PokeNav Moderation Channel not set yet! Run `{_settings[guildId].Prefix}set mod-channel` to set it, then run `{_settings[guildId].Prefix}resume` to create the PoI!");
                    }
                    catch (Exception e)
                    {
                        await _logger.Log(new LogMessage(LogSeverity.Error, nameof(Work), $"Error while sending error message in Guild {guildId}: {e.Message}", e));
                    }
                    if (message != null)
                    {
                        try
                        {
                            await message.ModifyAsync((x) =>
                            {
                                EmbedBuilder embed = message.Embeds.First().ToEmbedBuilder();
                                embed.Title        = "Paused";
                                x.Embed            = embed.Build();
                            }, options);
                        }
                        catch (Exception e)
                        {
                            await _logger.Log(new LogMessage(LogSeverity.Error, nameof(Work), $"Error while editing progress message in Guild {guildId}: {e.Message}", e));
                        }
                    }
                    await _logger.Log(new LogMessage(LogSeverity.Info, nameof(Work), $"Execution failed in Guild {guildId}: Mod-Channel was not set!"));
                }
            }

            if (editQueues.ContainsKey(guildId) && editQueues[guildId].Any())
            {
                if (message != null)
                {
                    try
                    {
                        await message.ModifyAsync((x) =>
                        {
                            EmbedBuilder embed = message.Embeds.First().ToEmbedBuilder();
                            embed.Fields.Find((x) => x.Name == "Creations").Value = queue.Count;
                            x.Embed = embed.Build();
                        }, options);
                    }
                    catch (Exception e)
                    {
                        await _logger.Log(new LogMessage(LogSeverity.Error, nameof(Work), $"Error while editing progress message in Guild {guildId}: {e.Message}", e));
                    }
                }
                workers[guildId] = Edit(guildId, invokedChannel, token); // proceed with edits after creation is complete if there are any.
            }
            else
            {
                workers.Remove(guildId);
                tokens.Remove(guildId, out CancellationTokenSource source);
                if (message != null)
                {
                    try
                    {
                        await message.DeleteAsync(options);
                    }
                    catch (Exception e)
                    {
                        await _logger.Log(new LogMessage(LogSeverity.Error, nameof(Work), $"Error while deleting progress message in Guild {guildId}: {e.Message}", e));
                    }
                    progress.Remove(guildId);
                }
                source.Dispose();
            }
        }
示例#8
0
 public IDisposable TriggerTyping(IMessageChannel channel)
 {
     return(channel.EnterTypingState());
 }
        public async Task GetMessagesExampleBody(IMessageChannel channel)
        {
#pragma warning disable IDISP001
#pragma warning disable IDISP014
            // We're just declaring this for the sample below.
            // Ideally, you want to get or create your HttpClient
            // from IHttpClientFactory.
            // You get a bonus for reading the example source though!
            var httpClient = new HttpClient();
#pragma warning restore IDISP014
#pragma warning restore IDISP001

            // Another dummy method
            Task LongRunningAsync()
            {
                return(Task.Delay(0));
            }

            #region GetMessagesAsync.FromLimit.Standard

            var messages = await channel.GetMessagesAsync(300).FlattenAsync();

            var userMessages = messages.Where(x => x.Author.Id == 53905483156684800);

            #endregion

            #region GetMessagesAsync.FromMessage

            var oldMessage = await channel.SendMessageAsync("boi");

            var messagesFromMsg = await channel.GetMessagesAsync(oldMessage, Direction.Before, 5).FlattenAsync();

            #endregion


            #region GetMessagesAsync.FromId.FromMessage

            await channel.GetMessagesAsync(442012544660537354, Direction.Before, 5).FlattenAsync();

            #endregion

            #region SendMessageAsync

            var message = await channel.SendMessageAsync(DateTimeOffset.UtcNow.ToString("R"));

            await Task.Delay(TimeSpan.FromSeconds(5))
            .ContinueWith(x => message.DeleteAsync());

            #endregion

            #region SendFileAsync.FilePath

            await channel.SendFileAsync("wumpus.txt", "good discord boi");

            #endregion

            #region SendFileAsync.FilePath.EmbeddedImage

            await channel.SendFileAsync("b1nzy.jpg",
                                        embed : new EmbedBuilder { ImageUrl = "attachment://b1nzy.jpg" }.Build());

            #endregion


            #region SendFileAsync.FileStream.EmbeddedImage

            using (var b1nzyStream = await httpClient.GetStreamAsync("https://example.com/b1nzy"))
                await channel.SendFileAsync(b1nzyStream, "b1nzy.jpg",
                                            embed : new EmbedBuilder { ImageUrl = "attachment://b1nzy.jpg" }.Build());

            #endregion

            #region EnterTypingState

            using (channel.EnterTypingState()) await LongRunningAsync();

            #endregion
        }