22 Commits
master ... dev

Author SHA1 Message Date
Karolis2011
e43cd71a7d Read ME update 2019-06-20 11:20:01 +03:00
Karolis2011
b74c666d05 Adds role specific channels. 2019-06-20 11:19:39 +03:00
Karolis2011
8058bffba5 Help part 2 2019-06-20 01:01:49 +03:00
Karolis2011
ed5f4d729e Better help part 1 2019-06-19 23:59:48 +03:00
Karolis
4907fe44f2 Merge pull request #1 from Geevies/spellChecks
Minor Spelling Mistake fixes
2019-06-19 19:20:31 +03:00
Geeves
2f04b31973 Update EventBot/Modules/EventModule.cs 2019-06-19 17:36:38 +02:00
Geeves
0c6733ac77 Update EventBot/Modules/EventModule.cs 2019-06-19 17:36:21 +02:00
Geeves
89139869c2 Update EventBot/Modules/EventModule.cs 2019-06-19 17:36:03 +02:00
Geeves
e1924269aa Update EventBot/Modules/EventModule.cs
Co-Authored-By: Karolis <Karolis2011@users.noreply.github.com>
2019-06-19 17:28:58 +02:00
Geeves
f5c28140c7 Update EventBot/Modules/EventModule.cs
Co-Authored-By: Karolis <Karolis2011@users.noreply.github.com>
2019-06-19 17:28:47 +02:00
Geeves
373f1ec2eb Update EventBot/Modules/EventModule.cs
Co-Authored-By: Karolis <Karolis2011@users.noreply.github.com>
2019-06-19 17:28:11 +02:00
Geeves
96ebf7b07c Update EventBot/Modules/EventModule.cs
Co-Authored-By: Karolis <Karolis2011@users.noreply.github.com>
2019-06-19 17:27:19 +02:00
Geeves
45878f5fcc Update EventBot/Modules/EventModule.cs
Co-Authored-By: Karolis <Karolis2011@users.noreply.github.com>
2019-06-19 17:23:47 +02:00
Geeves
104ea6e7bd Update EventBot/Modules/EventModule.cs
Co-Authored-By: Karolis <Karolis2011@users.noreply.github.com>
2019-06-19 17:14:00 +02:00
Geeves
0447308f40 Update EventBot/Modules/EventModule.cs
Co-Authored-By: Karolis <Karolis2011@users.noreply.github.com>
2019-06-19 17:13:46 +02:00
Geeves
e3d69dd9c5 Update EventBot/Misc/EventRoleTypeReader.cs
Co-Authored-By: Karolis <Karolis2011@users.noreply.github.com>
2019-06-19 17:13:29 +02:00
Geeves
e07853a8dd final commit 2019-06-19 07:12:22 +02:00
Geeves
d478e550ba Merge pull request #1 from Karolis2011/master
Update with master
2019-06-19 07:06:34 +02:00
Geeves
e094766bf4 spellfixes for commands 2019-06-18 23:24:12 +02:00
Karolis2011
9c7d370b5b Travis you can do it. 2019-06-19 00:23:15 +03:00
Karolis2011
a67f6f1666 Addes travis and README 2019-06-19 00:17:44 +03:00
Geeves
8d0093f1d3 spellfixes 2019-06-18 22:43:41 +02:00
19 changed files with 828 additions and 122 deletions

10
.travis.yml Normal file
View File

@@ -0,0 +1,10 @@
language: csharp
mono: none
dist: xenial
dotnet: 2.2
install:
- dotnet restore
script:
- dotnet build

View File

