Пример #1
0
        public async Task <MyISelfUser> GetUserFromAuthToken(string token)
        {
            var myClient = new DiscordRestClient();
            await myClient.LoginAsync(TokenType.Bearer, token);

            return(myClient.CurrentUser.Adapt <MyISelfUser>());
        }
 /// <summary>
 /// Constructs a new <see cref="InfractionSyncingHandler"/> object with the given injected dependencies.
 /// </summary>
 /// <param name="moderationService">A moderation service to interact with the infractions system.</param>
 /// <param name="restClient">A REST client to interact with the Discord API.</param>
 public InfractionSyncingHandler(
     IModerationService moderationService,
     DiscordRestClient restClient)
 {
     _moderationService = moderationService;
     _restClient        = restClient;
 }
        async Task InitializeDiscord()
        {
            client = new DiscordRestClient();
            await client.LoginAsync(TokenType.Bot, token);

            channel = await client.GetChannelAsync(GeneralChannelId) as RestTextChannel;
        }
Пример #4
0
        public async Task <IActionResult> Redirect()
        {
            if (!Request.Query.ContainsKey("code"))
            {
                return(new RedirectResult("/", false));
            }

            var response = await _authClient.RequestAccessToken(Request.Query["code"]);

            Response.Cookies.Append("DiscordAuth", JsonConvert.SerializeObject(response), new CookieOptions
            {
                Secure      = true,
                HttpOnly    = true,
                Expires     = DateTimeOffset.FromUnixTimeSeconds(int.MaxValue),
                IsEssential = true
            });

            _client = new DiscordRestClient(new DiscordConfiguration
            {
                Token     = response.AccessToken,
                TokenType = TokenType.Bearer
            });
            await _client.InitializeCacheAsync();

            await _client.InitializeAsync();

            Program.Client = _client;

            return(Redirect("/"));
        }
Пример #5
0
 public DiscordAnnouncer(DiscordRestClient discordClient, ulong guildId, ulong purgeLogChannelId, string warningText)
 {
     _warningText  = warningText;
     _guild        = discordClient.GetGuildAsync(guildId).Result;
     _purgeChannel = _guild.GetTextChannelAsync(purgeLogChannelId).Result;
     _userDict     = _guild.GetUsersAsync().FlattenAsync().Result.ToDictionary(u => u.Id, u => u);
 }
Пример #6
0
        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);
                }
            }
        }
        public async Task InitializeAsync()
        {
            var config     = ConfigurationService.Basic;
            var restClient = new DiscordRestClient();
            var client     = new DiscordSocketClient(new DiscordSocketConfig
            {
                MessageCacheSize = 100,
                LogLevel         = LogSeverity.Info
            });

            var provider = new ServiceCollection()
                           .AutoAddServices()
                           .AddSingleton(client)
                           .AddSingleton(restClient)
                           .AddSingleton <CommandService>()
                           .AddSingleton <CancellationTokenSource>()
                           .AddSingleton <Random>()
                           .AddEntityFrameworkNpgsql()
                           .BuildServiceProvider();

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

            await provider.InitializeServicesAsync();

            await client.LoginAsync(TokenType.Bot, config.DiscordToken);

            await client.StartAsync();

            try
            {
                await Task.Delay(-1, provider.GetRequiredService <CancellationTokenSource>().Token);
            }
            catch (TaskCanceledException)
            { }
        }
Пример #8
0
 public PartnerManagerService(GuildVerificationService channelVerification,
                              DiscordRestClient rest, IServiceProvider services)
 {
     this._channelVerification = channelVerification;
     this._rest = rest;
     _services  = services;
 }
Пример #9
0
        /// <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);
        }
Пример #10
0
        private async Task RunAsync()
        {
            socketClient = new DiscordSocketClient(new DiscordSocketConfig
            {
                LogLevel = LogSeverity.Verbose
            });
            socketClient.Log += Log; // Set up a method for logs to be output to the console window

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

            config = Config.Load(); // Load the config file

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

            await socketClient.StartAsync(); // Log in and keep it running in the background

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

            socketClient.MessageReceived += Client_MessageReceived;

            await Task.Delay(-1); // Prevent the bot from exiting immediately
        }
