Added the ability to recieve messages

This commit is contained in:
ION606
2023-03-12 14:42:15 -04:00
parent 7d2f847f44
commit 032e1de330
10 changed files with 2777 additions and 80 deletions
+42 -13
View File
@@ -50,10 +50,13 @@ namespace Discord_Client_Custom.Channels
private static string? cownerId; private static string? cownerId;
private string lastSent; private string lastSent;
private static System.Threading.Timer typingTimer; private static System.Threading.Timer typingTimer;
private int msgIndex;
private RichTextBox txtbx;
public ChannelObj() { } public ChannelObj() { }
//For displaying information //For displaying information
public ChannelObj(JsonNode contents) public ChannelObj(JsonNode contents)
{ {
@@ -173,8 +176,10 @@ namespace Discord_Client_Custom.Channels
return; return;
} }
msgIndex = i;
//Add the text box //Add the text box
var txtbx = new RichTextBox(); txtbx = new RichTextBox();
txtbx.AutoWordSelection = true; txtbx.AutoWordSelection = true;
txtbx.Size = new Size(dmFlowContent.Width - 50, 50); txtbx.Size = new Size(dmFlowContent.Width - 50, 50);
txtbx.KeyDown += async (object o, KeyEventArgs k) => txtbx.KeyDown += async (object o, KeyEventArgs k) =>
@@ -185,7 +190,8 @@ namespace Discord_Client_Custom.Channels
if (ctype == 1) if (ctype == 1)
{ {
ep = "https://discord.com/api/channels/" + cid2 + "/messages"; ep = "https://discord.com/api/channels/" + cid2 + "/messages";
} else }
else
{ {
//Deal with group message stuff here..... //Deal with group message stuff here.....
Debug.WriteLine("Message Sending has not been implemented for group DMs (yet)"); Debug.WriteLine("Message Sending has not been implemented for group DMs (yet)");
@@ -203,16 +209,9 @@ namespace Discord_Client_Custom.Channels
//arr[0] = response; //arr[0] = response;
//Add the message to chat in the app //Add the message to chat in the app
groupedMsgs.Add(new ChannelMsgGroup(response, dmFlowContent, uMainIcon, i + 1)); insertMessage(dmFlowContent, uMainIcon, response);
txtbx.Clear(); }
typingTimer.Dispose(); else
i++;
dmFlowContent.Controls.Remove(txtbx);
dmFlowContent.Controls.Add(txtbx, 1, i + 1);
dmFlowContent.SetColumnSpan(txtbx, 2);
dmFlowContent.ScrollControlIntoView(txtbx);
} else
{ {
//Do typing intent stuff here //Do typing intent stuff here
string ep; string ep;
@@ -244,6 +243,36 @@ namespace Discord_Client_Custom.Channels
} }
public async void insertMessage(TableLayoutPanel dmFlowContent, string iconUrl, JsonNode? response)
{
Image avatar = (Image)(new Bitmap(await ChannelObj.getIconStream(iconUrl), new Size(32, 32)));
avatar.Tag = iconUrl;
insertMessage(dmFlowContent, avatar, response, true);
}
//Response is the new message in Json format
public void insertMessage(TableLayoutPanel dmFlowContent, Image uMainIcon, JsonNode? response, bool isCalledFromHelper = true)
{
groupedMsgs.Add(new ChannelMsgGroup(response, dmFlowContent, uMainIcon, msgIndex + 1));
txtbx.Clear();
if (typingTimer != null) typingTimer.Dispose();
msgIndex += 2;
var temptxtbxtxt = "";
if (isCalledFromHelper) temptxtbxtxt = new string(txtbx.Text);
dmFlowContent.Controls.Remove(txtbx);
dmFlowContent.Controls.Add(txtbx, 1, msgIndex);
dmFlowContent.SetColumnSpan(txtbx, 2);
txtbx.AppendText(temptxtbxtxt);
dmFlowContent.ScrollControlIntoView(txtbx);
}
public string getName() public string getName()
{ {
if (cname != null) if (cname != null)
@@ -291,7 +320,7 @@ namespace Discord_Client_Custom.Channels
var imgRaw = await getIconStream(iconUrl); var imgRaw = await getIconStream(iconUrl);
imgRaw.Tag = iconUrl; imgRaw.Tag = iconUrl;
return (Image)(new Bitmap(imgRaw, new Size(32, 32))); ; return (Image)(new Bitmap(imgRaw, new Size(32, 32)));
//string rootPath = @"C:\DownloadedImageFromUrl"; //string rootPath = @"C:\DownloadedImageFromUrl";
//string fileName = System.IO.Path.Combine(rootPath, "test.gif"); //string fileName = System.IO.Path.Combine(rootPath, "test.gif");
+71 -22
View File
@@ -4,8 +4,8 @@ using System.Reactive.Linq;
using System.Text.Json.Nodes; using System.Text.Json.Nodes;
using Websocket.Client; using Websocket.Client;
using Discord_Client_Custom.client_internals; using Discord_Client_Custom.client_internals;
using Discord_Client_Custom.Channels;
using System.ComponentModel;
namespace Discord_Client_Custom.Connections namespace Discord_Client_Custom.Connections
{ {
@@ -19,6 +19,8 @@ namespace Discord_Client_Custom.Connections
private WebsocketClient WS; private WebsocketClient WS;
private GateWayIntents intents; private GateWayIntents intents;
public JsonNode uInfoRaw; public JsonNode uInfoRaw;
private object gateWayProperties;
private readonly mainPage pageRef;
private async void heartBeat(object o) private async void heartBeat(object o)
@@ -28,6 +30,7 @@ namespace Discord_Client_Custom.Connections
WS.Send(toSend); WS.Send(toSend);
heartBeatCounter++; heartBeatCounter++;
Debug.WriteLine("PING");
} }
@@ -37,6 +40,13 @@ namespace Discord_Client_Custom.Connections
heartBeatInterval = (int)confObj["d"]["heartbeat_interval"]; heartBeatInterval = (int)confObj["d"]["heartbeat_interval"];
Debug.WriteLine("INTERVAL SET TO: " + heartBeatInterval.ToString()); Debug.WriteLine("INTERVAL SET TO: " + heartBeatInterval.ToString());
gateWayProperties = new
{
os = "linux",
browser = "ion_",
device = "my_library"
};
var idObj = new var idObj = new
{ {
op = 2, op = 2,
@@ -44,12 +54,7 @@ namespace Discord_Client_Custom.Connections
{ {
token = MsgRequests.userToken, token = MsgRequests.userToken,
intents = intents.value, //61440, intents = intents.value, //61440,
properties = new properties = gateWayProperties
{
os = "linux",
browser = "my_library",
device = "my_library"
}
} }
}; };
@@ -60,18 +65,49 @@ namespace Discord_Client_Custom.Connections
} }
private static void statusUpdate(object statusObj) private void getStatusUpdate(object statusObj)
{ {
//Console.WriteLine(statusObj.ToString() + "\n\n"); //Console.WriteLine(statusObj.ToString() + "\n\n");
} }
private static void messageEvent(object msgObj) //{"t":"MESSAGE_CREATE","s":3,"op":0,"d":{"type":0,"tts":false,"timestamp":"2023-03-12T16:13:52.238000+00:00","referenced_message":null,"pinned":false,"nonce":"1084509575685603328","mentions":[],"mention_roles":[],"mention_everyone":false,"id":"1084509576445042838","flags":0,"embeds":[],"edited_timestamp":null,"content":"ping","components":[],"channel_id":"907088809169158164","author":{"username":"1.1.5","public_flags":0,"id":"720349017829015633","display_name":null,"discriminator":"4592","avatar_decoration":null,"avatar":null},"attachments":[]}}
private void messageEvent(object msgObj)
{ {
Console.WriteLine(msgObj.ToString() + "\n\n"); pageRef.insertMessageObj(msgObj);
} }
public async Task<JsonNode> connect(FlowLayoutPanel dmFlowPannel)
private bool isRunning(bool printToDebug = false)
{
if (printToDebug) Debug.WriteLine("WEBSOCKET SERVER IS RUNNING? " + WS.IsRunning.ToString());
return WS.IsRunning;
}
// Setters
// https://discord.com/developers/docs/topics/gateway-events#update-presence
public async void setStatusUpdate(string status)
{
var idObj = new
{
op = 3,
d = new
{
since = 0,
activities = new object[0],
status = status,
afk = false
}
};
var objToSend = System.Text.Json.JsonSerializer.Serialize(idObj);
WS.Send(objToSend);
}
public async void connect(FlowLayoutPanel dmFlowPannel)
{ {
using (var client = new WebsocketClient(gateWayUrl)) using (var client = new WebsocketClient(gateWayUrl))
{ {
@@ -89,6 +125,7 @@ namespace Discord_Client_Custom.Connections
{ {
var configs = JsonNode.Parse(msg.Text); var configs = JsonNode.Parse(msg.Text);
//var c = new Client(configs["d"], dmFlowPannel); //var c = new Client(configs["d"], dmFlowPannel);
Debug.WriteLine("\n\nlhkdsfgjhdsgfhsjdgf\n\n");
uInfoRaw = configs["d"]; uInfoRaw = configs["d"];
}); });
@@ -97,10 +134,18 @@ namespace Discord_Client_Custom.Connections
{ {
var msgObj = JsonNode.Parse(msg.Text); var msgObj = JsonNode.Parse(msg.Text);
return ((string)msgObj["t"] == "PRESENCE_UPDATE"); return ((string)msgObj["t"] == "PRESENCE_UPDATE");
}).Subscribe(statusUpdate); }).Subscribe(getStatusUpdate);
// client.MessageReceived.Subscribe(msg => Debug.WriteLine($"Message received: {msg}")); //client.MessageReceived.Subscribe(msg => Console.WriteLine($"Message received: {msg}"));
/*client.MessageReceived.Where(msg =>
{
var msgObj = JsonNode.Parse(msg.Text);
if (msgObj["t"] != null) return msgObj["t"].ToString() != "READY";
else return true;
}).Subscribe((msg) => Debug.WriteLine($"Message received: {msg}"));*/
client.MessageReceived.Where((msg) => client.MessageReceived.Where((msg) =>
{ {
@@ -118,29 +163,33 @@ namespace Discord_Client_Custom.Connections
{ {
var msgObj = JsonNode.Parse(msg.Text); var msgObj = JsonNode.Parse(msg.Text);
return ((string)msgObj["t"] == "PRESENCE_UPDATE"); return ((string)msgObj["t"] == "PRESENCE_UPDATE");
}).Subscribe(statusUpdate); }).Subscribe(getStatusUpdate);
client.MessageReceived.Where((msg) => client.MessageReceived.Where((msg) =>
{ {
var msgObj = JsonNode.Parse(msg.Text); var msgObj = JsonNode.Parse(msg.Text);
return ((int)msgObj["op"] == 0) && (string)msgObj["t"] == "MESSAGE_CREATE"; return ((int)msgObj["op"] == 0) && msgObj["t"].ToString() == "MESSAGE_CREATE";
}).Subscribe(messageEvent); }).Subscribe(messageEvent);
client.DisconnectionHappened.Subscribe((info) => Debug.WriteLine(info.ToString()));
client.Start(); client.Start();
Task.Run(() => client.Send("{ message }"));
WS = client; WS = client;
//exitEvent.WaitOne(); await Task.Run(() => client.Send("{ message }"));
while (uInfoRaw == null) { } exitEvent.WaitOne();
return uInfoRaw;
//return this.uInfoRaw;
} }
} }
public Connection() { public Connection(mainPage pageRefTemp)
{
this.pageRef = pageRefTemp;
} }
} }
} }
+4 -1
View File
@@ -46,7 +46,10 @@ namespace Discord_Client_Custom.Connections
{ {
if (isDmOnly) if (isDmOnly)
{ {
GatewayIntent[] intentsTemp = { GatewayIntent.DirectMessages, GatewayIntent.DirectMessageReactions, GatewayIntent.DirectMessageTyping }; GatewayIntent[] intentsTemp = {
GatewayIntent.DirectMessages, GatewayIntent.DirectMessageReactions, GatewayIntent.DirectMessageTyping,
GatewayIntent.GuildPresences, GatewayIntent.MessageContent
};
this.intents = intentsTemp; this.intents = intentsTemp;
this.value = sum(intents); this.value = sum(intents);
} else } else
+1 -1
View File
@@ -143,7 +143,7 @@ namespace Discord_Client_Custom.Connections
return responseJSON; return responseJSON;
} }
//Returns the
public static async Task<JsonNode> getMessages(string cid, string? lastId = null) public static async Task<JsonNode> getMessages(string cid, string? lastId = null)
{ {
string newUrl = dmGetMsgsBasepath.Replace("{{id}}", cid); string newUrl = dmGetMsgsBasepath.Replace("{{id}}", cid);
+87 -20
View File
@@ -5,6 +5,7 @@ using System.Drawing.Imaging;
using Discord_Client_Custom.Channels; using Discord_Client_Custom.Channels;
using Discord_Client_Custom.Connections; using Discord_Client_Custom.Connections;
using Discord_Client_Custom.client_internals; using Discord_Client_Custom.client_internals;
using System.Runtime.CompilerServices;
namespace Discord_Client_Custom namespace Discord_Client_Custom
{ {
@@ -12,6 +13,7 @@ namespace Discord_Client_Custom
{ {
private Connection con; private Connection con;
public Client clientMain; public Client clientMain;
internal ChannelObj channelCurrent;
public mainPage() public mainPage()
{ {
@@ -27,37 +29,69 @@ namespace Discord_Client_Custom
//MessageBox.Show(cid); //MessageBox.Show(cid);
var o = await MsgRequests.getMessages(cid); var o = await MsgRequests.getMessages(cid);
var p = (mainPage)((Button)sender).Parent.Parent; var p = (mainPage)((Button)sender).Parent.Parent;
p.dmFlowContent.Tag = cid;
ChannelObj c = new ChannelObj(o, cid, p.dmFlowContent, ((Button)sender).Image, p.clientMain.getUserMain()); p.channelCurrent = new ChannelObj(o, cid, p.dmFlowContent, ((Button)sender).Image, p.clientMain.getUserMain());
} }
private async void dmFlowPannel_Paint(object sender, EventArgs e) private ComboBox createStatusBar()
{ {
var cb = new ComboBox();
} cb.Items.Add("online");
cb.Items.Add("idle");
cb.Items.Add("dnd");
cb.Items.Add("offline");
cb.SelectedIndexChanged += (object o, EventArgs a) =>
private async void dmFlowContent_Paint(object sender, EventArgs e)
{
}
private async void mainPage_Load(object sender, EventArgs e)
{
/*if (Environment.GetEnvironmentVariable("userToken") == null)
{ {
string promptValue = Prompt.ShowDialog("Please enter token", "prompt"); Debug.WriteLine("Status updated to " + cb.Text);
string s = cb.Text;
if (s == "do not disturb") s = "dnd";
else if (s == "offline") s = "invisible";
con.setStatusUpdate(s);
};
Environment.SetEnvironmentVariable("userToken", promptValue); return cb;
}*/ }
var c = new Connection();
var uInfoRaw = await c.connect(dmFlowPannel);
public void insertMessageObj(object msgObj)
{
// Threading fix
this.Invoke(delegate
{
JsonNode response = JsonNode.Parse(msgObj.ToString());
JsonNode msg = JsonNode.Parse(response["d"].ToString());
if (dmFlowContent.Tag == null || msg["channel_id"].ToString() != dmFlowContent.Tag.ToString())
{
//Debug.WriteLine(dmFlowContent.Tag + "\n" + msg["channel_id"].ToString());
//Add a notif icon on the dmFlowPannel or something
Debug.WriteLine(false);
}
else
{
user u = new user(msg["author"]);
string avatarUrl = u.getAvatar();
string iconUrl = "https://cdn.discordapp.com/avatars/" + u.getId() + "/" + u.getAvatar() + ".png?size=32";
//null user
if (avatarUrl == null)
{
iconUrl = "https://discord.com/assets/1f0bfc0865d324c2587920a7d80c609b.png";
}
channelCurrent.insertMessage(dmFlowContent, iconUrl, msg);
}
});
}
public async void start(JsonNode uInfoRaw)
{
clientMain = new Client(uInfoRaw); clientMain = new Client(uInfoRaw);
var dmsRaw = c.uInfoRaw["private_channels"].AsArray().ToArray(); // (await getChannels()).AsArray().ToArray(); var dmsRaw = con.uInfoRaw["private_channels"].AsArray().ToArray(); // (await getChannels()).AsArray().ToArray();
if (dmsRaw == null) { throw new NotImplementedException(); } if (dmsRaw == null) { throw new NotImplementedException(); }
@@ -93,7 +127,40 @@ namespace Discord_Client_Custom
dmFlowPannel.Controls.Add(btn); dmFlowPannel.Controls.Add(btn);
} }
//*/ // Add status update menu
var cb = createStatusBar();
cb.Location = new Point(5, dmFlowContent.Height + 5);
cb.SelectedText = clientMain.getUserMain().getStatus()["status"].ToString();
this.Controls.Add(cb);
}
private async void dmFlowPannel_Paint(object sender, EventArgs e)
{
}
private async void dmFlowContent_Paint(object sender, EventArgs e)
{
}
private async void mainPage_Load(object sender, EventArgs e)
{
/*if (Environment.GetEnvironmentVariable("userToken") == null)
{
string promptValue = Prompt.ShowDialog("Please enter token", "prompt");
Environment.SetEnvironmentVariable("userToken", promptValue);
}*/
con = new Connection(this);
Task.Run(() => { con.connect(dmFlowPannel); });
while (con.uInfoRaw == null) { }
start(con.uInfoRaw);
} }
} }
} }
+2541
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 149 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.3 MiB