@@ -3,6 +3,7 @@ using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
using System.Text.RegularExpressions;
namespace EventBot.Entities
{
@@ -15,6 +16,8 @@ namespace EventBot.Entities
public string Description { get; set; }
public string Emote { get; set; }
public int MaxParticipants { get; set; }
public ulong ChannelId { get; set; }
public ulong RoleId { get; set; }
public int EventId { get; set; }
[ForeignKey("EventId")]
public virtual Event Event { get; set; }
@@ -22,6 +25,8 @@ namespace EventBot.Entities
public int ParticipantCount => Participants == null ? 0 : Participants.Count;
public int ReamainingOpenings => MaxParticipants < 0 ? 1 : MaxParticipants - ParticipantCount;
public string ChannelName => Regex.Replace(Title.Replace(' ', '-'), "(?!\\w)", "");
public int SortNumber
{
get

View File

@@ -12,6 +12,7 @@ namespace EventBot.Entities
public string Prefix { get; set; }
public ulong EventRoleConfirmationChannelId { get; set; }
public ulong ParticipantRoleId { get; set; }
public ulong AutoRoleChannelCategoryId { get; set; }
public virtual ICollection<Event> Events { get; set; }
}

View File

@@ -0,0 +1,147 @@
// <auto-generated />
using System;
using EventBot.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace EventBot.Migrations.MySql
{
[DbContext(typeof(MySqlDatabaseService))]
[Migration("20190620075923_AutoRolesAndChannels")]
partial class AutoRolesAndChannels
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.2.4-servicing-10062")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("EventBot.Entities.Event", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<bool>("Active");
b.Property<string>("Description");
b.Property<ulong>("GuildId");
b.Property<ulong>("MessageChannelId");
b.Property<ulong>("MessageId");
b.Property<DateTime>("Opened");
b.Property<string>("Title");
b.Property<int>("Type");
b.HasKey("Id");
b.HasIndex("GuildId");
b.ToTable("Events");
});
modelBuilder.Entity("EventBot.Entities.EventParticipant", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("EventId");
b.Property<int>("EventRoleId");
b.Property<string>("UserData");
b.Property<ulong>("UserId");
b.HasKey("Id");
b.HasIndex("EventId");
b.HasIndex("EventRoleId");
b.ToTable("EventParticipants");
});
modelBuilder.Entity("EventBot.Entities.EventRole", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("ChannelId");
b.Property<string>("Description");
b.Property<string>("Emote");
b.Property<int>("EventId");
b.Property<int>("MaxParticipants");
b.Property<ulong>("RoleId");
b.Property<string>("Title");
b.HasKey("Id");
b.HasIndex("EventId");
b.ToTable("EventRoles");
});
modelBuilder.Entity("EventBot.Entities.GuildConfig", b =>
{
b.Property<ulong>("GuildId")
.ValueGeneratedOnAdd();
b.Property<ulong>("AutoRoleChannelCategoryId");
b.Property<ulong>("EventRoleConfirmationChannelId");
b.Property<ulong>("ParticipantRoleId");
b.Property<string>("Prefix");
b.HasKey("GuildId");
b.ToTable("GuildConfigs");
});
modelBuilder.Entity("EventBot.Entities.Event", b =>
{
b.HasOne("EventBot.Entities.GuildConfig", "Guild")
.WithMany("Events")
.HasForeignKey("GuildId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("EventBot.Entities.EventParticipant", b =>
{
b.HasOne("EventBot.Entities.Event", "Event")
.WithMany("Participants")
.HasForeignKey("EventId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("EventBot.Entities.EventRole", "Role")
.WithMany("Participants")
.HasForeignKey("EventRoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("EventBot.Entities.EventRole", b =>
{
b.HasOne("EventBot.Entities.Event", "Event")
.WithMany("Roles")
.HasForeignKey("EventId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,43 @@
using Microsoft.EntityFrameworkCore.Migrations;
namespace EventBot.Migrations.MySql
{
public partial class AutoRolesAndChannels : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<ulong>(
name: "AutoRoleChannelCategoryId",
table: "GuildConfigs",
nullable: false,
defaultValue: 0ul);
migrationBuilder.AddColumn<ulong>(
name: "ChannelId",
table: "EventRoles",
nullable: false,
defaultValue: 0ul);
migrationBuilder.AddColumn<ulong>(
name: "RoleId",
table: "EventRoles",
nullable: false,
defaultValue: 0ul);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "AutoRoleChannelCategoryId",
table: "GuildConfigs");
migrationBuilder.DropColumn(
name: "ChannelId",
table: "EventRoles");
migrationBuilder.DropColumn(
name: "RoleId",
table: "EventRoles");
}
}
}

View File

@@ -72,6 +72,8 @@ namespace EventBot.Migrations.MySql
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("ChannelId");
b.Property<string>("Description");
b.Property<string>("Emote");
@@ -80,6 +82,8 @@ namespace EventBot.Migrations.MySql
b.Property<int>("MaxParticipants");
b.Property<ulong>("RoleId");
b.Property<string>("Title");
b.HasKey("Id");
@@ -94,6 +98,8 @@ namespace EventBot.Migrations.MySql
b.Property<ulong>("GuildId")
.ValueGeneratedOnAdd();
b.Property<ulong>("AutoRoleChannelCategoryId");
b.Property<ulong>("EventRoleConfirmationChannelId");
b.Property<ulong>("ParticipantRoleId");

View File

@@ -0,0 +1,146 @@
// <auto-generated />
using System;
using EventBot.Services;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace EventBot.Migrations.Sqlite
{
[DbContext(typeof(SqliteDatabaseService))]
[Migration("20190620080021_AutoRolesAndChannels")]
partial class AutoRolesAndChannels
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "2.2.4-servicing-10062");
modelBuilder.Entity("EventBot.Entities.Event", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<bool>("Active");
b.Property<string>("Description");
b.Property<ulong>("GuildId");
b.Property<ulong>("MessageChannelId");
b.Property<ulong>("MessageId");
b.Property<DateTime>("Opened");
b.Property<string>("Title");
b.Property<int>("Type");
b.HasKey("Id");
b.HasIndex("GuildId");
b.ToTable("Events");
});
modelBuilder.Entity("EventBot.Entities.EventParticipant", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<int>("EventId");
b.Property<int>("EventRoleId");
b.Property<string>("UserData");
b.Property<ulong>("UserId");
b.HasKey("Id");
b.HasIndex("EventId");
b.HasIndex("EventRoleId");
b.ToTable("EventParticipants");
});
modelBuilder.Entity("EventBot.Entities.EventRole", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("ChannelId");
b.Property<string>("Description");
b.Property<string>("Emote");
b.Property<int>("EventId");
b.Property<int>("MaxParticipants");
b.Property<ulong>("RoleId");
b.Property<string>("Title");
b.HasKey("Id");
b.HasIndex("EventId");
b.ToTable("EventRoles");
});
modelBuilder.Entity("EventBot.Entities.GuildConfig", b =>
{
b.Property<ulong>("GuildId")
.ValueGeneratedOnAdd();
b.Property<ulong>("AutoRoleChannelCategoryId");
b.Property<ulong>("EventRoleConfirmationChannelId");
b.Property<ulong>("ParticipantRoleId");
b.Property<string>("Prefix");
b.HasKey("GuildId");
b.ToTable("GuildConfigs");
});
modelBuilder.Entity("EventBot.Entities.Event", b =>
{
b.HasOne("EventBot.Entities.GuildConfig", "Guild")
.WithMany("Events")
.HasForeignKey("GuildId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("EventBot.Entities.EventParticipant", b =>
{
b.HasOne("EventBot.Entities.Event", "Event")
.WithMany("Participants")
.HasForeignKey("EventId")
.OnDelete(DeleteBehavior.Cascade);
b.HasOne("EventBot.Entities.EventRole", "Role")
.WithMany("Participants")
.HasForeignKey("EventRoleId")
.OnDelete(DeleteBehavior.Cascade);
});
modelBuilder.Entity("EventBot.Entities.EventRole", b =>
{
b.HasOne("EventBot.Entities.Event", "Event")
.WithMany("Roles")
.HasForeignKey("EventId")
.OnDelete(DeleteBehavior.Cascade);
});
#pragma warning restore 612, 618
}
}
}

View File

@@ -0,0 +1,43 @@
using Microsoft.EntityFrameworkCore.Migrations;
namespace EventBot.Migrations.Sqlite
{
public partial class AutoRolesAndChannels : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<ulong>(
name: "AutoRoleChannelCategoryId",
table: "GuildConfigs",
nullable: false,
defaultValue: 0ul);
migrationBuilder.AddColumn<ulong>(
name: "ChannelId",
table: "EventRoles",
nullable: false,
defaultValue: 0ul);
migrationBuilder.AddColumn<ulong>(
name: "RoleId",
table: "EventRoles",
nullable: false,
defaultValue: 0ul);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "AutoRoleChannelCategoryId",
table: "GuildConfigs");
migrationBuilder.DropColumn(
name: "ChannelId",
table: "EventRoles");
migrationBuilder.DropColumn(
name: "RoleId",
table: "EventRoles");
}
}
}

View File

@@ -71,6 +71,8 @@ namespace EventBot.Migrations.Sqlite
b.Property<int>("Id")
.ValueGeneratedOnAdd();
b.Property<ulong>("ChannelId");
b.Property<string>("Description");
b.Property<string>("Emote");
@@ -79,6 +81,8 @@ namespace EventBot.Migrations.Sqlite
b.Property<int>("MaxParticipants");
b.Property<ulong>("RoleId");
b.Property<string>("Title");
b.HasKey("Id");
@@ -93,6 +97,8 @@ namespace EventBot.Migrations.Sqlite
b.Property<ulong>("GuildId")
.ValueGeneratedOnAdd();
b.Property<ulong>("AutoRoleChannelCategoryId");
b.Property<ulong>("EventRoleConfirmationChannelId");
b.Property<ulong>("ParticipantRoleId");

View File