Пример #11
0
        public static async Task <IEnumerable <RestUserGuild> > GetUserGuilds(HttpContext context)
        {
            var access_token = await context.GetTokenAsync("access_token");

            var clientConfig = new DiscordRestConfig()
            {
                LogLevel         = LogSeverity.Debug,
                DefaultRetryMode = RetryMode.AlwaysRetry
            };
            var client = new DiscordRestClient(clientConfig);

            await client.LoginAsync(TokenType.Bearer, access_token).ConfigureAwait(false);

            while (client.LoginState != LoginState.LoggedIn)
            {
                await Task.Delay(1);
            }

            var summaryModels = await client.GetGuildSummariesAsync().FlattenAsync().ConfigureAwait(false);

            var userGuilds = summaryModels;

            await client.LogoutAsync();

            return(userGuilds);
        }
Пример #12
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}");
                    }
                }
            }
        }
Пример #13
0
        private async Task ExecuteStressTestMessage(DiscordRestClient rest)
        {
            DiscordWebhookBuilder?hook = new DiscordWebhookBuilder()
                                         .WithContent($"This Channel: <#{this.GuildId}>" +
                                                      "\n```\n" +
                                                      "STRESS TEST\n\n" +
                                                      $"This Partner ({this.GuildName}):\n" +
                                                      $"ID: {this.GuildId}\n" +
                                                      $"Tags: {string.Join(", ", this.Tags)}\n" +
                                                      $"Size: {this.UserCount}\n" +
                                                      $"Donor Rank: {this.DonorRank}\n\n" +
                                                      $"Other Partner ({this.Match.GuildName}):\n" +
                                                      $"ID: {this.Match.GuildId}\n" +
                                                      $"Tags: {string.Join(", ", this.Match.Tags)}\n" +
                                                      $"Size: {this.Match.UserCount}\n" +
                                                      $"Donor Rank: {this.Match.DonorRank}\n" +
                                                      $"Extra: {this.ExtraMessage}" +
                                                      $"\n```\n" +
                                                      $"Other Channel: <#{this.Match.GuildId}>")
                                         .AddEmbed(new DiscordEmbedBuilder()
                                                   .WithColor(DiscordColor.Gray)
                                                   .WithTitle("Partner Bot Advertisment")
                                                   .WithDescription($"**ID:** {this.Match.GuildId}")
                                                   .WithImageUrl(this.Match.Banner)
                                                   );

            await rest.ExecuteWebhookAsync(this.WebhookId, this.WebhookToken, hook);
        }
Пример #14
0
        public async Task MigrateAsync()
        {
            DiscordRestClient client = null;
            RestGuild         guild  = null;

            await _cache.LoadInfoAsync(_config.GuildId).ConfigureAwait(false);

            while (_cache.Info.Version != MigrationCount)
            {
                if (client == null)
                {
                    client = new DiscordRestClient();
                    await client.LoginAsync(TokenType.Bot, _config.Token).ConfigureAwait(false);

                    guild = await client.GetGuildAsync(_config.GuildId);
                }

                uint nextVer = _cache.Info.Version + 1;
                try
                {
                    await DoMigrateAsync(client, guild, nextVer).ConfigureAwait(false);

                    _cache.Info.Version = nextVer;
                    await _cache.SaveInfoAsync().ConfigureAwait(false);
                }
                catch
                {
                    await _cache.ClearAsync().ConfigureAwait(false);

                    throw;
                }
            }
        }
Пример #15
0
        private static async Task Migration_WipeGuild(DiscordRestClient client, RestGuild guild)
        {
            var textChannels = await guild.GetTextChannelsAsync();

            var voiceChannels = await guild.GetVoiceChannelsAsync();

            var roles = guild.Roles;

            foreach (var channel in textChannels)
            {
                //if (channel.Id != guild.DefaultChannelId)
                await channel.DeleteAsync();
            }
            foreach (var channel in voiceChannels)
            {
                await channel.DeleteAsync();
            }
            foreach (var role in roles)
            {
                if (role.Id != guild.EveryoneRole.Id)
                {
                    await role.DeleteAsync();
                }
            }
        }
