示例#1
0
            public CommandServiceWrapper(IDiscordClient client, ILogger <CommandService> logger,
                                         IOptions <CommandServiceConfig> cmdServiceConfig, IConfiguration config) : base(cmdServiceConfig.Value)
            {
                if (ulong.TryParse(config["LoggingChannelId"], out var loggingChannelId))
                {
                    var channel = (IMessageChannel)client.GetChannelAsync(loggingChannelId).Result;
                    Log += async message =>
                    {
                        if (message.Exception is CommandException commandException)
                        {
                            await channel.SendMessageAsync(
                                $"```{commandException.Message}\n{commandException.InnerException}```");
                        }
                    };
                }

                Log += message =>
                {
                    logger.Log(
                        (LogLevel)Math.Abs((int)message.Severity - 5),
                        eventId: 0,
                        message,
                        message.Exception,
                        delegate { return(message.ToString()); });

                    return(Task.CompletedTask);
                };
            }
        /// <summary>
        /// Get the discord channel that is attached to the Facebook WebHook
        /// </summary>
        /// <param name="_discordClient">THe discord client</param>
        /// <returns></returns>
        public static async Task <IMessageChannel> GetFacebookFeedChannel(this IDiscordClient _discordClient)
        {
            //  THe channel to post facebook-posts in
            IMessageChannel channel = await _discordClient.GetChannelAsync(ulong.Parse(FacebookHook.FacebookHandler.Instance.FacebookFeedChannelID)) as IMessageChannel;

            return(channel);
        }
示例#3
0
        public async Task LogMessage(PKSystem system, PKMember member, ulong messageId, ulong originalMsgId, IGuildChannel originalChannel, IUser sender, string content)
        {
            var guildCfg = await _data.GetOrCreateGuildConfig(originalChannel.GuildId);

            // Bail if logging is disabled either globally or for this channel
            if (guildCfg.LogChannel == null)
            {
                return;
            }
            if (guildCfg.LogBlacklist.Contains(originalChannel.Id))
            {
                return;
            }

            // Bail if we can't find the channel
            if (!(await _client.GetChannelAsync(guildCfg.LogChannel.Value) is ITextChannel logChannel))
            {
                return;
            }

            var embed = _embed.CreateLoggedMessageEmbed(system, member, messageId, originalMsgId, sender, content, originalChannel);

            var url = $"https://discordapp.com/channels/{originalChannel.GuildId}/{originalChannel.Id}/{messageId}";
            await logChannel.SendMessageAsync(text : url, embed : embed);
        }
示例#4
0
        public async Task <IWebhook> GetWebhook(ulong channelId)
        {
            var channel = await _client.GetChannelAsync(channelId) as ITextChannel;

            if (channel == null)
            {
                return(null);
            }
            return(await GetWebhook(channel));
        }
        private async Task <ITextChannel> GetLogChannel(IGuild guild)
        {
            var guildCfg = await _data.GetGuildConfig(guild.Id);

            if (guildCfg.LogChannel == null)
            {
                return(null);
            }
            return(await _client.GetChannelAsync(guildCfg.LogChannel.Value) as ITextChannel);
        }
        public async ValueTask OnChannelDelete(DiscordChannelPacket packet)
        {
            var channel = await Client.GetChannelAsync(packet.Id, packet.GuildId);

            if (channel != null)
            {
                await EventHandler.OnChannelDelete(channel);
            }

            await DeleteChannelCacheAsync(packet);
        }
示例#7
0
        /// <summary>
        /// If this poll is being retreived from the database, please make a call to LOAD it.
        /// This will populate the actual values for channel/message.
        /// </summary>
        /// <param name="Client"></param>
        /// <returns></returns>
        public async Task LoadEntity(IDiscordClient Client)
        {
            this.channel = await Client.GetChannelAsync(this.ChannelId, CacheMode.AllowDownload) as ITextChannel;

            this.message = await channel.GetMessageAsync(this.MessageId, CacheMode.AllowDownload) as IUserMessage;

            //Populate the users.
            foreach (var vote in Votes)
            {
                vote.User = await Client.GetUserAsync(vote.UserId);
            }
        }
