Skip to content

Commit

Permalink
Ninja Commit 2
Browse files Browse the repository at this point in the history
Got events just barely working, so far the only working event is "UserJoined", had to make a bunch of minor changes to things to make that work.
  • Loading branch information
michaelgaultjr committed Sep 26, 2018
1 parent 7971f8c commit c3a37e6
Show file tree
Hide file tree
Showing 19 changed files with 160 additions and 62 deletions.
Binary file modified src/.vs/Discord.json/DesignTimeBuild/.dtbcache
Binary file not shown.
Binary file modified src/.vs/Discord.json/v15/.suo
Binary file not shown.
Binary file modified src/.vs/Discord.json/v15/Server/sqlite3/storage.ide
Binary file not shown.
Binary file modified src/.vs/Discord.json/v15/Server/sqlite3/storage.ide-shm
Binary file not shown.
Binary file modified src/.vs/Discord.json/v15/Server/sqlite3/storage.ide-wal
Binary file not shown.
104 changes: 58 additions & 46 deletions src/Actions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ namespace Discord.json
public class Actions
{
// Holds information about the guild, message, user, bot etc
public static SocketCommandContext Context { get; set; }
public static ICommandContext Context { get; set; }

// This is a list of all vaild jactions
public Dictionary<string, JMethodData> JActions { get; set; }
Expand Down Expand Up @@ -76,7 +76,7 @@ public async Task MoveChannel(SocketTextChannel channel, string categoryName)
{
try
{
var category = Context.Guild.CategoryChannels.ToList().Find(c => c.Name == categoryName);
var category = (Context.Guild as SocketGuild).CategoryChannels.ToList().Find(c => c.Name == categoryName);

await channel.ModifyAsync(x => x.CategoryId = category.Id);
}
Expand All @@ -91,10 +91,10 @@ public async Task ChangeServerName(string newName)
{
try
{
await Context.Guild.ModifyAsync(async x =>
{
x.Name = newName;
});
await Context.Guild.ModifyAsync(x =>
{
x.Name = newName;
});

}
catch (Exception e)
Expand All @@ -109,33 +109,37 @@ public async Task ExecuteAsync(SocketCommandContext context, JsonCommand command

foreach (var action in command.Actions)
{
var localArgs = ArgParser(action.Arguments, cmdData);
var args = ArgParser(action.Arguments, cmdData.Arguments);
await ExecuteActionAsync(action, args);
}
}

var commandMethod = JActions[action.Name.ToLower()];
try
public async Task ExecuteActionAsync(JsonAction action, List<object> localArgs)
{
var commandMethod = JActions[action.Name.ToLower()];
try
{
// Checks if the parameters are the correct legnth to avoid crashes
if (localArgs.Count > commandMethod.Parameters.Count)
{
// Checks if the parameters are the correct legnth to avoid crashes
if (localArgs.Count > commandMethod.Parameters.Count)
{
// Gets the amount of extra paramerts then removes those from the end of the list
var amount = localArgs.Count - commandMethod.Parameters.Count;
localArgs.RemoveRange(commandMethod.Parameters.Count, amount);
}
else if (localArgs.Count < commandMethod.Parameters.Count)
{
await ReplyAsync("Not Enough Parameters");
}

await ReflectionHelper.InvokeMethod<Actions>(new Actions(), commandMethod.Name, localArgs.ToArray());
// Gets the amount of extra paramerts then removes those from the end of the list
var amount = localArgs.Count - commandMethod.Parameters.Count;
localArgs.RemoveRange(commandMethod.Parameters.Count, amount);
}
catch (Exception e)
else if (localArgs.Count < commandMethod.Parameters.Count)
{
Console.WriteLine(e);
await ReplyAsync("Not Enough Parameters");
}

await ReflectionHelper.InvokeMethod<Actions>(new Actions(), commandMethod.Name, localArgs.ToArray());
}
catch (Exception e)
{
Console.WriteLine(e);
}
}

private List<object> ArgParser(List<string> actionArgs, CommandArgs userArgs)
public List<object> ArgParser(List<string> actionArgs, List<object> userArgs)
{
var returnArgs = new List<object>();

Expand All @@ -147,7 +151,7 @@ private List<object> ArgParser(List<string> actionArgs, CommandArgs userArgs)
var bind = new Regex(@"\|(.*?)\|"); // This pattern matches everything between ||
var bindMatches = bind.Matches(_arg);

var mention = new Regex("^<[#@&]+?([0-9]+?)>$");
var mention = new Regex("^<[#@&!]+?([0-9]+?)>$");

// Checks if there is any matches
// If there is go through each one and replace it with the correct information
Expand All @@ -163,35 +167,21 @@ private List<object> ArgParser(List<string> actionArgs, CommandArgs userArgs)

if (Int32.TryParse(arg, out int index))
{
var posArg = userArgs.Arguments[index];
var posArg = userArgs[index];
returnArg = (returnArg as string).Replace(match.Value, posArg.ToString());

var mentionMatch = mention.Match((string)returnArg);

if (mentionMatch.Success)
{
var mUlong = mentionMatch.Groups[1].Value;
var mMatch = mentionMatch.Value;

UInt64.TryParse(mUlong, out ulong id);
if (mMatch.StartsWith("<@"))
{
returnArg = Context.Guild.GetUser(id);
}
else if (mMatch.StartsWith("<#"))
{
returnArg = Context.Guild.GetTextChannel(id);
}
/*else if (mMatch.Contains("<@&")) // Allows for @[role] in the args to be used as SocketRole
{
returnArg = Context.Guild.GetRole(id);
}*/
}
returnArg = ReplaceMentions(mentionMatch);
}
else
{
var bindArg = ReflectionHelper.GetPropValue<string>(this, JPropertyBinds.Binds[arg]);
returnArg = (returnArg as string).Replace(match.Value, bindArg);

var mentionMatch = mention.Match((string)returnArg);
if (mentionMatch.Success)
returnArg = ReplaceMentions(mentionMatch);
}
}
returnArgs.Add(returnArg);
Expand All @@ -202,5 +192,27 @@ private List<object> ArgParser(List<string> actionArgs, CommandArgs userArgs)
}
return returnArgs;
}

object ReplaceMentions(Match match)
{
object returnArg = null;
var mUlong = match.Groups[1].Value;
var mMatch = match.Value;

UInt64.TryParse(mUlong, out ulong id);
if (mMatch.StartsWith("<@"))
{
returnArg = (Context.Guild as SocketGuild).GetUser(id);
}
else if (mMatch.StartsWith("<#"))
{
returnArg = (Context.Guild as SocketGuild).GetTextChannel(id);
}
/*else if (mMatch.Contains("<@&")) // Allows for @[role] in the args to be used as SocketRole
{
returnArg = Context.Guild.GetRole(id);
}*/
return returnArg;
}
}
}
38 changes: 36 additions & 2 deletions src/JBot.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@ private async Task RunBotAsync()

