Archived
0
0
Fork 0

Compare commits

..

No commits in common. "0e2ffa7e9a7226292c37838fa448e0440c818681" and "b6a2c1d68f14d8220fef9b909db3237d2823c7ba" have entirely different histories.

3 changed files with 259 additions and 310 deletions

View file

@ -3,13 +3,11 @@ using System.Text;
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
using Discord; using Discord;
using Discord.WebSocket; using Discord.WebSocket;
using DiscordRPC;
using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Configuration;
using RestSharp; using RestSharp;
using Terminal.Gui; using Terminal.Gui;
using Terminal.Gui.Trees; using Terminal.Gui.Trees;
using Attribute = Terminal.Gui.Attribute; using Attribute = Terminal.Gui.Attribute;
using Button = Terminal.Gui.Button;
using Color = Terminal.Gui.Color; using Color = Terminal.Gui.Color;
namespace chord namespace chord
@ -21,7 +19,6 @@ namespace chord
private ulong currentSelectedChannel; private ulong currentSelectedChannel;
private ulong currentSelectedGuild; private ulong currentSelectedGuild;
private SortedDictionary<ulong, List<ulong>> guilds; private SortedDictionary<ulong, List<ulong>> guilds;
private DiscordRpcClient rpcClient;
private Settings settings; private Settings settings;
private Window window; private Window window;
@ -34,367 +31,321 @@ namespace chord
{ {
try { try {
#if DEBUG #if DEBUG
var config = new ConfigurationBuilder() var config = new ConfigurationBuilder()
.AddJsonFile("config.json") .AddJsonFile("config.json")
.Build(); .Build();
#else #else
var config = new ConfigurationBuilder() var config = new ConfigurationBuilder()
.AddJsonFile($"{Environment.GetEnvironmentVariable("HOME")}/.config/chord/config.json") .AddJsonFile($"{Environment.GetEnvironmentVariable("HOME")}/.config/chord/config.json")
.Build(); .Build();
#endif #endif
settings = config.Get<Settings>(); settings = config.Get<Settings>();
var client = new DiscordSocketClient(new DiscordSocketConfig var client = new DiscordSocketClient(new DiscordSocketConfig
{ AlwaysDownloadUsers = true, GatewayIntents = GatewayIntents.All }); { AlwaysDownloadUsers = true, GatewayIntents = GatewayIntents.All });
await client.LoginAsync(TokenType.Bot, settings.Token); await client.LoginAsync(TokenType.Bot, settings.Token);
await client.StartAsync(); await client.StartAsync();
if (settings.EnableRichPresence) { Application.Init();
rpcClient = new DiscordRpcClient("923436807297859625");
rpcClient.Initialize(); window = new Window("chord")
rpcClient.SetPresence(new RichPresence()); {
X = 0,
Y = 1,
Width = Dim.Fill(),
Height = Dim.Fill(),
ColorScheme =
{
Normal = new Attribute(Color.White, Color.Black)
}
};
client.Ready += () =>
{
guilds = new SortedDictionary<ulong, List<ulong>>();
foreach (var guild in client.Guilds)
{
guilds.Add(guild.Id, new List<ulong>());
foreach (var channel in guild.TextChannels)
{
var findGuild = guilds.GetValueOrDefault(guild.Id);
if (channel.Users.ToList().Find(user => user.Id == client.CurrentUser.Id) == null) continue;
if (findGuild == null) continue;
findGuild.Add(channel.Id);
findGuild.Sort();
}
} }
Application.Init();
window = new Window("chord")
{
X = 0,
Y = 1,
Width = Dim.Fill(),
Height = Dim.Fill(),
ColorScheme =
{
Normal = new Attribute(Color.White, Color.Black)
}
};
var menuBar = buildMenu(); var menuBar = buildMenu();
var serverList = buildServerList();
var channelList = buildChannelList(serverList);
var chatBox = buildChatBox(serverList);
var messageBox = buildMessageBox(serverList, chatBox);
var userList = buildUserList(chatBox);
var loadingLabel = new Label("Loading...") var serverListList = new ListView
{ {
X = 0, X = 0,
Y = 0, Y = 0,
Width = Dim.Fill(), Width = Dim.Fill(),
Height = Dim.Fill(), Height = Dim.Fill()
TextAlignment = TextAlignment.Centered,
VerticalTextAlignment = VerticalTextAlignment.Middle,
}; };
client.Ready += () => var guildNames = guilds.Select(guild => client.GetGuild(guild.Key).Name).ToList();
serverListList.SetSource(guildNames);
var channelListTree = new TreeView
{ {
guilds = new SortedDictionary<ulong, List<ulong>>(); X = 0,
Y = 0,
Width = Dim.Fill(),
Height = Dim.Fill()
};
foreach (var guild in client.Guilds) chatBoxList = new ListView
{
X = 0,
Y = 0,
Width = Dim.Fill(),
Height = Dim.Fill()
};
var messageBoxText = new TextView
{
X = 0,
Y = 0,
Width = Dim.Percent(95),
Height = Dim.Fill()
};
var messageBoxSend = new Button("Send", true)
{
X = Pos.Right(messageBoxText) - 2,
Y = 0
};
var userListTree = new TreeView
{
X = 0,
Y = 0,
Width = Dim.Fill(),
Height = Dim.Fill()
};
serverListList.OpenSelectedItem += args =>
{
channelListTree.ClearObjects();
currentSelectedGuild = guilds.Keys.ToList()[args.Item];
var channelNames = guilds.GetValueOrDefault(currentSelectedGuild)!
.Select(channel => client.GetGuild(currentSelectedGuild).GetTextChannel(channel).Name).ToList();
var categoryDict = new SortedDictionary<ulong, TreeNode>();
foreach (var categories in client.GetGuild(currentSelectedGuild).CategoryChannels)
{ {
guilds.Add(guild.Id, new List<ulong>()); var categoryName = Regex.Replace(categories.Name, @"[^\u0000-\u007F]+", string.Empty);
var node = new TreeNode(categoryName);
foreach (var channel in guild.TextChannels) foreach(var channel in categories.Channels)
{ {
var findGuild = guilds.GetValueOrDefault(guild.Id); if (channel.GetType().Name == "SocketTextChannel")
{
var channelName = Regex.Replace(channel.Name, @"[^\u0000-\u007F]+", string.Empty);
var channelNode = new TreeNode(channelName);
channelNode.Tag = new { Id = channel.Id };
if (channel.Users.ToList().Find(user => user.Id == client.CurrentUser.Id) == null) continue; node.Children.Add(channelNode);
if (findGuild == null) continue; }
findGuild.Add(channel.Id);
findGuild.Sort();
} }
categoryDict.Add(categories.Id, node);
} }
var serverList = buildServerList(); foreach (var category in categoryDict)
var channelList = buildChannelList(serverList);
var chatBox = buildChatBox(serverList);
var messageBox = buildMessageBox(serverList, chatBox);
var userList = buildUserList(chatBox);
var serverListList = new ListView
{ {
X = 0, channelListTree.AddObject(category.Value);
Y = 0, }
Width = Dim.Fill(), };
Height = Dim.Fill()
};
var guildNames = guilds.Select(guild => client.GetGuild(guild.Key).Name).ToList(); channelListTree.SelectionChanged += async (arg1, arg2) =>
{
userListTree.ClearObjects();
serverListList.SetSource(guildNames); try {
currentSelectedChannel = (ulong)arg2.NewValue.Tag.GetType().GetProperty("Id").GetValue(arg2.NewValue.Tag);
} catch {
return;
}
var channelListTree = new TreeView try {
{
X = 0,
Y = 0,
Width = Dim.Fill(),
Height = Dim.Fill()
};
chatBoxList = new ListView
{
X = 0,
Y = 0,
Width = Dim.Fill(),
Height = Dim.Fill()
};
var messageBoxText = new TextView
{
X = 0,
Y = 0,
Width = Dim.Percent(95),
Height = Dim.Fill()
};
var messageBoxSend = new Button("Send", true)
{
X = Pos.Right(messageBoxText) - 2,
Y = 0
};
var userListTree = new TreeView
{
X = 0,
Y = 0,
Width = Dim.Fill(),
Height = Dim.Fill()
};
serverListList.OpenSelectedItem += args =>
{
channelListTree.ClearObjects();
currentSelectedGuild = guilds.Keys.ToList()[args.Item];
var channelNames = guilds.GetValueOrDefault(currentSelectedGuild)!
.Select(channel => client.GetGuild(currentSelectedGuild).GetTextChannel(channel).Name).ToList();
var categoryDict = new SortedDictionary<ulong, TreeNode>();
foreach (var categories in client.GetGuild(currentSelectedGuild).CategoryChannels)
{
var categoryName = Regex.Replace(categories.Name, @"[^\u0000-\u007F]+", string.Empty);
var node = new TreeNode(categoryName);
foreach(var channel in categories.Channels)
{
if (channel.GetType().Name == "SocketTextChannel")
{
var channelName = Regex.Replace(channel.Name, @"[^\u0000-\u007F]+", string.Empty);
var channelNode = new TreeNode(channelName);
channelNode.Tag = new { Id = channel.Id };
node.Children.Add(channelNode);
}
}
categoryDict.Add(categories.Id, node);
}
foreach (var category in categoryDict)
{
channelListTree.AddObject(category.Value);
}
if (settings.EnableRichPresence) {
rpcClient.UpdateDetails($"Chatting in {client.GetGuild(currentSelectedGuild).Name}");
}
};
channelListTree.SelectionChanged += async (arg1, arg2) =>
{
userListTree.ClearObjects();
try {
currentSelectedChannel = (ulong)arg2.NewValue.Tag.GetType().GetProperty("Id").GetValue(arg2.NewValue.Tag);
} catch {
return;
}
try {
var restSharpClient = new RestClient("https://discord.com/api/v9");
var restSharpReq = new RestRequest($"channels/{currentSelectedChannel}/messages");
restSharpClient.AddDefaultHeader("Authorization", settings.Token);
var response = await restSharpClient.GetAsync<List<GetMessagesResponse>>(restSharpReq);
var messages = new List<string>();
foreach (var msg in response)
{
var msgNewLines = msg.content.Split("\n").ToList();
var firstMsg = msgNewLines[0];
msgNewLines.RemoveAt(0);
msgNewLines.Reverse();
messages.AddRange(msgNewLines.Select(message => $"{message}"));
messages.Add($"{msg.author.username}#{msg.author.discriminator} | {firstMsg}");
if (msg.embeds.Count != 0)
messages.Add($"{msg.author.username}#{msg.author.discriminator} | [Unable to display embed]");
if (msg.attachments.Count == 0) continue;
messages.AddRange(msg.attachments
.Select(attachment => $"{msg.author.username}#{msg.author.discriminator} | {attachment.url}")
.Select(dummy => dummy));
}
messages.Reverse();
await chatBoxList.SetSourceAsync(messages);
currentChannelMessages = messages;
chatBoxList.ScrollDown(currentChannelMessages.Count - chatBoxList.Bounds.Height);
chatBoxList.SelectedItem = currentChannelMessages.Count - 1;
var rolesDict = new SortedDictionary<int, TreeNode>();
foreach (var roles in client.GetGuild(currentSelectedGuild).Roles)
{
if (roles.IsHoisted) {
if (roles.Members.Count() != 0) {
var roleName = Regex.Replace(roles.Name, @"[^\u0000-\u007F]+", string.Empty);
var node = new TreeNode(roleName);
foreach (var users in roles.Members)
{
var userName = Regex.Replace(users.Username, @"[^\u0000-\u007F]+", string.Empty);
string userNick = string.Empty;
if (users.Nickname != null)
userNick = Regex.Replace(users.Nickname, @"[^\u0000-\u007F]+", string.Empty);
node.Children.Add(new TreeNode($"{userName}#{users.Discriminator} ({userNick})"));
}
rolesDict.TryAdd(Math.Abs(roles.Position - client.GetGuild(currentSelectedGuild).Roles.Count()), node);
}
}
}
foreach (var role in rolesDict)
{
userListTree.AddObject(role.Value);
}
if (settings.EnableRichPresence) {
rpcClient.UpdateState($"In channel {client.GetGuild(currentSelectedGuild).GetTextChannel(currentSelectedChannel).Name}");
rpcClient.UpdateStartTime();
}
} catch(Exception err) {
Console.WriteLine(err);
await chatBoxList.SetSourceAsync(new List<string>());
}
};
messageBoxSend.Clicked += async () =>
{
var restSharpClient = new RestClient("https://discord.com/api/v9"); var restSharpClient = new RestClient("https://discord.com/api/v9");
var restSharpReq = new RestRequest($"channels/{currentSelectedChannel}/messages"); var restSharpReq = new RestRequest($"channels/{currentSelectedChannel}/messages");
restSharpClient.AddDefaultHeader("Authorization", settings.Token); restSharpClient.AddDefaultHeader("Authorization", settings.Token);
restSharpReq.AddJsonBody(new { content = Encoding.UTF8.GetString(messageBoxText.Text.ToByteArray()) });
await restSharpClient.PostAsync<List<object>>(restSharpReq); var response = await restSharpClient.GetAsync<List<GetMessagesResponse>>(restSharpReq);
messageBoxText.Text = ""; var messages = new List<string>();
};
chatBoxList.OpenSelectedItem += args => foreach (var msg in response)
{ {
if (currentChannelMessages[args.Item].Split(" | ")[1].Contains("http")) var msgNewLines = msg.content.Split("\n").ToList();
for (var i = 0; i < currentChannelMessages[args.Item].Split(" | ")[1].Split(" ").Count(); i++)
if (currentChannelMessages[args.Item].Split(" | ")[1].Split(" ")[i].Contains("http"))
{
var procStartInfo = new ProcessStartInfo("/bin/sh",
$"-c \"xdg-open {currentChannelMessages[args.Item].Split(" | ")[1].Split(" ")[i]}\"")
{
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
UseShellExecute = false
};
var proc = new Process(); var firstMsg = msgNewLines[0];
proc.StartInfo = procStartInfo;
proc.Start();
}
};
Application.Top.KeyPress += async args => msgNewLines.RemoveAt(0);
{ msgNewLines.Reverse();
switch (ShortcutHelper.GetModifiersKey(args.KeyEvent)) {
case Key.CtrlMask | Key.S:
serverListList.SetFocus();
break;
case Key.CtrlMask | Key.C:
channelListTree.SetFocus();
break;
case Key.CtrlMask | Key.AltMask | Key.C:
chatBoxList.SetFocus();
break;
case Key.CtrlMask | Key.U:
userListTree.SetFocus();
break;
case Key.CtrlMask | Key.Enter:
var restSharpClient = new RestClient("https://discord.com/api/v9");
var restSharpReq = new RestRequest($"channels/{currentSelectedChannel}/messages");
restSharpClient.AddDefaultHeader("Authorization", settings.Token);
restSharpReq.AddJsonBody(new { content = Encoding.UTF8.GetString(messageBoxText.Text.ToByteArray()) });
await restSharpClient.PostAsync<List<object>>(restSharpReq); messages.AddRange(msgNewLines.Select(message => $"{message}"));
messageBoxText.Text = ""; messages.Add($"{msg.author.username}#{msg.author.discriminator} | {firstMsg}");
break;
if (msg.embeds.Count != 0)
messages.Add($"{msg.author.username}#{msg.author.discriminator} | [Unable to display embed]");
if (msg.attachments.Count == 0) continue;
messages.AddRange(msg.attachments
.Select(attachment => $"{msg.author.username}#{msg.author.discriminator} | {attachment.url}")
.Select(dummy => dummy));
} }
};
window.RemoveAll(); messages.Reverse();
window.Add(serverList, channelList, messageBox, chatBox, userList);
serverList.Add(serverListList);
channelList.Add(channelListTree);
chatBox.Add(chatBoxList);
messageBox.Add(messageBoxText, messageBoxSend);
userList.Add(userListTree);
return Task.CompletedTask; await chatBoxList.SetSourceAsync(messages);
currentChannelMessages = messages;
chatBoxList.ScrollDown(currentChannelMessages.Count - chatBoxList.Bounds.Height);
chatBoxList.SelectedItem = currentChannelMessages.Count - 1;
var rolesDict = new SortedDictionary<int, TreeNode>();
foreach (var roles in client.GetGuild(currentSelectedGuild).Roles)
{
var roleName = Regex.Replace(roles.Name, @"[^\u0000-\u007F]+", string.Empty);
var node = new TreeNode(roleName);
foreach (var users in roles.Members)
{
node.Children.Add(new TreeNode($"{users.Username}#{users.Discriminator} ({users.Nickname})"));
}
rolesDict.Add(roles.Position, node);
}
foreach (var role in rolesDict)
{
userListTree.AddObject(role.Value);
}
} catch {
await chatBoxList.SetSourceAsync(new List<string>());
}
}; };
client.MessageReceived += async msg => messageBoxSend.Clicked += async () =>
{ {
if (msg.Channel.Id != currentSelectedChannel) return;
var restSharpClient = new RestClient("https://discord.com/api/v9"); var restSharpClient = new RestClient("https://discord.com/api/v9");
var restSharpReq = new RestRequest($"channels/{currentSelectedChannel}/messages"); var restSharpReq = new RestRequest($"channels/{currentSelectedChannel}/messages");
restSharpReq.AddQueryParameter("limit", "1");
restSharpClient.AddDefaultHeader("Authorization", settings.Token); restSharpClient.AddDefaultHeader("Authorization", settings.Token);
restSharpReq.AddJsonBody(new { content = Encoding.UTF8.GetString(messageBoxText.Text.ToByteArray()) });
var response = await restSharpClient.GetAsync<List<GetMessagesResponse>>(restSharpReq); await restSharpClient.PostAsync<List<object>>(restSharpReq);
currentChannelMessages.Add( messageBoxText.Text = "";
$"{response.First().author.username}#{response.First().author.discriminator} | {response.First().content}");
await chatBoxList.SetSourceAsync(currentChannelMessages);
chatBoxList.ScrollDown(currentChannelMessages.Count - chatBoxList.Bounds.Height);
chatBoxList.SelectedItem = currentChannelMessages.Count - 1;
}; };
Application.MainLoop.AddTimeout(TimeSpan.FromMilliseconds(100), caller => { chatBoxList.OpenSelectedItem += args =>
if (settings.EnableRichPresence) {
rpcClient.Invoke(); if (currentChannelMessages[args.Item].Split(" | ")[1].Contains("http"))
return true; for (var i = 0; i < currentChannelMessages[args.Item].Split(" | ")[1].Split(" ").Count(); i++)
}); if (currentChannelMessages[args.Item].Split(" | ")[1].Split(" ")[i].Contains("http"))
{
var procStartInfo = new ProcessStartInfo("/bin/sh",
$"-c \"xdg-open {currentChannelMessages[args.Item].Split(" | ")[1].Split(" ")[i]}\"")
{
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true,
UseShellExecute = false
};
var proc = new Process();
proc.StartInfo = procStartInfo;
proc.Start();
}
};
Application.Top.KeyPress += async args =>
{
switch (ShortcutHelper.GetModifiersKey(args.KeyEvent)) {
case Key.CtrlMask | Key.S:
serverListList.SetFocus();
break;
case Key.CtrlMask | Key.C:
channelListTree.SetFocus();
break;
case Key.CtrlMask | Key.AltMask | Key.C:
chatBoxList.SetFocus();
break;
case Key.CtrlMask | Key.U:
userListTree.SetFocus();
break;
case Key.CtrlMask | Key.Enter:
var restSharpClient = new RestClient("https://discord.com/api/v9");
var restSharpReq = new RestRequest($"channels/{currentSelectedChannel}/messages");
restSharpClient.AddDefaultHeader("Authorization", settings.Token);
restSharpReq.AddJsonBody(new { content = Encoding.UTF8.GetString(messageBoxText.Text.ToByteArray()) });
await restSharpClient.PostAsync<List<object>>(restSharpReq);
messageBoxText.Text = "";
break;
}
};
Application.Top.Add(window, menuBar); Application.Top.Add(window, menuBar);
window.Add(loadingLabel); window.Add(serverList, channelList, messageBox, chatBox, userList);
serverList.Add(serverListList);
channelList.Add(channelListTree);
chatBox.Add(chatBoxList);
messageBox.Add(messageBoxText, messageBoxSend);
userList.Add(userListTree);
Application.Run(); return Task.CompletedTask;
Application.Shutdown(); };
client.MessageReceived += async msg =>
{
if (msg.Channel.Id != currentSelectedChannel) return;
var restSharpClient = new RestClient("https://discord.com/api/v9");
var restSharpReq = new RestRequest($"channels/{currentSelectedChannel}/messages");
restSharpReq.AddQueryParameter("limit", "1");
restSharpClient.AddDefaultHeader("Authorization", settings.Token);
var response = await restSharpClient.GetAsync<List<GetMessagesResponse>>(restSharpReq);
currentChannelMessages.Add(
$"{response.First().author.username}#{response.First().author.discriminator} | {response.First().content}");
await chatBoxList.SetSourceAsync(currentChannelMessages);
chatBoxList.ScrollDown(currentChannelMessages.Count - chatBoxList.Bounds.Height);
chatBoxList.SelectedItem = currentChannelMessages.Count - 1;
};
Application.MainLoop.AddTimeout(TimeSpan.FromMilliseconds(100), caller => true);
Application.Run();
Application.Shutdown();
} catch (System.Exception err) { } catch (System.Exception err) {
Console.WriteLine(err); Console.WriteLine(err);
Application.Shutdown();
} }
} }
@ -475,7 +426,6 @@ namespace chord
public class Settings public class Settings
{ {
public string Token { get; set; } public string Token { get; set; }
public bool EnableRichPresence { get; set; }
} }
public class GetMessagesResponse public class GetMessagesResponse

2
TODO
View file

@ -3,6 +3,6 @@
- Convert message attachments to links (DONE) - Convert message attachments to links (DONE)
- Sort Channels by catagories (DONE) - Sort Channels by catagories (DONE)
- DMs - DMs
- Loading Screen (DONE) - Loading Screen
- Hotkeys (Partially Done. Still some weird stuff that happens that idfk why happens) - Hotkeys (Partially Done. Still some weird stuff that happens that idfk why happens)
- User roles sorting (DONE) - User roles sorting (DONE)

View file

@ -23,7 +23,6 @@
<ItemGroup> <ItemGroup>
<PackageReference Include="Discord.Net.Labs" Version="3.5.0" /> <PackageReference Include="Discord.Net.Labs" Version="3.5.0" />
<PackageReference Include="DiscordRichPresence" Version="1.0.175" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" /> <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="6.0.0" />