示例#8
0
        public async Task UserLeft(SocketGuildUser user)
        {
            try
            {
                var sendLeftEnabled = _redis.HashGet($"{user.Guild.Id}:Settings", "ShowLeave");
                if (sendLeftEnabled.ToString() == "1")
                {
                    var modChannel = _redis.HashGet($"{user.Guild.Id}:Settings", "ModChannel");
                    if (!string.IsNullOrEmpty(modChannel))
                    {
                        var modChannelSocket = (ISocketMessageChannel)await _client.GetChannelAsync((ulong)modChannel);

                        await modChannelSocket.SendMessageAsync($"{user.Username}#{user.Discriminator} left the server");
                    }
                }
            }
            catch (Exception e)
            {
                _logger.Error(e, "Failed to send leave message...");
            }
            _logger.Information($"[Geekbot] {user.Id} ({user.Username}) left {user.Guild.Id} ({user.Guild.Name})");
        }
示例#9
0
        public async Task <Embed> CreateMessageInfoEmbed(FullMessage msg)
        {
            var channel = await _client.GetChannelAsync(msg.Message.Channel) as ITextChannel;

            var serverMsg = channel != null ? await channel.GetMessageAsync(msg.Message.Mid) : null;

            var memberStr = $"{msg.Member.Name} (`{msg.Member.Hid}`)";

            var userStr = $"*(deleted user {msg.Message.Sender})*";
            ICollection <IRole> roles = null;

            if (channel != null)
            {
                // Look up the user with the REST client
                // this ensures we'll still get the information even if the user's not cached,
                // even if this means an extra API request (meh, it'll be fine)
                var shard     = ((DiscordShardedClient)_client).GetShardFor(channel.Guild);
                var guildUser = await shard.Rest.GetGuildUserAsync(channel.Guild.Id, msg.Message.Sender);

                if (guildUser != null)
                {
                    if (guildUser.RoleIds.Count > 0)
                    {
                        roles = guildUser.RoleIds
                                .Select(roleId => channel.Guild.GetRole(roleId))
                                .Where(role => role.Name != "@everyone")
                                .OrderByDescending(role => role.Position)
                                .ToList();
                    }

                    userStr = guildUser.Nickname != null ? $"**Username:** {guildUser?.NameAndMention()}\n**Nickname:** {guildUser.Nickname}" : guildUser?.NameAndMention();
                }
            }

            var eb = new EmbedBuilder()
                     .WithAuthor(msg.Member.Name, msg.Member.AvatarUrl)
                     .WithDescription(serverMsg?.Content ?? "*(message contents deleted or inaccessible)*")
                     .WithImageUrl(serverMsg?.Attachments?.FirstOrDefault()?.Url)
                     .AddField("System",
                               msg.System.Name != null ? $"{msg.System.Name} (`{msg.System.Hid}`)" : $"`{msg.System.Hid}`", true)
                     .AddField("Member", memberStr, true)
                     .AddField("Sent by", userStr, inline: true)
                     .WithTimestamp(SnowflakeUtils.FromSnowflake(msg.Message.Mid));

            if (roles != null && roles.Count > 0)
            {
                eb.AddField($"Account roles ({roles.Count})", string.Join(", ", roles.Select(role => role.Name)));
            }
            return(eb.Build());
        }
示例#10
0
        public async Task <ITextChannel> GetLogChannel(IGuild guild)
        {
            using (var conn = await _conn.Obtain())
            {
                var server =
                    await conn.QueryFirstOrDefaultAsync <ServerDefinition>("select * from servers where id = @Id",
                                                                           new { Id = guild.Id });

                if (server?.LogChannel == null)
                {
                    return(null);
                }
                return(await _client.GetChannelAsync(server.LogChannel.Value) as ITextChannel);
            }
        }