@@ -15,16 +15,16 @@ namespace EventBot.Misc
{
var database = services.GetRequiredService<DatabaseService>();
if (context.Guild == null)
return Task.FromResult(TypeReaderResult.FromError(CommandError.UnmetPrecondition, "Event roles are avaivable only inside guild context."));
return Task.FromResult(TypeReaderResult.FromError(CommandError.UnmetPrecondition, "Event roles are available only inside a discord server."));
EventRole er = null;
if (int.TryParse(input, out int id))
er = database.EventRoles.FirstOrDefault(r => r.Id == id);
else
return Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "Event role id is not a valid number."));
return Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "Event role ID is not a valid number."));
if(er == null)
return Task.FromResult(TypeReaderResult.FromError(CommandError.ObjectNotFound, "Specified event role was not found."));
if(er.Event?.GuildId != context.Guild.Id)
return Task.FromResult(TypeReaderResult.FromError(CommandError.Exception, "Cross guild event role access is denied."));
return Task.FromResult(TypeReaderResult.FromError(CommandError.Exception, "Cross server event role access is denied."));
return Task.FromResult(TypeReaderResult.FromSuccess(er));
}
}

View File

@@ -15,14 +15,14 @@ namespace EventBot.Misc
{
var events = services.GetRequiredService<EventManagementService>();
if (context.Guild == null)
return Task.FromResult(TypeReaderResult.FromError(CommandError.UnmetPrecondition, "Events are avaivable only inside guild context."));
return Task.FromResult(TypeReaderResult.FromError(CommandError.UnmetPrecondition, "Events are available only inside a discord server."));
Event ev;
if (input == null)
ev = events.FindEventBy(context.Guild, true);
else if (int.TryParse(input, out int id))
ev = events.FindEventBy(context.Guild, id, true);
else
return Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "Event id is not a number."));
return Task.FromResult(TypeReaderResult.FromError(CommandError.ParseFailed, "Event ID is not a number."));
return Task.FromResult(TypeReaderResult.FromSuccess(ev));
}

View File

@@ -0,0 +1,47 @@
using Discord;
using Discord.Commands;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace EventBot.Misc
{
public static class Extensions
{
public static ContextType GetContextType(this ICommandContext context)
{
ContextType type = 0;
if (context.Channel is IGuildChannel)
type |= ContextType.Guild;
if (context.Channel is IDMChannel)
type |= ContextType.DM;
if (context.Channel is IGroupChannel)
type |= ContextType.Group;
return type;
}
public static bool IsContextType(this ICommandContext context, ContextType type) => (context.GetContextType() & type) != 0;
public static string FormatCallHelpString(this CommandInfo command)
{
return $"{command.Aliases[0]} {string.Join(" ", command.Parameters.Select(p => p.FormatParameter()))}";
}
public static string FormatParameter(this ParameterInfo p) => p.IsOptional ? $"[{p.Name}]" : $"<{p.Name}>";
public static string FormatParameterType(this ParameterInfo p)
{
var @switch = new Dictionary<Type, Func<ParameterInfo, string>>()
{
{ typeof(int), (_) => "Number" },
};
if (@switch.ContainsKey(p.Type))
return @switch[p.Type](p);
else
return p.Type.Name;
}
}
}

View File

