public async Task UpdateSupport(ulong guildId, ulong msgId, [Remainder] string msg) { if (Global.IsDev(Context.User)) { try { SocketDMChannel chn = (SocketDMChannel)await _client.GetDMChannelAsync(guildId); EmbedBuilder eb = new EmbedBuilder(); eb.WithTitle("Support ticket update"); eb.WithFooter($"Support ticket update for {msgId}"); eb.WithCurrentTimestamp(); eb.WithDescription(msg); eb.WithColor(DiscColour.Purple); try { await chn.SendMessageAsync("", false, eb.Build()); //This throws an exception claiming chn is null....yet it still sends the message. await Context.Message.ReplyAsync("Sent support message response successfully"); } catch { return; } } catch (Exception ex) { await Context.Message.ReplyAsync($"I encountered an error trying to respond to that support message. Here are the details:\n{ex.Message}\n{ex.Source}"); } } }
async Task HandleCardDraw(SocketUser sUser, SocketDMChannel DM) { Player user = GetPlayerObject(sUser); bool hasPlayableCards = false; foreach (Card card in GetCurrentTurnOrderPlayer().Cards) { if (IsCardCompatable(card)) { hasPlayableCards = true; break; } } if (!hasPlayableCards) { List <Card> drewCards = new List <Card>(); if (drawMultiplier == 0) { drawMultiplier++; } while (drawMultiplier > 0) { drewCards.Add(GetCurrentTurnOrderPlayer().DrawCard()); drawMultiplier--; } string playableAlert = IsCardCompatable(drewCards[0]) && drewCards.Count == 1 ? "You can play this card." : null; string cardNames = ""; foreach (Card card in drewCards) { if (cardNames != "") { cardNames += ", "; } cardNames += CardToString(card); } await AlertPlayerAsync(user, $"You drew a {cardNames}.", playableAlert); await DM.SendMessageAsync(null, false, GetTurnBriefing(GetCurrentTurnOrderPlayer(), true, false).Build()); foreach (Player player in players) { if (player != user) { await AlertPlayerAsync(player, $"{user.name} drew {(drewCards.Count == 1 ? "a card" : drewCards.Count + " cards")}", $"{user.name} now has {user.Cards.Count} cards."); } } if (!IsCardCompatable(drewCards[0]) || drewCards.Count > 1) { nextTurnFlag = true; } } else { await AlertPlayerAsync(GetCurrentTurnOrderPlayer(), "You have playable cards so you cannot draw!"); } }
public async Task HandleMessage(SocketUserMessage message, SocketDMChannel channel) { if (serverService.IsPasswordRequestInProgress(message.Author.Id)) { var nsp = serverService.RemoveNewPasswordRequest(message.Author.Id); var server = await serverService.Get(nsp.GuildId, nsp.ServerName); if (server == null) { await channel.SendMessageAsync("Server was removed in the meantime - request invalid"); return; } IAdminPortClient client = adminPortClientFactory.Create(new ServerInfo(server.ServerIp, server.ServerPort, message.Content)); try { await client.Join(); } catch { await channel.SendMessageAsync("Password was incorrect or connection to server was impossible"); return; } finally { await client.Disconnect(); } await this.serverService.ChangePassword(server.Id, message.Content); await channel.SendMessageAsync("Password has been changed."); } }
private void UserDMBtn_Click(object sender, RoutedEventArgs e) { Button btn = (Button)sender; if (btn.Tag == null) { return; } if (btn.Tag is SocketDMChannel) { SocketDMChannel c = btn.Tag as SocketDMChannel; DMUserEntry etry = new DMUserEntry(); etry.Channel = c; etry.UpdateMe(); var body = new DirectMsgsContents.DirectMessagesSidebarContent(); App.MainWnd.Sidebar.Set(new DirectMsgsContents.SidebarHeaderSerach(), body); body.Select(etry); } if (btn.Tag is SocketGroupChannel) { SocketGroupChannel c = btn.Tag as SocketGroupChannel; DMUserEntry etry = new DMUserEntry(); etry.Channel = c; etry.UpdateMe(); var body = new DirectMsgsContents.DirectMessagesSidebarContent(); App.MainWnd.Sidebar.Set(new DirectMsgsContents.SidebarHeaderSerach(), body); body.Select(etry); } }
public void AddUserDM(SocketDMChannel u) { if (!Dispatcher.CheckAccess()) { Dispatcher.Invoke(() => AddUserDM(u)); return; } Grid g = new Grid(); g.Margin = new Thickness(4); TextBlock i = new TextBlock(); i.Text = u.Recipient.Username; g.Children.Add(i); i.HorizontalAlignment = HorizontalAlignment.Left; i.VerticalAlignment = VerticalAlignment.Center; i.Margin = new Thickness(4); var UserDMBtn = GetContainer(g); UserDMBtn.Click += UserDMBtn_Click; UserDMBtn.Tag = u; Add(UserDMBtn); }
public static string GetChannelName(SocketMessage e) { if (e.Channel as SocketDMChannel != null) { SocketDMChannel dmChannel = (e.Channel) as SocketDMChannel; return $"[DM / {dmChannel.Recipient}] {e.Author.Username}"; } else { return $"[{e.Channel.Name} / {e.Author.Username}]"; } }
public void UpdateMessages() { new Thread(() => { const int HowManyMessagesDownload = 25; if (Channel != null) { if (Channel is SocketDMChannel) { SocketDMChannel c = (SocketDMChannel)Channel; var msgs = c.GetMessagesAsync(HowManyMessagesDownload).ToList(); var reslt = msgs.GetAwaiter().GetResult()[1]; UpdateMessagesEx(reslt.ToArray()); } else if (Channel is SocketGroupChannel) { SocketGroupChannel c = (SocketGroupChannel)Channel; var msgs = c.GetMessagesAsync(HowManyMessagesDownload).ToList(); var reslt = msgs.GetAwaiter().GetResult()[1]; UpdateMessagesEx(reslt.ToArray()); } else if (Channel is SocketTextChannel) { SocketTextChannel c = (SocketTextChannel)Channel; var msgs = c.GetMessagesAsync(HowManyMessagesDownload).ToList(); var reslt = msgs.GetAwaiter().GetResult()[1]; UpdateMessagesEx(reslt.ToArray()); } else if (Channel is SocketChannel) { SocketTextChannel c = (SocketTextChannel)Channel; var msgs = c.GetMessagesAsync(HowManyMessagesDownload).ToList(); var reslt = msgs.GetAwaiter().GetResult()[1]; UpdateMessagesEx(reslt.ToArray()); } } if (DmBotChannel != null) { var msgs = DmBotChannel.GetMessagesAsync(HowManyMessagesDownload).ToList(); var reslt1 = msgs.GetAwaiter().GetResult(); var reslt = reslt1[0]; UpdateMessagesEx(reslt.ToArray()); } }).Start(); }
private void safeSendPM(SocketDMChannel c, String m) { try { c.SendMessageAsync(m); } catch (Exception e) { Console.WriteLine("Writing to channel with Id " + c.Id + " failed with: " + e.Message); } }
private async void DMTextBox_KeyUp(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { if (SelectedDMIndex != null) { SocketDMChannel ch = Global.Kuro.Client.DMChannels.Where(u => u.Recipient.Username + "#" + u.Recipient.Discriminator == DMListView.Items[(int)SelectedDMIndex].Text).FirstOrDefault(); if (!string.IsNullOrWhiteSpace(DMInTextBox.Text.Trim())) { await ch?.SendMessageAsync(DMInTextBox.Text.Trim()); DMInTextBox.Text = string.Empty; } } } }
private void SendFileDMChannel(object sender, EventArgs e) { if (Global.Kuro.Client.DMChannels.Count > 0) { OpenFileDialog file = new OpenFileDialog() { Multiselect = false }; file.FileOk += async(o, ev) => { SocketDMChannel ch = Global.Kuro.Client.DMChannels.Where(u => u.Recipient.Username + "#" + u.Recipient.Discriminator == DMListView.Items[(int)SelectedDMIndex].Text).FirstOrDefault(); await ch?.SendFileAsync(file.InitialDirectory + file.FileName, string.Empty); }; file.ShowDialog(); } }
// If the message contains image or image url and sender is bot administrator // It will Add new dragon with tags specified in message // If message contains only tags it will send random dragon ^^ // Prefix is not used here, so format is: tag1 tag2 tag3... and image in attachment // or tag1 tag2 tag3 http://<url> https://<url> private async Task ProcessDirectMessage( SocketMessage message, SocketDMChannel channel ) { if (administrators.Contains(message.Author.Id)) { List <Attachment> attachments = message.Attachments.ToList(); if (attachments.Count > 0) { if (message.Content.Trim() == "") { await channel.SendMessageAsync("You can't add Dragon without tags"); return; } List <string> tags = message.Content.Split(" ").ToList(); await AddDragonAsync(tags, attachments[0].Url, channel); return; } else { List <string> splitted = message.Content.Split(" ").ToList(); if (splitted.Last().StartsWith("http://") || splitted.Last().StartsWith("https://")) { if (splitted.Count < 2) { await channel.SendMessageAsync("You can't add Dragon without tags"); return; } string url = splitted.Last(); List <string> tags = splitted.SkipLast(1).ToList(); await AddDragonAsync(tags, url, channel); return; } } } { List <string> tags = message.Content.Split(" ").ToList(); await SendRandomDragon(tags, channel); } }
public SocketCommandContext(DiscordSocketClient client, Interaction interaction) { Client = client; Guild = interaction.Guild as SocketGuild; User = interaction.User as SocketUser; if (Guild != null) { Channel = interaction.Channel as SocketTextChannel; GuildUser = interaction.Member as SocketGuildUser; } else { Channel = new SocketDMChannel(client, interaction.ChannelId, User as SocketGlobalUser); } Message = new SocketUserMessage(client, interaction.MessageId.HasValue ? interaction.MessageId.Value : 0, Channel, User, MessageSource.User, CommandService.ParseInteractionData(interaction.Data)); InteractionData = interaction.Data; }
//DM Part private async void DMSelectionChanged(object s, ListViewItemSelectionChangedEventArgs e) { if (e.IsSelected) { DMUploadButton.Enabled = true; SelectedDMIndex = DMListView.SelectedIndices.Cast <int>().FirstOrDefault(); SocketDMChannel SelectedDMChannel = Global.Kuro.Client.DMChannels.Where(u => u.Recipient.Username + "#" + u.Recipient.Discriminator == DMListView.SelectedItems[0].Text).FirstOrDefault(); Program.UserInterface.Text = "[PRIVATE] " + "#" + SelectedDMChannel.Recipient.Username; Program.UserInterface.Refresh(); IEnumerable <IMessage> messages = await(Global.Kuro.Client.GetChannel(SelectedDMChannel.Id) as SocketDMChannel).GetMessagesAsync(60).Flatten <IMessage>(); await ControlHandler.ClearDMAsync(); for (int i = messages.Count() - 1; i >= 0; i--) { IMessage message = messages.ElementAt(i); await ControlHandler.LogDMAsync("[" + message.Timestamp.LocalDateTime + "] " + message.Author + ": " + (message.Attachments.Count != 0 ? "[" + message.Attachments.FirstOrDefault().Url + "] " + message.Content : message.Content)); } } }
public async Task MessageReceived(SocketMessage message) { string Guild = message.Channel is SocketDMChannel ? "PRIVATE" : (message.Channel as SocketGuildChannel).Guild.Name; if (Guild != "PRIVATE") { if (Program.UserInterface.SelectedChannels.Count != 0 && Program.UserInterface.SelectedChannels.IndexOf(message.Channel as SocketTextChannel) > -1) { SocketTextChannel ch = Program.UserInterface.SelectedChannels[Program.UserInterface.SelectedChannels.IndexOf(message.Channel as SocketTextChannel)]; if (message.Channel.Name == ch.Name && Guild == ch.Guild.Name) { await ControlHandler.LogAsync("[" + message.Timestamp.LocalDateTime + "] " + "#" + message.Channel.Name + " | " + message.Author + ": " + (message.Attachments.Count != 0 ? "[" + message.Attachments.FirstOrDefault().Url + "] " + message.Content : message.Content), Guild); } else { await ControlHandler.LogAsync("[" + message.Timestamp.LocalDateTime + "] " + "#" + message.Channel.Name + " | " + message.Author + ": " + (message.Attachments.Count != 0 ? "[" + message.Attachments.FirstOrDefault().Url + "] " + message.Content : message.Content)); } } else { await ControlHandler.LogAsync("[" + message.Timestamp.LocalDateTime + "] " + "#" + message.Channel.Name + " | " + message.Author + ": " + (message.Attachments.Count != 0 ? "[" + message.Attachments.FirstOrDefault().Url + "] " + message.Content : message.Content)); } } else { Program.UserInterface.DMListView.Invoke(new Action(async() => { SocketDMChannel Channel = message.Channel as SocketDMChannel; await ControlHandler.LogAsync("[" + message.Timestamp.LocalDateTime + "] PRIVATE/" + message.Author + ": " + (message.Attachments.Count != 0 ? "[" + message.Attachments.FirstOrDefault().Url + "] " + message.Content : message.Content)); if (Program.UserInterface.DMListView.Items.IndexOf(Program.UserInterface.DMListView.FindItemWithText(Channel.Recipient.Username + "#" + Channel.Recipient.Discriminator)) == -1) { await ControlHandler.AddNewDM(Channel.Recipient.Username + "#" + Channel.Recipient.Discriminator); } if (Program.UserInterface.SelectedDMIndex != null) { if ((int)Program.UserInterface.SelectedDMIndex == Program.UserInterface.DMListView.Items.IndexOf(Program.UserInterface.DMListView.FindItemWithText(Channel.Recipient.Username + "#" + Channel.Recipient.Discriminator))) { await ControlHandler.LogDMAsync("[" + message.Timestamp.LocalDateTime + "] " + message.Author + ": " + (message.Attachments.Count != 0 ? "[" + message.Attachments.FirstOrDefault().Url + "] " + message.Content : message.Content)); } } })); } }
private void OnDmReaction(SocketReaction reaction, IMessage msg, SocketDMChannel dmChannel) { // Check if user can vote var usrId = reaction.UserId; if (!CanVote(usrId)) { _logger.LogError($"User {usrId} - {msg.Author.Username} can't vote"); return; } if (reaction.Emote.Name == Constants.OkEmoji.Name) { var result = ProcessVote(msg.Content); _polls.SendVote(result, usrId); dmChannel.SendMessageAsync("Voto guardado correctamente."); } }
private async Task messageRecieved(SocketMessage msg) { if (msg.Channel is IPrivateChannel && msg.Author.IsBot == false) { SocketGuild gld = _client.GetGuild(257984126718574592) as SocketGuild; if (!activeDMChannels.Contains(msg.Channel)) { activeDMChannels.Add(msg.Channel as SocketDMChannel); } if (activeDMChannel == null) { activeDMChannel = msg.Channel as SocketDMChannel; } await(gld.GetChannel(686551634863849519) as ITextChannel).SendMessageAsync($"***{msg.Author.Username}** : {msg.Timestamp.Day}/{msg.Timestamp.Month}/{msg.Timestamp.Year} at {msg.Timestamp.Hour}:{msg.Timestamp.Minute} UTC*\n{msg.Content}"); } else if (msg.Channel.Id == 686551634863849519 && msg.Author.IsBot == false && !msg.Content.Contains('/')) { if (activeDMChannel != null) { await activeDMChannel.SendMessageAsync(msg.Content); } } else { string Message = msg.Content.ToLower(); if ((msg.Channel.Id == 257984126718574592 || msg.Channel.Id == 426713281135116288) && (Message.Contains("rockstar") || Message.Contains("r*") || Message.Contains("rock*"))) { List <string> Replies = new List <string> { "Shark cards anyone?", "Anyone for shark cards?", "Shark cards lads only $100 for $800,000" }; await msg.Channel.SendMessageAsync(Replies[new Random().Next(0, Replies.Count)]); } else if (msg.Channel.Id == 492273478993444864) { await(msg as SocketUserMessage).AddReactionAsync(new Emoji("👍")); await(msg as SocketUserMessage).AddReactionAsync(new Emoji("👎")); } } }
private async Task <DiscordChannelConfig> GetChatConfiguration(SocketUserMessage message, IServiceProvider serviceProvider) { var channelConfigService = serviceProvider.GetService <IDiscordChannelConfigService>(); var channelConfig = await channelConfigService.GetConfigurationByChannelId(message.Channel.Id); if (channelConfig != null) { return(channelConfig); } var messageBuilder = new StringBuilder(); messageBuilder.AppendLine("Hi, I'm GrammarNazi."); messageBuilder.AppendLine("I'm currently working and correcting all spelling errors in this channel."); messageBuilder.AppendLine($"Type `{DiscordBotCommands.Help}` to get useful commands."); ulong guild = message.Channel switch { SocketDMChannel dmChannel => dmChannel.Id, SocketGuildChannel guildChannel => guildChannel.Guild.Id, _ => default }; var channelConfiguration = new DiscordChannelConfig { ChannelId = message.Channel.Id, GrammarAlgorithm = Defaults.DefaultAlgorithm, Guild = guild, SelectedLanguage = SupportedLanguages.Auto }; await channelConfigService.AddConfiguration(channelConfiguration); await message.Channel.SendMessageAsync(messageBuilder.ToString()); return(channelConfiguration); }
private void tabControl1_SelectedIndexChanged(object sender, EventArgs e) { if (tabControl1.SelectedTab.Name != "DMTabPage") { SocketTextChannel ch = SelectedChannels.Find(o => o.Guild.Name == tabControl1.SelectedTab.Text); if (ch != null) { Program.UserInterface.Text = "[" + ch.Guild.Name + "] " + "#" + ch.Name; Program.UserInterface.Refresh(); } } else if (tabControl1.SelectedTab.Name == "DMTabPage") { if (SelectedDMIndex != null) { SocketDMChannel ch = Global.Kuro.Client.DMChannels.Where(u => DMListView.Items[(int)SelectedDMIndex].Text == u.Recipient.Username).FirstOrDefault(); if (ch != null) { Program.UserInterface.Text = "[PRIVATE] " + "#" + ch.Recipient.Username; Program.UserInterface.Refresh(); } } } }
/// <summary> /// /// </summary> /// <param name="wrapper">A reference to the api wrapper</param> /// <param name="channel">A reference to the discord dm channel object</param> public DiscordChannel(ApiWrapper.ApiWrapper wrapper, SocketDMChannel channel) : base(wrapper) { this.DMChannel = channel ?? throw new ArgumentNullException(nameof(channel)); }
private async Task HandleCommandAsync(SocketMessage arg) { // Bail out if it's a System Message. var msg = arg as SocketUserMessage; if (msg == null) { return; } // We don't want the bot to respond to itself or other bots. if (msg.Author.Id == _client.CurrentUser.Id || msg.Author.IsBot) { return; } // Create a number to track where the prefix ends and the command begins int pos = 0; // Replace the '!' with whatever character // you want to prefix your commands with. // Uncomment the second half if you also want // commands to be invoked by mentioning the bot instead. //if (msg.HasCharPrefix('!', ref pos) /* || msg.HasMentionPrefix(_client.CurrentUser, ref pos) */) //{ // Create a Command Context. //var context = new SocketCommandContext(_client, msg); // Execute the command. (result does not indicate a return value, // rather an object stating if the command executed successfully). //var result = await _commands.ExecuteAsync(context, pos, _services); // Uncomment the following lines if you want the bot // to send a message if it failed. // This does not catch errors from commands with 'RunMode.Async', // subscribe a handler for '_commands.CommandExecuted' to see those. //if (!result.IsSuccess && result.Error != CommandError.UnknownCommand) // await msg.Channel.SendMessageAsync(result.ErrorReason); //} SocketGuildChannel guildChannel = msg.Channel as SocketGuildChannel; if (guildChannel != null) { if (msg.HasMentionPrefix(_client.CurrentUser, ref pos) && msg.Content.Contains("link")) { await msg.Channel.SendMessageAsync("Please DM me your link key"); LinkRequest lr = new LinkRequest(); lr.author = msg.Author.Id; lr.channel = msg.Channel.Id; lr.server = guildChannel.Guild.Id; lock (requests) { requests.Add(lr); } } else { ulong linkkey = database.GetLinkFromChannel(msg.Channel.Id); if (linkkey != 0) { Console.WriteLine("[Discord->Server:" + linkkey + "] [" + msg.Author.Username + "] " + msg.Content); sendToDMP(linkkey, "[" + msg.Author.Username + "] " + msg.Content); } else { Console.WriteLine("[Discord->Server:Unlinked] " + msg.Content); } } } SocketDMChannel dMChannel = msg.Channel as SocketDMChannel; if (dMChannel != null) { ulong linkkey = 0; if (ulong.TryParse(msg.Content, out linkkey)) { LinkRequest linkRequest = null; foreach (LinkRequest lr in requests) { if (lr.author == msg.Author.Id) { linkRequest = lr; Console.WriteLine("Linking " + lr.channel + " to " + linkkey); database.SetLink(lr.server, lr.channel, linkkey); } } if (linkRequest != null) { lock (requests) { requests.Remove(linkRequest); } await msg.Channel.SendMessageAsync("Thankyou! You are now be linked."); } else { await msg.Channel.SendMessageAsync("You must type '@DiscordMultiPlayer link' in the channel you wish to link"); } } else { await msg.Channel.SendMessageAsync("Type only just the link key number as the message."); } } }