示例#11
0
        protected override async Task Handle(IssueChangedPriorityIntegrationEvent command)
        {
            var embed = EmbedHelper.PriorityChanged(command.Issue, command.PreviousPriority);

            await foreach (var(channelId, nexusModsGameId, nexusModsModId, _, _) in _subscriptionQueries.GetAllAsync())
            {
                if (await _discordClient.GetChannelAsync(channelId) is not IMessageChannel channel)
                {
                    continue;
                }
                if (nexusModsGameId != command.Issue.NexusModsGameId || nexusModsModId != command.Issue.NexusModsModId)
                {
                    continue;
                }
                await channel.SendMessageAsync(embed : embed);
            }
        }
        protected override async Task Handle(CommentRemovedReplyIntegrationEvent command)
        {
            var embed = EmbedHelper.DeletedCommentReply(command.Comment, command.Reply);

            await foreach (var(channelId, nexusModsGameId, nexusModsModId, _, _) in _subscriptionQueries.GetAllAsync())
            {
                if (await _discordClient.GetChannelAsync(channelId) is not IMessageChannel channel)
                {
                    continue;
                }
                if (nexusModsGameId != command.Comment.NexusModsGameId || nexusModsModId != command.Comment.NexusModsModId)
                {
                    continue;
                }
                await channel.SendMessageAsync(embed : embed);
            }
        }
        public static async Task WriteServerInfo(this IServerHandler serverHandler, IDiscordClient client)
        {
            var channel = await client.GetChannelAsync(serverHandler.ServerInfoChannel) as ITextChannel;

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

            var servers = serverHandler.GetServers();

            if (servers.Count < messages.Count() && messages.Any(m => (DateTimeOffset.UtcNow - m.Timestamp).TotalDays > 14))
            {
                //Recreate channel because discord does not allow deletion of messages older then 2 weeks
                var guild = channel.Guild;
                await channel.DeleteAsync();

                channel = await guild.CreateTextChannelAsync(channel.Name,
                                                             p => p.CategoryId = channel.CategoryId);

                messages.Clear();
            }
            else
            {
                var messagesToDelete = messages.Skip(servers.Count);
                await channel.DeleteMessagesAsync(messagesToDelete);

                messages = messages.Take(servers.Count).ToList();
            }

            for (int i = 0; i < servers.Count; i++)
            {
                var server = servers[i];
                var embed  = await BuildServerInfoEmbed(server, client);

                var message = messages.ElementAtOrDefault(i);

                if (message != null)
                {
                    await(message as RestUserMessage).ModifyAsync(m => m.Embed = embed);
                }
                else
                {
                    await channel.SendMessageAsync(null, embed : embed);
                }
            }
        }
示例#14
0
        public async Task UseTagAsync(ulong guildId, ulong channelId, string name)
        {
            _authorizationService.RequireClaims(AuthorizationClaim.UseTag);

            if (string.IsNullOrWhiteSpace(name))
            {
                throw new ArgumentException("The tag name cannot be blank or whitespace.", nameof(name));
            }

            name = name.Trim().ToLower();

            var channel = await _discordClient.GetChannelAsync(channelId);

            if (!(channel is IMessageChannel messageChannel))
            {
                throw new InvalidOperationException($"The channel '{channel.Name}' is not a message channel.");
            }

            var tag = await _modixContext
                      .Set <TagEntity>()
                      .Where(x => x.GuildId == guildId)
                      .Where(x => x.DeleteActionId == null)
                      .Where(x => x.Name == name)
                      .SingleOrDefaultAsync();

            if (tag is null)
            {
                return;
            }

            var sanitizedContent = FormatUtilities.SanitizeAllMentions(tag.Content);

            await messageChannel.SendMessageAsync(sanitizedContent);

            tag.IncrementUse();

            await _modixContext.SaveChangesAsync();
        }
