コード例 #1
0
        public static async Task SendMessage(ParticipantData participant, string message)
        {
            if (participant.IsDiscordIdValid())
            {
                var user = await restClient.GetUserAsync(participant.discordId);

                await user.SendMessageAsync(message);
            }
        }
コード例 #2
0
        public async Task <UserWaifusAPI> GetUserWaifus(ulong userId)
        {
            try
            {
                IUser user = _client.GetUser(userId) ?? await _restClient.GetUserAsync(userId) as IUser;

                using (var soraContext = new SoraContext())
                {
                    var userwaifus = new UserWaifusAPI();
                    var userdb     = Utility.OnlyGetUser(userId, soraContext);
                    if (userdb == null || userdb.UserWaifus.Count == 0)
                    {
                        userwaifus.Success = false;
                        return(userwaifus);
                    }

                    userwaifus.Success   = true;
                    userwaifus.Username  = user?.Username ?? "Undefined";
                    userwaifus.AvatarUrl = user?.GetAvatarUrl();

                    foreach (var userWaifu in userdb.UserWaifus)
                    {
                        var waifu = soraContext.Waifus.FirstOrDefault(x => x.Id == userWaifu.WaifuId);
                        if (waifu == null)
                        {
                            continue;
                        }

                        userwaifus.Waifus.Add(new UserWaifuAPI()
                        {
                            Count      = userWaifu.Count,
                            Id         = waifu.Id,
                            ImageUrl   = waifu.ImageUrl,
                            Name       = waifu.Name,
                            Rarity     = WaifuService.GetRarityString(waifu.Rarity),
                            SortRarity = waifu.Rarity
                        });
                    }

                    if (userwaifus.Waifus.Count == 0)
                    {
                        userwaifus.Success = false;
                        return(userwaifus);
                    }

                    userwaifus.Waifus = userwaifus.Waifus.OrderByDescending(x => x.SortRarity).ToList();

                    return(userwaifus);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            return(null);
        }
コード例 #3
0
        public override async Task <TypeReaderResult> ReadAsync(
            ICommandContext context,
            string input,
            IServiceProvider services)
        {
            var result = await base.ReadAsync(context, input, services);

            if (result.IsSuccess)
            {
                return(result);
            }
            else
            {
                DiscordRestClient restClient = (context.Client as DiscordSocketClient).Rest;
                if (MentionUtils.TryParseUser(input, out var id))
                {
                    RestUser user = await restClient.GetUserAsync(id);

                    if (user != null)
                    {
                        return(TypeReaderResult.FromSuccess(user));
                    }
                }
                if (ulong.TryParse(input, NumberStyles.None, CultureInfo.InvariantCulture, out id))
                {
                    RestUser user = await restClient.GetUserAsync(id);

                    if (user != null)
                    {
                        return(TypeReaderResult.FromSuccess(user));
                    }
                }
                return(TypeReaderResult.FromError(CommandError.ObjectNotFound, "User not found."));
            }

            /*
             * if (svc != null) {
             *  var game = svc.GetGameFromChannel(context.Channel);
             *  if (game != null) {
             *      var player = game.Players.SingleOrDefault(p => p.User.Id == user.Id);
             *      return (player != null)
             *          ? TypeReaderResult.FromSuccess(player)
             *          : TypeReaderResult.FromError(CommandError.ObjectNotFound, "Specified user not a player in this game.");
             *  }
             *  return TypeReaderResult.FromError(CommandError.ObjectNotFound, "No game going on.");
             * }
             * return TypeReaderResult.FromError(CommandError.ObjectNotFound, "Game service not found.");*/
        }
コード例 #4
0
ファイル: CoreService.cs プロジェクト: zio3/VetCoin
        public async Task SendDirectMessage(VetMember[] members, string message, Discord.Embed enbed = null)
        {
            var rclient  = new DiscordRestClient(new DiscordRestConfig {
            });
            string token = Configuration.GetValue <string>("DiscordBotToken");

            //トークンが未設定の場合、何も起こらなくする
            if (string.IsNullOrEmpty(token))
            {
                return;
            }


            await rclient.LoginAsync(TokenType.Bot, token);

            foreach (var member in members)
            {
                var user = await rclient.GetUserAsync(member.DiscordId);

                var dmc = await user.GetOrCreateDMChannelAsync();


                if (enbed == null)
                {
                    await dmc.SendMessageAsync(message);
                }
                else
                {
                    await dmc.SendMessageAsync(message, false, enbed);
                }
            }
        }
コード例 #5
0
ファイル: UserService.cs プロジェクト: jrusbatch/MODiX
        /// <inheritdoc />
        public async Task <EphemeralUser> GetUserInformationAsync(ulong guildId, ulong userId)
        {
            if (userId == 0)
            {
                return(null);
            }

            var guild = await DiscordClient.GetGuildAsync(guildId);

            var guildUser = await guild.GetUserAsync(userId);

            if (!(guildUser is null))
            {
                await TrackUserAsync(guildUser);
            }

            var user = await DiscordClient.GetUserAsync(userId);

            var restUser = await DiscordRestClient.GetUserAsync(userId);

            var guildUserSummary = await GetGuildUserSummaryAsync(guildId, userId);

            var ban = (await guild.GetBansAsync()).FirstOrDefault(x => x.User.Id == userId);

            var buildUser = new EphemeralUser()
                            .WithGuildUserSummaryData(guildUserSummary)
                            .WithIUserData(restUser)
                            .WithIUserData(user)
                            .WithIGuildUserData(guildUser)
                            .WithGuildContext(guild)
                            .WithBanData(ban);

            return(buildUser.Id == 0 ? null : buildUser);
        }
コード例 #6
0
        private static async Task ParseNewDiscordIds()
        {
            DiscordRestClient discordClient = new DiscordRestClient();

            discordClient.Log += new Func <LogMessage, Task>(l => { Console.WriteLine(l); return(Task.CompletedTask); });
            await discordClient.LoginAsync(TokenType.Bot, config.DiscordApiToken);

            List <string> DiscordIdsToParse = FetchDiscordIds(true);

            using (BatchQueryBuilder batchQuerybuilder = new BatchQueryBuilder(config.ConnString, 4000))
            {
                foreach (string i in DiscordIdsToParse)
                {
                    if (i == "0")
                    {
                        continue;
                    }
                    try
                    {
                        Console.WriteLine($"Parsing Discord ID {i}");
                        var discordUser = await discordClient.GetUserAsync(UInt64.Parse(i));

                        batchQuerybuilder.AppendSqlCommand($"UPDATE FamilyRpServerAccess.ParsedDiscordAccounts SET DiscordCreated = '{discordUser.CreatedAt.UtcDateTime}', DiscordUsername = '******', DiscordDiscriminator = {MySqlHelper.EscapeString(discordUser.Discriminator)}, IsParsed = 1 WHERE DiscordId = {i};");
                        AuditLog(null, "Discord", "Parsed", "", i, batchQuerybuilder);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"Could not parse Discord ID {i}; {ex}");
                    }
                }
            }
        }
コード例 #7
0
        public async Task <IGuildUser?> TryGetGuildUserAsync(IGuild guild, ulong userId, CancellationToken cancellationToken)
        {
            var user = await guild.GetUserAsync(userId);

            if (user is not null)
            {
                await TrackUserAsync(user, cancellationToken);

                return(user);
            }

            var restUser = await DiscordRestClient.GetUserAsync(userId);

            // Even if they aren't in the guild, we still want to track them.
            if (restUser is not null)
            {
                var ephemeralUser = new EphemeralUser()
                                    .WithIUserData(restUser)
                                    .WithGuildContext(guild);

                await TrackUserAsync(ephemeralUser, cancellationToken);

                return(null);
            }

            throw new InvalidOperationException($"Discord user {userId} does not exist");
        }
コード例 #8
0
        private async Task _client_ReactionAdded(Cacheable <IUserMessage, ulong> arg1, ISocketMessageChannel arg2, SocketReaction arg3)
        {
            var amount = 0;

            if (arg3.Emote.Name == "10")
            {
                amount = 10;
            }

            if (arg3.Emote.Name == "50")
            {
                amount = 50;
            }

            if (amount == 0)
            {
                return;
            }

            var message = await arg2.GetMessageAsync(arg3.MessageId);

            var toId   = message.Author.Id;
            var fromId = arg3.UserId;

            //if(toId == fromId)
            //{
            //    return;
            //}

            IDMChannel fromDmChannel = null;

            if (arg3.User.IsSpecified)
            {
                fromDmChannel = await arg3.User.Value.GetOrCreateDMChannelAsync();
            }
            else
            {
                var user = await _rclient.GetUserAsync(fromId);

                fromDmChannel = await user.GetOrCreateDMChannelAsync();
            }
            var toDmChannel = await message.Author.GetOrCreateDMChannelAsync();



            using (var scope = Services.CreateScope())
            {
                var service = ActivatorUtilities.CreateInstance <ReactionSendService>(scope.ServiceProvider);
                await service.SendCoin(fromId, toId, amount, fromDmChannel, toDmChannel);
            }


            //arg2.GetMessageAsync()
            await Task.Yield();

            Console.WriteLine();
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: Googie2149/ReactWelcome
        private async Task RunAsync()
        {
            socketClient = new DiscordSocketClient(new DiscordSocketConfig
            {
                LogLevel            = LogSeverity.Error,
                AlwaysDownloadUsers = false,
                MessageCacheSize    = 0
            });
            socketClient.Log += Log;

            restClient = new DiscordRestClient(new DiscordRestConfig
            {
                LogLevel = LogSeverity.Verbose
            });
            restClient.Log += Log;

            if (File.Exists("./update"))
            {
                var temp = File.ReadAllText("./update");
                ulong.TryParse(temp, out updateChannel);
                File.Delete("./update");
                Console.WriteLine($"Found an update file! It contained [{temp}] and we got [{updateChannel}] from it!");
            }

            config = await Config.Load();

            await socketClient.LoginAsync(TokenType.Bot, config.Token);

            await socketClient.StartAsync();

            await restClient.LoginAsync(TokenType.Bot, config.Token);

            if (File.Exists("./deadlock"))
            {
                Console.WriteLine("We're recovering from a deadlock.");
                File.Delete("./deadlock");
                foreach (var u in config.OwnerIds)
                {
                    (await restClient.GetUserAsync(u))?
                    .SendMessageAsync($"I recovered from a deadlock.\n`{DateTime.Now.ToShortDateString()}` `{DateTime.Now.ToLongTimeString()}`");
                }
            }

            socketClient.GuildAvailable += Client_GuildAvailable;
            socketClient.Disconnected   += SocketClient_Disconnected;

            try
            {
                socketClient.ReactionAdded += Client_ReactionAdded;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex.Source}\n{ex.Message}\n{ex.StackTrace}");
            }

            await Task.Delay(-1);
        }
コード例 #10
0
        public async Task IconCheck()
        {
            var members = DbContext.VetMembers
                          .AsQueryable()
                          .Where(c => c.MemberType == MemberType.User)
                          .ToArray();

            var hc = HttpClientFactory.CreateClient("IconCheckService");

            hc.DefaultRequestHeaders.CacheControl = new System.Net.Http.Headers.CacheControlHeaderValue
            {
                NoCache = true
            };

            string token    = Configuration.GetValue <string>("DiscordBotToken");
            var    _rclient = new DiscordRestClient(new DiscordRestConfig {
            });
            await _rclient.LoginAsync(TokenType.Bot, token);

            foreach (var member in members)
            {
                var url = member.GetAvaterIconUrl();

                try
                {
                    var result = await hc.GetAsync(url);

                    if (result.StatusCode == System.Net.HttpStatusCode.NotFound)
                    {
                        //Console.WriteLine();
                        var discordUser = await _rclient.GetUserAsync(member.DiscordId);

                        if (discordUser != null)
                        {
                            member.AvatarId = discordUser.AvatarId;
                        }
                        else
                        {
                            Console.WriteLine();
                        }
                    }
                    else
                    {
                        if (result.StatusCode != System.Net.HttpStatusCode.OK)
                        {
                            Console.WriteLine();
                        }
                    }
                }
                catch (HttpRequestException hre)
                {
                    Console.WriteLine(hre.ToString());;
                }
            }
            await DbContext.SaveChangesAsync();
        }
コード例 #11
0
        private async Task RunAsync()
        {
            socketClient = new DiscordSocketClient(new DiscordSocketConfig
            {
                LogLevel            = LogSeverity.Verbose,
                AlwaysDownloadUsers = true
            });
            socketClient.Log += Log;

            restClient = new DiscordRestClient(new DiscordRestConfig
            {
                LogLevel = LogSeverity.Verbose
            });
            restClient.Log += Log;

            if (File.Exists("./update"))
            {
                var temp = File.ReadAllText("./update");
                ulong.TryParse(temp, out updateChannel);
                File.Delete("./update");
                Console.WriteLine($"Found an update file! It contained [{temp}] and we got [{updateChannel}] from it!");
            }

            config = await Config.Load();

            steam = new SteamService();

            map = new ServiceCollection().AddSingleton(socketClient).AddSingleton(config).AddSingleton(steam).BuildServiceProvider();


            await socketClient.LoginAsync(TokenType.Bot, config.Token);

            await socketClient.StartAsync();

            await restClient.LoginAsync(TokenType.Bot, config.Token);

            if (File.Exists("./deadlock"))
            {
                Console.WriteLine("We're recovering from a deadlock.");
                File.Delete("./deadlock");
                (await restClient.GetUserAsync(config.OwnerId))?.SendMessageAsync($"I recovered from a deadlock.\n`{DateTime.Now.ToShortDateString()}` `{DateTime.Now.ToLongTimeString()}`");
            }

            socketClient.GuildAvailable += Client_GuildAvailable;
            socketClient.Disconnected   += SocketClient_Disconnected;

            await steam.Install(map);

            handler = new CommandHandler();
            await handler.Install(map);

            Console.WriteLine("test");

            await Task.Delay(-1);
        }
コード例 #12
0
            private static async Task <IUser?> TryDownloadUserAsync(
                IDiscordClient client, string input)
            {
                if (!UInt64.TryParse(input, out var uid))
                {
                    if (!MentionUtils.TryParseUser(input, out uid))
                    {
                        return(null);
                    }
                }

                return(client switch
                {
                    DiscordRestClient rest => await rest.GetUserAsync(uid),
                    DiscordSocketClient sock => await sock.Rest.GetUserAsync(uid),
                    _ => null
                });
コード例 #13
0
ファイル: UserService.cs プロジェクト: zumpanik/SoraBot-v2
        public async Task <Option <IUser> > GetOrSetAndGet(ulong id)
        {
            var user = this.Get(id);

            if (user.HasValue)
            {
                return(user);
            }
            // Otherwise we gotta fetch and store it in cache
            var userResp = await _restClient.GetUserAsync(id).ConfigureAwait(false);

            if (userResp == null)
            {
                return(Option.None <IUser>());
            }
            // Otherwise we save it
            _cacheService.Set(CacheId.GetUser(id), userResp, TimeSpan.FromMinutes(_USER_TTL_MINS));
            return(Option.Some <IUser>(userResp));
        }
コード例 #14
0
        public async Task <EphemeralUser?> GetUserInformationAsync(ulong guildId, ulong userId)
        {
            if (userId == 0)
            {
                return(null);
            }

            var guildTask        = DiscordClient.GetGuildAsync(guildId);
            var userTask         = DiscordClient.GetUserAsync(userId);
            var restUserTask     = DiscordRestClient.GetUserAsync(userId);
            var guildUserSummary = await GetGuildUserSummaryAsync(guildId, userId);

            var guild = await guildTask;

            var guildUser = await guild.GetUserAsync(userId);

            var ban = await guild.GetBanAsync(userId);

            var user     = await userTask;
            var restUser = await restUserTask;

            if (guildUser is { })
コード例 #15
0
        /// <inheritdoc />
        public async Task <EphemeralUser> GetUserInformationAsync(ulong guildId, ulong userId)
        {
            if (userId == 0)
            {
                return(null);
            }

            var guildTask            = DiscordClient.GetGuildAsync(guildId);
            var userTask             = DiscordClient.GetUserAsync(userId);
            var restUserTask         = DiscordRestClient.GetUserAsync(userId);
            var guildUserSummaryTask = GetGuildUserSummaryAsync(guildId, userId);

            var guild = await guildTask;

            var guildUserTask = guild.GetUserAsync(userId);
            var bansTask      = guild.GetBansAsync();

            var user             = await userTask;
            var restUser         = await restUserTask;
            var guildUserSummary = await guildUserSummaryTask;
            var ban       = (await bansTask).FirstOrDefault(x => x.User.Id == userId);
            var guildUser = await guildUserTask;

            if (guildUser is {})
コード例 #16
0
        public async Task SendDmToUser(ulong discordUserId, string message)
        {
            var user = await restClient.GetUserAsync(discordUserId).ConfigureAwait(false);

            await user.SendMessageAsync(message).ConfigureAwait(false);
        }
コード例 #17
0
        private async Task RunAsync()
        {
            socketClient = new DiscordSocketClient(new DiscordSocketConfig
            {
                LogLevel            = LogSeverity.Verbose,
                AlwaysDownloadUsers = true,
                GatewayIntents      = GatewayIntents.GuildBans | GatewayIntents.DirectMessages | GatewayIntents.DirectMessageReactions |
                                      GatewayIntents.GuildBans | GatewayIntents.GuildEmojis | GatewayIntents.GuildMembers | GatewayIntents.GuildPresences | GatewayIntents.GuildMessageReactions |
                                      GatewayIntents.GuildMessages | GatewayIntents.Guilds
            });
            socketClient.Log += Log;

            restClient = new DiscordRestClient(new DiscordRestConfig
            {
                LogLevel = LogSeverity.Verbose
            });
            restClient.Log += Log;

            if (File.Exists("./update"))
            {
                var temp = File.ReadAllText("./update");
                ulong.TryParse(temp, out updateChannel);
                File.Delete("./update");
                Console.WriteLine($"Found an update file! It contained [{temp}] and we got [{updateChannel}] from it!");
            }

            config = Config.Load();
            //uptime = new UptimeService();
            events             = EventStorage.Load();
            rankedService      = new RankedService();
            strings            = new RandomStrings();
            discordBotsService = new DiscordBotsService();
            //gate = new AccountGateService();


            //var map = new DependencyMap();
            map = new ServiceCollection().AddSingleton(socketClient).AddSingleton(config).AddSingleton(strings).AddSingleton(events).AddSingleton(rankedService).AddSingleton(discordBotsService) /*.AddSingleton(gate)*/.BuildServiceProvider();

            //await ConfigureServicesAsync(map);

            await socketClient.LoginAsync(TokenType.Bot, config.Token);

            await socketClient.StartAsync();

            await restClient.LoginAsync(TokenType.Bot, config.Token);

            if (File.Exists("./deadlock"))
            {
                Console.WriteLine("We're recovering from a deadlock.");
                File.Delete("./deadlock");
                foreach (var u in config.OwnerIds)
                {
                    (await restClient.GetUserAsync(u))?
                    .SendMessageAsync($"I recovered from a deadlock.\n`{DateTime.Now.ToShortDateString()}` `{DateTime.Now.ToLongTimeString()}`");
                }
            }

            socketClient.GuildAvailable  += Client_GuildAvailable;
            socketClient.Disconnected    += SocketClient_Disconnected;
            socketClient.MessageReceived += SocketClient_MessageReceived;
            socketClient.ReactionAdded   += SocketClient_ReactionAdded;
            //client.GuildMemberUpdated += Client_UserUpdated;
            // memes

            //await uptime.Install(map);

            socketClient.UserJoined += Client_UserJoined;

            //await gate.Install(map);
            await discordBotsService.Install(map);

            handler = new CommandHandler();
            await handler.Install(map);

            //Task.Run(async () =>
            //{
            //    await Task.Delay(1000 * 60); // wait a minute before downloading to ensure we have access to the server
            //    await client.DownloadUsersAsync(new IGuild[] { client.GetGuild(110373943822540800) });
            //    var role = client.GetGuild(110373943822540800).GetRole(110374777914417152);

            //    while (true)
            //    {
            //        foreach (var u in client.GetGuild(110373943822540800).Users.Where(x => x?.IsBot == true))
            //        {
            //            if (!u.Roles.Contains(role))
            //            {
            //                await u.AddRoleAsync(role);
            //            }
            //        }

            //        await Task.Delay(1000 * 60 * 30); // Wait 30 minutes
            //    }
            //});

            //await client.CurrentUser.ModifyAsync(x => x.Avatar = new Image(File.OpenRead("Minitori.png")));

            await Task.Delay(-1);
        }
コード例 #18
0
        public async Task MLogs(params string[] aa)
        {
            if (aa.Length == 0)
            {
                await ReplyAsync("", false, new EmbedBuilder
                {
                    Title       = "What user?",
                    Description = "Mention the user you wish to get modlogs of",
                    Color       = Color.Red
                }.WithCurrentTimestamp());

                return;
            }

            IUser user;

            if (await GetUser(aa[0]) == null)
            {
                var regex = new Regex(@"(\d{18}|\d{17})");
                if (regex.IsMatch(aa[0]))
                {
                    var aadrc = new DiscordRestClient();
                    await aadrc.LoginAsync(TokenType.Bot, Program.token);

                    var aala = await aadrc.GetUserAsync(ulong.Parse(regex.Match(aa[0]).Groups[1].Value));

                    if (aala == null)
                    {
                        await ReplyAsync("", false, new EmbedBuilder
                        {
                            Title       = "What user?",
                            Description = "That user isn't valid :(",
                            Color       = Color.Red
                        }.WithCurrentTimestamp());

                        return;
                    }

                    user = aala;
                }
                else if (Context.Message.MentionedUsers.Any())
                {
                    user = Context.Message.MentionedUsers.First();
                }
                else
                {
                    await ReplyAsync("", false, new EmbedBuilder
                    {
                        Title       = "What user?",
                        Description = "That user isn't valid :(",
                        Color       = Color.Red
                    }.WithCurrentTimestamp());

                    return;
                }
            }
            else
            {
                user = await GetUser(aa[0]);
            }

            var emb = new EmbedBuilder
            {
                Title        = $"Modlogs for user {user.Username}#{user.Discriminator}",
                Color        = Blurple,
                ThumbnailUrl = user.GetAvatarUrl(size: 64)
            };
            var eb = new List <EmbedFieldBuilder>();

            foreach (var i in await GetUserModlogs(Context.Guild.Id, user.Id))
            {
                eb.Add(new EmbedFieldBuilder
                {
                    Name  = Infraction.GetPunishment(i.Punishment),
                    Value =
                        $"**Mod:** <@{i.ModeratorId}>\n**Date:** {i.Time.ToUniversalTime().ToShortDateString()}\n**Time: **{(i.Time.ToUniversalTime().TimeOfDay.Hours <= 12 ? i.Time.ToUniversalTime().TimeOfDay.Hours : i.Time.ToUniversalTime().TimeOfDay.Hours - 12)}:{i.Time.ToUniversalTime().TimeOfDay.Minutes} {(i.Time.ToUniversalTime().TimeOfDay.Hours < 12 ? "AM" : "PM")}\n**Reason:** {i.Reason}",
                    IsInline = true
                });
            }
            if (eb.Count == 0)
            {
                emb.Description = "They've been a good user! No modlogs :)";
            }
            var pm = new PaginatedMessage(PaginatedAppearanceOptions.Default, Context.Message.Channel,
                                          new PaginatedMessage.MessagePage {
                Description = "Error!"
            });

            pm.SetPages("Here's a list of the user's modlogs", eb, 7);
            await pm.Resend();
        }
コード例 #19
0
 public static Task <DiscordUser> GetUser(this DiscordRestClient client, ulong id) =>
 WrapDiscordCall(client.GetUserAsync(id));
コード例 #20
0
 public RestUser GetUser(ulong id)
 {
     return(_client.GetUserAsync(id).Result);
 }
コード例 #21
0
ファイル: Program.cs プロジェクト: Googie2149/TaranzaSoul
        private async Task RunAsync()
        {
            socketClient = new DiscordSocketClient(new DiscordSocketConfig
            {
                LogLevel            = LogSeverity.Verbose,
                AlwaysDownloadUsers = true,
                MessageCacheSize    = 100,
                GatewayIntents      = GatewayIntents.DirectMessages | GatewayIntents.GuildMessages |
                                      GatewayIntents.GuildMembers | GatewayIntents.Guilds | GatewayIntents.GuildMessageReactions
            });
            socketClient.Log += Log;

            restClient = new DiscordRestClient(new DiscordRestConfig
            {
                LogLevel = LogSeverity.Verbose
            });
            restClient.Log += Log;

            if (File.Exists("./update"))
            {
                var temp = File.ReadAllText("./update");
                ulong.TryParse(temp, out updateChannel);
                File.Delete("./update");
                Console.WriteLine($"Found an update file! It contained [{temp}] and we got [{updateChannel}] from it!");
            }

            config = await Config.Load();

            dbhelper = new DatabaseHelper();
            logger   = new Logger();

            var map = new ServiceCollection().AddSingleton(socketClient).AddSingleton(config).AddSingleton(logger).AddSingleton(dbhelper).AddSingleton(restClient).BuildServiceProvider();

            await socketClient.LoginAsync(TokenType.Bot, config.Token);

            await socketClient.StartAsync();

            await restClient.LoginAsync(TokenType.Bot, config.Token);

            if (File.Exists("./deadlock"))
            {
                Console.WriteLine("We're recovering from a deadlock.");
                File.Delete("./deadlock");
                foreach (var u in config.OwnerIds)
                {
                    (await restClient.GetUserAsync(u))?
                    .SendMessageAsync($"I recovered from a deadlock.\n`{DateTime.Now.ToShortDateString()}` `{DateTime.Now.ToLongTimeString()}`");
                }
            }

            socketClient.GuildAvailable += Client_GuildAvailable;
            socketClient.Disconnected   += SocketClient_Disconnected;

            await dbhelper.Install(map);

            await logger.Install(map);

            SpoilerWords = JsonStorage.DeserializeObjectFromFile <List <string> >("filter.json");
            RoleColors   = JsonStorage.DeserializeObjectFromFile <Dictionary <string, ulong> >("colors.json");

            handler = new CommandHandler();
            await handler.Install(map);

            try
            {
                socketClient.MessageReceived    += Client_MessageReceived;
                socketClient.ReactionAdded      += Client_ReactionAdded;
                socketClient.ReactionRemoved    += Client_ReactionRemoved;
                socketClient.GuildMemberUpdated += SocketClient_GuildMemberUpdated;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex.Source}\n{ex.Message}\n{ex.StackTrace}");
            }

            // perpetual queue to add/remove color roles
            Task.Run(async() =>
            {
                while (true)
                {
                    await Task.Delay(3000);

                    try
                    {
                        if (lastRole < DateTimeOffset.Now.AddSeconds(-15))
                        {
                            continue;
                        }

                        List <RoleAddition> temp = new List <RoleAddition>();
                        RoleAddition tempAction  = null;

                        while (RoleAdditions.TryDequeue(out tempAction))
                        {
                            if (config.BlacklistedUsers.ContainsKey(tempAction.userId) &&
                                config.BlacklistedUsers[tempAction.userId] > DateTimeOffset.Now)
                            {
                                continue;
                            }
                            else
                            {
                                temp.Add(tempAction);
                            }
                        }

                        if (temp.Count() != temp.Select(x => x.userId).Distinct().Count())
                        {
                            // SOMEONE clicked on more than one role at a time!
                            Dictionary <ulong, int> counter = new Dictionary <ulong, int>();

                            foreach (var u in temp.Select(x => x.userId))
                            {
                                if (!counter.ContainsKey(u))
                                {
                                    counter[u] = 0;
                                }

                                counter[u]++;
                            }

                            foreach (var u in counter)
                            {
                                if (u.Value > 4)
                                {
                                    try
                                    {
                                        await socketClient.GetUser(u.Key).SendMessageAsync("Hey, slow down! You don't need every color on that list! No more colors for an hour!");
                                    }
                                    catch (Exception ex)
                                    {
                                        // User has their DMs disabled
                                    }

                                    await RemoveAllColors(u.Key);
                                    //config.BlacklistedUsers.Add(u.Key, DateTimeOffset.Now.AddHours(1));
                                    Console.WriteLine($"Blacklisted [{u.Key}] from colors.");

                                    while (temp.Select(x => x.userId).Contains(u.Key))
                                    {
                                        temp.Remove(temp.FirstOrDefault(x => x.userId == u.Key));
                                    }
                                }
                            }
                        }

                        foreach (var ra in temp)
                        {
                            if (ra.remove)
                            {
                                await RemoveAllColors(ra.userId);
                            }
                            else
                            {
                                var user = socketClient.GetGuild(config.HomeGuildId).GetUser(ra.userId) as SocketGuildUser;
                                user.AddRoleAsync(user.Guild.GetRole(ra.roleId));
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        await Task.Delay(1000);
                        // idk something errored
                    }
                }
            });

            //var avatar = new Image(File.OpenRead(".\\TaranzaSOUL.png"));
            //await client.CurrentUser.ModifyAsync(x => x.Avatar = avatar);

            await Task.Delay(-1);
        }
コード例 #22
0
        public async Task ShowMarriages(SocketCommandContext context, SocketUser user)
        {
            using (var _soraContext = new SoraContext())
            {
                var userDb = Utility.OnlyGetUser(user.Id, _soraContext);
                if (userDb == null || userDb.Marriages.Count == 0)
                {
                    await context.Channel.SendMessageAsync("", embed : Utility.ResultFeedback(
                                                               Utility.RedFailiureEmbed, Utility.SuccessLevelEmoji[2],
                                                               $"{Utility.GiveUsernameDiscrimComb(user)} has no marriages yet!"));

                    return;
                }

                var eb = new EmbedBuilder()
                {
                    Color        = Utility.PurpleEmbed,
                    Title        = $"💕 Marriages of {Utility.GiveUsernameDiscrimComb(user)}",
                    ThumbnailUrl = user.GetAvatarUrl() ?? Utility.StandardDiscordAvatar,
                    Footer       = new EmbedFooterBuilder()
                    {
                        Text = "To increase performance some usernames might not be showing. sorry."
                    }
                };
                foreach (var marriage in userDb.Marriages)
                {
                    IUser partner = context.Client.GetUser(marriage.PartnerId) ?? await _restClient.GetUserAsync(marriage.PartnerId) as IUser;

                    eb.AddField(x =>
                    {
                        x.Name =
                            $"{(partner == null ? $"{marriage.PartnerId}" : $"{Utility.GiveUsernameDiscrimComb(partner)}")}";
                        x.IsInline = true;
                        x.Value    = $"*Since {marriage.Since.ToString("dd/MM/yyyy")}*";
                    });
                }

                await context.Channel.SendMessageAsync("", embed : eb);
            }
        }
コード例 #23
0
        private async Task RunAsync()
        {
            socketClient = new DiscordSocketClient(new DiscordSocketConfig
            {
                LogLevel            = LogSeverity.Verbose,
                AlwaysDownloadUsers = true,
                MessageCacheSize    = 100
            });
            socketClient.Log += Log;

            restClient = new DiscordRestClient(new DiscordRestConfig
            {
                LogLevel = LogSeverity.Verbose
            });
            restClient.Log += Log;

            if (File.Exists("./update"))
            {
                var temp = File.ReadAllText("./update");
                ulong.TryParse(temp, out updateChannel);
                File.Delete("./update");
                Console.WriteLine($"Found an update file! It contained [{temp}] and we got [{updateChannel}] from it!");
            }

            config = await Config.Load();

            dbhelper = new DatabaseHelper();
            logger   = new Logger();

            var map = new ServiceCollection().AddSingleton(socketClient).AddSingleton(config).AddSingleton(logger).AddSingleton(dbhelper).BuildServiceProvider();

            await socketClient.LoginAsync(TokenType.Bot, config.Token);

            await socketClient.StartAsync();

            await restClient.LoginAsync(TokenType.Bot, config.Token);

            if (File.Exists("./deadlock"))
            {
                Console.WriteLine("We're recovering from a deadlock.");
                File.Delete("./deadlock");
                foreach (var u in config.OwnerIds)
                {
                    (await restClient.GetUserAsync(u))?
                    .SendMessageAsync($"I recovered from a deadlock.\n`{DateTime.Now.ToShortDateString()}` `{DateTime.Now.ToLongTimeString()}`");
                }
            }

            socketClient.GuildAvailable += Client_GuildAvailable;
            socketClient.Disconnected   += SocketClient_Disconnected;

            await dbhelper.Install(map);

            await logger.Install(map);

            SpoilerWords = JsonStorage.DeserializeObjectFromFile <List <string> >("filter.json");
            RoleColors   = JsonStorage.DeserializeObjectFromFile <Dictionary <string, ulong> >("colors.json");

            handler = new CommandHandler();
            await handler.Install(map);

            try
            {
                socketClient.MessageReceived += Client_MessageReceived;
                socketClient.ReactionAdded   += Client_ReactionAdded;
                socketClient.ReactionRemoved += Client_ReactionRemoved;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex.Source}\n{ex.Message}\n{ex.StackTrace}");
            }

            //var avatar = new Image(File.OpenRead(".\\TaranzaSOUL.png"));
            //await client.CurrentUser.ModifyAsync(x => x.Avatar = avatar);

            await Task.Delay(-1);
        }
コード例 #24
0
        private async Task RunAsync()
        {
            socketClient = new DiscordSocketClient(new DiscordSocketConfig
            {
                //WebSocketProvider = WS4NetProvider.Instance,
                LogLevel = LogSeverity.Verbose
            });
            socketClient.Log += Log;

            restClient = new DiscordRestClient(new DiscordRestConfig
            {
                LogLevel = LogSeverity.Verbose
            });
            restClient.Log += Log;

            if (File.Exists("./update"))
            {
                var temp = File.ReadAllText("./update");
                ulong.TryParse(temp, out updateChannel);
                File.Delete("./update");
                Console.WriteLine($"Found an update file! It contained [{temp}] and we got [{updateChannel}] from it!");
            }

            config = Config.Load();
            events = EventStorage.Load();

            var map = new ServiceCollection().AddSingleton(socketClient).AddSingleton(config).AddSingleton(events).BuildServiceProvider();

            await socketClient.LoginAsync(TokenType.Bot, config.Token);

            await socketClient.StartAsync();

            await restClient.LoginAsync(TokenType.Bot, config.Token);

            if (File.Exists("./deadlock"))
            {
                Console.WriteLine("We're recovering from a deadlock.");
                File.Delete("./deadlock");
                foreach (var u in config.OwnerIds)
                {
                    (await restClient.GetUserAsync(u))?
                    .SendMessageAsync($"I recovered from a deadlock.\n`{DateTime.Now.ToShortDateString()}` `{DateTime.Now.ToLongTimeString()}`");
                }
            }

            eqService = new EmergencyQuestService();
            await eqService.Install(map);

            map = new ServiceCollection().AddSingleton(socketClient).AddSingleton(config).AddSingleton(events).AddSingleton(eqService).BuildServiceProvider();

            socketClient.Disconnected   += SocketClient_Disconnected;
            socketClient.GuildAvailable += Client_GuildAvailable;

            handler = new CommandHandler();
            await handler.Install(map);

            //await Task.Delay(3000);

            //var avatar = new Image(File.OpenRead(".\\TaranzaSOUL.png"));
            //await client.CurrentUser.ModifyAsync(x => x.Avatar = avatar);

            await Task.Delay(-1);
        }