@@ -7,6 +7,8 @@ using System.Threading.Tasks;
using System.Linq;
using EventBot.Attributes;
using EventBot.Services;
using Discord.Addons.Interactive;
using EventBot.Misc;
namespace EventBot.Modules
{
@@ -22,6 +24,7 @@ namespace EventBot.Modules
[RequireOwner(Group = "Permission")]
[RequireContext(ContextType.Guild)]
[Command("prefix")]
[Name("Configure prefix")]
[Summary("Gets prefix.")]
public async Task PrefixCommand()
{
@@ -38,6 +41,7 @@ namespace EventBot.Modules
[RequireOwner(Group = "Permission")]
[RequireContext(ContextType.Guild)]
[Command("prefix")]
[Name("Configure prefix")]
[Summary("Sets prefix.")]
public async Task PrefixCommand(
[Summary("New prefix to set")] string newPrefix)
@@ -50,8 +54,9 @@ namespace EventBot.Modules
await ReplyAsync($"Prefix has been set to `{guildConfig.Prefix}`");
}
[Group("help")]
public class HelpModule : ModuleBase<SocketCommandContext>
public class HelpModule : InteractiveBase<SocketCommandContext>
{
private readonly CommandService _commands;
@@ -61,23 +66,88 @@ namespace EventBot.Modules
}
[Command]
[Name("Help")]
[Summary("Lists all commands with there descriptions.")]
public async Task DefaultHelpAsync()
{
var embed = new EmbedBuilder()
.WithTitle("Command list")
.WithColor(Color.DarkBlue)
.WithCurrentTimestamp()
.WithFields(_commands.Commands
.Where(c => c.Attributes.Where(a => a is NoHelpAttribute || (a is RequireContextAttribute requireContext)).Count() == 0)
.Select(c =>
new EmbedFieldBuilder()
var pagedCommands = _commands.Commands
.OrderBy(c => c.Aliases[0])
.Where(c => c.Attributes
.Select(a =>
{
Name = $"`{string.Join(", ", c.Aliases)} {string.Join(" ", c.Parameters.Select(p => p.IsOptional ? $"[{p.Name}]" : $"<{p.Name}>"))}`",
Value = c.Summary
switch (a)
{
case NoHelpAttribute _:
return false;
case RequireContextAttribute rc:
return Context.IsContextType(rc.Contexts);
default:
return true;
}
})
.Aggregate(true, (a, r) => a && r))
.SelectMany(c => c.Aliases.Select(a => new { CI = c, MA = (c.Aliases[0] == a), A = a }).Reverse())
.Select((e, i) => new { Command = e, Index = i })
.GroupBy(o => o.Index / 30)
.Select(g => g.Select(o => o.Command));
var pager = new PaginatedMessage()
{
Title = "Command list",
Color = Color.DarkBlue,
Pages = pagedCommands.Select(p => string.Join("\r\n", p.Select(c =>
{
if (c.MA)
return $"`{c.CI.FormatCallHelpString()}` - **{c.CI.Name}**";
else
return $"`{c.A}` `↪`";
}))),
Options = new PaginatedAppearanceOptions()
{
Info = null,
JumpDisplayOptions = JumpDisplayOptions.Never
}
};
await PagedReplyAsync(pager);
}
[Command]
[Name("Help")]
[Summary("Shows detailed info about command.")]
public async Task DefaultHelpAsync([Summary("Command ")][Remainder] string commandAlias)
{
var command = _commands.Commands.Where(c => c.Aliases.Contains(commandAlias)).FirstOrDefault();
if (command == null)
throw new Exception("This command was not found.");
var embed = new EmbedBuilder()
.WithTitle(command.Name)
.WithDescription(command.Summary)
.WithColor(Color.DarkTeal);
embed.AddField("Module", command.Module.Name, true);
if (command.Aliases.Count > 1)
embed.AddField("Aliases", string.Join(", ", command.Aliases));
if(command.Parameters.Count > 0)
embed.AddField("Parameters",
string.Join("\r\n", command.Parameters.Select(p => $"`{p.FormatParameter()}` *(Type: {p.FormatParameterType()})* - **{p.Summary}** {(p.IsRemainder ? "_No quotes are needed, when providing this parameter._" : "")}" ))
);
await Context.User.SendMessageAsync(embed: embed.Build());
await ReplyAsync($"I got this information about command `{commandAlias}`:", embed: embed.Build());
}
[Command("types")]
[Name("Type help")]
[Priority(1)]
[Summary("Shows information about avaivable types for command paramters.")]
[NoHelp]
public async Task TypeHelp()
{
await ReplyAsync($"There are following avaivable types for command input: \r\n" +
$"***String*** - The most basic text input, must be qouted if there is space inside. Ex: `\"This is a string\"`; `ThisCanBeUsedAlsoAsString`\r\n" +
$"***Number*** - Just a simple number. Ex: `1`; `-2`; `1523`\r\n" +
$"***User*** - Mention or ID of user. Ex: `360710685186850826`; `Skull132#1984`; {Context.Client.CurrentUser.Mention}\r\n" +
$"***Event*** - ID of event. Just positive numbers 🙂.\r\n" +
$"***EventRole*** - ID of event's role. Also positive numbers 😊.\r\n" +
$"***EventParticipactionType*** - What type you want. Ex: `Quick`; `Detailed`");
}
}
}

View File

@@ -13,6 +13,7 @@ using Discord.Addons.Interactive;
namespace EventBot.Modules
{
[RequireContext(ContextType.Guild)]
[Name("Event")]
public class EventModule : ModuleBase<SocketCommandContext>
{
private readonly EventManagementService _events;
@@ -24,27 +25,29 @@ namespace EventBot.Modules
}
[Command("join")]
[Alias("j")]
[Name("Join event")]
[Summary("Joins latest or specified event with specified event role.")]
public async Task JoinAsync(
[Summary("Role emote or role id to join.")] string emoteOrId,
[Summary("Extra information that migth be needed by organizers.")] string extraInformation = null,
[Summary("Optional event ID for joining event that is not most recent one.")] Event @event = null)
public async Task JoinEvent(
[Summary("Role emote or role ID to join the most recent event.")] string emoteOrId,
[Summary("Extra information that might be needed by organizers.")] string extraInformation = null,
[Summary("Optional event ID, used to join an event that started before the most recent one.")] Event @event = null)
{
EventRole er;
if (!(Context.User is SocketGuildUser guildUser))
throw new Exception("This command must be executed inside guild.");
throw new Exception("This command must be executed inside a discord server.");
if (@event == null)
@event = _events.FindEventBy(Context.Guild);
if (@event == null & !(int.TryParse(emoteOrId, out int roleId)))
throw new Exception("Unable to locate any events for this guild.");
throw new Exception("Unable to locate any events for this discord server.");
else if (@event == null)
er = _database.EventRoles.FirstOrDefault(r => r.Id == roleId);
else
er = @event.Roles.FirstOrDefault(r => r.Emote == emoteOrId);
if (er == null)
throw new ArgumentException("Invalid emote or event id specified");
throw new ArgumentException("Invalid emote or event ID specified.");
if (@event.MessageId == 0)
throw new Exception("You can't join not opened event.");
throw new Exception("You cannot join an event that hasn't been opened!");
await _events.TryJoinEvent(guildUser, er, extraInformation);
await Context.Message.DeleteAsync(); // Protect somewhat sensitive data.
@@ -53,6 +56,8 @@ namespace EventBot.Modules
[RequireUserPermission(GuildPermission.Administrator, Group = "Permission")]
[RequireOwner(Group = "Permission")]
[Group("event")]
//[Alias("e")]
[Name("Event management")]
public class EventManagementModule : InteractiveBase<SocketCommandContext>
{
private readonly EventManagementService _events;
@@ -63,14 +68,16 @@ namespace EventBot.Modules
_database = database;
}
[Priority(2)]
[Command("config logchannel")]
[Name("Configure logging channel")]
[Summary("Sets logging channel for role changes.")]
public async Task SetRoleChannelAsync(
public async Task ConfigureEventLogChannel(
[Summary("Channel to use for logging.")] IChannel channel)
{
var guild = _database.GuildConfigs.FirstOrDefault(g => g.GuildId == Context.Guild.Id);
if (guild == null)
throw new Exception("This command must be executed inside guild.");
throw new Exception("This command must be executed inside a discord server.");
guild.EventRoleConfirmationChannelId = channel.Id;
var s = _database.SaveChangesAsync();
@@ -78,14 +85,16 @@ namespace EventBot.Modules
await s;
}
[Priority(2)]
[Command("config partrole")]
[Summary("Sets role to assign when they selelct role.")]
public async Task SetParticipationRole(
[Name("Configure participant role")]
[Summary("Sets discord role to assign when the user selects a role.")]
public async Task ConfigureEventParticipantRole(
[Summary("Role to assign.")] IRole role)
{
var guild = _database.GuildConfigs.FirstOrDefault(g => g.GuildId == Context.Guild.Id);
if (guild == null)
throw new Exception("This command must be executed inside guild.");
throw new Exception("This command must be executed inside a discord server.");
guild.ParticipantRoleId = role.Id;
var s = _database.SaveChangesAsync();
@@ -93,16 +102,41 @@ namespace EventBot.Modules
await s;
}
[Priority(2)]
[Command("config category")]
[Name("Configure auto channel category")]
[Summary("Configures auto channel category, where new channels will be created for each role.")]
public async Task ConfigureParticipantCategory(
[Summary("Category to use when making channels for roles.")] ICategoryChannel category = null)
{
var guild = _database.GuildConfigs.FirstOrDefault(g => g.GuildId == Context.Guild.Id);
if (guild == null)
throw new Exception("This command must be executed inside a discord server.");
if (category == null)
{
guild.AutoRoleChannelCategoryId = 0;
await ReplyAsync("No channels and discord roles will be created for event roles.");
} else
{
guild.AutoRoleChannelCategoryId = category.Id;
await ReplyAsync($"Bot will create discord roles and channels for each new role inside `{category.Name}` category.");
}
await _database.SaveChangesAsync();
}
[Priority(1)]
[Command("new")]
[Summary("Creates new event.")]
public async Task NewEvent(
[Alias("add", "create")]
[Name("Create event")]
[Summary("Creates a new event.")]
public async Task CreateEvent(
[Summary("Title for the event.")] string title,
[Summary("Description for the event.")] string description,
[Summary("Type of event registration.")] Event.EventParticipactionType type = Event.EventParticipactionType.Quick)
{
var guild = _database.GuildConfigs.FirstOrDefault(g => g.GuildId == Context.Guild.Id);
if (guild == null)
throw new Exception("This command must be executed inside guild.");
throw new Exception("This command must be executed inside a discord server.");
var @event = new Event()
{
Title = title,
@@ -113,11 +147,13 @@ namespace EventBot.Modules
_database.Add(@event);
await _database.SaveChangesAsync();
await ReplyAsync($"Created new {@event.Type} event `{title}`, with description of `{description}`. It's ID is `{@event.Id}`.");
await ReplyAsync($"Created new {@event.Type} event `{title}`, with description: `{description}`. Its ID is `{@event.Id}`.");
}
[Priority(2)]
[Command("update title")]
[Summary("Updates event title.")]
[Name("Update event's title")]
[Summary("Updates the event's title.")]
public async Task UpdateEventTitle(
[Summary("Title for the event.")] string title,
[Summary("Event to update, if not specified, updates latest event.")] Event @event = null)
@@ -125,16 +161,19 @@ namespace EventBot.Modules
if (@event == null)
@event = _events.FindEventBy(Context.Guild);
if (@event == null)
throw new Exception("Unable to locate any events for this guild.");
throw new Exception("Unable to locate any events for this discord server.");
if (!@event.Active)
throw new Exception("This event is finalized. Please make a new event.");
@event.Title = title;
await _database.SaveChangesAsync();
await ReplyAsync($"Updated event(`{@event.Id}`) title to `{@event.Title}`");
await ReplyAsync($"Updated event's (`{@event.Id}`) title to `{@event.Title}`");
await _events.UpdateEventMessage(@event);
}
[Priority(2)]
[Command("update description")]
[Summary("Updates event description.")]
[Alias("update desc")]
[Name("Update event's description")]
[Summary("Updates the event's description.")]
public async Task UpdateEventDescription(
[Summary("Description for the event.")] string description,
[Summary("Event to update, if not specified, updates latest event.")] Event @event = null)
@@ -142,17 +181,19 @@ namespace EventBot.Modules
if (@event == null)
@event = _events.FindEventBy(Context.Guild);
if (@event == null)
throw new Exception("Unable to locate any events for this guild.");
throw new Exception("Unable to locate any events for this discord server.");
if (!@event.Active)
throw new Exception("This event is finalized. Please make a new event.");
@event.Description = description;
await _database.SaveChangesAsync();
await ReplyAsync($"Updated event(`{@event.Id}`) description to `{@event.Description}`");
await ReplyAsync($"Updated event's (`{@event.Id}`) description to `{@event.Description}`");
await _events.UpdateEventMessage(@event);
}
[Priority(2)]
[Command("update type")]
[Summary("Updates event type.")]
[Name("Update event's type")]
[Summary("Updates the event type.")]
public async Task UpdateEventType(
[Summary("Type of event registration.")] Event.EventParticipactionType type,
[Summary("Event to update, if not specified, updates latest event.")] Event @event = null)
@@ -162,11 +203,11 @@ namespace EventBot.Modules
if (@event == null)
@event = _events.FindEventBy(Context.Guild);
if (@event == null)
throw new Exception("Unable to locate any events for this guild.");
throw new Exception("Unable to locate any events for this discord server.");
if (!@event.Active)
throw new Exception("This event is finalized. Please make a new event.");
if (@event.MessageId != 0 && @event.Type != type)
throw new Exception("Can't change event registration type when it's open for registration. Maube you meant to set type to `Unspecified` (-1)");
throw new Exception("Can't change event registration type when it's open for registration. Maybe you meant to set type to `Unspecified` (-1)");
if(@event.Type != type)
@event.Type = type;
await _database.SaveChangesAsync();
@@ -174,25 +215,28 @@ namespace EventBot.Modules
}
[Priority(2)]
[Command("role new")]
[Summary("Adds new role to the event.")]
[Alias("role add", "role create")]
[Name("Add role")]
[Summary("Adds a new role to the event.")]
public async Task NewEventRole(
[Summary("Title for the role.")] string title,
[Summary("Description for the role.")] string description,
[Summary("Title of the role.")] string title,
[Summary("Description of the role.")] string description,
[Summary("Emote for the role.")] string emote,
[Summary("Max openings, if number is negative, opening count is unlimited.")] int maxOpenings = -1,
[Summary("Event to that role is meant for.")] Event @event = null)
[Summary("Which event to assign the role to.")] Event @event = null)
{
if (@event == null)
@event = _events.FindEventBy(Context.Guild);
if (@event == null)
throw new Exception("Unable to locate any events for this guild.");
throw new Exception("Unable to locate any events for this discord server.");
if (!@event.Active)
throw new Exception("This event is finalized. Please make a new event.");
if (@event.Roles != null && @event.Roles.Count >= 20)
throw new Exception("There are too many roles for this event.");
if(@event.MessageId != 0)
throw new Exception("Can't add new roles to event with open reigstration.");
throw new Exception("Can't add new roles to event with open registration.");
if (!EmoteHelper.TryParse(emote, out IEmote parsedEmote))
throw new ArgumentException("Invalid emote provided.");
if(@event.Roles != null && @event.Roles.Count(r => r.Emote == parsedEmote.ToString()) > 0)
@@ -205,73 +249,91 @@ namespace EventBot.Modules
Emote = parsedEmote.ToString(),
Event = @event
};
_database.Add(er);
await _database.SaveChangesAsync();
await ReplyAsync($"Added event role `{er.Id}` for event `{er.Event.Id}`, title: `{er.Title}`, description: `{er.Description}`, maxPart: `{er.MaxParticipants}`, emote: {er.Emote}");
if(@event.Guild.AutoRoleChannelCategoryId != 0)
{
var channel = await Context.Guild.CreateTextChannelAsync(er.ChannelName, o => o.CategoryId = @event.Guild.AutoRoleChannelCategoryId);
var role = await Context.Guild.CreateRoleAsync(er.Title);
await channel.AddPermissionOverwriteAsync(role, new OverwritePermissions(viewChannel: PermValue.Allow, sendMessages: PermValue.Allow));
er.RoleId = role.Id;
er.ChannelId = channel.Id;
}
_database.Add(er);
await _database.SaveChangesAsync();
await ReplyAsync($"Added event role `{er.Id}` for event `{er.Event.Id}`, title: `{er.Title}`, description: `{er.Description}`, slots: `{er.MaxParticipants}`, emote: {er.Emote}");
}
[Priority(2)]
[Command("role update title")]
[Summary("Updates role's title")]
[Name("Update role's title")]
[Summary("Updates the role's title.")]
public async Task UpdateEventRoleTitle(
[Summary("Role witch to update.")] EventRole eventRole,
[Summary("New title for role.")][Remainder] string title)
[Summary("Which role to update.")] EventRole eventRole,
[Summary("The new title for the role.")][Remainder] string title)
{
if(eventRole == null)
throw new Exception("Please provide correct role.");
throw new Exception("Please provide the correct role info, this one does not exist.");
if (!eventRole.Event.Active)
throw new Exception("This event is finalized. Please make a new event.");
eventRole.Title = title;
var s = _database.SaveChangesAsync();
await ReplyAsync($"Updated event role `{eventRole.Id}` title to `{eventRole.Title}`");
await ReplyAsync($"Updated event role `{eventRole.Id}`'s title to `{eventRole.Title}`");
await s;
await _events.UpdateEventMessage(eventRole.Event);
}
[Command("role update desc")]
[Summary("Updates role's description.")]
[Priority(2)]
[Command("role update description")]
[Alias("role update desc")]
[Name("Update role's description")]
[Summary("Updates the role's description.")]
public async Task UpdateEventRoleDescription(
[Summary("Role witch to update.")] EventRole eventRole,
[Summary("New description for role.")][Remainder] string description)
[Summary("Which role to update.")] EventRole eventRole,
[Summary("New description for the role.")][Remainder] string description)
{
if (eventRole == null)
throw new Exception("Please provide correct role.");
throw new Exception("Please provide the correct role ID, this one does not exist.");
if (!eventRole.Event.Active)
throw new Exception("This event is finalized. Please make a new event.");
eventRole.Description = description;
var s = _database.SaveChangesAsync();
await ReplyAsync($"Updated event role `{eventRole.Id}` description to `{eventRole.Description}`");
await ReplyAsync($"Updated event role's `{eventRole.Id}` description to `{eventRole.Description}`");
await s;
await _events.UpdateEventMessage(eventRole.Event);
}
[Priority(2)]
[Command("role update slots")]
[Summary("Updates role's maximum participants count.")]
[Name("Update role's slots")]
[Summary("Updates a role's maximum participants count.")]
public async Task UpdateEventRoleMaxParticipants(
[Summary("Role witch to update.")] EventRole eventRole,
[Summary("Which role to update.")] EventRole eventRole,
[Summary("New maximum participant count for role.")] int maxParticipants)
{
if (eventRole == null)
throw new Exception("Please provide correct role.");
throw new Exception("Please provide the correct role info, this one does not exist.");
if (!eventRole.Event.Active)
throw new Exception("This event is finalized. Please make a new event.");
eventRole.MaxParticipants = maxParticipants;
var s = _database.SaveChangesAsync();
await ReplyAsync($"Updated event role `{eventRole.Id}` maximum participant count to `{eventRole.MaxParticipants}`");
await ReplyAsync($"Updated event role `{eventRole.Id}`'s maximum participant count to `{eventRole.MaxParticipants}`");
await s;
await _events.UpdateEventMessage(eventRole.Event);
}
[Priority(2)]
[Command("role update emote")]
[Summary("Updates role's emote.")]
[Name("Update role's role")]
[Summary("Updates a role's emote.")]
public async Task UpdateEventRoleEmote(
[Summary("Role witch to update.")] EventRole eventRole,
[Summary("Which role to update.")] EventRole eventRole,
[Summary("New emote for the role.")] string emote)
{
if (eventRole == null)
throw new Exception("Please provide correct role.");
throw new Exception("Please provide the correct role info, this one does not exist.");
if (eventRole.Event.MessageId != 0)
throw new Exception("Role emote can't be edited while event is open for registrasion.");
throw new Exception("A role's emote cannot be edited while the event is open for registration.");
if (!eventRole.Event.Active)
throw new Exception("This event is finalized. Please make a new event.");
if (!EmoteHelper.TryParse(emote, out IEmote parsedEmote))
@@ -286,19 +348,21 @@ namespace EventBot.Modules
}
[Command()]
[Alias("info")]
[Name("Event info")]
[Summary("Get info about event.")]
public async Task EventInfo(
[Summary("Event about witch info is wanted.")] Event @event = null)
[Summary("Event ID of event you wish to know more of.")] Event @event = null)
{
if (@event == null)
@event = _events.FindEventBy(Context.Guild);
if (@event == null)
throw new Exception("No events were found for this guild.");
throw new Exception("No events were found for this discord server.");
var embed = new EmbedBuilder()
.WithTitle(@event.Title)
.WithDescription(@event.Description)
.WithTimestamp(@event.Opened)
.WithFooter($"EventId: {@event.Id}; MessageId: {@event.MessageId}; MessageChannelId: {@event.MessageChannelId}")
.WithFooter($"EventId: {@event.Id}; MessageID: {@event.MessageId}; MessageChannelID: {@event.MessageChannelId}")
.AddField("Active", @event.Active ? "Yes" : "No", true)
.AddField("Type", @event.Type, true)
.AddField("Participants", @event.ParticipantCount, true);
@@ -314,14 +378,43 @@ namespace EventBot.Modules
await ReplyAsync(embed: embed.Build());
}
[Priority(2)]
[Command("role delete")]
[Alias("role remove")]
[Name("Delete role")]
[Summary("Deletes role and all information about it.")]
public async Task EventRoleDelete(
[Summary("Role you wish to delete.")] EventRole eventRole)
{
if (!(Context.User is SocketGuildUser guildUser))
throw new Exception("This command must be executed inside a discord server.");
if (eventRole == null)
throw new Exception("Please provide the correct role, this one does not exist.");
if (eventRole.Event.MessageId != 0)
throw new Exception("Can't remove role from open event.");
foreach (var p in eventRole.Participants)
await _events.RemoveParticipant(p, guildUser);
if(eventRole.ChannelId != 0)
await Context.Guild.GetTextChannel(eventRole.ChannelId)?.DeleteAsync();
if (eventRole.RoleId != 0)
await Context.Guild.GetRole(eventRole.RoleId)?.DeleteAsync();
_database.Remove(eventRole);
await _database.SaveChangesAsync();
await ReplyAsync($"Role {eventRole.Title} has been deleted, and it's participants removed.");
}
[Priority(1)]
[Command("role")]
[Summary("Gets role info.")]
[Alias("role info")]
[Name("Role info")]
[Summary("Gets info about a role.")]
public async Task EventRoleInfo(
[Summary("Role about witch info is wanted.")] EventRole eventRole)
[Summary("Role you wish to have more info about.")] EventRole eventRole)
{
if (eventRole == null)
throw new Exception("Please provide correct role.");
throw new Exception("Please provide the correct role info, this one does not exist.");
var embed = new EmbedBuilder()
.WithTitle($"{eventRole.Emote} {eventRole.Title}")
.WithDescription($"{eventRole.Description}")
@@ -338,7 +431,10 @@ namespace EventBot.Modules
}
}
[Priority(1)]
[Command("open")]
[Alias("start", "begin")]
[Name("Open event")]
[Summary("Open registration for event here.")]
public async Task EventOpen(
[Summary("Event to open")] Event @event = null)
@@ -346,7 +442,7 @@ namespace EventBot.Modules
if (@event == null)
@event = _events.FindEventBy(Context.Guild);
if (@event == null)
throw new Exception("No events were found for this guild.");
throw new Exception("No events were found for this discord server.");
if (!@event.Active)
throw new Exception("This event is finalized. Please make a new event.");
@@ -370,7 +466,11 @@ namespace EventBot.Modules
}
}
[Priority(1)]
[Command("close")]
[Alias("stop", "end")]
[Name("Close event")]
[Summary("Closes event registration.")]
public async Task EventClose(
[Summary("Event to close")] Event @event = null)
@@ -378,7 +478,7 @@ namespace EventBot.Modules
if (@event == null)
@event = _events.FindEventBy(Context.Guild);
if (@event == null)
throw new Exception("No events were found for this guild.");
throw new Exception("No events were found for this discord server.");
if (!@event.Active)
throw new Exception("This event is finalized. Please make a new event.");
if (@event.MessageId == 0)
@@ -387,10 +487,14 @@ namespace EventBot.Modules
@event.MessageId = 0;
@event.MessageChannelId = 0;
await _database.SaveChangesAsync();
await ReplyAsync($"Event `{@event.Id}` registration has been closed, it's registration message will now be normal message.");
await ReplyAsync($"Event's `{@event.Id}` registration has been closed, its registration message will now be normal message.");
}
[Priority(1)]
[Command("finalize")]
[Alias("archive")]
[Name("Archive event")]
[Summary("Archives event and reverts all role additions. This is irreversable.")]
public async Task EventFinilize(
[Summary("Event to finilize")] Event @event = null)
@@ -398,30 +502,41 @@ namespace EventBot.Modules
if (@event == null)
@event = _events.FindEventBy(Context.Guild);
if (@event == null)
throw new Exception("No events were found for this guild.");
throw new Exception("No events were found for this discord server.");
if (!@event.Active)
throw new Exception("This event is already finalized.");
@event.Active = false;
await _database.SaveChangesAsync();
await ReplyAsync($"Event `{@event.Id}` has been finilized. Removing participant roles...");
await ReplyAsync($"Event `{@event.Id}` has been finalized. Removing participant roles..");
if (@event.Guild.ParticipantRoleId != 0)
foreach (var participant in @event.Participants)
{
var user = Context.Guild.GetUser(participant.UserId);
await user.RemoveRoleAsync(Context.Guild.GetRole(@event.Guild.ParticipantRoleId));
}
foreach (var role in @event.Roles)
{
if (role.ChannelId != 0)
await Context.Guild.GetTextChannel(role.ChannelId)?.DeleteAsync();
if (role.RoleId != 0)
await Context.Guild.GetRole(role.RoleId)?.DeleteAsync();
}
await ReplyAsync($"Everyone's roles have been removed. I hope it was fun!");
}
[Priority(1)]
[Command("list")]
[Alias("all")]
[Name("Lists events")]
[Summary("Lists all prevous events that took on this server.")]
public async Task EventArchive()
{
var guildEvents = _database.Events.Where(e => e.GuildId == Context.Guild.Id).OrderBy(e => e.Opened).ToList();
if (guildEvents.Count() == 0)
throw new Exception("There are no events that roon on this server.");
throw new Exception("There are no events that have been run on this server.");
var pagedEvents = guildEvents
.Select((e, i) => new { Event = e, Index = i })
@@ -429,7 +544,7 @@ namespace EventBot.Modules
.Select(g => g.Select(o => o.Event));
var pager = new PaginatedMessage()
{
Title = "List al all prevous events.",
Title = "Lists all previous events.",
Color = Color.Blue,
Options = new PaginatedAppearanceOptions()
{
@@ -447,27 +562,30 @@ namespace EventBot.Modules
await PagedReplyAsync(pager);
}
[Priority(2)]
[Command("participant add")]
[Name("Add participant")]
[Summary("Add user to event role. Acts like join command.")]
public async Task EventParticipantAdd(
[Summary("User id or mention")] IUser user,
[Summary("Role emote or role id to join.")] string emoteOrId,
[Summary("Extra information that migth be needed by organizers.")] string extraInformation = null,
[Summary("Optional event ID for joining event that is not most recent one.")] Event @event = null)
[Summary("User ID or discord mention.")] IUser user,
[Summary("Role emote or role ID to join.")] string emoteOrId,
[Summary("Extra information that might be needed by organizers.")] string extraInformation = null,
[Summary("Optional event ID for joining event that is not the most recent one.")] Event @event = null)
{
EventRole er;
if (!(user is SocketGuildUser guildUser))
throw new Exception("This command must be executed inside guild.");
throw new Exception("This command must be executed inside a discord server.");
if (@event == null)
@event = _events.FindEventBy(Context.Guild);
if (@event == null & !(int.TryParse(emoteOrId, out int roleId)))
throw new Exception("Unable to locate any events for this guild.");
throw new Exception("Unable to locate any events for this discord server.");
else if (@event == null || roleId != 0)
er = _database.EventRoles.FirstOrDefault(r => r.Id == roleId);
else
er = @event.Roles.FirstOrDefault(r => r.Emote == emoteOrId);
if (er == null)
throw new ArgumentException("Invalid emote or event id specified");
throw new ArgumentException("Invalid emote or event ID specified");
if (!er.Event.Active)
throw new Exception("This event is finalized. Please make a new event.");
@@ -475,37 +593,30 @@ namespace EventBot.Modules
await Context.Message.DeleteAsync(); // Protect somewhat sensitive data.
}
[Priority(2)]
[Command("participant remove")]
[Alias("participant delete")]
[Name("Remove participant")]
[Summary("Remove participant from event role.")]
public async Task EventParticipantRemove(
[Summary("User that is participanting id or mention")] IUser user,
[Summary("Event to romove participant from")] Event @event = null)
[Summary("User that is participating's ID or discord mention.")] IUser user,
[Summary("Event to remove the participant from.")] Event @event = null)
{
if (@event == null)
@event = _events.FindEventBy(Context.Guild);
if (@event == null)
throw new Exception("No events were found for this guild.");
throw new Exception("No events were found for this discord server.");
if (!@event.Active)
throw new Exception("This event is finalized. Please make a new event.");
if (!(user is IGuildUser guildUser) || !(Context.User is IGuildUser initiator))
throw new Exception("This command must be executed inside a discord server.");
if (!(user is IGuildUser guildUser))
throw new Exception("This command must be executed inside guild.");
var participant = @event.Participants.FirstOrDefault(p => p.UserId == guildUser.Id);
_database.Remove(participant);
var embed = new EmbedBuilder()
.WithTitle($"{user} been removed from event `{@event.Title}`, by {Context.User}")
.WithDescription($"They were in `{participant.Role.Title}` role")
.WithColor(Color.Red);
if (participant.UserData != null)
embed.AddField("Provided details", $"`{participant.UserData}`");
await _events.RemoveParticipant(guildUser, @event, initiator);
await _database.SaveChangesAsync();
await ReplyAsync($"{guildUser} has been removed from event.");
await _events.UpdateEventMessage(@event);
if (@event.Guild.EventRoleConfirmationChannelId != 0)
await (await ((IGuild)Context.Guild).GetTextChannelAsync(@event.Guild.EventRoleConfirmationChannelId)).SendMessageAsync(embed: embed.Build());
if (@event.Guild.ParticipantRoleId != 0)
await guildUser.RemoveRoleAsync(Context.Guild.GetRole(@event.Guild.ParticipantRoleId));
}
}
}