+3
View File
@@ -48,6 +48,8 @@ namespace Discord_Client_Custom.client_internals
public userMain(JsonNode uConfigs, JsonNode uObj, JsonNode[] chnls, user[] relshnshps) { public userMain(JsonNode uConfigs, JsonNode uObj, JsonNode[] chnls, user[] relshnshps) {
customStatus = uConfigs["custom_status"]; customStatus = uConfigs["custom_status"];
customStatus["status"] = JsonNode.Parse(uConfigs["status"].ToJsonString());
locale = uConfigs["locale"].ToString(); locale = uConfigs["locale"].ToString();
theme = uConfigs["theme"].ToString(); theme = uConfigs["theme"].ToString();
@@ -71,6 +73,7 @@ namespace Discord_Client_Custom.client_internals
public Image getAvatar() { return avatar; } public Image getAvatar() { return avatar; }
public string getId() { return id; } public string getId() { return id; }
public JsonNode getStatus() { return this.customStatus; }
} }
userMain uMain; userMain uMain;
+5
View File
@@ -86,6 +86,9 @@
//this.dmFlowContent.WrapContents = true; //this.dmFlowContent.WrapContents = true;
this.Controls.Add(this.dmFlowContent); this.Controls.Add(this.dmFlowContent);
this.statusbox = new ComboBox();
this.statusbox.Location = new System.Drawing.Point(1, this.dmFlowContent.Bottom + 1);
} }
#endregion #endregion
@@ -94,5 +97,7 @@
//FFS find a way to fix this ASAP //FFS find a way to fix this ASAP
public TableLayoutPanel dmFlowContent; public TableLayoutPanel dmFlowContent;
private ComboBox statusbox;
} }
} }