Client.MessageReceived += HandleCommandAsync;
RegisterCommands();
RegisterEvents();

// Log in as bot
try
Expand Down Expand Up @@ -140,6 +141,39 @@ private void RegisterCommands()
}
}

private void RegisterEvents()
{
if (_data.Events.Find(e => e.Name == "UserJoined") != null)
Client.UserJoined += ExecuteEvent;
}

public async Task ExecuteEvent(object args)
{
var eventObjects = new Dictionary<Type, string>
{
{ typeof(SocketGuildUser), "UserJoined" }
};
await ExecuteActionsAsync(eventObjects[args.GetType()], args);
}

private async Task ExecuteActionsAsync(string eventName, object args)
{
var eventData = _data.Events.Find(e => e.Name == eventName);
switch (eventName)
{
case "UserJoined":

foreach (var action in eventData.Actions)
{
var user = (args as SocketGuildUser);
Actions.Context = new SocketEventContext(Client, user);
var argList = _actions.ArgParser(action.Arguments, new List<object>());//new List<object>(action.Arguments);
await _actions.ExecuteActionAsync(action, argList);
}
break;
}
}

private Task Log(LogMessage arg)
{
if (PrintLog)
Expand All @@ -151,7 +185,7 @@ private Task Log(LogMessage arg)
private async Task HandleCommandAsync(SocketMessage arg)
{
if (!(arg is SocketUserMessage message) || message.Author.IsBot) return;
Console.WriteLine(message.Content);

int argPos = 0;
if (message.HasStringPrefix(Prefix, ref argPos) || message.HasMentionPrefix(Client.CurrentUser, ref argPos) && AllowMentionPrefix)
{
Expand Down Expand Up @@ -190,4 +224,4 @@ public JsonCommand GetCommand(string command)
}
}
}
}
}
1 change: 0 additions & 1 deletion src/Program.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
using Newtonsoft.Json;
using System;
using System.IO;
using System.Linq;