Пример #16
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");
        }
Пример #17
0
        protected override async void OnBackgroundActivated(BackgroundActivatedEventArgs args)
        {
            var deferral = args.TaskInstance.GetDeferral();

            switch (args.TaskInstance.Task.Name)
            {
            case TOAST_BACKGROUND_TASK_NAME:
                if (args.TaskInstance.TriggerDetails is ToastNotificationActionTriggerDetail details && TryGetToken(out var token))
                {
                    var arguments = ParseArgs(details.Argument);
                    var userInput = details.UserInput;

                    if (arguments.TryGetValue("channelId", out var cId) && ulong.TryParse(cId, out var channelId))
                    {
                        if (userInput.TryGetValue("tbReply", out var t) && t is string text)
                        {
                            var client = new DiscordRestClient(new DiscordConfiguration()
                            {
                                Token = token, TokenType = TokenType.User
                            });
                            await client.CreateMessageAsync(channelId, text, false, null, Enumerable.Empty <IMention>(), null);
                        }
                    }
                }
                break;
            }

            deferral.Complete();
        }
Пример #18
0
        internal static async Task Migration_CreateVoiceChannels(DiscordRestClient client, RestGuild guild)
        {
            var voice1 = await guild.CreateVoiceChannelAsync("voice1");

            var voice2 = await guild.CreateVoiceChannelAsync("voice2");

            var voice3 = await guild.CreateVoiceChannelAsync("voice3");

            var cat2 = await guild.CreateCategoryChannelAsync("cat2");

            await voice1.ModifyAsync(x =>
            {
                x.Bitrate    = 96000;
                x.Position   = 1;
                x.CategoryId = cat2.Id;
            });

            await voice2.ModifyAsync(x =>
            {
                x.UserLimit = null;
            });

            await voice3.ModifyAsync(x =>
            {
                x.Bitrate    = 8000;
                x.Position   = 1;
                x.UserLimit  = 16;
                x.CategoryId = cat2.Id;
            });

            CheckVoiceChannels(voice1, voice2, voice3);
        }
Пример #19
0
        private static async Task <RestSelfUser> GetUser(string token)
        {
            if (!string.IsNullOrWhiteSpace(token))
            {
                if (TokenUserMap.ContainsKey(token))
                {
                    return(TokenUserMap[token]);
                }
                else
                {
                    try
                    {
                        using (var drc = new DiscordRestClient())
                        {
                            await drc.LoginAsync(TokenType.Bearer, token);

                            TokenUserMap.Add(token, drc.CurrentUser);
                            IDUserMap.Add(drc.CurrentUser.Id, drc.CurrentUser);
                            return(drc.CurrentUser);
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine($"Exception while Getting Discord User: {e}");
                    }
                }
            }


            return(null);
        }
Пример #20
0
        public static Task <DiscordMember> GetMember(this DiscordRestClient client, ulong guild, ulong user)
        {
            async Task <DiscordMember> Inner() =>
            await(await client.GetGuildAsync(guild)).GetMemberAsync(user);

            return(WrapDiscordCall(Inner()));
        }
Пример #21
0
 public DonorService(DiscordShardedClient client, PartnerBotConfiguration pcfg,
                     DiscordRestClient rest)
 {
     this._client = client;
     this._pcfg   = pcfg;
     this._rest   = rest;
 }
Пример #22
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            _client = new DiscordSocketClient(new DiscordSocketConfig
            {
                LogLevel = LogSeverity.Info
            });
            _client.MessageReceived       += CommandRecieved;
            _client.ReactionAdded         += _client_ReactionAdded;
            _client.UserVoiceStateUpdated += _client_UserVoiceStateUpdated;

            _rclient = new DiscordRestClient(new DiscordRestConfig {
            });

            //次の行に書かれているstring token = "hoge"に先程取得したDiscordTokenを指定する。
            string token = Configuration.GetValue <string>("DiscordBotToken");

            //トークンが取得出来ない場合、BOTは活動しません。
            if (string.IsNullOrEmpty(token))
            {
                return;
            }

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

            await _client.StartAsync();

            await _rclient.LoginAsync(TokenType.Bot, token);
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;

                options.DefaultChallengeScheme = "Discord";
            })
            .AddCookie()
            .AddDiscord(options =>
            {
                options.AppId     = Configuration[ConfigConstants.DiscordAppId];
                options.AppSecret = Configuration[ConfigConstants.DiscordAppSecret];
                options.Scope.Add("guilds");
                // options.Scope.Add("guilds.join"); // maybe later
                options.SaveTokens = true;
            });

            var restConfig = new DiscordRestConfig()
            {
                DefaultRetryMode = Discord.RetryMode.AlwaysRetry,
                LogLevel         = Discord.LogSeverity.Warning,
            };
            var discordRestClient = new DiscordRestClient(restConfig);

            services.AddSingleton <DiscordRestClient>(discordRestClient);
        }
