Skip to content

Commit

Permalink
Remove WebHooks implementation. Add Discord bot for the connection ha…
Browse files Browse the repository at this point in the history
…ndler. Removed unused files. update json objects and settings
  • Loading branch information
GeoSaffer committed Mar 28, 2019
1 parent 805e863 commit 971d74f
Show file tree
Hide file tree
Showing 17 changed files with 221 additions and 644 deletions.
75 changes: 75 additions & 0 deletions Post-It/Bot/DiscordBot.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Discord.WebSocket;

namespace Post_It.Bot
{
public class DiscordBot
{
#region private

private DiscordSocketClient _client;
private readonly string _token;
private bool _isReady;

#endregion

#region public
public bool IsReady => _isReady;
public DiscordSocketClient Client => _client;
#endregion

public DiscordBot(string token)
{
_token = token;
}

internal void Run()
{
//setup the client
_client = new DiscordSocketClient(new DiscordSocketConfig
{
LogLevel = LogSeverity.Debug
});

//Setup events
_client.Ready += OnClientOnReady;
_client.Connected += OnClientOnConnected;
_client.Disconnected += OnClientOnDisconnected;
_client.Log += OnClientOnLog;

//Login
_client.LoginAsync(TokenType.Bot, _token);
_client.StartAsync();
}

private async Task OnClientOnLog(LogMessage l)
{
Debug.WriteLine(l.Message);
}

private async Task OnClientOnDisconnected(Exception e)
{
_isReady = false;
Debug.WriteLine("Bot Disconnected");
}

private async Task OnClientOnConnected()
{
Debug.WriteLine("Bot Connected");
}

private async Task OnClientOnReady()
{
_isReady = true;
}


}
}
3 changes: 1 addition & 2 deletions Post-It/MainWindow.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,12 @@
<Grid.ColumnDefinitions>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<ComboBox x:Name="cmbChannelPicker" HorizontalAlignment="Left" Width="120" Margin="28,57,0,0" SelectionChanged="CmbColorPicker_SelectionChanged" Height="22" VerticalAlignment="Top">
<ComboBox x:Name="cmbChannelPicker" HorizontalAlignment="Left" Width="120" Margin="28,57,0,0" SelectionChanged="CmbChanelPicker_SelectionChanged" Height="22" VerticalAlignment="Top">
</ComboBox>
<Label Content="Title" HorizontalAlignment="Left" Height="24" Margin="28,87,0,0" VerticalAlignment="Top" Width="61"/>
<TextBox x:Name="TxtTitle" MaxLength="250" Margin="28,116,30,0" TextWrapping="Wrap" Text="" RenderTransformOrigin="0.496,0.522" Height="56" VerticalAlignment="Top" />
<Label Content="MessageBody" HorizontalAlignment="Left" Height="29" Margin="28,197,0,0" VerticalAlignment="Top" Width="93"/>
<TextBox x:Name="TxtMessage" MaxLength="2000" Margin="28,226,30,163" TextWrapping="Wrap" AcceptsReturn="True" Text="" RenderTransformOrigin="0.496,0.522"/>
<ComboBox Visibility="Hidden" x:Name="CmbColorPicker" HorizontalAlignment="Left" Width="120" Margin="28,0,0,39" SelectionChanged="CmbColorPicker_SelectionChanged" Height="20" VerticalAlignment="Bottom"/>
<Button Content="Send Message" Margin="0,0,30,39" Click="Button_Click" HorizontalAlignment="Right" Width="158" Height="38" VerticalAlignment="Bottom"/>
<Label Content="Channel" HorizontalAlignment="Left" Height="24" Margin="28,31,0,0" VerticalAlignment="Top" Width="84"/>
<Label Content="Colour" HorizontalAlignment="Left" Margin="28,0,0,113" Width="93" Height="27" VerticalAlignment="Bottom"/>
Expand Down
206 changes: 123 additions & 83 deletions Post-It/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,41 +4,58 @@
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Discord.Commands;
using Discord.WebSocket;
using DiscordWebhook;
using Embed = DiscordWebhook.Embed;
using Embed = Discord.Embed;
using Uri = System.Uri;
using static Post_It.WebHooks.Extensions;
using Post_It.Models;
using System.IO;
using Post_It.Utils;
using System;
using System.Diagnostics;
using System.Linq;
using System.Windows.Threading;
using Discord;
using Post_It.Bot;
using Color = Discord.Color;

