public void SendMessage(TwitchLib.PubSub.Events.OnBitsReceivedArgs e, string message) { foreach (var integration in Controller.Integrations) { if (integration.TwitchChannel == e.ChannelName) { _client?.GetGuild(ulong.Parse(integration.DiscordGuild)).GetTextChannel(ulong.Parse(integration.DiscordChannel)) .SendMessageAsync("[" + integration.TwitchChannel + "] " + "Just received {e.BitsUsed} bits from {e.Username}. That brings their total to {e.TotalBitsUsed} bits!"); } } }
private void TimerCallback(object state) { lock (timerLock) { try { if (discord?.LoginState != LoginState.LoggedIn) { return; } if (server?.ConnectedUsers?.Count == null) { return; } DiscordZkUserCount = discord?.GetGuild(DiscordZkServerID)?.Users?.Count ?? 0; var zkTopic = $"[game: {server.ConnectedUsers.Count} online, {server.MatchMaker.GetTotalWaiting()} in queue, {server.Battles.Values.Where(x => x != null).Sum(x => (int?)x.NonSpectatorCount + x.SpectatorCount) ?? 0} in custom]"; if (zkTopic != lastZkTopic) { foreach (var ch in channels) { discordZkRelay?.SetTopic(ch, $"{server.Channels.Get(ch)?.Topic?.Text} {zkTopic}"); } } lastZkTopic = zkTopic; } catch (Exception ex) { Trace.TraceError("Error processing relay timer: {0}", ex); } } }
public async Task <Infraction> BanUserFromGuildAsync(IUser user, ulong guildId, ulong modId, string reason, TimeSpan time, int pruneDays = 0) { var guild = _guilds.GetOrCreateGuildAccount(guildId); DateTime?endsAt = null; if (time.TotalMilliseconds >= 1000) { endsAt = DateTime.UtcNow.Add(time); } var infraction = AddInfractionToGuild(user.Id, modId, InfractionType.Ban, endsAt, reason, guild); if (endsAt != null) { guild.TimedInfractions.Add(infraction); } await _client.GetGuild(guildId).AddBanAsync(user, pruneDays, reason); _guilds.SaveGuildAccount(guild); return(infraction); }
public IActionResult SwitchGuild(ulong guildId) { var user = DiscordSocketClient.GetGuild(guildId)?.GetUser(SocketUser.Id); if (user == null) { return(BadRequest("Invalid guild, or user is not a member of the guild.")); } Response.Cookies.Append("SelectedGuild", user.Guild.Id.ToString()); return(Ok()); }
public async Task Quarentine(ulong userId, ulong guildId, bool isBot) { // Give the user the quarantine role. await _client.GetGuild(guildId).GetUser(userId).AddRoleAsync(_client.GetGuild(guildId).GetRole(645413078405611540)); // Add to db. if (!await AddUser(userId, "Quarantined")) { await UpdateUser(userId, "Quarantined"); } // If the user already exists, update the DB (user already has quarantine role and will be automatically quarantined when updated) // Send owner a DM. if (isBot) { await _client.GetGuild(guildId).Owner.SendMessageAsync("Someone invited a bot to your server that was not whitelisted. Here are the details:"); } else { await _client.GetGuild(guildId).Owner.SendMessageAsync($"{_client.GetUser(userId).Username} just joined your server but their account is only {DateTime.Now.Subtract(_client.GetUser(userId).CreatedAt.Date).TotalDays} days old!"); } }
/// <summary> /// Runs everytime the bot starts - Sets the Discord channel it is looking at. /// </summary> /// <param name="client"></param> public static async Task BootUp(DiscordSocketClient client) { channel = client.GetGuild(612788621799587850); if (!File.Exists("Data/Users.json")) // If the file that contains all the user data does not exist, then.. { await Init(); // The bot has to be initialized. } Constants.rewards = Bot.GetRewardsFromFile(); Constants.users = Bot.GetUsersFromFile(); Constants.invites = Bot.GetInvitesFromFile(); Constants.blacklistedLeaderboardRoles = Bot.GetRolesFromFile(); }
public async Task <AntiRaidStats> StartAntiRaidAsync(ulong guildId, int userThreshold, int seconds, PunishmentAction action, int minutesDuration) { var g = _client.GetGuild(guildId); await _mute.GetMuteRole(g).ConfigureAwait(false); if (action == PunishmentAction.AddRole) { return(null); } if (!IsDurationAllowed(action)) { minutesDuration = 0; } var stats = new AntiRaidStats() { AntiRaidSettings = new AntiRaidSetting() { Action = action, Seconds = seconds, UserThreshold = userThreshold, PunishDuration = minutesDuration } }; _antiRaidGuilds.AddOrUpdate(guildId, stats, (key, old) => stats); using (var uow = _db.GetDbContext()) { var gc = uow.GuildConfigs.ForId(guildId, set => set.Include(x => x.AntiRaidSetting)); gc.AntiRaidSetting = stats.AntiRaidSettings; await uow.SaveChangesAsync(); } return(stats); }
private async Task _client_ReactionAdded(Cacheable <IUserMessage, ulong> arg1, ISocketMessageChannel arg2, SocketReaction arg3) { if (arg2.Id == 618852225602551818) { var user = _client.GetGuild(Global.GuildID).GetUser(arg3.UserId); EmbedBuilder eb = new EmbedBuilder() { Title = $"***Welcome to Lucaas's Official Discord server!***", Footer = new EmbedFooterBuilder() { IconUrl = user.GetAvatarUrl(), Text = $"{user.Username}#{user.Discriminator}" }, Description = Global.WelcomeMessage, ThumbnailUrl = Global.WelcomeMessageURL, Color = Color.Green }; await _client.GetGuild(Global.GuildID).GetTextChannel(Global.WelcomeMessageChanID).SendMessageAsync("", false, eb.Build()); Global.ConsoleLog($"WelcomeMessage for {user.Username}#{user.Discriminator}", ConsoleColor.Blue); } }
public async Task ToggleMuteForAllUsersAsync(ulong serverId, string channelName, bool toggle = true) { SocketGuild guild = client.GetGuild(serverId); Console.WriteLine(); Console.WriteLine("Task: Mute All"); Console.WriteLine($"Guild Name: {guild.Name}"); var channel = guild.VoiceChannels.FirstOrDefault(p => p.Name.Equals(channelName)); if (channel.Users.Any()) { var names = new List <string>(); var tasks = new List <Task>(); foreach (var user in channel.Users) { Console.WriteLine($"User name: {user.Id}"); if ((!user.IsMuted && toggle) || (user.IsMuted && !toggle)) { tasks.Add(user.ModifyAsync(p => p.Mute = toggle)); names.Add(user.Mention); } } while (tasks.Any()) { Task finished = await Task.WhenAny(tasks); tasks.Remove(finished); } if (names.Any()) { string message = $"I just {(toggle ? "muted" : "unmuted")} the following users on {channelName}:\n {string.Join("\n", names)}\n I'm not spamming guys...blame EXD!"; await LogToChannel(serverId, this.logChannel, message); } } }
public static async Task <DiscordUser> MapUserAsync(DiscordSocketClient discord, BotState state, DBDiscordUser dBUser) { var guild = discord.GetGuild(dBUser.GuildIDSnowflake); if (guild == null) { return(null); } var socketUser = await guild.GetUserFromGuildAsync(dBUser.UserIDSnowflake); return(await DiscordUser.CreateAsync(guild, socketUser, dBUser, discord, state.AppInfo)); }
/// <summary> /// Attempts to unmuzzle a target user. /// </summary> /// <param name="Parameters"> /// A string-string dictionary containing a definition for "User". /// This value should be parsable to a <c>ulong</c>. /// </param> /// <returns>A <c>Task</c> object, which can be awaited until this method completes successfully.</returns> public async Task UnmuzzleCallback(Dictionary <string, string> Parameters) { ulong UserID = Convert.ToUInt64(Parameters["User"]); IGuildUser User = DiscordSocketClient.GetGuild(BotConfiguration.GuildID).GetUser(UserID); if (User == null) { return; } await Unmuzzle(User); }
private async Task Ready() { MagicHelper.UseEmojis(_client.GetGuild(246090768240869386).Emotes); var reminderService = _serviceProvider.GetService(typeof(ReminderService)) as ReminderService; await reminderService.StartAsync(_client); var subscriptionService = _serviceProvider.GetService(typeof(SubscriptionService)) as SubscriptionService; subscriptionService.Start(); await _client.SetGameAsync("prefix ;"); }
public async Task CreateEmbedInVerificationChannelAsync(SocketMessage message) { if (!message.Author.IsAUser()) { return; } if (message.Channel is IPrivateChannel && message.Source == MessageSource.User && message.Attachments.Count > 0) { Console.WriteLine("I'm making another embed!"); var embedBuilder = new EmbedBuilder().WithTitle("Verificatie student"); foreach (IAttachment attachment in message.Attachments) { if (attachment.IsSpoiler()) { embedBuilder = embedBuilder.AddField("Foto", $"||{attachment.Url}||"); } else { embedBuilder = embedBuilder.WithImageUrl(attachment.Url); } } var embed = embedBuilder .AddField("Id", message.Author.Id.ToString()) .WithAuthor(message.Author.ToString(), message.Author.GetAvatarUrl()) .WithColor(Color.Blue) .WithFooter(footer => footer.WithText($"Account gecreëerd op: {message.Author.CreatedAt}")) .WithTimestamp(DateTime.Now.ToLocalTime()) .Build(); var guild = _client.GetGuild(ulong.Parse(_config["ids:server"])); var verificationLogChannel = (ISocketMessageChannel)guild.GetChannel(ulong.Parse(_config["ids:verificatielog"])); var verificationEmbed = await verificationLogChannel.SendMessageAsync("", false, embed); await verificationEmbed.AddReactionsAsync(Emojis.emojiVerificatie); } }
private async Task OnReady() { if (connection != null) { connection.Dispose(); } connection = new Rabbit(config.hostName, config.username, config.password, config.vhost); connection.NewMessage += OnPhaseMessage; JObject json = new JObject(); json.Add("token", config.token); json.Add("type", "started"); if (connection != null) { connection.Publish(json.ToString()); } await client.GetGuild(config.GuildID).GetTextChannel(config.ChannelID).SendMessageAsync("Bridge connected."); }
protected override async Task CoreAsync(CancellationToken cancellationToken) { var guild = _client.GetGuild(728459950468104284); var role = guild.GetRole(766125283244769340); await guild.DownloadUsersAsync(); await using var db = _services.GetRequiredService <LyricaContext>(); var users = await db.Users.AsNoTracking().AsAsyncEnumerable() .Where(u => { if (u.BirthDate is null) { return(false); } var tz = u.Timezone ?? TimeSpan.FromHours(8); var start = new DateTimeOffset(u.BirthDate.Value, tz); var end = start.AddDays(1); var now = DateTimeOffset.Now.ToOffset(tz); return(now > start && now < end); }).ToListAsync(cancellationToken); await db.DisposeAsync(); var guildUsers = users .Select(u => guild.GetUser(u.Id)) .Where(u => u is not null).ToList(); var roleMembers = role.Members?.ToList() ?? new List <SocketGuildUser>(); var birthdayPassed = roleMembers.Except(guildUsers); var celebrants = guildUsers.Except(roleMembers); foreach (var user in birthdayPassed) { await user.RemoveRoleAsync(role); } foreach (var celebrant in celebrants) { await celebrant.AddRoleAsync(role); var greeting = $"It's {celebrant.Mention}'s birthday today! 🎉"; await guild.GetTextChannel(767979232868827137).SendMessageAsync(greeting); await guild.SystemChannel.SendMessageAsync(greeting); } }
internal async Task MessageReceived(SocketMessage socketMessage) { var message = socketMessage as SocketUserMessage; var context = new CommandContext(_discordSocketClient, message); if (context.IsPrivate) { //Console.WriteLine(message.ToString()); ulong guildId; if (Map.TryGetValue(context.User.Id, out guildId)) { var guild = _discordSocketClient.GetGuild(guildId); await guild.DownloadUsersAsync(); var users = guild.Users; foreach (var socketGuildUser in users) { if (socketGuildUser.IsBot) { continue; } try { await socketGuildUser.SendMessageAsync(message.ToString()); } catch (Exception e) { Debug.Log(e); } } Debug.Log($"spam:{message.ToString()}:{users.Count}人"); Map.Remove(context.User.Id); return; } } else { if (message.Channel.Id != EnvManager.CommandChannel) { return; } int argPos = 0; if (!message.HasStringPrefix(CommandString.Prefix, ref argPos)) { return; } var result = _commandService.ExecuteAsync(context, argPos); Debug.Log(result.Result); } }
private async void ReminderTimerAction(object rObj) { var r = (Reminder)rObj; try { IMessageChannel ch; if (r.IsPrivate) { var user = _client.GetUser(r.ChannelId); if (user == null) { return; } ch = await user.GetOrCreateDMChannelAsync().ConfigureAwait(false); } else { ch = _client.GetGuild(r.ServerId)?.GetTextChannel(r.ChannelId); } if (ch == null) { return; } await ch.EmbedAsync(new EmbedBuilder() .WithOkColor() .WithTitle("Reminder") .AddField("Created At", r.DateAdded.HasValue ? r.DateAdded.Value.ToLongDateString() : "?") .AddField("By", (await ch.GetUserAsync(r.UserId).ConfigureAwait(false))?.ToString() ?? r.UserId.ToString()), msg : r.Message.SanitizeMentions()).ConfigureAwait(false); } catch (Exception ex) { _log.Info(ex.Message + $"({r.Id})"); } finally { using (var uow = _db.GetDbContext()) { if (uow._context.Database.IsNpgsql()) { uow._context.Database.ExecuteSqlCommand($"DELETE FROM \"Reminders\" WHERE \"Id\"={r.Id};"); uow.SaveChanges(); } if (uow._context.Database.IsSqlServer()) { uow._context.Database.ExecuteSqlCommand($"DELETE FROM Reminders WHERE Id={r.Id};"); uow.SaveChanges(); } } RemoveReminder(r.Id); } }
public async Task MainAsync() { Console.WriteLine("Starting Foodah Interface Client, once client has loaded input loadchannels"); _client = new DiscordSocketClient(); _service = new CommandService(); _client.Log += Log; // You can assign your bot token to a string, and pass that in to connect. // This is, however, insecure, particularly if you plan to have your code hosted in a public repository. // Some alternative options would be to keep your token in an Environment Variable or a standalone file. // var token = Environment.GetEnvironmentVariable("NameOfYourEnvironmentVariable"); // var token = File.ReadAllText("token.txt"); // var token = JsonConvert.DeserializeObject<AConfigurationClass>(File.ReadAllText("config.json")).Token; var token = ""; if (Environment.GetEnvironmentVariable("FOODAHTOKEN") == null) { Console.WriteLine("Cannot Find Auth Token, Please Input it"); while (true) { try { token = Console.ReadLine(); await _client.LoginAsync(TokenType.Bot, token); await _client.StartAsync(); break; } catch { Console.WriteLine("Incorrect Token"); } } } else { token = Environment.GetEnvironmentVariable("FOODAHTOKEN"); await _client.LoginAsync(TokenType.Bot, token); await _client.StartAsync(); } // Block this task until the program is closed. HandleConsole(); _guild = _client.GetGuild(672344980970536960); _general = _guild.GetTextChannel(672661558895050782); _updates = _guild.GetTextChannel(673063695827337247); }
//private async Task userjoinGiveaway(SocketGuildUser arg) //{ // if (arg.Guild.Id == currgiveaway.giveawayguild.guildID) // { // var role = _client.GetGuild(currgiveaway.giveawayguild.guildID).Roles.FirstOrDefault(r1 => r1.Name == "Admins"); // var role2 = _client.GetGuild(currgiveaway.giveawayguild.guildID).Roles.FirstOrDefault(r2 => r2.Name == "Contestants"); // var r = _client.GetGuild(SwissGuildId).GetUser(arg.Id).Roles; // var adminrolepos = _client.GetGuild(SwissGuildId).Roles.FirstOrDefault(x => x.Id == Global.DeveloperRoleId).Position; // var rolepos = r.FirstOrDefault(x => x.Position >= adminrolepos); // if (rolepos != null) // { // await arg.AddRoleAsync(role); // } // else // { // await arg.AddRoleAsync(role2); // GiveawayUser u = new GiveawayUser() // { // id = arg.Id, // user = arg, // bannedUsers = new List<GiveawayUser>(), // bans = 0, // DiscordName = arg.ToString() // }; // currgiveaway.giveawayguild.giveawayEntryMembers.Add(u); // } // } //} internal async Task UpdateTime(int seconds) { TimeSpan ts = TimeSpan.FromSeconds(seconds); string timefromsec = ""; if (ts.Days != 0) { timefromsec += $"{ts.Days} Days, "; } if (ts.Hours != 0) { timefromsec += $"{ts.Hours} Hours, "; } if (ts.Minutes != 0) { timefromsec += $"{ts.Minutes} Minutes"; } if (ts.Seconds != 0) { if (ts.Minutes != 0) { timefromsec += $", and {ts.Seconds} Seconds"; } else { timefromsec += $"{ts.Seconds} Seconds"; } } await chantimer.ModifyAsync(x => x.Name = $"Time: {timefromsec}"); EmbedBuilder eb = new EmbedBuilder(); eb.Title = "GIVEAWAY"; eb.Color = Color.Blue; eb.Description = $"{_client.GetGuild(SwissGuildId).GetUser(currgiveaway.GiveAwayUser).Mention} Has started a giveaway for **{currgiveaway.GiveAwayItem}** with {currgiveaway.numWinners} winners, to enter the giveaway join {currgiveaway.discordInvite}\n\n **How does it work?** \n after the timer reaches 0 everyone will get access to the \"ban command, its like a FFA. the last person(s) remaining will get the giveaway item \n \n ***GIVEAWAY STARTS IN {timefromsec} ({seconds} seconds)***"; await currgiveaway.giveawaymsg.ModifyAsync(x => x.Embed = eb.Build()); }
public async void CheckUnityBetas(FeedData feedData) { try { HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(BETA_URL); HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse(); Stream dataStream = webResponse.GetResponseStream(); StreamReader streamReader = new StreamReader(dataStream, Encoding.UTF8); string response = streamReader.ReadToEnd(); streamReader.Close(); response = Utils.SanitizeXml(response); XmlReader reader = new XmlTextReader(new StringReader(response)); SyndicationFeed feed = SyndicationFeed.Load(reader); var channel = _client.GetChannel(_settings.UnityNewsChannel.Id) as ISocketMessageChannel; var role = _client.GetGuild(_settings.guildId).GetRole(_settings.SubsReleasesRoleId); foreach (var item in feed.Items.Take(MAXIMUM_CHECK)) { if (!feedData.PostedIds.Contains(item.Id)) { feedData.PostedIds.Add(item.Id); await role.ModifyAsync(properties => { properties.Mentionable = true; }); string message = $"{role.Mention} New unity **beta **release !** {item.Title.Text}** \n <{item.Links[0].Uri.ToString().Replace("/fr/", "/")}>"; await channel.SendMessageAsync(message); await role.ModifyAsync(properties => { properties.Mentionable = false; }); } } } catch (Exception e) { Console.WriteLine(e); } }
public static bool CheckPermission(ulong userId, ulong channelId, ulong guildId, ulong?authenticatedUserId = null) { SocketGuildUser user = client.GetGuild(guildId).GetUser(userId); var moderatorRole = (user as IGuildUser).Guild.Roles.FirstOrDefault(x => x.Id == 567267964529803275); var adminRole = (user as IGuildUser).Guild.Roles.FirstOrDefault(x => x.Id == 568767102706647050); if (user.Roles.Contains(moderatorRole) || user.Roles.Contains(adminRole) || userId == authenticatedUserId) { return(true); } else if (!(user.Roles.Contains(moderatorRole) || user.Roles.Contains(adminRole))) { client.GetGuild(guildId).GetTextChannel(channelId).SendMessageAsync("You don't have permission for this command. Ya Dummy :) "); return(false); } else { client.GetGuild(guildId).GetTextChannel(channelId).SendMessageAsync("Oops what embarrasing: I messed up and now we have an error, try again."); return(false); } }
public static void Main(string[] args) { ApplicationBase = Path.GetDirectoryName(new Uri(Assembly.GetEntryAssembly().CodeBase).LocalPath); if (!File.Exists(Path.Combine(Program.ApplicationBase, "Opux.db"))) { File.Copy(ApplicationBase + "/Opux.def.db", Path.Combine(Program.ApplicationBase, "Opux.db")); } UpdateSettings(); Client = new DiscordSocketClient(new DiscordSocketConfig() { }); Commands = new CommandService(); EveLib = new EveLib(); MainAsync(args).GetAwaiter().GetResult(); while (!quit) { var command = Console.ReadLine(); switch (command.Split(" ")[0]) { case "quit": Console.WriteLine($"Quitting Opux"); quit = true; break; case "debug": if (!debug) { Console.WriteLine($"Debug mode Active"); debug = true; } else { Console.WriteLine($"Debug mode Disabled"); debug = false; } break; case "admin": var guild = Client.GetGuild(Convert.ToUInt64(Settings.GetSection("config")["guildId"])); var rolesToAdd = new List <SocketRole>(); var GuildRoles = guild.Roles; guild.GetUser(Convert.ToUInt64(command.Split(" ")[2])).AddRoleAsync(GuildRoles.FirstOrDefault(x => x.Name == command.Split(" ")[1])); break; } } Client.StopAsync(); }
/* fill config with data from record */ void LoadGuild(GuildsConfig config) { /* get aliases of guild and single config entry */ SocketGuild guild = _client.GetGuild(config.GuildID); IConfigMember con = _config[guild.Id]; /* load prefix from db record */ con.Prefix = config.Prefix; /* find actuall channels from ids in db and load into config */ con.GeneralChannel = guild.GetTextChannel(config.GeneralChannel); con.AnnouncementsChannel = guild.GetTextChannel(config.AnnouncementsChannel); con.BotLogChannel = guild.GetTextChannel(config.BotLogChannel); con.LogChannel = guild.GetTextChannel(config.LogChannel); }
private void InitializeResources() { _tutorialServer = _client.GetGuild(TutorialServerId); _waitingRoomChannel = _tutorialServer.GetTextChannel(WaitingRoomChannelId); _generalChannel = _tutorialServer.GetTextChannel(TutorialGeneralId); _memberRole = _tutorialServer.GetRole(MemberRoleId); _botRole = _tutorialServer.GetRole(BotRoleId); _botDevRole = _tutorialServer.GetRole(BotDevRoleId); }
private async void OnInsultTimer(object source, ElapsedEventArgs e) { var guild = client.GetGuild(Utility.guildid); var channel = (SocketTextChannel)client.GetChannel(Utility.generalchannelid); var users = guild.Users //.Where(x => !x.IsBot && x.Status < UserStatus.Offline && x.Status != UserStatus.Unknown) .Where(x => !x.IsBot) .ToList(); SocketGuildUser insulted_user = users[Utility.numgen.Next(0, users.Count)]; await Utility.RandomMessage(insulted_user, channel); }
//public static bool GrabSlotbot(DiscordSocketClient client, MessageEventArgs args) public static bool GrabSlotbot(DiscordSocketClient client, MessageEventArgs args) { string serverName = client.GetGuild(args.Message.Guild.Id).Name; try { args.Message.Channel.SendMessage("~grab"); return(true); } catch (Exception) { Console.WriteLine("[ERROR] Could not send the message. Server:{0} Date:{1}", serverName, DateTime.Now); //SlotBotData() return(false); } }
private Task UserJoined(SocketGuildUser user) { IRole membersRole = client.GetGuild(303997236482801670).GetRole(305921894513770499); IRole pugsRole = client.GetGuild(303997236482801670).GetRole(306107573277425664); Console.WriteLine(user.Id); //SocketUser newUser = client.GetUser(user.Id).; //client.GetGuild().GetVoiceChannel().Users. //if (newUser..VoiceChannel.Id == client.GetChannel(306107185145053194).Id) //{ Console.WriteLine("PUG!"); user.AddRoleAsync(pugsRole); //} //else //{ Console.WriteLine("MEMBER!"); user.AddRoleAsync(membersRole); //} return(Task.FromResult(true)); }
public async Task PeriodicCheckMute(TimeSpan interval, System.Threading.CancellationToken cancellationToken) { while (true) { Parallel.For(0, Data.Mutes.Mutes.Count, async index => { try { var current = Data.Mutes.Mutes.ElementAt(index); if (DateTime.UtcNow.ToBinary() >= long.Parse(current.Value)) { SocketGuild guild = _client.GetGuild(ulong.Parse(current.Key.Split(',')[1])); SocketGuildUser user = guild.GetUser(ulong.Parse(current.Key.Split(',')[0])); await user.Unmute(); Data.Mutes.Remove(current.Key); } } catch { } }); await Task.Delay(interval, cancellationToken); } }
private async Task MessageReceived(SocketMessage message) { if (message.Channel is IDMChannel) { if (message.Attachments.Count > 0) { foreach (Attachment attachment in message.Attachments.ToList()) { string imageUrl = attachment.Url; var embed = new EmbedBuilder(); embed.WithImageUrl(imageUrl); await client.GetGuild(guildId).GetTextChannel(textChannel).SendMessageAsync(message.Content, false, embed); } } else { await client.GetGuild(guildId).GetTextChannel(textChannel).SendMessageAsync(message.Content); } } }
private async Task ClientOnReady() { var cfg = _services.ThrowOrGet <BotConfig>(); Guild = _client.GetGuild(cfg.GuildId); Debug.Assert(Guild != null); PinChannel = Guild.GetTextChannel(cfg.PinChannelId); Debug.Assert(PinChannel != null); _services.ThrowOrGet <PinDispatcher>().IgnoreChannels.Add(PinChannel.Id); await ParsePins(); }