示例#15
0
        public static async void ReminderHandler(IDiscordClient client)
        {
            while (true)
            {
                List <string> reminders = new List <string>();
                int           f         = 1;
                do
                {
                    try
                    {
                        reminders = File.ReadLines(Path.GetFullPath(Resources.reminders, Extensions.config_values.root_path)).ToList();
                    }
                    catch
                    {
                        f = 0;
                        continue;
                    }
                } while (f == 0);
                StringBuilder sb      = new StringBuilder();
                ITextChannel  channel = null;
                IGuildUser    u       = null;
                foreach (var r in reminders)
                {
                    string[] separators = { ";" };
                    string[] temp       = r.Split(separators, StringSplitOptions.RemoveEmptyEntries);
                    DateTime rd         = DateTime.FromBinary(long.Parse(temp[0]));
                    TimeSpan dif        = rd - DateTime.Now;
                    TimeSpan check      = new TimeSpan(0, 1, 0);
                    try
                    {
                        if (dif <= check)
                        {
                            channel = (ITextChannel)await client.GetChannelAsync(ulong.Parse(temp[3]));

                            ulong uid = ulong.Parse(temp[2]);
                            u = await channel.GetUserAsync(uid);

                            await channel.SendMessageAsync(u.Mention + " " + temp[1]);

                            TimeSpan check2 = new TimeSpan(0, 0, 0);
                            if (dif < check2)
                            {
                                await channel.SendMessageAsync("``Apologies, sir, but this reminder was late by " + TimeToString(dif) + ".``");
                            }
                        }
                        else
                        {
                            sb.Append(r);
                            sb.AppendLine();
                        }
                    }
                    catch { continue; }
                }
                f = 1;
                do
                {
                    try
                    {
                        File.WriteAllText(Path.GetFullPath(Resources.reminders, Extensions.config_values.root_path), sb.ToString());
                    }
                    catch
                    {
                        f = 0;
                        continue;
                    }
                } while (f == 0);
                await Task.Delay(58000);
            }
        }
示例#16
0
 public NewsProvider(IDiscordClient client, IOptions <DependencyInjection.NewsProviderOptions> options)
 {
     _channel = (ISocketMessageChannel)client.GetChannelAsync(options.Value.NewsChannelId).Result;
 }
示例#17
0
 /// <inheritdoc />
 public async Task <IDiscordGuildChannel> GetChannelAsync(ulong id)
 => (await client.GetChannelAsync(id, Id)) as IDiscordGuildChannel;
 public static async Task <IPrivateChannel> GetPrivateChannelAsync(this IDiscordClient client, ulong id)
 => await client.GetChannelAsync(id).ConfigureAwait(false) as IPrivateChannel;
示例#19
0
        /// <inheritdoc/>
        public async Task <IDiscordTextChannel> GetChannelAsync()
        {
            var channel = await client.GetChannelAsync(packet.ChannelId, packet.GuildId);

            return(channel as IDiscordTextChannel);
        }
示例#20
0
 /// <inheritdoc/>
 public async ValueTask <IDiscordTextChannel> GetChannelAsync()
 {
     return(await client.GetChannelAsync(packet.ChannelId, packet.GuildId)
            as IDiscordTextChannel);
 }
示例#21
0
 public static async Task <IVoiceChannel> GetVoiceChannelAsync(this IDiscordClient client, ulong id) => client == null ? null : (await client.GetChannelAsync(id).ConfigureAwait(false) as IVoiceChannel);
        /// <summary>
        /// Get the Discord channel that is attached to the Suggestion command
        /// </summary>
        /// <param name="_discordClient">THe Discord application client</param>
        /// <returns></returns>
        public static async Task <IMessageChannel> GetSuggestionChannel(this IDiscordClient _discordClient)
        {
            ISocketMessageChannel channel = await _discordClient.GetChannelAsync(ulong.Parse(DiscordHandler.Instance.SuggestionChannelID)) as ISocketMessageChannel;

            return(channel);
        }
示例#23
0
 public ValueTask <IDiscordGuildChannel> GetChannelAsync(ulong id)
 {
     return(_client.GetChannelAsync <IDiscordGuildChannel>(id, Id));
 }