Expand Down
41 changes: 41 additions & 0 deletions src/SocketEventContext.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
using Discord.Commands;
using Discord.WebSocket;
using System;
using System.Collections.Generic;
using System.Text;

namespace Discord.json
{
public class SocketEventContext : ICommandContext
{
public DiscordSocketClient Client { get; }
public SocketGuild Guild { get; }
public ISocketMessageChannel Channel { get; }
public SocketUser User { get; }
public SocketUserMessage Message { get; }

public bool IsPrivate => Channel is IPrivateChannel;

public SocketEventContext(DiscordSocketClient client, SocketGuild guild)
{
Client = client;
Guild = guild;
Channel = guild.DefaultChannel;
}

public SocketEventContext(DiscordSocketClient client, SocketGuildUser user)
{
Client = client;
Guild = user.Guild;
Channel = user.Guild.DefaultChannel;
User = user;
}

//ICommandContext
IDiscordClient ICommandContext.Client => Client;
IGuild ICommandContext.Guild => Guild;
IMessageChannel ICommandContext.Channel => Channel;
IUser ICommandContext.User => User;
IUserMessage ICommandContext.Message => Message;
}
}
13 changes: 12 additions & 1 deletion src/bot/main.bot
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,13 @@
"actions": [
{ "action": "DeleteRole", "args": [ "|0|" ]}
]
},
{
"name": "me",
"args": 0,
"actions": [
{ "action": "Reply", "args": [ "|user|" ]}
]
}
],
"events": [
Expand All @@ -32,7 +39,11 @@
"actions": [
{
"action": "Reply",
"args": [ "Hello |user| welcome to |guild|" ]
"args": [ "Hello |user-name| welcome to |guild|" ]
},
{
"action": "AddRole",
"args": [ "|user|", "red" ]
}
]
}
Expand Down
3 changes: 2 additions & 1 deletion src/bot/properties.binds
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{
"user": "Context.User.Username",
"user-name": "Context.User.Username",
"user": "Context.User.Mention",
"guild": "Context.Guild.Name"
}
Binary file modified src/obj/Debug/netcoreapp2.1/Discord.json.assets.cache
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -1 +1 @@
8b9b3faa1965784bd980f396bcac7ebac9f7989c
9a297fc2bf746ff33ff76604dbf5b235bf418e75
Binary file not shown.
Binary file modified src/obj/Debug/netcoreapp2.1/Discord.json.dll
Binary file not shown.
Binary file modified src/obj/Debug/netcoreapp2.1/Discord.json.pdb
Binary file not shown.
2 changes: 1 addition & 1 deletion src/obj/Discord.json.csproj.nuget.cache
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"version": 1,
"dgSpecHash": "Wym/vBQUn0ukCzyHlvYd/HRcIgzsYJGAUx+8A03czho3gyGOiSWjAdFSQmQGL66MOJr/Y2BoSp8OjMvTbXU7IQ==",
"dgSpecHash": "nH5wfO3r7TR9jL7bFyRNdbmHI7iYdvX8mDWQ0SxnTL/RiFYzY6K/Ulp7vxwI/eo20KBQE2Z5JcCc8QezgtKfRA==",
"success": true
}
6 changes: 3 additions & 3 deletions src/obj/Discord.json.csproj.nuget.g.props
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@
<PropertyGroup Condition=" '$(ExcludeRestorePackageImports)' != 'true' ">
<RestoreSuccess Condition=" '$(RestoreSuccess)' == '' ">True</RestoreSuccess>
<RestoreTool Condition=" '$(RestoreTool)' == '' ">NuGet</RestoreTool>
<ProjectAssetsFile Condition=" '$(ProjectAssetsFile)' == '' ">C:\Users\dotcd\Desktop\Desktop\Git\Discord.json\src\obj\project.assets.json</ProjectAssetsFile>
<ProjectAssetsFile Condition=" '$(ProjectAssetsFile)' == '' ">C:\Users\TGN-PC\Documents\Visual Studio 2017\Projects\EzBot\EzBot.Json\src\obj\project.assets.json</ProjectAssetsFile>
<NuGetPackageRoot Condition=" '$(NuGetPackageRoot)' == '' ">$(UserProfile)\.nuget\packages\</NuGetPackageRoot>
<NuGetPackageFolders Condition=" '$(NuGetPackageFolders)' == '' ">C:\Users\dotcd\.nuget\packages\;C:\Program Files\dotnet\sdk\NuGetFallbackFolder</NuGetPackageFolders>
<NuGetPackageFolders Condition=" '$(NuGetPackageFolders)' == '' ">C:\Users\TGN-PC\.nuget\packages\;C:\Program Files\dotnet\sdk\NuGetFallbackFolder</NuGetPackageFolders>
<NuGetProjectStyle Condition=" '$(NuGetProjectStyle)' == '' ">PackageReference</NuGetProjectStyle>
<NuGetToolVersion Condition=" '$(NuGetToolVersion)' == '' ">4.8.1</NuGetToolVersion>
<NuGetToolVersion Condition=" '$(NuGetToolVersion)' == '' ">4.7.0</NuGetToolVersion>
</PropertyGroup>
<PropertyGroup>
<MSBuildAllProjects>$(MSBuildAllProjects);$(MSBuildThisFileFullPath)</MSBuildAllProjects>
Expand Down
12 changes: 6 additions & 6 deletions src/obj/project.assets.json
Original file line number Diff line number Diff line change
Expand Up @@ -5891,23 +5891,23 @@
]
},
"packageFolders": {
"C:\\Users\\dotcd\\.nuget\\packages\\": {},
"C:\\Users\\TGN-PC\\.nuget\\packages\\": {},
"C:\\Program Files\\dotnet\\sdk\\NuGetFallbackFolder": {}
},
"project": {
"version": "1.0.0",
"restore": {
"projectUniqueName": "C:\\Users\\dotcd\\Desktop\\Desktop\\Git\\Discord.json\\src\\Discord.json.csproj",
"projectUniqueName": "C:\\Users\\TGN-PC\\Documents\\Visual Studio 2017\\Projects\\EzBot\\EzBot.Json\\src\\Discord.json.csproj",
"projectName": "Discord.json",
"projectPath": "C:\\Users\\dotcd\\Desktop\\Desktop\\Git\\Discord.json\\src\\Discord.json.csproj",
"packagesPath": "C:\\Users\\dotcd\\.nuget\\packages\\",
"outputPath": "C:\\Users\\dotcd\\Desktop\\Desktop\\Git\\Discord.json\\src\\obj\\",
"projectPath": "C:\\Users\\TGN-PC\\Documents\\Visual Studio 2017\\Projects\\EzBot\\EzBot.Json\\src\\Discord.json.csproj",
"packagesPath": "C:\\Users\\TGN-PC\\.nuget\\packages\\",
"outputPath": "C:\\Users\\TGN-PC\\Documents\\Visual Studio 2017\\Projects\\EzBot\\EzBot.Json\\src\\obj\\",
"projectStyle": "PackageReference",
"fallbackFolders": [
"C:\\Program Files\\dotnet\\sdk\\NuGetFallbackFolder"
],
"configFilePaths": [
"C:\\Users\\dotcd\\AppData\\Roaming\\NuGet\\NuGet.Config",
"C:\\Users\\TGN-PC\\AppData\\Roaming\\NuGet\\NuGet.Config",
"C:\\Program Files (x86)\\NuGet\\Config\\Microsoft.VisualStudio.Offline.config"
],
"originalTargetFrameworks": [
Expand Down

0 comments on commit c3a37e6

Please sign in to comment.