namespace Post_It
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private Discord.Color Color { get; set; }
private DiscordSocketClient _client;
private CommandService _commands;
private string _defaultImageUrl = "http://i.imgur.com/XLgutLX.png";

private string imageFolderLocation;


private string _selectedImagePath;
private string _fileName;
private readonly DiscordSocketClient _client;
private string _serverName;
private string _botToken;
private SocketGuild _guild;
private IReadOnlyCollection<SocketTextChannel> _channels;
private SocketTextChannel _selectedChannel;

public MainWindow()
{
InitializeComponent();
GetSettings();
//start bot
var bot = new DiscordBot(_botToken);
bot.Run();
_client = bot.Client;
_client.Ready += OnClientOnReady;
}

#region Onload
private Task OnClientOnReady()
{
//get guild and channels
_guild = _client.Guilds.Single(g => g.Name == _serverName);
_channels = _guild.TextChannels;

PopulateChannelDropdown();

return Task.CompletedTask;
}

private Settings GetSettings()
private void GetSettings()
{
var settings = new Settings();
try
{
var settingsFile = myFiles.Json.Settings;
Expand All @@ -49,97 +66,130 @@ private Settings GetSettings()

if (File.Exists(settingsFile))
{
settings = JsonFile.Load<Settings>(settingsFile);
imageFolderLocation = settings.ImageFolderLocation;
PopulateChannelDropdown(settings);
var settings = JsonFile.Load<Settings>(settingsFile);
_serverName = settings.ServerName;
_botToken = settings.BotToken;
}
}
catch (Exception e)
{

Debug.WriteLine(e);
DumpFile.Create(e);
throw;
}
return settings;
}

private void PopulateChannelDropdown(Settings settings)
private void PopulateChannelDropdown()
{
foreach (var channel in settings.DiscordChannels)
try
{
var item = new ComboBoxItem()
Dispatcher.Invoke(new Action(() =>
{
Content = channel.Name,
Tag = channel.Webhook
};
cmbChannelPicker.Items.Add(item);
var channelItems = _channels
.Select(s => new ComboBoxItem
{
Content = (s.Category == null ? $"{s.Name} " : $"({s.Category?.Name}) {s.Name} "), Tag = s.Id
})
.OrderBy(o => o.Content).ToList();

channelItems.ForEach(item => cmbChannelPicker.Items.Add(item));
}), DispatcherPriority.ContextIdle);

}
catch (Exception e)
{
Debug.WriteLine(e);
DumpFile.Create(e);
throw;
}


}
#endregion

private void Button_Click(object sender, RoutedEventArgs e)
private async void Button_Click(object sender, RoutedEventArgs e)
{
SendMessage();
await SendMessage();
}

private void UseTitle(Embed myEmbed)

#region EmbedBuilder
private void UseTitle(EmbedBuilder myEmbed)
{
myEmbed.Title = TxtTitle.Text;
}

private void UseMessage(Embed myEmbed)
private void UseMessage(EmbedBuilder myEmbed)
{
myEmbed.Description = TxtMessage.Text;
}

private void UseThumbnail(Embed myEmbed)
private void UseThumbnail(EmbedBuilder myEmbed)
{
var thumb = new DiscordWebhook.EmbedThumbnail();
thumb.Url = EmbedImage.Source.ToString();
myEmbed.Thumbnail = thumb;
myEmbed.ThumbnailUrl = $"attachment://{_fileName}";
}

