Skip to content

Commit

Permalink
listadd: allow adding to private lists and auto update lists
Browse files Browse the repository at this point in the history
  • Loading branch information
Erisa committed Feb 20, 2025
1 parent 0a5c4da commit 85f3b48
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 14 deletions.
40 changes: 29 additions & 11 deletions Commands/ListCmds.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,18 +67,21 @@ public async Task ListAdd(
[RemainingText, Description("The text to add the list. Can be in a codeblock and across multiple line.")] string content
)
{
if (Environment.GetEnvironmentVariable("CLIPTOK_GITHUB_TOKEN") is null)
var githubToken = Environment.GetEnvironmentVariable("CLIPTOK_GITHUB_TOKEN");
var githubTokenPrivate = Environment.GetEnvironmentVariable("CLIPTOK_GITHUB_TOKEN_PRIVATE");

if (githubToken is null)
{
await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} `CLIPTOK_GITHUB_TOKEN` was not set, so GitHub API commands cannot be used.");
return;
}

if (!fileName.EndsWith(".txt"))
fileName += ".txt";


if (content.Length < 3)
{
await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} Your input is too short, please reconsider.");
await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} Your input is too short, please don't add this to the list.");
return;
}

Expand All @@ -88,28 +91,43 @@ public async Task ListAdd(
content = content.Replace("```", "").Trim();

string[] lines = content.Split(
new string[] { "\r\n", "\r", "\n" },
["\r\n", "\r", "\n"],
StringSplitOptions.None
);

if (lines.Any(line => line.Length < 4))
{
await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} One of your lines is shorter than 4 characters.\nFor safety reasons I can't accept this input over command. Please submit a PR manually.");
await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} One of your lines is shorter than 4 characters.\nTo prevent accidents I can't accept this input over command. Please submit a PR manually.");
return;
}

string nameToSend = $"{DiscordHelpers.UniqueUsername(ctx.User)}";

var workflowId = Program.cfgjson.GitHubWorkflow.WorkflowId;
var refName = Program.cfgjson.GitHubWorkflow.Ref;
var repoName = Program.cfgjson.GitHubWorkflow.Repo;

if (
Program.cfgjson.GitHubWorkflowPrivate is not null
&& githubTokenPrivate is not null
&& Directory.GetFiles($"Lists/{Program.cfgjson.GitListDirectory}").Any(x => x.EndsWith(fileName)) )
{
workflowId = Program.cfgjson.GitHubWorkflowPrivate.WorkflowId;
refName = Program.cfgjson.GitHubWorkflowPrivate.Ref;
repoName = Program.cfgjson.GitHubWorkflowPrivate.Repo;
githubToken = githubTokenPrivate;
}

using HttpClient httpClient = new()
{
BaseAddress = new Uri("https://api.github.com/")
};

httpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/vnd.github.v3+json"));
httpClient.DefaultRequestHeaders.UserAgent.Add(new System.Net.Http.Headers.ProductInfoHeaderValue("Cliptok", "1.0"));
httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Token", Environment.GetEnvironmentVariable("CLIPTOK_GITHUB_TOKEN"));
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github.v3+json"));
httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("Cliptok", "1.0"));
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Token", githubToken);

HttpRequestMessage request = new(HttpMethod.Post, $"/repos/{Program.cfgjson.GitHubWorkFlow.Repo}/actions/workflows/{Program.cfgjson.GitHubWorkFlow.WorkflowId}/dispatches");
HttpRequestMessage request = new(HttpMethod.Post, $"/repos/{repoName}/actions/workflows/{workflowId}/dispatches");