Пример #24
0
        private void InitializeNewRestClient()
        {
            Task.WaitAll(DisposeRestClient());
            RestClient = new();

            RestClient.LoggedIn += AddRestClientDisconnectionLoggers;
        }
Пример #25
0
        public async Task WorldsAsync()
        {
            var response = $"*worlds report ({GameConfiguration.PublicURL})*\n";

            using (var drc = new DiscordRestClient())
            {
                foreach (var world in Worlds.AllWorlds)
                {
                    var players = Player.GetWorldPlayers(world.Value);

                    foreach (var player in players)
                    {
                        if (!string.IsNullOrWhiteSpace(player.Token))
                        {
                            try
                            {
                                await drc.LoginAsync(TokenType.Bearer, player.Token);

                                response += $"{world.Key}({world.Value.AdvertisedPlayerCount}): {player.Name} is @{drc.CurrentUser}\n";
                            }
                            catch (Exception e)
                            {
                                response += $"{world.Key}({world.Value.AdvertisedPlayerCount}): {player.Name} FAIL: ${e.Message}\n";
                            }
                        }
                    }
                }
            }
            response += "\n";

            await ReplyAsync(response);
        }
        public DiscordControllerBase(DiscordRestClient discordRestClient, IConfiguration configuration) : base() // DI
        {
            this.discordRestAppClient = discordRestClient;
            this.configuration        = configuration;

            GuildId    = ulong.Parse(configuration[ConfigConstants.DiscordGuildId]);
            CategoryId = ulong.Parse(configuration[ConfigConstants.DiscordCategoryId]);
        }
Пример #27
0
 public LogChannelService(EmbedService embed, ILogger logger, DiscordRestClient rest, IDatabase db, IDataStore data)
 {
     _embed  = embed;
     _rest   = rest;
     _db     = db;
     _data   = data;
     _logger = logger.ForContext <LogChannelService>();
 }
Пример #28
0
 public CommandHandlingService(EnergizeClient client)
 {
     this.Client         = client.DiscordClient;
     this.RestClient     = client.DiscordRestClient;
     this.Logger         = client.Logger;
     this.MessageSender  = client.MessageSender;
     this.ServiceManager = client.ServiceManager;
 }
        async Task InitializeDiscord(string token)
        {
            client = new DiscordRestClient();

            await client.LoginAsync(TokenType.Bot, "NDU5NzM3ODk4NjUzMzE5MTY4.XrA89w.H6nM6U4zhpde3gJOu471KEErMJQ");

            channel = await client.GetChannelAsync(GeneralChannelId) as RestTextChannel;
        }
Пример #30
0
 public LogChannelService(EmbedService embed, ILogger logger, DiscordRestClient rest, IDatabase db, ModelRepository repo)
 {
     _embed  = embed;
     _rest   = rest;
     _db     = db;
     _repo   = repo;
     _logger = logger.ForContext <LogChannelService>();
 }