private List<Embed> CheckWhatToSend()
private Embed CheckWhatToSend()
{
//create new Embed
var myEmbed = new Embed();
var myEmbed = new EmbedBuilder();

//check if we cshould add a title
//check if we should add a title
if (!string.IsNullOrEmpty(TxtTitle.Text))
UseTitle(myEmbed);

//check if we should add a message
if (!string.IsNullOrEmpty(TxtMessage.Text))
UseMessage(myEmbed);

//check if we should add a thumbnail
if (EmbedImage.Source.ToString() != _defaultImageUrl)
if (_selectedImagePath != null)
UseThumbnail(myEmbed);

//assign the colour for the Embed
myEmbed.Color = SelectedColour.Fill.ToString().FromHexString();
//assign the color for the Embed
myEmbed.Color = new Color(SelectedColour.Fill.ToString().FromHexString());

//Add Embeds to list
var embeds = new List<Embed>();
embeds.Add(myEmbed);
return embeds;
// add footer
myEmbed.Footer = new EmbedFooterBuilder()
{
Text = "....created by 'Post It on Discord'"
};

//build and return embed
return myEmbed.Build();
}
#endregion

private async Task SendMessage()
{
var embeds = CheckWhatToSend();
if (embeds.Count > 0)
if (_selectedChannel != null)
{
var selectedChannelWebhook = ((ComboBoxItem)cmbChannelPicker.SelectedItem)?.Tag.ToString();
if (!string.IsNullOrEmpty(selectedChannelWebhook))
var embed = CheckWhatToSend();
try
{
//create new webhook
var newHook = new Webhook($"{selectedChannelWebhook}");
newHook.Content = string.Empty;
newHook.Username = "Grumpy";
newHook.Embeds = embeds;
await newHook.Send();
if (embed.Thumbnail == null)
{
await _selectedChannel.SendMessageAsync(null, false, embed);
}
else
{
await _selectedChannel.SendFileAsync(_selectedImagePath,string.Empty, false, embed, RequestOptions.Default);
}

MessageBox.Show(this, "Message sent to Discord.");
}
catch (Exception e)
{
Debug.WriteLine(e);
DumpFile.Create(e);
throw;
}
}
else
{
MessageBox.Show(this,"Please select a channel to continue.", "Select Channel",MessageBoxButton.OK,MessageBoxImage.Exclamation);
}

}


#region colour button events
private void BtnRed_Click(object sender, RoutedEventArgs e)
Expand Down Expand Up @@ -172,16 +222,11 @@ private void BtnBlack_Click(object sender, RoutedEventArgs e)
SelectedColour.Fill = new SolidColorBrush(Colors.Black);
}

private void CmbColorPicker_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
Color = Discord.Color.Blue;
}

#endregion

private void ImageButton_Click(object sender, RoutedEventArgs e)
{
//TODO: use impersonation to get network drives visibility
//TODO: if important...... use impersonation to get network drives visibility
var dlg = new Microsoft.Win32.OpenFileDialog
{
// Set filter for file extension and default file extension
Expand All @@ -195,23 +240,18 @@ private void ImageButton_Click(object sender, RoutedEventArgs e)
// Get the selected file name and display in a TextBox
if (result == true)
{
if (dlg.FileName.ToLower().Contains("http://") || dlg.FileName.ToLower().Contains("https://"))
{
if (CheckImageFromUrlExist(dlg.FileName))
{
EmbedImage.Source = new BitmapImage(new Uri(dlg.FileName));
}
}
else
{
var filename = dlg.SafeFileName;
var myWebPath = $"{imageFolderLocation}/{filename}";
if (CheckImageFromUrlExist(myWebPath))
{
EmbedImage.Source = new BitmapImage(new Uri(myWebPath));
}
}
_fileName = dlg.SafeFileName;
_selectedImagePath = dlg.FileName;
EmbedImage.Source = new BitmapImage(new Uri(_selectedImagePath));
}
}

private void CmbChanelPicker_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var tag = ((ComboBoxItem) cmbChannelPicker.SelectedItem)?.Tag;
if (tag == null) return;
var channelId = (ulong) tag;
_selectedChannel = _channels.Single(c => c.Id == channelId);
}
}
}
Loading

0 comments on commit 971d74f

Please sign in to comment.