private async Task OpenChannels() { InputChannel = new InputChannel( await StartChannelAsync(ServiceType.SystemInput)); /* * InputTvRemoteChannel fails when connecting non-authenticated * (Either a bug or feature from Microsoft!) * Simply disabling it for now - it serves no use anyways atm * InputTvRemoteChannel = new InputTVRemoteChannel( * await StartChannelAsync(ServiceType.SystemInputTVRemote)); */ MediaChannel = new MediaChannel( await StartChannelAsync(ServiceType.SystemMedia)); TextChannel = new TextChannel( await StartChannelAsync(ServiceType.SystemText)); BroadcastChannel = new BroadcastChannel( await StartChannelAsync(ServiceType.SystemBroadcast)); if (this.connectedAuthenticated) { InputTvRemoteChannel = new InputTVRemoteChannel( await StartChannelAsync(ServiceType.SystemInputTVRemote) ); } }
private void SpamGuild_Click(object sender, EventArgs e) { var rt = Task.Run(async delegate { foreach (string line in File.ReadAllLines("Tokens.txt")) { try { DiscordClient client = new DiscordClient(line); TextChannel channel = client.GetChannel(ulong.Parse(ChannelId.Text)).ToTextChannel(); if (Typing.Checked) { channel.TriggerTyping(); channel.SendMessage(SpamText.Text); await Task.Delay(Int32.Parse(Delay.Text)); } else { channel.SendMessage(SpamText.Text); await Task.Delay(Int32.Parse(Delay.Text)); } } catch (Exception ex) { WriteErrorLog("[Spam Guild] " + ex.ToString()); await Task.Delay(50); } } }); }
private async void UserLeft(object sender, UserEventArgs e) { foreach (var TextChannel in e.Server.TextChannels.Where(x => FeedLinks.Values.Any(y => y.TextChannel == x.Id.ToString()))) { await TextChannel.SendMessage($"Bye, {e.User.Name}!"); } }
public async Task DisplayAsync() { if (Context != null) { Message = await Context.Channel.SendMessageAsync(_actioner.Content, embed : _actioner.Embed).ConfigureAwait(false); } else if (TextChannel != null) { Message = await TextChannel.SendMessageAsync(_actioner.Content, embed : _actioner.Embed).ConfigureAwait(false); } else { Message = await Client.GetGuild(GuildId).GetTextChannel(ChannelId).SendMessageAsync(_actioner.Content, embed: _actioner.Embed).ConfigureAwait(false); } ExtendedInteractive.AddReactionCallback(Message, this); ExtendedInteractive.AddReactionRemovedCallback(Message, this); _ = Task.Run(async() => { foreach (var emoteAction in _actioner.EmoteActions) { await Message.AddReactionAsync(emoteAction.Emote); } }); if (Timeout.HasValue) { _ = Task.Delay(Timeout.Value).ContinueWith(_ => { ExtendedInteractive.RemoveReactionCallback(Message); _ = Message.DeleteAsync(); }); } }
private async Task SendMessage(string message) { if (string.IsNullOrWhiteSpace(message)) { return; } using (var releaser = await _MessageUpdateLock.LockAsync()) { try { NowSendingMessage.Value = true; var userMessage = await TextChannel.SendMessageAsync(message); SendMessageText.Value = ""; } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } finally { NowSendingMessage.Value = false; } } }
/// <summary> /// The Create Or Get Webhook finds the given channel and, when provided a name, attempts to find a webhook /// with that said name. If the webhook can not be found, it creates a new webhook in the channel with the set name. /// </summary> /// <param name="ChannelID">The Channel ID is the snowflake ID of the channel which you wish the webhook to be made in.</param> /// <param name="WebhookName">The Webhook Name is the identifier of the webhook, and is what the webhook will be called.</param> /// <returns>The DiscordWebhookClient of the webhook that has been gotten or created.</returns> public async Task <DiscordWebhookClient> CreateOrGetWebhook(ulong ChannelID, string WebhookName) { if (ChannelID > 0) { try { SocketChannel Channel = DiscordSocketClient.GetChannel(ChannelID); if (Channel is SocketTextChannel TextChannel) { foreach (RestWebhook RestWebhook in await TextChannel.GetWebhooksAsync()) { if (RestWebhook.Name.Equals(WebhookName)) { return(new DiscordWebhookClient(RestWebhook.Id, RestWebhook.Token)); } } RestWebhook Webhook = await TextChannel.CreateWebhookAsync(WebhookName, ProfileService.GetRandomPFP()); return(new DiscordWebhookClient(Webhook.Id, Webhook.Token)); } throw new Exception($"The webhook {WebhookName} could not be initialized in the given channel {Channel} due to it being of type {Channel.GetType().Name}."); } catch (HttpException) { } } return(null); }
/// <summary> /// Updates a proposal linked to a given ID, by setting its status and relevant information, modifying the linked embed. /// </summary> /// <param name="EventID">The ID of the target event to update.</param> /// <returns>A <c>Task</c> object, which can be awaited until the method completes successfully.</returns> public async Task UpdateEventProposal(int EventID) { CommunityEvent Event = GetEvent(EventID); if (Event == null) { return; } if (Event.EventType == EventType.Official) { return; } SocketChannel ProposalChannel = DiscordSocketClient.GetChannel(CommunityConfiguration.EventsNotificationsChannel); IUserMessage Proposal = null; if (ProposalChannel is SocketTextChannel TextChannel) { try { Proposal = await TextChannel.GetMessageAsync(Event.EventProposal) as IUserMessage; } catch (HttpException) { await BuildEmbed(EmojiEnum.Annoyed) .WithTitle("Failed to update event proposal") .WithDescription("The message doesn't exist anymore! Perhaps it was deleted?") .AddField("Message ID", Event.EventProposal) .SendEmbed(Context.Channel); } } if (Proposal == null) { return; } string ProposalText = Event.Status switch { EventStatus.Pending => $"**New Event Proposal >>>** {CommunityConfiguration.EventsNotificationMention}", EventStatus.Approved => $"**Upcoming Event [{DateTimeOffset.FromUnixTimeSeconds(Event.DateTimeRelease).ToOffset(TimeSpan.FromHours(BotConfiguration.StandardTimeZone)):MMM M 'at' h:mm tt}] >>>**", EventStatus.Released => $"**Released Event**", _ => $"**{Event.Status} Event Proposal >>>**" }; if (Event.Status is EventStatus.Pending or EventStatus.Approved or EventStatus.Released) { string Link = Event.Description.GetHyperLinks().FirstOrDefault(); if (Link != null && Link.Length > 0) { ProposalText += $"\n{Link}"; } } await Proposal.ModifyAsync(Properties => { Properties.Content = ProposalText; Properties.Embed = CreateEventProposalEmbed(Event).Build(); }); }
public MessagePacketOut(TextChannel chan, string msg) { UsageType = NetUsageType.GENERAL; ID = ServerToClientPacket.MESSAGE; byte[] text = FileHandler.encoding.GetBytes(msg); Data = new byte[1 + text.Length]; Data[0] = (byte)chan; text.CopyTo(Data, 1); }
static async Task Main(string[] args) { if (args.Length == 4) { guildId = ulong.Parse(args[0]); voiceChannelId = ulong.Parse(args[1]); textChannelId = ulong.Parse(args[2]); MediaFoundationApi.Startup(); Config conf = JsonConvert.DeserializeObject <Config>(File.ReadAllText(args[3])); conf.AdditionalPluginDirectories.Clear(); conf.AdditionalPluginDirectories.Add(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); BotContext context = new BotContext(conf, true) { SingleGuild = guildId }; context.LogMessage += Context_LogMessage; context.DSharpPlusLogMessage += Context_DSharpPlusLogMessage; context.Client.GuildAvailable += Client_GuildAvailable; await context.ConnectAsync().ConfigureAwait(false); while (!ready) { await Task.Delay(1000); } VoiceExtension = context.Client.UseVoiceNext(new VoiceNextConfiguration() { VoiceApplication = VoiceApplication.Music, EnableIncoming = true }); Guild = await context.Client.GetGuildAsync(guildId); Console.WriteLine(Guild); VoiceChannel = Guild.Channels.FirstOrDefault(c => c.Id == voiceChannelId); Console.WriteLine(VoiceChannel); TextChannel = Guild.Channels.FirstOrDefault(c => c.Id == textChannelId); Console.WriteLine(TextChannel); var connection = await VoiceExtension.ConnectAsync(VoiceChannel).ConfigureAwait(false); ConnectionModel = new ConnectionModel(connection); await TextChannel.SendMessageAsync($"Connected to {VoiceChannel.Name}!"); await MusicPlayLoop(TextChannel, ConnectionModel); } else { Console.WriteLine("This is an internal tool to be used by WamBot's music commands. Use outside will cause unexpected results and is not recommended."); Console.Write("Press any key to exit..."); Console.ReadKey(true); Environment.Exit(0); } }
public override bool ParseBytesAndExecute(byte[] data) { if (data.Length < 1) { return(false); } TextChannel tc = (TextChannel)data[0]; TheClient.WriteMessage(tc, FileHandler.encoding.GetString(data, 1, data.Length - 1)); return(true); }
private async Task OpenChannels() { InputChannel = new InputChannel( await StartChannelAsync(ServiceType.SystemInput)); MediaChannel = new MediaChannel( await StartChannelAsync(ServiceType.SystemMedia)); TextChannel = new TextChannel( await StartChannelAsync(ServiceType.SystemText)); BroadcastChannel = new BroadcastChannel( await StartChannelAsync(ServiceType.SystemBroadcast)); InputTvRemoteChannel = new InputTVRemoteChannel( await StartChannelAsync(ServiceType.SystemInputTVRemote)); }
public async Task TestReady() { AssertEvent( "READY never received", async() => await _targetBot.Login(), x => _targetBot.Connected += x, x => _targetBot.Connected -= x, null, true); (await _targetBot.GetGuilds()).Select(x => x.Owner.Id == _targetBot.CurrentUser.Id ? x.Delete() : x.Leave()); _testGuildChannel = _testGuild.DefaultChannel; }
private void Application_Startup(object sender, StartupEventArgs e) { string errMsg; if (!ParseCommandLineArguments(e.Args, out errMsg)) { MessageBox.Show( String.Format("{0}\nUsage: FlowDocumentXmlEditor [-xuk:<xuk_uri>]", errMsg)); this.Shutdown(-1); return; } mProject = new Project(); //MainWindow mw1 = new MainWindow(); mw2 = new MainWindow(mProject, mProjectUri); if (mProjectUri != null) { OpenXukAction action = new OpenXukAction(mProject, mProjectUri); bool wasCancelled; ProgressWindow.ExecuteProgressAction(action, out wasCancelled); if (wasCancelled) { Shutdown(-1); return; } } if (mProject.NumberOfPresentations > 0) { Presentation pres = mProject.GetPresentation(0); TextChannel textCh = null; foreach (Channel ch in pres.ChannelsManager.ListOfChannels) { if (ch is TextChannel) { textCh = (TextChannel)ch; break; } } //UrakawaHtmlFlowDocument doc1 = new UrakawaHtmlFlowDocument(pres.getRootNode(), textCh); //mw1.EditedDocument = doc1; GenericExtractionVisitor.USE_TEXT_BOX_UIELEMENT = false; UrakawaHtmlFlowDocument doc2 = new UrakawaHtmlFlowDocument(pres.RootNode, textCh); mw2.EditedDocument = doc2; } //mw1.Show(); mw2.Show(); }
public void Dispose() { // TODO: Close opened channels? // Assuming so for the time being, but don't know how to send stop messages yet InputChannel.Dispose(); // InputTvRemoteChannel.Dispose(); TextChannel.Dispose(); MediaChannel.Dispose(); BroadcastChannel.Dispose(); _sessionMessageTransport.Dispose(); _messageTransport.Dispose(); }
public void WriteMessage(TextChannel channel, string message) { UIConsole.WriteLine(channel + ": " + message); ChatMessage cm = new ChatMessage() { Channel = channel, Text = message }; ChatMessages.Add(cm); if (ChatMessages.Count > 550) { ChatMessages.RemoveRange(0, 50); } UpdateChats(); }
public override bool ParseBytesAndExecute(byte[] data) { if (data.Length < 1) { return(false); } TextChannel tc = (TextChannel)data[0]; if (tc <= TextChannel.ALWAYS || tc >= TextChannel.COUNT) { SysConsole.Output(OutputType.WARNING, "Invalid TEXTCHANEL specified: " + tc); return(false); } TheClient.WriteMessage(tc, FileHandler.encoding.GetString(data, 1, data.Length - 1)); return(true); }
protected virtual void initializeProject(string dataFolderPrefix) { m_dataFolderPrefix = dataFolderPrefix; m_Project = new Project(); m_Project.PrettyFormat = m_XukPrettyFormat; Presentation presentation = m_Project.AddNewPresentation(new Uri(m_outDirectory), dataFolderPrefix); PCMFormatInfo pcmFormat = presentation.MediaDataManager.DefaultPCMFormat; //.Copy(); pcmFormat.Data.SampleRate = (ushort)m_audioProjectSampleRate; pcmFormat.Data.NumberOfChannels = m_audioStereo ? (ushort)2 : (ushort)1; presentation.MediaDataManager.DefaultPCMFormat = pcmFormat; //presentation.MediaDataFactory.DefaultAudioMediaDataType = typeof(WavAudioMediaData); //presentation.MediaDataManager.EnforceSinglePCMFormat = true; TextChannel textChannel = presentation.ChannelFactory.CreateTextChannel(); textChannel.Name = "The Text Channel"; DebugFix.Assert(textChannel == presentation.ChannelsManager.GetOrCreateTextChannel()); AudioChannel audioChannel = presentation.ChannelFactory.CreateAudioChannel(); audioChannel.Name = "The Audio Channel"; DebugFix.Assert(audioChannel == presentation.ChannelsManager.GetOrCreateAudioChannel()); ImageChannel imageChannel = presentation.ChannelFactory.CreateImageChannel(); imageChannel.Name = "The Image Channel"; DebugFix.Assert(imageChannel == presentation.ChannelsManager.GetOrCreateImageChannel()); VideoChannel videoChannel = presentation.ChannelFactory.CreateVideoChannel(); videoChannel.Name = "The Video Channel"; DebugFix.Assert(videoChannel == presentation.ChannelsManager.GetOrCreateVideoChannel()); /*string dataPath = presentation.DataProviderManager.DataFileDirectoryFullPath; * if (Directory.Exists(dataPath)) * { * Directory.Delete(dataPath, true); * }*/ }
protected virtual void Dispose(bool disposing) { if (!_disposed) { if (disposing) { // TODO: Close opened channels? // Assuming so for the time being, but don't know how to send stop messages yet InputChannel.Dispose(); // InputTvRemoteChannel.Dispose(); TextChannel.Dispose(); MediaChannel.Dispose(); BroadcastChannel.Dispose(); _sessionMessageTransport.Dispose(); _messageTransport.Dispose(); } _disposed = true; } }
public void WriteMessage(TextChannel channel, string message) { FontSets.Standard.MeasureFancyText(message, pushStr: true); bool bottomed = ChatIsAtBottom(); UIConsole.WriteLine(channel + ": " + message); ChatMessage cm = new ChatMessage() { Channel = channel, Text = message, Sent = GlobalTickTimeLocal }; ChatMessages.Add(cm); if (ChatMessages.Count > 550) { ChatMessages.RemoveRange(0, 50); } UpdateChats(); if (bottomed) { ChatScrollToBottom(); } }
public void SendLanguageData(TextChannel channel, params string[] message) { Network.SendLanguageData(channel, message); }
static void Main() { //Create a client with the token Console.Write("Token: "); DiscordClient client = new DiscordClient(Console.ReadLine()); //find the guild Console.Write($"Guild id: "); Guild targetGuild = client.GetGuild(long.Parse(Console.ReadLine())); Guild ourGuild = DuplicateGuild(client, targetGuild); DeleteAllChannels(client, ourGuild); List<RoleDupe> ourRoles = DuplicateRoles(client, targetGuild, ourGuild); #region create channels OrganizedChannelList channels = new OrganizedChannelList(targetGuild.GetChannels()); Console.WriteLine("Duplicating categories..."); //duplicate category channels List<CategoryDupe> ourCategories = new List<CategoryDupe>(); foreach (var c in channels.Categories) { GuildChannel category; try { category = client.GetGuildChannel(c.Id); } catch (DiscordHttpErrorException e) { //ofcourse you could make it return no matter what error, but this is better for debugging if (e.Error.Code == 50001) continue; else throw; } //create the category GuildChannel ourCategory = ourGuild.CreateChannel(new ChannelCreationProperties() { Name = category.Name, Type = ChannelType.Category }); ourCategory.Modify(new GuildChannelProperties() { Position = category.Position }); foreach (var overwrite in category.PermissionOverwrites) { if (overwrite.Type == PermissionOverwriteType.Member) continue; PermissionOverwrite ourOverwrite = overwrite; ourOverwrite.Id = ourRoles.First(ro => ro.TargetRole.Id == overwrite.Id).OurRole.Id; ourCategory.AddPermissionOverwrite(ourOverwrite); } CategoryDupe dupe = new CategoryDupe { TargetCategory = category, OurCategory = ourCategory }; ourCategories.Add(dupe); Console.WriteLine($"Duplicated {category.Name}"); Thread.Sleep(50); } Console.WriteLine("Duplicating channels..."); //duplicate text channels foreach (var c in channels.TextChannels) { TextChannel channel; try { channel = client.GetTextChannel(c.Id); } catch (DiscordHttpErrorException e) { //ofcourse you could make it return no matter what error, but this is better for debugging if (e.Error.Code == 50001) continue; else throw; } TextChannel ourChannel = ourGuild.CreateTextChannel(new ChannelCreationProperties() { Name = channel.Name, ParentId = channel.ParentId != null ? (long?)ourCategories.First(ca => ca.TargetCategory.Id == channel.ParentId).OurCategory.Id : null }); ourChannel.Modify(new TextChannelProperties() { Nsfw = channel.Nsfw, Position = channel.Position, Topic = channel.Topic, SlowMode = channel.SlowMode }); foreach (var overwrite in channel.PermissionOverwrites) { if (overwrite.Type == PermissionOverwriteType.Member) continue; PermissionOverwrite ourOverwrite = overwrite; ourOverwrite.Id = ourRoles.First(ro => ro.TargetRole.Id == overwrite.Id).OurRole.Id; ourChannel.AddPermissionOverwrite(ourOverwrite); } Console.WriteLine($"Duplicated {channel.Name}"); Thread.Sleep(50); } //duplicate voice channels foreach (var c in channels.VoiceChannels) { VoiceChannel channel; try { channel = client.GetVoiceChannel(c.Id); } catch (DiscordHttpErrorException e) { //ofcourse you could make it return no matter what error, but this is better for debugging if (e.Error.Code == 50001) continue; else throw; } //create voice channels VoiceChannel ourChannel = ourGuild.CreateVoiceChannel(new ChannelCreationProperties() { Name = channel.Name, ParentId = channel.ParentId != null ? (long?)ourCategories.First(ca => ca.TargetCategory.Id == channel.ParentId).OurCategory.Id : null }); ourChannel.Modify(new VoiceChannelProperties() { Bitrate = channel.Bitrate, Position = channel.Position, UserLimit = channel.UserLimit }); foreach (var overwrite in channel.PermissionOverwrites) { if (overwrite.Type == PermissionOverwriteType.Member) continue; PermissionOverwrite ourOverwrite = overwrite; ourOverwrite.Id = ourRoles.First(ro => ro.TargetRole.Id == overwrite.Id).OurRole.Id; ourChannel.AddPermissionOverwrite(ourOverwrite); } Console.WriteLine($"Duplicated {channel.Name}"); Thread.Sleep(100); } #endregion Console.WriteLine("Done!"); Console.ReadLine(); }
private static void DuplicateChannels(Guild targetGuild, Guild ourGuild, List <RoleDupe> ourRoles) { OrganizedChannelList channels = new OrganizedChannelList(targetGuild.GetChannels()); Console.WriteLine("Duplicating categories..."); //duplicate category channels List <CategoryDupe> ourCategories = new List <CategoryDupe>(); foreach (var category in channels.Categories) { //create the category GuildChannel ourCategory = ourGuild.CreateChannel(category.Name, ChannelType.Category); ourCategory.Modify(new GuildChannelProperties() { Position = category.Position }); foreach (var overwrite in category.PermissionOverwrites) { if (overwrite.Type == PermissionOverwriteType.Member) { continue; } DiscordPermissionOverwrite ourOverwrite = overwrite; ourOverwrite.Id = ourRoles.First(ro => ro.TargetRole.Id == overwrite.Id).OurRole.Id; ourCategory.AddPermissionOverwrite(ourOverwrite); } CategoryDupe dupe = new CategoryDupe { TargetCategory = category, OurCategory = ourCategory }; ourCategories.Add(dupe); Console.WriteLine($"Duplicated {category.Name}"); } Console.WriteLine("Duplicating channels..."); //duplicate text channels foreach (var c in channels.TextChannels) { TextChannel channel = c.ToTextChannel(); TextChannel ourChannel = ourGuild.CreateChannel(channel.Name, ChannelType.Text, channel.ParentId != null ? (ulong?)ourCategories.First(ca => ca.TargetCategory.Id == channel.ParentId).OurCategory.Id : null).ToTextChannel(); ourChannel.Modify(new TextChannelProperties() { Nsfw = channel.Nsfw, Position = channel.Position, Topic = channel.Topic, SlowMode = channel.SlowMode }); foreach (var overwrite in channel.PermissionOverwrites) { if (overwrite.Type == PermissionOverwriteType.Member) { continue; } DiscordPermissionOverwrite ourOverwrite = overwrite; ourOverwrite.Id = ourRoles.First(ro => ro.TargetRole.Id == overwrite.Id).OurRole.Id; ourChannel.AddPermissionOverwrite(ourOverwrite); } Console.WriteLine($"Duplicated {channel.Name}"); } //duplicate voice channels foreach (var channel in channels.VoiceChannels) { //create voice channels VoiceChannel ourChannel = ourGuild.CreateChannel(channel.Name, ChannelType.Voice, channel.ParentId != null ? (ulong?)ourCategories.First(ca => ca.TargetCategory.Id == channel.ParentId).OurCategory.Id : null).ToVoiceChannel(); ourChannel.Modify(new VoiceChannelProperties() { Bitrate = channel.Bitrate, Position = channel.Position, UserLimit = channel.UserLimit }); foreach (var overwrite in channel.PermissionOverwrites) { if (overwrite.Type == PermissionOverwriteType.Member) { continue; } DiscordPermissionOverwrite ourOverwrite = overwrite; ourOverwrite.Id = ourRoles.First(ro => ro.TargetRole.Id == overwrite.Id).OurRole.Id; ourChannel.AddPermissionOverwrite(ourOverwrite); } Console.WriteLine($"Duplicated {channel.Name}"); } }
private void transformDTBook() { XmlDocument bookXmlDoc = readXmlDocument(m_Book_FilePath); m_Project = new Project(); //m_Project.PresentationFactory.Create(); Presentation presentation = m_Project.AddNewPresentation(); string dirPath = Path.GetDirectoryName(m_Book_FilePath); if (!dirPath.EndsWith("" + Path.DirectorySeparatorChar)) { dirPath = dirPath + Path.DirectorySeparatorChar; } presentation.RootUri = new Uri(dirPath); m_Project.SetPrettyFormat(false); // BEGIN OF TEST // => creating all kinds of objects in order to initialize the factories // and cache the mapping between XUK names (pretty or compressed) and actual types. Channel ch = presentation.ChannelFactory.Create(); presentation.ChannelsManager.RemoveChannel(ch); ch = presentation.ChannelFactory.CreateAudioChannel(); presentation.ChannelsManager.RemoveChannel(ch); ch = presentation.ChannelFactory.CreateTextChannel(); presentation.ChannelsManager.RemoveChannel(ch); // DataProvider dp = presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE); presentation.DataProviderManager.RemoveDataProvider(dp, true); // MediaData md = presentation.MediaDataFactory.CreateAudioMediaData(); presentation.MediaDataManager.RemoveMediaData(md); // presentation.CommandFactory.CreateCompositeCommand(); // presentation.MediaFactory.CreateExternalImageMedia(); presentation.MediaFactory.CreateExternalVideoMedia(); presentation.MediaFactory.CreateExternalTextMedia(); presentation.MediaFactory.CreateExternalAudioMedia(); presentation.MediaFactory.CreateManagedAudioMedia(); presentation.MediaFactory.CreateSequenceMedia(); presentation.MediaFactory.CreateTextMedia(); // presentation.MetadataFactory.CreateMetadata(); // presentation.PropertyFactory.CreateChannelsProperty(); presentation.PropertyFactory.CreateXmlProperty(); // presentation.TreeNodeFactory.Create(); // // END OF TEST /* * Metadata mdAuthor = presentation.MetadataFactory.CreateMetadata(); * mdAuthor.Name = "dc:author"; * mdAuthor.Content = "Daniel + Chhavi + Rachana"; * * presentation.AddMetadata(mdAuthor); * * Metadata mdDate = presentation.MetadataFactory.CreateMetadata(); * mdDate.Name = "dc:date"; * mdDate.Content = System.DateTime.Now.ToString(); * * presentation.AddMetadata(mdDate); */ m_textChannel = presentation.ChannelFactory.CreateTextChannel(); m_textChannel.Name = "Our Text Channel"; //FileInfo DTBFilePathInfo = new FileInfo(m_Book_FilePath); //switch (DTBFilePathInfo.Extension) int indexOfDot = m_Book_FilePath.LastIndexOf('.'); if (indexOfDot < 0 || indexOfDot == m_Book_FilePath.Length - 1) { return; } string fileExt = m_Book_FilePath.Substring(indexOfDot); switch (fileExt) { case ".opf": { parseOPFAndPopulateDataModel(); break; } case ".xml": { parseDTBookXmlDocAndPopulateDataModel(bookXmlDoc, null); break; } default: break; } }
public bool ShouldShowMessage(TextChannel channel) { return(channel == TextChannel.CHAT || channel == TextChannel.BROADCAST || channel == TextChannel.IMPORTANT); }
public void SendMessage(TextChannel channel, string message) { SendPacket(new MessagePacketOut(channel, message)); }
public async Task UserDMCommand(string Token, [Remainder] string Message) { ModMail ModMail = ModMailDB.ModMail.Find(Token); IUser User = null; if (ModMail != null) { User = DiscordSocketClient.GetUser(ModMail.UserID); } if (ModMail == null || User == null) { await BuildEmbed(EmojiEnum.Annoyed) .WithTitle("Could Not Find Token!") .WithDescription("Haiya! I couldn't find the modmail for the given token. Are you sure this exists in the database? " + "The token should be given as the footer of the embed. Make sure this is the token and not the modmail number.") .WithCurrentTimestamp() .SendEmbed(Context.Channel); } else { SocketChannel SocketChannel = DiscordSocketClient.GetChannel(ModerationConfiguration.ModMailChannelID); if (SocketChannel is SocketTextChannel TextChannel) { IMessage MailMessage = await TextChannel.GetMessageAsync(ModMail.MessageID); if (MailMessage is IUserMessage MailMSG) { try { await MailMSG.ModifyAsync(MailMSGs => MailMSGs.Embed = MailMessage.Embeds.FirstOrDefault().ToEmbedBuilder() .WithColor(Color.Green) .AddField($"Replied By: {Context.User.Username}", Message.Length > 300 ? $"{Message.Substring(0, 300)} ..." : Message) .Build() ); } catch (InvalidOperationException) { IMessage Messaged = await MailMSG.Channel.SendMessageAsync(embed : MailMSG.Embeds.FirstOrDefault().ToEmbedBuilder().Build()); ModMail.MessageID = Messaged.Id; ModMailDB.SaveChanges(); } } else { throw new Exception($"Woa, this is strange! The message required isn't a socket user message! Are you sure this message exists? ModMail Type: {MailMessage.GetType()}"); } } else { throw new Exception($"Eek! The given channel of {SocketChannel} turned out *not* to be an instance of SocketTextChannel, rather {SocketChannel.GetType().Name}!"); } await BuildEmbed(EmojiEnum.Love) .WithTitle("Modmail User DM") .WithDescription(Message) .AddField("Sent By", Context.User.GetUserInformation()) .SendDMAttachedEmbed(Context.Channel, BotConfiguration, User, BuildEmbed(EmojiEnum.Unknown) .WithTitle($"Modmail From {Context.Guild.Name}") .WithDescription(Message) .WithCurrentTimestamp() .WithFooter(Token) ); } }
public void SendLanguageData(TextChannel channel, params string[] message) { SendMessage(channel, GetLanguageData(message)); }
protected virtual void parseContentDocuments(List <string> spineOfContentDocuments, Dictionary <string, string> spineAttributes, List <Dictionary <string, string> > spineItemsAttributes, string coverImagePath, string navDocPath) { if (spineOfContentDocuments == null || spineOfContentDocuments.Count <= 0) { return; } Presentation spinePresentation = m_Project.Presentations.Get(0); spinePresentation.RootNode.GetOrCreateXmlProperty().SetQName("spine", ""); if (!string.IsNullOrEmpty(m_OPF_ContainerRelativePath)) { spinePresentation.RootNode.GetOrCreateXmlProperty().SetAttribute(OPF_ContainerRelativePath, "", m_OPF_ContainerRelativePath); } foreach (KeyValuePair <string, string> spineAttribute in spineAttributes) { spinePresentation.RootNode.GetOrCreateXmlProperty().SetAttribute(spineAttribute.Key, "", spineAttribute.Value); } if (m_PackagePrefixAttr != null) { spinePresentation.RootNode.GetOrCreateXmlProperty().SetAttribute("prefix", "", m_PackagePrefixAttr.Value); } // Audio files may be shared between chapters of a book! m_OriginalAudioFile_FileDataProviderMap.Clear(); Presentation spineItemPresentation = null; int index = -1; foreach (string docPath in spineOfContentDocuments) { index++; reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ReadXMLDoc, docPath)); //DirectoryInfo opfParentDir = Directory.GetParent(m_Book_FilePath); //string dirPath = opfParentDir.ToString(); string fullDocPath = Path.Combine(Path.GetDirectoryName(m_Book_FilePath), docPath); fullDocPath = FileDataProvider.NormaliseFullFilePath(fullDocPath).Replace('/', '\\'); if (!File.Exists(fullDocPath)) { #if DEBUG Debugger.Break(); #endif //DEBUG continue; } addOPF_GlobalAssetPath(fullDocPath); TreeNode spineChild = spinePresentation.TreeNodeFactory.Create(); TextMedia txt = spinePresentation.MediaFactory.CreateTextMedia(); txt.Text = docPath; // Path.GetFileName(fullDocPath); spineChild.GetOrCreateChannelsProperty().SetMedia(spinePresentation.ChannelsManager.GetOrCreateTextChannel(), txt); spinePresentation.RootNode.AppendChild(spineChild); spineChild.GetOrCreateXmlProperty().SetQName("metadata", ""); foreach (KeyValuePair <string, string> spineItemAttribute in spineItemsAttributes[index]) { spineChild.GetOrCreateXmlProperty().SetAttribute(spineItemAttribute.Key, "", spineItemAttribute.Value); } string ext = Path.GetExtension(fullDocPath); if (docPath == coverImagePath) { DebugFix.Assert(ext.Equals(DataProviderFactory.IMAGE_SVG_EXTENSION, StringComparison.OrdinalIgnoreCase)); spineChild.GetOrCreateXmlProperty().SetAttribute("cover-image", "", "true"); } if (docPath == navDocPath) { DebugFix.Assert( ext.Equals(DataProviderFactory.XHTML_EXTENSION, StringComparison.OrdinalIgnoreCase) || ext.Equals(DataProviderFactory.HTML_EXTENSION, StringComparison.OrdinalIgnoreCase)); spineChild.GetOrCreateXmlProperty().SetAttribute("nav", "", "true"); } if ( !ext.Equals(DataProviderFactory.XHTML_EXTENSION, StringComparison.OrdinalIgnoreCase) && !ext.Equals(DataProviderFactory.HTML_EXTENSION, StringComparison.OrdinalIgnoreCase) && !ext.Equals(DataProviderFactory.DTBOOK_EXTENSION, StringComparison.OrdinalIgnoreCase) && !ext.Equals(DataProviderFactory.XML_EXTENSION, StringComparison.OrdinalIgnoreCase) ) { DebugFix.Assert(ext.Equals(DataProviderFactory.IMAGE_SVG_EXTENSION, StringComparison.OrdinalIgnoreCase)); bool notExistYet = true; foreach (ExternalFiles.ExternalFileData externalFileData in m_Project.Presentations.Get(0).ExternalFilesDataManager.ManagedObjects.ContentsAs_Enumerable) { if (!string.IsNullOrEmpty(externalFileData.OriginalRelativePath)) { bool notExist = docPath != externalFileData.OriginalRelativePath; notExistYet = notExistYet && notExist; if (!notExist) { break; } } } DebugFix.Assert(notExistYet); if (notExistYet) { ExternalFiles.ExternalFileData externalData = null; if (docPath == coverImagePath) { externalData = m_Project.Presentations.Get(0).ExternalFilesDataFactory.Create <ExternalFiles.CoverImageExternalFileData>(); } else { externalData = m_Project.Presentations.Get(0).ExternalFilesDataFactory.Create <ExternalFiles.GenericExternalFileData>(); } if (externalData != null) { externalData.InitializeWithData(fullDocPath, docPath, true, null); addOPF_GlobalAssetPath(fullDocPath); } } continue; } spineChild.GetOrCreateXmlProperty().SetAttribute("xuk", "", "true"); XmlDocument xmlDoc = XmlReaderWriterHelper.ParseXmlDocument(fullDocPath, true, true); if (RequestCancellation) { return; } m_PublicationUniqueIdentifier = null; m_PublicationUniqueIdentifierNode = null; Project spineItemProject = new Project(); spineItemProject.PrettyFormat = m_XukPrettyFormat; string dataFolderPrefix = FileDataProvider.EliminateForbiddenFileNameCharacters(docPath); spineItemPresentation = spineItemProject.AddNewPresentation(new Uri(m_outDirectory), //Path.GetFileName(fullDocPath) dataFolderPrefix ); PCMFormatInfo pcmFormat = spineItemPresentation.MediaDataManager.DefaultPCMFormat; //.Copy(); pcmFormat.Data.SampleRate = (ushort)m_audioProjectSampleRate; pcmFormat.Data.NumberOfChannels = m_audioStereo ? (ushort)2 : (ushort)1; spineItemPresentation.MediaDataManager.DefaultPCMFormat = pcmFormat; //presentation.MediaDataManager.EnforceSinglePCMFormat = true; //presentation.MediaDataFactory.DefaultAudioMediaDataType = typeof(WavAudioMediaData); TextChannel textChannel = spineItemPresentation.ChannelFactory.CreateTextChannel(); textChannel.Name = "The Text Channel"; DebugFix.Assert(textChannel == spineItemPresentation.ChannelsManager.GetOrCreateTextChannel()); AudioChannel audioChannel = spineItemPresentation.ChannelFactory.CreateAudioChannel(); audioChannel.Name = "The Audio Channel"; DebugFix.Assert(audioChannel == spineItemPresentation.ChannelsManager.GetOrCreateAudioChannel()); ImageChannel imageChannel = spineItemPresentation.ChannelFactory.CreateImageChannel(); imageChannel.Name = "The Image Channel"; DebugFix.Assert(imageChannel == spineItemPresentation.ChannelsManager.GetOrCreateImageChannel()); VideoChannel videoChannel = spineItemPresentation.ChannelFactory.CreateVideoChannel(); videoChannel.Name = "The Video Channel"; DebugFix.Assert(videoChannel == spineItemPresentation.ChannelsManager.GetOrCreateVideoChannel()); /*string dataPath = presentation.DataProviderManager.DataFileDirectoryFullPath; * if (Directory.Exists(dataPath)) * { * Directory.Delete(dataPath, true); * }*/ //AudioLibPCMFormat previousPcm = null; if (m_AudioConversionSession != null) { //previousPcm = m_AudioConversionSession.FirstDiscoveredPCMFormat; RemoveSubCancellable(m_AudioConversionSession); m_AudioConversionSession = null; } m_AudioConversionSession = new AudioFormatConvertorSession( //AudioFormatConvertorSession.TEMP_AUDIO_DIRECTORY, spineItemPresentation.DataProviderManager.DataFileDirectoryFullPath, spineItemPresentation.MediaDataManager.DefaultPCMFormat, m_autoDetectPcmFormat, m_SkipACM); //if (previousPcm != null) //{ // m_AudioConversionSession.FirstDiscoveredPCMFormat = previousPcm; //} AddSubCancellable(m_AudioConversionSession); TreenodesWithoutManagedAudioMediaData = new List <TreeNode>(); //foreach (var key in m_OriginalAudioFile_FileDataProviderMap.Keys) //{ // FileDataProvider dataProv = (FileDataProvider)presentation.DataProviderFactory.Create(DataProviderFactory.AUDIO_WAV_MIME_TYPE); //VERSUS// // FileDataProvider dataProv = new FileDataProvider(); // dataProv.MimeType = DataProviderFactory.AUDIO_WAV_MIME_TYPE; //} //m_Project.Presentations.Get(0).ExternalFilesDataManager.ManagedObjects.ContentsAs_Enumerable if (RequestCancellation) { return; } if (parseContentDocParts(fullDocPath, spineItemProject, xmlDoc, docPath, DocumentMarkupType.NA)) { return; // user cancel } //if (RequestCancellation) return; //reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ParsingMetadata, docPath)); //parseMetadata(fullDocPath, project, xmlDoc); //if (RequestCancellation) return; //ParseHeadLinks(fullDocPath, project, xmlDoc); //reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ParsingContent, docPath)); //parseContentDocument(fullDocPath, project, xmlDoc, null, fullDocPath, null, DocumentMarkupType.NA); string title = GetTitle(spineItemPresentation); if (!string.IsNullOrEmpty(title)) { spineChild.GetOrCreateXmlProperty().SetAttribute("title", "", title); } if (false) // do not copy metadata from project to individual chapter { foreach (Metadata metadata in m_Project.Presentations.Get(0).Metadatas.ContentsAs_Enumerable) { Metadata md = spineItemPresentation.MetadataFactory.CreateMetadata(); md.NameContentAttribute = metadata.NameContentAttribute.Copy(); foreach (MetadataAttribute metadataAttribute in metadata.OtherAttributes.ContentsAs_Enumerable) { MetadataAttribute mdAttr = metadataAttribute.Copy(); md.OtherAttributes.Insert(md.OtherAttributes.Count, mdAttr); } spineItemPresentation.Metadatas.Insert(spineItemPresentation.Metadatas.Count, md); } } //XmlNodeList listOfBodies = xmlDoc.GetElementsByTagName("body"); //if (listOfBodies.Count == 0) //{ // listOfBodies = xmlDoc.GetElementsByTagName("book"); //} //XmlNode bodyElement = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(xmlDoc, true, "body", null); //if (bodyElement == null) //{ // bodyElement = XmlDocumentHelper.GetFirstChildElementOrSelfWithName(xmlDoc, true, "book", null); //} //if (bodyElement == null) //{ // continue; //} // TODO: return hierarchical outline where each node points to a XUK relative path, + XukAble.Uid (TreeNode are not corrupted during XukAbleManager.RegenerateUids(); foreach (KeyValuePair <string, string> spineItemAttribute in spineItemsAttributes[index]) { if (spineItemAttribute.Key == "media-overlay") { string opfDirPath = Path.GetDirectoryName(m_Book_FilePath); string overlayPath = spineItemAttribute.Value; reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.ParsingMediaOverlay, overlayPath)); string fullOverlayPath = Path.Combine(opfDirPath, overlayPath); if (!File.Exists(fullOverlayPath)) { continue; } XmlDocument overlayXmlDoc = XmlReaderWriterHelper.ParseXmlDocument(fullOverlayPath, false, false); IEnumerable <XmlNode> audioElements = XmlDocumentHelper.GetChildrenElementsOrSelfWithName(overlayXmlDoc, true, "audio", null, false); if (audioElements == null) { continue; } foreach (XmlNode audioNode in audioElements) { XmlAttributeCollection attrs = audioNode.Attributes; if (attrs == null) { continue; } XmlNode attrSrc = attrs.GetNamedItem("src"); if (attrSrc == null) { continue; } //XmlNode attrBegin = attrs.GetNamedItem("clipBegin"); //XmlNode attrEnd = attrs.GetNamedItem("clipEnd"); //string overlayDirPath = Path.GetDirectoryName(fullOverlayPath); //string fullAudioPath = Path.Combine(overlayDirPath, attrSrc.Value); //if (!File.Exists(fullAudioPath)) //{ // continue; //} //if (RequestCancellation) return; //reportProgress(-1, String.Format(UrakawaSDK_daisy_Lang.DecodingAudio, Path.GetFileName(fullAudioPath))); TreeNode textTreeNode = null; XmlNodeList children = audioNode.ParentNode.ChildNodes; foreach (XmlNode child in children) { if (child == audioNode) { continue; } if (child.LocalName != "text") { continue; } XmlAttributeCollection textAttrs = child.Attributes; if (textAttrs == null) { continue; } XmlNode textSrc = textAttrs.GetNamedItem("src"); if (textSrc == null) { continue; } string urlDecoded = FileDataProvider.UriDecode(textSrc.Value); if (urlDecoded.IndexOf('#') > 0) { string[] srcParts = urlDecoded.Split('#'); if (srcParts.Length != 2) { continue; } string fullTextRefPath = Path.Combine(Path.GetDirectoryName(fullOverlayPath), srcParts[0]); fullTextRefPath = FileDataProvider.NormaliseFullFilePath(fullTextRefPath).Replace('/', '\\'); if (!fullTextRefPath.Equals(fullDocPath, StringComparison.OrdinalIgnoreCase)) { //#if DEBUG // Debugger.Break(); //#endif //DEBUG continue; } string txtId = srcParts[1]; textTreeNode = spineItemPresentation.RootNode.GetFirstDescendantWithXmlID(txtId); } else { string fullTextRefPath = Path.Combine(Path.GetDirectoryName(fullOverlayPath), urlDecoded); fullTextRefPath = FileDataProvider.NormaliseFullFilePath(fullTextRefPath).Replace('/', '\\'); if (!fullTextRefPath.Equals(fullDocPath, StringComparison.OrdinalIgnoreCase)) { //#if DEBUG // Debugger.Break(); //#endif //DEBUG continue; } textTreeNode = spineItemPresentation.RootNode; } } if (textTreeNode != null) { addAudio(textTreeNode, audioNode, false, fullOverlayPath); } } } } spinePresentation.MediaDataManager.DefaultPCMFormat = spineItemPresentation.MediaDataManager.DefaultPCMFormat; //copied! string xuk_FilePath = GetXukFilePath_SpineItem(m_outDirectory, docPath, title, index); string xukFileName = Path.GetFileName(xuk_FilePath); spineChild.GetOrCreateXmlProperty().SetAttribute("xukFileName", "", xukFileName); //deleteDataDirectoryIfEmpty(); string dataFolderPath = spineItemPresentation.DataProviderManager.DataFileDirectoryFullPath; spineItemPresentation.DataProviderManager.SetCustomDataFileDirectory(Path.GetFileNameWithoutExtension(xuk_FilePath)); string newDataFolderPath = spineItemPresentation.DataProviderManager.DataFileDirectoryFullPath; DebugFix.Assert(Directory.Exists(newDataFolderPath)); if (newDataFolderPath != dataFolderPath) { try { if (Directory.Exists(newDataFolderPath)) { FileDataProvider.TryDeleteDirectory(newDataFolderPath, false); } Directory.Move(dataFolderPath, newDataFolderPath); } catch (Exception ex) { #if DEBUG Debugger.Break(); #endif // DEBUG Console.WriteLine(ex.Message); Console.WriteLine(ex.StackTrace); spineItemPresentation.DataProviderManager.SetCustomDataFileDirectory(dataFolderPrefix); } } spineItemProject.PrettyFormat = m_XukPrettyFormat; SaveXukAction action = new SaveXukAction(spineItemProject, spineItemProject, new Uri(xuk_FilePath), true); action.ShortDescription = UrakawaSDK_daisy_Lang.SavingXUKFile; action.LongDescription = UrakawaSDK_daisy_Lang.SerializeDOMIntoXUKFile; action.Progress += new EventHandler <ProgressEventArgs>( delegate(object sender, ProgressEventArgs e) { double val = e.Current; double max = e.Total; int percent = -1; if (val != max) { percent = (int)((val / max) * 100); } reportProgress_Throttle(percent, val + "/" + max); //reportProgress(-1, action.LongDescription); if (RequestCancellation) { e.Cancel(); } } ); action.Finished += new EventHandler <FinishedEventArgs>( delegate(object sender, FinishedEventArgs e) { reportProgress(100, UrakawaSDK_daisy_Lang.XUKSaved); } ); action.Cancelled += new EventHandler <CancelledEventArgs>( delegate(object sender, CancelledEventArgs e) { reportProgress(0, UrakawaSDK_daisy_Lang.CancelledXUKSaving); } ); action.DoWork(); //if (first) //{ // Presentation presentation = m_Project.Presentations.Get(0); // XmlProperty xmlProp = presentation.PropertyFactory.CreateXmlProperty(); // xmlProp.LocalName = "book"; // presentation.PropertyFactory.DefaultXmlNamespaceUri = bodyElement.NamespaceURI; // xmlProp.NamespaceUri = presentation.PropertyFactory.DefaultXmlNamespaceUri; // TreeNode treeNode = presentation.TreeNodeFactory.Create(); // treeNode.AddProperty(xmlProp); // presentation.RootNode = treeNode; // first = false; //} //foreach (XmlNode childOfBody in bodyElement.ChildNodes) //{ // parseContentDocument(childOfBody, m_Project.Presentations.Get(0).RootNode, fullDocPath); //} } }
public void SendMessage(TextChannel channel, string message) { Network.SendMessage(channel, message); }
public override void OnNavigatedTo(NavigatedToEventArgs e, Dictionary <string, object> viewModelState) { // ログインしていない? if (SocketClient == null) { IsInvalidTextChannel.Value = true; Debug.WriteLine("TextChannelPage にテキストチャンネルID(ulong)が正常に渡されませんでした。"); return; } // ナビゲーションパラメータにはテキストチャンネルIDが必要 if (e.Parameter is ulong) { var textChannelId = (ulong)e.Parameter; TextChannel = SocketClient.GetChannel(textChannelId) as SocketTextChannel; } // テキストチャンネルが見つからない場合は異常をページ表示に反映 if (TextChannel == null) { IsInvalidTextChannel.Value = true; Debug.WriteLine("TextChannelPage にテキストチャンネルID(ulong)が正常に渡されませんでした。"); return; } DiscordContext.CurrentTextChannel = TextChannel; try { NowMessageLoading.Value = true; Name = TextChannel.Name; RaisePropertyChanged(nameof(Name)); // テキストチャンネルページを表示中だけメッセージ受信を処理する SocketClient.MessageReceived += Discord_MessageReceived; SocketClient.MessageDeleted += SocketClient_MessageDeleted; SocketClient.MessageUpdated += SocketClient_MessageUpdated; RawMessages.Clear(); var task = _MessageUpdateLock.LockAsync() .ContinueWith(async x => { using (x.Result) { if (RawMessages.Count > 0) { return; } if (TextChannel == null) { throw new Exception(); } var rawMessages = await TextChannel.GetMessagesAsync().Flatten(); UIDispatcherScheduler.Default.Schedule(this, TimeSpan.Zero, (scheeduler, state) => { var sorted = rawMessages.ToList(); sorted.Sort((a, b) => (int)(a.Timestamp - b.Timestamp).TotalSeconds); foreach (var message in sorted) { RawMessages.Add(message); } return(null); }); await Task.Delay(500); } }); task.Wait(); } finally { NowMessageLoading.Value = false; } base.OnNavigatedTo(e, viewModelState); }