View File

@@ -50,7 +50,9 @@ namespace EventBot
{
return new ServiceCollection()
.AddSingleton(s => new DiscordSocketClient(new DiscordSocketConfig() {
#if DEBUG
LogLevel = LogSeverity.Debug,
#endif
MessageCacheSize = 1500
}))
.AddSingleton<CommandService>()

View File

@@ -35,6 +35,7 @@ namespace EventBot.Services
_discord = services.GetRequiredService<DiscordSocketClient>();
_discord.GuildAvailable += OnGuildAvaivable;
_discord.JoinedGuild += OnGuildAvaivable;
}
public DatabaseService(): base() {}

View File

@@ -25,21 +25,45 @@ namespace EventBot.Services
_discord.ReactionAdded += ReactionAddedAsync;
_discord.MessageDeleted += MessageDeletedAsync;
_discord.ChannelDestroyed += ChannelDeleted;
_discord.RoleDeleted += RoleDeleted;
}
private async Task RoleDeleted(SocketRole role)
{
var eventRole = _database.EventRoles.FirstOrDefault(r => r.RoleId == role.Id);
if(eventRole != null)
{
eventRole.ChannelId = 0;
await _database.SaveChangesAsync();
}
}
private async Task ChannelDeleted(SocketChannel channel)
{
var eventRole = _database.EventRoles.FirstOrDefault(r => r.ChannelId == channel.Id);
if (eventRole != null)
{
eventRole.ChannelId = 0;
await _database.SaveChangesAsync();
}
}
public async Task TryJoinEvent(IGuildUser user, EventRole er, string extra, bool extraChecks = true)
{
if (er.Event.GuildId != user.GuildId)
throw new Exception("Cross guild events are fobidden.");
throw new Exception("Cross server events are forbidden.");
if (extraChecks && er.ReamainingOpenings <= 0)
throw new Exception("No openings left.");
if(er.Event.Participants.Where(p => p.UserId == user.Id).Count() > 0)
throw new Exception("No openings are left.");
if(er.Event.ParticipantCount > 0 && er.Event.Participants.Where(p => p.UserId == user.Id).Count() > 0)
throw new Exception("You are already participating.");
if(extraChecks && !er.Event.Active)
throw new Exception("Event is closed.");
if (er.Event.Guild.ParticipantRoleId != 0)
await user.AddRoleAsync(user.Guild.GetRole(er.Event.Guild.ParticipantRoleId));
if (er.RoleId != 0)
await user.AddRoleAsync(user.Guild.GetRole(er.RoleId));
var ep = new EventParticipant()
{
@@ -63,6 +87,42 @@ namespace EventBot.Services
await (await user.Guild.GetTextChannelAsync(er.Event.Guild.EventRoleConfirmationChannelId)).SendMessageAsync(embed: embed.Build());
}
public async Task RemoveParticipant(IGuildUser user, Event @event, IGuildUser initiator)
{
var participant = @event.Participants.FirstOrDefault(p => p.UserId == user.Id);
_database.Remove(participant);
var embed = new EmbedBuilder()
.WithTitle($"{user} been removed from event `{@event.Title}`, by {initiator}.")
.WithDescription($"Their role was: `{participant.Role.Title}`")
.WithColor(Color.Red);
if (participant.UserData != null)
embed.AddField("Provided details", $"`{participant.UserData}`");
if (@event.Guild.EventRoleConfirmationChannelId != 0)
await (await user.Guild.GetTextChannelAsync(@event.Guild.EventRoleConfirmationChannelId)).SendMessageAsync(embed: embed.Build());
if (@event.Guild.ParticipantRoleId != 0)
await user.RemoveRoleAsync(user.Guild.GetRole(@event.Guild.ParticipantRoleId));
if (participant.Role.RoleId != 0)
await user.RemoveRoleAsync(user.Guild.GetRole(participant.Role.RoleId));
}
public async Task RemoveParticipant(EventParticipant participant, IGuildUser initiator)
{
IGuildUser user = await initiator.Guild.GetUserAsync(participant.UserId);
_database.Remove(participant);
var embed = new EmbedBuilder()
.WithTitle($"{user} been removed from event `{participant.Event.Title}`, by {initiator}.")
.WithDescription($"Their role was: `{participant.Role.Title}`")
.WithColor(Color.Red);
if (participant.UserData != null)
embed.AddField("Provided details", $"`{participant.UserData}`");
if (participant.Event.Guild.EventRoleConfirmationChannelId != 0)
await (await user.Guild.GetTextChannelAsync(participant.Event.Guild.EventRoleConfirmationChannelId)).SendMessageAsync(embed: embed.Build());
if (participant.Event.Guild.ParticipantRoleId != 0)
await user.RemoveRoleAsync(user.Guild.GetRole(participant.Event.Guild.ParticipantRoleId));
}
public async Task RemoveParticipant(IGuildUser user, EventRole eventRole, IGuildUser initiator) => await RemoveParticipant(user, eventRole.Event, initiator);
public Event FindEventBy(IGuild guild, bool bypassActive = false)
{
return _database.Events.OrderByDescending(e => e.Opened).FirstOrDefault(e => e.GuildId == guild.Id && (e.Active || bypassActive));
@@ -95,12 +155,12 @@ namespace EventBot.Services
if (@event.Type == Event.EventParticipactionType.Quick)
embed.Description += "\r\nTo participate in this event react with following emotes:";
if (@event.Type == Event.EventParticipactionType.Detailed)
embed.Description += "\r\nTo participate in this event use command `join <emote or id> <extra information>` as following emotes are awaivable:";
embed.Description += "\r\nTo participate in this event use command `join <emote or id> <extra information>` as following emotes are available:";
embed.WithFields(@event.Roles
.OrderBy(e => e.SortNumber)
.Select(e => new EmbedFieldBuilder()
.WithName($"{e.Emote} `{e.Id}`: *{e.Title}*`{ (e.MaxParticipants > 0 ? $" - {e.ReamainingOpenings} ramaining" : "")} - {e.ParticipantCount} participating.`")
.WithName($"{e.Emote} `{e.Id}`: *{e.Title}*`{ (e.MaxParticipants > 0 ? $" - {e.ReamainingOpenings} remaining" : "")} - {e.ParticipantCount} participating.`")
.WithValue($"{e.Description}")
));
return embed;
@@ -141,7 +201,7 @@ namespace EventBot.Services
catch (Exception ex)
{
if (reaction.User.IsSpecified)
await reaction.User.Value.SendMessageAsync($"Error ocured while processing your reaction: \r\n{ex.GetType()}: {ex.Message}");
await reaction.User.Value.SendMessageAsync($"Error occured while processing your reaction: \r\n{ex.GetType()}: {ex.Message}");
}
}
}

6
README
View File

@@ -1,6 +0,0 @@
`set dbconnection="Server=localhost;Database=eventbot;User=root;Password=password;"`
`Add-Migration InitialDatabase -Context MySqlDatabaseService -OutputDir Migrations\MySql`
`Add-Migration InitialDatabase -Context SqliteDatabaseService -OutputDir Migrations\Sqlite`

14
README.md Normal file
View File

@@ -0,0 +1,14 @@
# EventBot
## Environment variables
### `token` variable
This is variable for discord bot's token obtained from discord developer panel.
### `dbconnection` variable
This is environment variable for Mysql / MariaDb database connection. Example connection string:
```Server=localhost,123;Database=eventbot;User=root;Password=password;```
## Making migrations
`Add-Migration InitialDatabase -Context MySqlDatabaseService -OutputDir Migrations\MySql`
`Add-Migration InitialDatabase -Context SqliteDatabaseService -OutputDir Migrations\Sqlite`