GitHubDispatchInputs inputs = new()
{
Expand All @@ -120,7 +138,7 @@ public async Task ListAdd(

GitHubDispatchBody body = new()
{
Ref = Program.cfgjson.GitHubWorkFlow.Ref,
Ref = refName,
Inputs = inputs
};

Expand All @@ -131,7 +149,7 @@ public async Task ListAdd(

if (response.IsSuccessStatusCode)
await ctx.RespondAsync($"{Program.cfgjson.Emoji.Success} The request was successful.\n" +
$"You should see the result in <#{Program.cfgjson.HomeChannel}> soon or can check at <https://github.com/{Program.cfgjson.GitHubWorkFlow.Repo}/actions>");
$"You should see the result in <#{Program.cfgjson.HomeChannel}> soon or can check at <https://github.com/{repoName}/actions>");
else
await ctx.RespondAsync($"{Program.cfgjson.Emoji.Error} An error with code `{response.StatusCode}` was returned when trying to request the Action run.\n" +
$"Body: ```json\n{responseText}```");
Expand Down
28 changes: 28 additions & 0 deletions Events/MessageEvent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -289,6 +289,34 @@ public static async Task MessageHandlerAsync(DiscordClient client, MockDiscordMe
}
}

// automatic listupdate for private lists
if (
Program.cfgjson.GitListDirectory is not null
&& Program.cfgjson.GitListDirectory != ""
&& message.Channel.Id == Program.cfgjson.HomeChannel
&& message.Author.Discriminator == "0000"
&& message.Embeds is not null
&& message.Embeds.Count > 0
&& message.Embeds[0].Title.StartsWith("[lists] fileappend success"))
{
string command = $"cd Lists/{Program.cfgjson.GitListDirectory} && git pull";
var msg = await LogChannelHelper.LogMessageAsync("home", $"{Program.cfgjson.Emoji.Loading} Updating private lists..");

ShellResult finishedShell = RunShellCommand(command);

string result = Regex.Replace(finishedShell.result, "(?:ghp)|(?:github_pat)_[0-9a-zA-Z_]+", "ghp_REDACTED").Replace(Environment.GetEnvironmentVariable("CLIPTOK_TOKEN"), "REDACTED");

if (finishedShell.proc.ExitCode != 0)
{
await msg.ModifyAsync($"{Program.cfgjson.Emoji.Error} An error occurred trying to update private lists!\n```\n{result}\n```");
}
else
{
Program.UpdateLists();
await msg.ModifyAsync($"{Program.cfgjson.Emoji.Success} Successfully updated and reloaded private lists!\n```\n{result}\n```");
}
}

// Skip DMs, external guilds, and messages from bots, beyond this point.
if (channel.IsPrivate || channel.Guild.Id != Program.cfgjson.ServerID || message.Author.IsBot)
return;
Expand Down
8 changes: 7 additions & 1 deletion Structs.cs
Original file line number Diff line number Diff line change
Expand Up @@ -216,7 +216,10 @@ public class ConfigJson
public string GiveawayTriggerMessage { get; private set; }

[JsonProperty("githubWorkflow")]
public WorkflowConfig GitHubWorkFlow { get; private set; }
public WorkflowConfig GitHubWorkflow { get; private set; }

[JsonProperty("githubWorkflowPrivate")]
public WorkflowConfig GitHubWorkflowPrivate { get; private set; }

[JsonProperty("everyoneExcludedChannels")]
public List<ulong> EveryoneExcludedChannels { get; private set; } = new();
Expand Down Expand Up @@ -330,6 +333,9 @@ public ulong InsidersChannel

[JsonProperty("pingBotOwnersOnBadErrors")]
public bool PingBotOwnersOnBadErrors { get; private set; } = false;

[JsonProperty("githubWorkflowSucessString")]
public string HithubWorkflowSucessString { get; private set; } = "";
}

public enum Level { Information, Warning, Error, Debug, Verbose }
Expand Down
10 changes: 8 additions & 2 deletions config.json
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,11 @@
"ref": "main",
"workflowId": "append-lists-txt.yml"
},
"githubWorkflowPrivate": {
"repo": "Microsoft-community/lists",
"ref": "main",
"workflowId": "append-lists-txt.yml"
},
"everyoneFilter": true,
"logChannels": {
"mod": {
Expand Down Expand Up @@ -327,7 +332,7 @@
"logLevel": "Debug",
"lokiURL": "http://100.79.19.82:3100",
"lokiServiceName": "cliptok",
"voiceChannelPurge": true,
"voiceChannelPurge": true,
"forumChannelAutoWarnFallbackChannel": 150662382874525696,
"rulesAllowedPublicChannels": [
150909451270881280,
Expand All @@ -342,5 +347,6 @@
593381041629298688,
450181490345508884
],
"pingBotOwnersOnBadErrors": true
"pingBotOwnersOnBadErrors": true,
"githubWorkflowSucessString": "[lists:main] 1 new commit"
}

0 comments on commit 85f3b48

Please sign in to comment.