private async void UserJoined(object sender, Discord.UserEventArgs e)
        {
            try
            {
                if (!AnnouncementsDictionary.ContainsKey(e.Server.Id) ||
                    !AnnouncementsDictionary[e.Server.Id].Greet) return;

                var controls = AnnouncementsDictionary[e.Server.Id];
                var channel = NadekoBot.Client.GetChannel(controls.GreetChannel);

                var msg = controls.GreetText.Replace("%user%", e.User.Mention).Trim();
                if (string.IsNullOrEmpty(msg))
                    return;
                if (controls.GreetPM)
                {
                    Greeted++;
                    await e.User.SendMessage($"`Welcome Message From {e.Server.Name}`\n" + msg);
                }
                else
                {
                    if (channel == null) return;
                    Greeted++;
                    var toDelete = await channel.SendMessage(msg);
                    if (e.Server.CurrentUser.GetPermissions(channel).ManageMessages)
                    {
                        await Task.Delay(300000); // 5 minutes
                        await toDelete.Delete();
                    }
                }
            }
            catch { }
        }
Exemple #2
0
 private async void Client_MessageReceived(object sender, Discord.MessageEventArgs e)
 {
     if (string.IsNullOrWhiteSpace(e.Message.Text))
         return;
     if (CopiedUsers.Contains(e.User.Id)) {
         await e.Send( e.Message.Text.Replace("@everyone","@everryone"));
     }
 }
        private async void UserJoined(object sender, Discord.UserEventArgs e) {
            if (!AnnouncementsDictionary.ContainsKey(e.Server.Id) || 
                !AnnouncementsDictionary[e.Server.Id].Greet) return;

            var controls = AnnouncementsDictionary[e.Server.Id];
            var channel = NadekoBot.client.GetChannel(controls.GreetChannel);
            if (channel == null) return;

            await channel.Send(controls.GreetText.Replace("%user%", e.User.Mention));
        }
        internal override void Init(CommandGroupBuilder cgb)
        {
            cgb.CreateCommand(Module.Prefix + "pick")
                .Description("Picks a flower planted in this channel.")
                .Do(async e =>
                {
                    Message msg;

                    await e.Message.Delete().ConfigureAwait(false);
                    if (!plantedFlowerChannels.TryRemove(e.Channel.Id, out msg))
                        return;

                    await msg.Delete().ConfigureAwait(false);
                    await FlowersHandler.AddFlowersAsync(e.User, "Picked a flower.", 1, true).ConfigureAwait(false);
                    msg = await e.Channel.SendMessage($"**{e.User.Name}** picked a {NadekoBot.Config.CurrencyName}!").ConfigureAwait(false);
                    await Task.Delay(10000).ConfigureAwait(false);
                    await msg.Delete().ConfigureAwait(false);
                });

            cgb.CreateCommand(Module.Prefix + "plant")
                .Description("Spend a flower to plant it in this channel. (If bot is restarted or crashes, flower will be lost)")
                .Do(async e =>
                {
                    lock (locker)
                    {
                        if (plantedFlowerChannels.ContainsKey(e.Channel.Id))
                        {
                            e.Channel.SendMessage($"There is already a {NadekoBot.Config.CurrencyName} in this channel.");
                            return;
                        }
                        var removed = FlowersHandler.RemoveFlowers(e.User, "Planted a flower.", 1);
                        if (!removed)
                        {
                            e.Channel.SendMessage($"You don't have any {NadekoBot.Config.CurrencyName}s.").Wait();
                            return;
                        }

                        var rng = new Random();
                        var file = Directory.GetFiles("data/currency_images").OrderBy(s => rng.Next()).FirstOrDefault();
                        Message msg;
                        //todo send message after, not in lock
                        if (file == null)
                            msg = e.Channel.SendMessage(NadekoBot.Config.CurrencySign).GetAwaiter().GetResult();
                        else
                            msg = e.Channel.SendFile(file).GetAwaiter().GetResult();
                        plantedFlowerChannels.TryAdd(e.Channel.Id, msg);
                    }
                    var vowelFirst = new[] { 'a', 'e', 'i', 'o', 'u' }.Contains(NadekoBot.Config.CurrencyName[0]);
                    var msg2 = await e.Channel.SendMessage($"Oh how Nice! **{e.User.Name}** planted {(vowelFirst ? "an" : "a")} {NadekoBot.Config.CurrencyName}. Pick it using {Module.Prefix}pick");
                    await Task.Delay(20000).ConfigureAwait(false);
                    await msg2.Delete().ConfigureAwait(false);
                });
        }
Exemple #5
0
 private async void Client_MessageReceived(object sender, Discord.MessageEventArgs e)
 {
     if (e.User.Id == NadekoBot.Client.CurrentUser.Id) return;
     try
     {
         if (string.IsNullOrWhiteSpace(e.Message.Text))
             return;
         if (CopiedUsers.Contains(e.User.Id))
         {
             await e.Channel.SendMessage(e.Message.Text);
         }
     }
     catch { }
 }
Exemple #6
0
 public static async Task AddFlowersAsync(Discord.User u, string reason, int amount) {
     if (amount <= 0)
         return;
     await Task.Run(() => {
         DBHandler.Instance.InsertData(new _DataModels.CurrencyTransaction {
             Reason = reason,
             UserId = (long)u.Id,
             Value = amount,
         });
     });
     string flows = "";
     for (int i = 0; i < amount; i++) {
         flows += "🌸";
     }
     await u.SendMessage("👑Congratulations!👑\nYou got: "+flows);
 }
        public static async Task WelcomeUserAsync (Discord.WebSocket.DiscordSocketClient client, Discord.WebSocket.SocketUser u, ulong ServerID)
        {
            //Welcoming people.
            string[] replies = GetWelcomeReplies();
            string reply = String.Format(replies[BotTools.Tools.random.Next(replies.Length)], u.Mention);
            ITextChannel channelToAnswerIn = client.GetChannel(BotTools.Tools.GetServerInfo(ServerID).welcomingChannel) as ITextChannel;

            try
            {
                if (channelToAnswerIn != null)
                    await channelToAnswerIn.SendMessageAsync(reply);
            }
            catch (Exception ex)
            {
                BotTools.Tools.LogError("Couldn't send message.", ex.Message);
            }
        }       
        public static bool RemoveFlowers(Discord.User u, string reason, int amount)
        {
            if (amount <= 0)
                return false;
            var uid = (long)u.Id;
            var state = DbHandler.Instance.FindOne<DataModels.CurrencyState>(cs => cs.UserId == uid);

            if (state.Value < amount)
                return false;

            DbHandler.Instance.InsertData(new DataModels.CurrencyTransaction
            {
                Reason = reason,
                UserId = (long)u.Id,
                Value = -amount,
            });
            return true;
        }
        private async void UserJoined(object sender, Discord.UserEventArgs e) {
            if (!AnnouncementsDictionary.ContainsKey(e.Server.Id) ||
                !AnnouncementsDictionary[e.Server.Id].Greet) return;

            var controls = AnnouncementsDictionary[e.Server.Id];
            var channel = NadekoBot.client.GetChannel(controls.GreetChannel);

            var msg = controls.GreetText.Replace("%user%", e.User.Mention).Trim();
            if (string.IsNullOrEmpty(msg))
                return;
            if (controls.GreetPM) {
                Greeted++;
                await e.User.SendMessage($"`Welcome Message From {e.Server.Name}`\n" + msg);
            } else {
                if (channel == null) return;
                Greeted++;
                await channel.Send(msg);
            }
        }
Exemple #10
0
        public static async Task AddFlowersAsync(Discord.User u, string reason, int amount, bool silent = false)
        {
            if (amount <= 0)
                return;
            await Task.Run(() =>
            {
                DbHandler.Instance.Connection.Insert(new DataModels.CurrencyTransaction
                {
                    Reason = reason,
                    UserId = (long)u.Id,
                    Value = amount,
                });
            }).ConfigureAwait(false);

            if (silent)
                return;

            var flows = amount + " " + NadekoBot.Config.CurrencySign;

            await u.SendMessage("👑Congratulations!👑\nYou received: " + flows).ConfigureAwait(false);
        }
Exemple #11
0
        public static async Task<bool> RemoveFlowers(Discord.User u, string reason, int amount, bool silent=false, string message="👎`Bot owner has taken {0}{1} from you.`")
        {
            if (amount <= 0)
                return false;
            var uid = (long)u.Id;
            var state = DbHandler.Instance.FindOne<DataModels.CurrencyState>(cs => cs.UserId == uid);

            if (state.Value < amount)
                return false;

            DbHandler.Instance.Connection.Insert(new DataModels.CurrencyTransaction
            {
                Reason = reason,
                UserId = (long)u.Id,
                Value = -amount,
            });

            if (silent)
                return true;

            await u.SendMessage(string.Format(message,amount,NadekoBot.Config.CurrencySign)).ConfigureAwait(false);
            return true;
        }
        //React with text
        public static async Task ReceivedMessageAsync(Discord.IMessage message)
        {
            MultiSelector selector = selectors.FirstOrDefault(x => x.GetUser().Id == message.Author.Id);
            if (selector == null)
                return;
            if (selector.canRespond == false)
            {
                selector.canRespond = true;
                return;
            }

            switch(message.Content.ToLower())
            {
                case "n":
                    NextPage();
                    selector.AddDeleteMessage(message);
                    return;
                case "p":
                    PreviousPage();
                    selector.AddDeleteMessage(message);
                    return;
            }

            selector.AddDeleteMessage(message);
            var obj = selector.ReturnAction()(message.Content);
            await selector.GetResponse()(message, message.Author as IGuildUser, obj);
            selectors.Remove(selector); //Delete if completed successfully

            foreach (var msg in selector.messagesToDelete)
            {
                try
                {
                    await msg.DeleteAsync();
                }
                catch (Exception) { }
            }
        }
Exemple #13
0
 private async void PotentialFlowerGeneration(object sender, Discord.MessageEventArgs e)
 {
     try
     {
         if (e.Server == null || e.Channel.IsPrivate || e.Message.IsAuthor)
             return;
         var config = Classes.SpecificConfigurations.Default.Of(e.Server.Id);
         var now = DateTime.Now;
         int cd;
         DateTime lastSpawned;
         if (config.GenerateCurrencyChannels.TryGetValue(e.Channel.Id, out cd))
             if (!plantpickCooldowns.TryGetValue(e.Channel.Id, out lastSpawned) || (lastSpawned + new TimeSpan(0, cd, 0)) < now)
             {
                 var rnd = Math.Abs(rng.Next(0,101));
                 if (rnd == 0)
                 {
                     var msgs = new[] { await e.Channel.SendFile(GetRandomCurrencyImagePath()), await e.Channel.SendMessage($"❗ A random {NadekoBot.Config.CurrencyName} appeared! Pick it up by typing `>pick`") };
                     plantedFlowerChannels.AddOrUpdate(e.Channel.Id, msgs, (u, m) => { m.ForEach(async msgToDelete => { try { await msgToDelete.Delete(); } catch { } }); return msgs; });
                     plantpickCooldowns.AddOrUpdate(e.Channel.Id, now, (i, d) => now);
                 }
             }
     }
     catch { }
 }
            public async Task Plant(IUserMessage imsg)
            {
                var channel = (ITextChannel)imsg.Channel;

                var removed = await CurrencyHandler.RemoveCurrencyAsync((IGuildUser)imsg.Author, "Planted a flower.", 1, false).ConfigureAwait(false);
                if (!removed)
                {
                    await channel.SendMessageAsync($"You don't have any {Gambling.Gambling.CurrencyPluralName}.").ConfigureAwait(false);
                    return;
                }

                var file = GetRandomCurrencyImagePath();
                IUserMessage msg;
                var vowelFirst = new[] { 'a', 'e', 'i', 'o', 'u' }.Contains(Gambling.Gambling.CurrencyName[0]);
                
                var msgToSend = $"Oh how Nice! **{imsg.Author.Username}** planted {(vowelFirst ? "an" : "a")} {Gambling.Gambling.CurrencyName}. Pick it using {NadekoBot.ModulePrefixes[typeof(Games).Name]}pick";
                if (file == null)
                {
                    msg = await channel.SendMessageAsync(Gambling.Gambling.CurrencySign).ConfigureAwait(false);
                }
                else
                {
                    msg = await channel.SendFileAsync(file, msgToSend).ConfigureAwait(false);
                }
                plantedFlowers.AddOrUpdate(channel.Id, new List<IUserMessage>() { msg }, (id, old) => { old.Add(msg); return old; });
            }
Exemple #15
0
        /// <summary>
        /// Removes users which exist in database but not on server.
        /// </summary>
        /// <param name="server">Discord server to check</param>
        /// <param name="msg">Return message</param>
        private void DeleteDeadUsers(Discord.Server server, out string msg)
        {
            msg = "";
            _ctx = new MoetronDBContext();

            Model.Server modelServer = _ctx.Servers.Find((long)server.Id);
            if (modelServer == null)
            {
                msg = "Server does not exist in database.";
                return;
            }

            int count = 0;
            Discord.User user;
            foreach (Model.ServerUser su in modelServer.ServerUsers.ToList())
            {
                user = server.Users.FirstOrDefault(x => (long)x.Id == su.UserId);
                if (user == null)
                {
                    _ctx.ServerUsers.Remove(su);
                    count++;
                }
            }
            msg = $"Removed {count} users!";
            _ctx.SaveChanges();
        }
Exemple #16
0
 private async Task Whois(CommandEventArgs e, User user)
 {
     if (user != null)
     {
         var response = new
         {
             Id = user.Id,
             Name = user.Name,
             Discriminator = user.Discriminator
         };
         await _client.Reply(e, "User Info", response);
     }
     else
         await _client.Reply(e, "Unknown User");
 }
Exemple #17
0
        public async Task StartAsync()
        {
            await _gitHub.DownloadConfig();

            var discordToken = _gitHub.Config.DiscordToken;    // Get Discord token

            if (string.IsNullOrWhiteSpace(discordToken))       // Check if token is valid
            {
                throw new ArgumentNullException(discordToken); // Throw exception if token is invalid
            }
            while (true)
            {
                try
                {
                    await Discord.LoginAsync(TokenType.Bot, discordToken); // Login to Discord

                    await Discord.StartAsync();                            // Connect to the websocket

                    break;
                }
                catch (HttpException he)
                {
                    await LoggingService.OnLogAsync(new LogMessage(LogSeverity.Error, "Discord", he.Message));

                    await Task.Delay(TimeSpan.FromSeconds(10));

                    await LoggingService.OnLogAsync(new LogMessage(LogSeverity.Warning, "Discord", "Trying to start again"));
                }
                catch (Exception e)
                {
                    await LoggingService.OnLogAsync(new LogMessage(LogSeverity.Critical, "Discord", e.Message, e));   // Log exception
                }
            }

            // Create datamap with required objects
            var defaultJobDataMap = new JobDataMap()
            {
                { "Client", Discord },
                { "GitHub", _gitHub },
                { "Logging", Logging },
                { "Reddit", _reddit }
            };

            // Create job for updating counters
            IJobDetail countersJob = JobBuilder.Create <UpdateCountersJob>()
                                     .WithIdentity("updateCountersJob", "discordGroup")
                                     .UsingJobData(defaultJobDataMap)
                                     .Build();
            ITrigger countersTrigger = TriggerBuilder.Create()
                                       .WithIdentity("updateCountersTrigger", "discordGroup")
                                       //.StartAt(DateTimeOffset.UtcNow.AddSeconds(15))
                                       //.WithSimpleSchedule(x => x.WithIntervalInMinutes(5).RepeatForever())
                                       .WithCronSchedule("0 0/5 * 1/1 * ? *")
                                       .StartNow()
                                       .Build();

            // Create job for clearing messages
            IJobDetail clearJob = JobBuilder.Create <ClearVcChatJob>()
                                  .WithIdentity("clearVcChatJob", "discordGroup")
                                  .UsingJobData(defaultJobDataMap)
                                  .Build();
            ITrigger clearTrigger = TriggerBuilder.Create()
                                    .WithIdentity("cleatVcChatTrigger", "discordGroup")
                                    .WithCronSchedule("0 0 5 1/1 * ? *")
                                    .StartNow()
                                    //.StartAt(DateTimeOffset.UtcNow.AddSeconds(5))
                                    //.WithSimpleSchedule(x => x.WithIntervalInMinutes(1).WithRepeatCount(0))
                                    .Build();

            IJobDetail lockdownBeginJob = JobBuilder.Create <LockdownBeginJob>()
                                          .WithIdentity("lockdownBeginJob", "discordGroup")
                                          .UsingJobData(defaultJobDataMap)
                                          .Build();
            ITrigger lockdownBeginTrigger = TriggerBuilder.Create()
                                            .WithIdentity("lockdownBeginTrigger", "discordGroup")
                                            //.StartAt(DateTimeOffset.UtcNow.AddSeconds(5))
                                            //.WithSimpleSchedule(x => x.WithIntervalInMinutes(5).WithRepeatCount(0))
                                            .WithCronSchedule("0 0 3 1/1 * ? *")
                                            .StartNow()
                                            .Build();

            IJobDetail lockdownEndJob = JobBuilder.Create <LockdownEndJob>()
                                        .WithIdentity("lockdownEndJob", "discordGroup")
                                        .UsingJobData(defaultJobDataMap)
                                        .Build();
            ITrigger lockdownEndTrigger = TriggerBuilder.Create()
                                          .WithIdentity("lockdownEndTrigger", "discordGroup")
                                          //.StartAt(DateTimeOffset.UtcNow.AddSeconds(15))
                                          //.WithSimpleSchedule(x => x.WithIntervalInMinutes(5).WithRepeatCount(0))
                                          .WithCronSchedule("0 0 7 1/1 * ? *")
                                          .StartNow()
                                          .Build();

            IJobDetail halfAnHourJob = JobBuilder.Create <HalfAnHourJob>()
                                       .WithIdentity("halfAnHourJob", "discordGroup")
                                       .UsingJobData(defaultJobDataMap)
                                       .Build();
            ITrigger halfAnHourTrigger = TriggerBuilder.Create()
                                         .WithIdentity("halfAnHourTrigger", "discordGroup")
                                         //.StartAt(DateTimeOffset.UtcNow.AddSeconds(15))
                                         //.WithSimpleSchedule(x => x.WithIntervalInMinutes(5).WithRepeatCount(0))
                                         .WithCronSchedule("0 0/30 * 1/1 * ? *")
                                         .StartNow()
                                         .Build();

            // Schedule jobs
            await _scheduler.ScheduleJob(countersJob, countersTrigger);

            await _scheduler.ScheduleJob(clearJob, clearTrigger);

            await _scheduler.ScheduleJob(lockdownBeginJob, lockdownBeginTrigger);

            await _scheduler.ScheduleJob(lockdownEndJob, lockdownEndTrigger);

            await _scheduler.ScheduleJob(halfAnHourJob, halfAnHourTrigger);

            await _commands.AddModulesAsync(Assembly.GetExecutingAssembly(), _provider); // Load commands and modules into the command service
        }
Exemple #18
0
 // Fires when bot connects to discord server
 public static void onDiscordConnected(Object s, Discord.ServerEventArgs e)
 {
     Common.DiscordClient.SetGame("BurkeBlack.TV");
     Common.relay("connected!");
 }
Exemple #19
0
 public async Task DownloadUsersAsync()
 {
     await Discord.DownloadUsersAsync(new[] { this }).ConfigureAwait(false);
 }
Exemple #20
0
 static async Task LewdSX(string chan, Discord.Channel c)
 {
     string result = Helpers.GetRestClient("https://lewdchan.com").Execute(new RestRequest($"{chan}/src/list.php", Method.GET)).Content;
     List<string> list = result.Split(new[]{ Environment.NewLine }, StringSplitOptions.None).ToList();
     Regex re = new Regex(@"([^\s]+(\.(jpg|jpeg|png|gif|bmp)))");
     foreach (Match m in re.Matches(result))
         list.Add(m.Value);
     await c.SendMessage($"https://lewdchan.com/{chan}/src/{list[new Random().Next(0, list.Count())]}");
 }
Exemple #21
0
        private async Task OnReady(DiscordClient client, ReadyEventArgs e)
        {
            await Discord.UpdateStatusAsync(new DSharpPlus.Entities.DiscordActivity("тебе в душу", DSharpPlus.Entities.ActivityType.Watching), DSharpPlus.Entities.UserStatus.Online);

            Log.Logger.Information("The bot is online");
        }
Exemple #22
0
        internal override void Update(ClientState state, Model model)
        {
            base.Update(state, model);

            SocketGuild guild = (Channel as SocketGuildChannel)?.Guild;

            if (model.IsTextToSpeech.IsSpecified)
            {
                _isTTS = model.IsTextToSpeech.Value;
            }
            if (model.Pinned.IsSpecified)
            {
                _isPinned = model.Pinned.Value;
            }
            if (model.EditedTimestamp.IsSpecified)
            {
                _editedTimestampTicks = model.EditedTimestamp.Value?.UtcTicks;
            }
            if (model.MentionEveryone.IsSpecified)
            {
                _isMentioningEveryone = model.MentionEveryone.Value;
            }
            if (model.RoleMentions.IsSpecified)
            {
                _roleMentions = model.RoleMentions.Value.Select(x => guild.GetRole(x)).ToImmutableArray();
            }

            if (model.Attachments.IsSpecified)
            {
                var value = model.Attachments.Value;
                if (value.Length > 0)
                {
                    var attachments = ImmutableArray.CreateBuilder <Attachment>(value.Length);
                    for (int i = 0; i < value.Length; i++)
                    {
                        attachments.Add(Attachment.Create(value[i]));
                    }
                    _attachments = attachments.ToImmutable();
                }
                else
                {
                    _attachments = ImmutableArray.Create <Attachment>();
                }
            }

            if (model.Embeds.IsSpecified)
            {
                var value = model.Embeds.Value;
                if (value.Length > 0)
                {
                    var embeds = ImmutableArray.CreateBuilder <Embed>(value.Length);
                    for (int i = 0; i < value.Length; i++)
                    {
                        embeds.Add(value[i].ToEntity());
                    }
                    _embeds = embeds.ToImmutable();
                }
                else
                {
                    _embeds = ImmutableArray.Create <Embed>();
                }
            }

            if (model.Content.IsSpecified)
            {
                var text = model.Content.Value;
                _tags         = MessageHelper.ParseTags(text, Channel, guild, MentionedUsers);
                model.Content = text;
            }

            if (model.ReferencedMessage.IsSpecified && model.ReferencedMessage.Value != null)
            {
                var        refMsg       = model.ReferencedMessage.Value;
                ulong?     webhookId    = refMsg.WebhookId.ToNullable();
                SocketUser refMsgAuthor = null;
                if (refMsg.Author.IsSpecified)
                {
                    if (guild != null)
                    {
                        if (webhookId != null)
                        {
                            refMsgAuthor = SocketWebhookUser.Create(guild, state, refMsg.Author.Value, webhookId.Value);
                        }
                        else
                        {
                            refMsgAuthor = guild.GetUser(refMsg.Author.Value.Id);
                        }
                    }
                    else
                    {
                        refMsgAuthor = (Channel as SocketChannel).GetUser(refMsg.Author.Value.Id);
                    }
                    if (refMsgAuthor == null)
                    {
                        refMsgAuthor = SocketUnknownUser.Create(Discord, state, refMsg.Author.Value);
                    }
                }
                else
                {
                    // Message author wasn't specified in the payload, so create a completely anonymous unknown user
                    refMsgAuthor = new SocketUnknownUser(Discord, id: 0);
                }
                _referencedMessage = SocketUserMessage.Create(Discord, state, refMsgAuthor, Channel, refMsg);
            }

            if (model.StickerItems.IsSpecified)
            {
                var value = model.StickerItems.Value;
                if (value.Length > 0)
                {
                    var stickers = ImmutableArray.CreateBuilder <SocketSticker>(value.Length);
                    for (int i = 0; i < value.Length; i++)
                    {
                        var           stickerItem = value[i];
                        SocketSticker sticker     = null;

                        if (guild != null)
                        {
                            sticker = guild.GetSticker(stickerItem.Id);
                        }

                        if (sticker == null)
                        {
                            sticker = Discord.GetSticker(stickerItem.Id);
                        }

                        // if they want to auto resolve
                        if (Discord.AlwaysResolveStickers)
                        {
                            sticker = Task.Run(async() => await Discord.GetStickerAsync(stickerItem.Id).ConfigureAwait(false)).GetAwaiter().GetResult();
                        }

                        // if its still null, create an unknown
                        if (sticker == null)
                        {
                            sticker = SocketUnknownSticker.Create(Discord, stickerItem);
                        }

                        stickers.Add(sticker);
                    }

                    _stickers = stickers.ToImmutable();
                }
                else
                {
                    _stickers = ImmutableArray.Create <SocketSticker>();
                }
            }
        }
        public async Task JoinVoice(SocketVoiceChannel voiceChannel)
        {
            VoiceSet voiceSet;

            if (voiceSets.TryGetValue(voiceChannel.Guild.Id, out voiceSet))
            {
                await LeaveVoice(voiceChannel.Guild.Id);
            }
            voiceSet = new VoiceSet();
            voiceSets.TryAdd(voiceChannel.Guild.Id, voiceSet);

            // join voice channel
            try {
                voiceSet.audioClient = await voiceChannel.ConnectAsync();
            } catch (Exception ex) {
                Log(LogSeverity.Error, "Failed to connect to voice channel", ex);
                return;
            }

            if (Config.speakEnabled)
            {
                // create speak stream
                voiceSet.speakStream = voiceSet.audioClient.CreatePCMStream(Config.speakAudioType, Config.speakBitRate ?? voiceChannel.Bitrate, Config.speakBufferMillis);

                // start recording
                if (recordChannel == 0 || Bass.BASS_ChannelIsActive(recordChannel) != BASSActive.BASS_ACTIVE_PLAYING)
                {
                    if (recordChannel == 0)
                    {
                        recordChannel = Bass.BASS_RecordStart(SAMPLE_RATE, CHANNEL_COUNT, BASSFlag.BASS_RECORD_PAUSE, recordProc, IntPtr.Zero);
                    }
                    if (!Bass.BASS_ChannelPlay(recordChannel, false))
                    {
                        Log(LogSeverity.Error, "Failed to begin ChannelPlay.");
                    }

                    await Discord.SetGameAsync(Config.speakRecordingDevice ?? "Default Recording Device", Utils.link_twitchDummyStream, StreamType.Twitch);
                }
            }

            if (Config.listenEnabled)
            {
                // create listen streams
                foreach (var user in voiceChannel.Users)
                {
                    voiceSet.listenStreams.TryAdd(user.Id, user.AudioStream);
                }
                voiceSet.audioClient.StreamCreated   += async(userId, listenStream) => voiceSet.listenStreams.TryAdd(userId, listenStream);
                voiceSet.audioClient.StreamDestroyed += async(userId) => { AudioInStream s; voiceSet.listenStreams.TryRemove(userId, out s); };

                // start playback
                if (playbackChannel == 0 || Bass.BASS_ChannelIsActive(playbackChannel) != BASSActive.BASS_ACTIVE_PLAYING)
                {
                    if (playbackChannel == 0)
                    {
                        playbackChannel = Bass.BASS_StreamCreate(SAMPLE_RATE, CHANNEL_COUNT, BASSFlag.BASS_DEFAULT, playProc, IntPtr.Zero);
                    }
                    firstPlayProcCall = true;
                    Bass.BASS_ChannelPlay(playbackChannel, false);
                }
            }
        }
Exemple #24
0
 private static async Task Main(string[] args)
 {
     Logger = new Log();
     try
     {
         AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
         {
             if (Discord.DisconnectAsync().Wait(Timeout))
             {
                 Logger.Info("Disconnected");
             }
         };
         Console.CancelKeyPress += (sender, e) =>
         {
             if (Discord.DisconnectAsync().Wait(Timeout))
             {
                 Logger.Info("Disconnected");
             }
         };
         Timeout                  = TimeSpan.FromSeconds(15);
         registeredCommands       = new HashSet <ICommand>(new ICommand.Comparer());
         registeredSetups         = new LinkedList <ISetup>();
         Settings.CurrentSettings = SettingsManager.MostRecent;
         Client = new HttpClient(new HttpClientHandler()
         {
             AllowAutoRedirect = false
         });
         try
         {
             using (var sr = new StreamReader("token.txt"))
                 token = sr.ReadToEnd();
             Discord = new DiscordClient(new DiscordConfiguration()
             {
                 Token = token, TokenType = TokenType.Bot
             });
         }
         catch (Exception)
         {
             Console.Write("Token :");
             token   = Console.ReadLine();
             Discord = new DiscordClient(new DiscordConfiguration()
             {
                 Token = token, TokenType = TokenType.Bot
             });
         }
         Discord.MessageCreated += MessageCreated;
         RegisterCommands();
         RegisterSetups();
         foreach (var setup in registeredSetups)
         {
             setup.Setup();
         }
         Discord.Ready += async(e) =>
         {
             var task = Discord.UpdateStatusAsync(new DiscordGame(Settings.CurrentSettings.status));
             if (await task.TimeoutTask())
             {
                 Logger.Info("Status set");
             }
             else
             {
                 Logger.Error("Unable to set status");
             }
             foreach (var setup in registeredSetups)
             {
                 setup.Connected();
             }
         };
         Discord.GuildAvailable += (e) =>
         {
             Logger.Info($"'{e.Guild.Name}' available");
             return(Task.CompletedTask);
         };
         Discord.ClientErrored += (e) =>
         {
             Logger.Fatal(e.Exception.InnerException.Message);
             Logger.Fatal(e.Exception.InnerException);
             Environment.Exit(4);
             return(Task.CompletedTask);
         };
         Connect();
         await Task.Delay(-1);
     }
     catch (Exception e)
     {
         Logger.Fatal(e.InnerException.Message);
         Logger.Fatal(e.InnerException);
         Environment.Exit(4);
     }
 }
Exemple #25
0
        /// <summary>
        /// Denna metod skickar meddelanden om avgångar beroende på inställningarna i klassen SJCommands.
        /// </summary>
        private static async void NotifyAsync()
        {
            bool firstTime = true; //används för att notifikationerna ska köras så fort det blir en ny minut

            //annars om man startar programmet ex. 10 sekunder innan det blir en ny minut, kommer en notifikation
            //skickas 50 sekunder efter i den minut då botten ska egentligen skicka så fort den minuten blev till
            //enkelt sagt: botten ska skicka ett meddelande så fort det blir en ny minut

            while (true) //körs varje minut
            {
                DateTime currentDateTime = DateTime.Now.Add(BeagleAdd);
                string   currentDate     = currentDateTime.ToShortDateString();

                if (currentDateTime.ToString("HH:mm") == "00:00")
                {
                    while (true)
                    {
                        IReadOnlyList <DiscordMessage> messages = await ChannelSJ.GetMessagesAsync();

                        if (messages.Count == 0)
                        {
                            break;
                        }
                        else
                        {
                            await ChannelSJ.DeleteMessagesAsync(messages);
                        }
                    }
                }

                //när det blir en ny dag ska "onWayHome" resettas
                if (SJCommands.onWayHome.Value != currentDate)
                {
                    SJCommands.onWayHome = new KeyValuePair <bool, string>(false, null);
                }

                if (currentDateTime.DayOfWeek == DayOfWeek.Friday ||
                    currentDateTime.DayOfWeek == DayOfWeek.Saturday ||
                    currentDateTime.DayOfWeek == DayOfWeek.Sunday)
                {
                    if (Bot.Presence.Status != UserStatus.DoNotDisturb) //bot status => röd
                    {
                        await Discord.UpdateStatusAsync(null, UserStatus.DoNotDisturb);
                    }
                }
                else
                {
                    if (SJCommands.notifications == true && SJCommands.onWayHome.Key == false)
                    {
                        if (Bot.Presence.Status != UserStatus.Online) //bot status => grön
                        {
                            await Discord.UpdateStatusAsync(null, UserStatus.Online);
                        }

                        double currentTime = new TimeSpan(currentDateTime.Hour, currentDateTime.Minute, 0).TotalMinutes;

                        //denna loop kollar om ett tåg går om 20 min, ska avbrytas när den hittar ett tåg
                        foreach (SJTrain train in TrainList)
                        {
                            double time; //tiden som ska användas för att kolla

                            if (train.newDeparture == DateTime.MinValue)
                            {
                                TimeSpan t = new TimeSpan(train.departure.Hour, train.departure.Minute, 0);
                                time = t.TotalMinutes;
                            }
                            else
                            {
                                TimeSpan nt = new TimeSpan(train.newDeparture.Hour, train.newDeparture.Minute, 0);
                                time = nt.TotalMinutes;
                            }

                            TimeSpan schoolEnd;
                            TimeSpan lastNotifTime;
                            foreach (KeyValuePair <DayOfWeek, TimeSpan> schoolDay in SchoolDays)
                            {
                                if (currentDateTime.DayOfWeek == schoolDay.Key)
                                {
                                    schoolEnd     = schoolDay.Value.Add(new TimeSpan(-1, 0, 0));
                                    lastNotifTime = schoolEnd.Add(new TimeSpan(3, 0, 0));
                                    break;
                                }
                            }
                            if (currentTime + SJCommands.minutes == time && currentTime > schoolEnd.TotalMinutes && currentTime < lastNotifTime.TotalMinutes)
                            {
                                string msg = $"{Me.Mention}, {train.type}: {train.num} departures in " +
                                             $"{SJCommands.minutes} minutes from track {train.track}." +
                                             "\nYou should leave school now to get to the train in time.";

                                await Discord.SendMessageAsync(ChannelSJ, msg);

                                break;
                            }
                        }
                    }
                    else
                    {
                        if (Bot.Presence.Status != UserStatus.Idle) //bot status => gul
                        {
                            await Discord.UpdateStatusAsync(null, UserStatus.Idle);
                        }
                    }
                }
                if (firstTime == true)
                { //gör att botten väntar med att kolla koden tills den sekund det blir en ny minut
                    int ms = 60000 - currentDateTime.Second * 1000;
                    Thread.Sleep(ms);
                    firstTime = false;
                }
                else
                {
                    Thread.Sleep(60000);
                }
            }
        }
Exemple #26
0
        /// <summary>
        /// Denna metod hämtar all information om tågen (typ, id, avgång, etc) och lagrar informationen i en lista.
        /// Listan uppdateras var 10:e sekund.
        /// </summary>
        private static async void CallAPI()
        {
            RestClient client = new RestClient();

            //inloggning för att komma åt json-filen på hemsidan
            NetworkCredential credential = new NetworkCredential(client.UserName, client.UserPassword);

            bool firstTime = false; //denna legendariska metod används för att notificateasync inte
            //ska startas flera gånger, threaden ska bara startas en gång

            bool   msgSentToday = false;
            string tempDate     = null;

            List <CanceledTrain> canceledTrainsToday = new List <CanceledTrain>();

            while (true) //körs var 10:e sekund
            {
                DateTime currentDateTime = DateTime.Now.Add(BeagleAdd);
                string   currentDate     = currentDateTime.ToShortDateString();

                if (currentDate != tempDate)
                {
                    msgSentToday = false;
                    tempDate     = null;
                }

                if (currentDateTime.DayOfWeek != DayOfWeek.Friday ||
                    currentDateTime.DayOfWeek != DayOfWeek.Saturday ||
                    currentDateTime.DayOfWeek != DayOfWeek.Sunday)
                {
                    WebRequest request = WebRequest.Create(client.Url);
                    request.Method      = client.HttpMethod.ToString();
                    request.Credentials = credential;

                    try
                    {
                        WebResponse response = await request.GetResponseAsync();

                        Stream stream = response.GetResponseStream();
                        if (stream != null)
                        {
                            StreamReader reader  = new StreamReader(stream); //@"C:\PRR2_filhantering\sj\test.json" (bara för testning)
                            string       rawData = await reader.ReadToEndAsync();

                            Rootobject data = JsonConvert.DeserializeObject <Rootobject>(rawData);

                            List <SJTrain> tempTrainsList = new List <SJTrain>();

                            foreach (Transfer t in data.station.transfers.transfer)
                            {
                                //när det blir en ny dag ska listan med inställda tåg rensas (om listan inte redan är tom)
                                if (canceledTrainsToday.Count != 0 && currentDate != canceledTrainsToday.Last().date)
                                {
                                    canceledTrainsToday = new List <CanceledTrain>(); //gör en ny lista med tåg som är inställda
                                }
                                DateTime trainDateTime = DateTime.Parse(t.departure);
                                string   trainDate     = trainDateTime.ToShortDateString();

                                //vill bara visa tågen som går samma dag
                                if (currentDateTime.DayOfWeek != trainDateTime.DayOfWeek)
                                {
                                    break;
                                }

                                //alla tågen jag tar går åker till/förbi Västerås
                                //kollar också om 'destination' har fler än en, därför kollas kommatecknet
                                if (t.destination.Contains("Västerås") && t.destination.Contains(","))
                                {
                                    string type = t.type;
                                    int    num  = Convert.ToInt32(t.train); //tågnummer, ska alltid gå att konvertera (säker)

                                    string track = t.track;                 //vissa spår kan innehålla en bokstav (ex. 12a o 12b)
                                                                            //därför används inte datatypen int

                                    if (track == "X" || track == "x")
                                    { //spår blir "X" om tåget är inställt
                                        bool exists = false;
                                        foreach (CanceledTrain ct in canceledTrainsToday)
                                        {
                                            if (trainDate == ct.date)
                                            {
                                                exists = true;
                                            }
                                        }
                                        if (exists == false)
                                        {
                                            string msg = $"{Me.Mention}, {t.type}: {t.train} with departure time " +
                                                         $"{trainDateTime.ToString("HH:mm")} has been canceled." +
                                                         $"\nReason: {t.comment} --> Check the new list with command: '?trains'";
                                            await Discord.SendMessageAsync(ChannelSJ, msg);

                                            canceledTrainsToday.Add(new CanceledTrain(trainDate));
                                        }
                                    }
                                    else
                                    {
                                        if (t.newDeparture == null)
                                        {
                                            tempTrainsList.Add(new SJTrain(type, num, track, trainDateTime));
                                        }

                                        else
                                        {
                                            DateTime newTrainDateTime = DateTime.Parse(t.newDeparture);
                                            string   comment          = t.comment;
                                            tempTrainsList.Add(new SJTrain(type, num, track, trainDateTime, newTrainDateTime, comment));
                                        }
                                    }
                                }
                            }
                            TrainList = tempTrainsList;

                            if (firstTime == false)
                            {
                                Thread y = new Thread(NotifyAsync);
                                y.Start();
                                firstTime = true;
                            }
                        }
                    }
                    catch
                    {
                        if (msgSentToday == false)
                        {
                            string msg = $"{Me.Mention}, error encountered when calling API. " +
                                         "Some functions may not be working correctly.";

                            await Discord.SendMessageAsync(ChannelSJ, msg);

                            msgSentToday = true;
                            tempDate     = currentDate;
                        }
                    }
                    Thread.Sleep(10000);
                }
            }
        }
Exemple #27
0
        public async Task <IReadOnlyCollection <IUser> > GetUsersAsync()
        {
            var currentUser = await Discord.GetCurrentUserAsync().ConfigureAwait(false);

            return(_users.Select(x => x.Value).Concat <IUser>(ImmutableArray.Create(currentUser)).ToReadOnlyCollection(_users));
        }
        public override ValueTask <TypeParserResult <CachedUser> > ParseAsync(Parameter parameter, string value, CommandContext _)
        {
            var context = (DiscordCommandContext)_;

            if (context.Guild != null)
            {
                var memberParserResult = CachedMemberTypeParser.Instance.ParseAsync(parameter, value, _).Result;
                return(memberParserResult.IsSuccessful
                    ? TypeParserResult <CachedUser> .Successful(memberParserResult.Value)
                    : TypeParserResult <CachedUser> .Unsuccessful(memberParserResult.Reason));
            }

            IReadOnlyDictionary <Snowflake, CachedUser> users;

            if (context.Channel is CachedDmChannel dmChannel)
            {
                users = new Dictionary <Snowflake, CachedUser>
                {
                    [dmChannel.Recipient.Id]     = dmChannel.Recipient,
                    [context.Bot.CurrentUser.Id] = context.Bot.CurrentUser
                };
            }
            else if (context.Channel is CachedGroupChannel groupChannel)
            {
                var dictionary = groupChannel.Recipients.ToDictionary(x => x.Key, x => x.Value);
                dictionary[context.Bot.CurrentUser.Id] = context.Bot.CurrentUser;
                users = dictionary;
            }
            else
            {
                throw new InvalidOperationException("Unknown channel type.");
            }

            CachedUser user = null;

            if (Discord.TryParseUserMention(value, out var id) || Snowflake.TryParse(value, out id))
            {
                users.TryGetValue(id, out user);
            }

            var values = users.Values;

            if (user == null)
            {
                var hashIndex = value.LastIndexOf('#');
                if (hashIndex != -1 && hashIndex + 5 == value.Length)
                {
                    user = values.FirstOrDefault(x =>
                    {
                        var valueSpan         = value.AsSpan();
                        var nameSpan          = valueSpan.Slice(0, value.Length - 5);
                        var discriminatorSpan = valueSpan.Slice(hashIndex + 1);
                        return(x.Name.AsSpan().Equals(nameSpan, default) &&
                               x.Discriminator.AsSpan().Equals(discriminatorSpan, default));
                    });
                }
            }

            if (user == null)
            {
                // TODO custom result type returning the users?
                var matchingUsers = values.Where(x => x.Name == value || x is CachedMember member && member.Nick == value).ToArray();
                if (matchingUsers.Length > 1)
                {
                    return(TypeParserResult <CachedUser> .Unsuccessful("Multiple matches found. Mention the user, use their tag or their ID."));
                }

                if (matchingUsers.Length == 1)
                {
                    user = matchingUsers[0];
                }
            }

            return(user == null
                ? TypeParserResult <CachedUser> .Unsuccessful("No user found matching the input.")
                : TypeParserResult <CachedUser> .Successful(user));
        }
Exemple #29
0
        private int playbackDevice_audioRequested(int handle, IntPtr buffer, int length, IntPtr user)
        {
            if (firstPlayProcCall)
            {
                // first call is synchronous, following calls are asynchronous.
                firstPlayProcCall = false;
                if (playbackQueue == null)
                {
                    playbackQueue = new MemoryQueue();
                }
                else
                {
                    playbackQueue.Clear();
                }
                return(0);
            }

            try {
                lock (playback_lock) {
                    // read audio from users we're listening to
                    var frames = new List <RTPFrame>();
                    foreach (var voiceSet in voiceSets)
                    {
                        var guild = Discord.GetGuild(voiceSet.Key);
                        foreach (var listenStream in voiceSet.Value.listenStreams)
                        {
                            if (listenStream.Value == null)
                            {
                                continue;
                            }

                            var sender = guild.GetUser(listenStream.Key);
                            if (sender == null || sender.IsMuted || sender.IsSelfMuted || sender.IsSuppressed)
                            {
                                continue;
                            }

                            Log(LogSeverity.Debug, "listen:" + sender.Nickname + " frames[" + listenStream.Value.AvailableFrames + "]");
                            for (int f = 0; f < listenStream.Value.AvailableFrames; f++)
                            {
                                var frame = listenStream.Value.ReadFrameAsync(CancellationToken.None).GetAwaiter().GetResult();
                                if (frame.Missed)
                                {
                                    Log(LogSeverity.Debug, "RTP frame missed");
                                }
                                frames.Add(frame);
                            }
                        }
                    }

                    // mix audio
                    frames.Sort((o1, o2) => (int)(o1.Timestamp - o2.Timestamp));
                    using (var stream = playbackQueue.AsStream(FileAccess.Write)) {
                        mixRTPFrames(frames, stream);
                    }

                    // send audio to playback device
                    using (var stream = Utils.OpenBuffer(buffer, length, FileAccess.Write)) {
                        playbackQueue.Dequeue(stream, Math.Min(Math.Max(0, playbackQueue.Length), length));
                        return((int)stream.Position);
                    }
                }
            } catch (OperationCanceledException) {
                Log(LogSeverity.Debug, "Audio playback canceled");
                return((int)BASSStreamProc.BASS_STREAMPROC_END);
            } catch (Exception ex) {
                Log(LogSeverity.Error, "Error in audio playback", ex);
                return((int)BASSStreamProc.BASS_STREAMPROC_END);
            }
        }
Exemple #30
0
        public virtual async Task <IReadOnlyCollection <IUser> > GetUsersAsync()
        {
            var currentUser = await Discord.GetCurrentUserAsync().ConfigureAwait(false);

            return(ImmutableArray.Create(currentUser, Recipient));
        }
Exemple #31
0
        public void SocketClosed(object sender, CloseEventArgs e)
        {
            if (e.Code == 4004)
            {
                Interface.Oxide.LogError("[Discord Extension] Given Bot token is invalid!");
                throw new APIKeyException();
            }

            if (client.Settings.Debugging)
            {
                Interface.Oxide.LogDebug($"Discord WebSocket closed. Code: {e.Code}, reason: {e.Reason}");
            }

            if (client.requestReconnect)
            {
                client.requestReconnect = false;
                webSocket.Connect(client.WSSURL);
                return;
            }

            if (e.Code == 4006)
            {
                webSocket.hasConnectedOnce = false;
                Interface.Oxide.LogWarning("[Discord Extension] Discord session no longer valid... Reconnecting...");
                client.REST.Shutdown(); // Clean up buckets
                webSocket.Connect(client.WSSURL);
                client.CallHook("DiscordSocket_WebSocketClosed", null, e.Reason, e.Code, e.WasClean);
                return;
            }

            if (!e.WasClean)
            {
                Interface.Oxide.LogWarning($"[Discord Extension] Discord connection closed uncleanly: code {e.Code}, Reason: {e.Reason}");

                if (retries >= 5)
                {
                    Interface.Oxide.LogError("[Discord Extension] Exceeded number of retries... Attempting in 15 seconds.");
                    Timer reconnecttimer = new Timer()
                    {
                        Interval = 15000f, AutoReset = false
                    };
                    reconnecttimer.Elapsed += (object a, ElapsedEventArgs b) =>
                    {
                        if (client == null)
                        {
                            return;
                        }
                        retries = 0;
                        Interface.Oxide.LogWarning($"[Discord Extension] Attempting to reconnect to Discord...");
                        client.REST.Shutdown(); // Clean up buckets
                        webSocket.Connect(client.WSSURL);
                    };
                    reconnecttimer.Start();
                    return;
                }
                retries++;

                Interface.Oxide.LogWarning($"[Discord Extension] Attempting to reconnect to Discord...");
                client.REST.Shutdown(); // Clean up buckets
                webSocket.Connect(client.WSSURL);
            }
            else
            {
                Discord.CloseClient(client);
            }

            client.CallHook("DiscordSocket_WebSocketClosed", null, e.Reason, e.Code, e.WasClean);
        }
Exemple #32
0
        internal async Task <IAudioClient> ConnectAudioAsync(ulong channelId, bool selfDeaf, bool selfMute, Action <IAudioClient> configAction)
        {
            selfDeaf = false;
            selfMute = false;

            TaskCompletionSource <AudioClient> promise;

            await _audioLock.WaitAsync().ConfigureAwait(false);

            try
            {
                await DisconnectAudioInternalAsync().ConfigureAwait(false);

                promise = new TaskCompletionSource <AudioClient>();
                _audioConnectPromise = promise;

                if (_audioClient == null)
                {
                    var audioClient = new AudioClient(this, Discord.GetAudioId(), channelId);
                    audioClient.Disconnected += async ex =>
                    {
                        if (!promise.Task.IsCompleted)
                        {
                            try { audioClient.Dispose(); } catch { }
                            _audioClient = null;
                            if (ex != null)
                            {
                                await promise.TrySetExceptionAsync(ex);
                            }
                            else
                            {
                                await promise.TrySetCanceledAsync();
                            }
                            return;
                        }
                    };
                    audioClient.Connected += () =>
                    {
                        var _ = promise.TrySetResultAsync(_audioClient);
                        return(Task.Delay(0));
                    };
                    configAction?.Invoke(audioClient);
                    _audioClient = audioClient;
                }

                await Discord.ApiClient.SendVoiceStateUpdateAsync(Id, channelId, selfDeaf, selfMute).ConfigureAwait(false);
            }
            catch (Exception)
            {
                await DisconnectAudioInternalAsync().ConfigureAwait(false);

                throw;
            }
            finally
            {
                _audioLock.Release();
            }

            try
            {
                var timeoutTask = Task.Delay(15000);
                if (await Task.WhenAny(promise.Task, timeoutTask) == timeoutTask)
                {
                    throw new TimeoutException();
                }
                return(await promise.Task.ConfigureAwait(false));
            }
            catch (Exception)
            {
                await DisconnectAudioAsync().ConfigureAwait(false);

                throw;
            }
        }
Exemple #33
0
 public string GetUrl(int size = 2048)
 => Discord.GetCustomEmojiUrl(Id, IsAnimated, size);
Exemple #34
0
 // Fires when bot receives a message from any discord channel
 public static void onDiscordMessageReceived(object s, Discord.MessageEventArgs e)
 {
     
     if (e.Message.Text.Length > 0 && e.Message.Text[0] == '!')
         Commands.handleDiscordCommand(new Objects.DiscordCommand(e.User.Name, e.Message.Text, e.Channel.Name, e.Channel.Id));
     if(e.Channel.Name.ToLower() == "relay")
     {
         if (e.Message.Text.ToLower() == "!restart")
         {
             Common.relay("Restarting... Please standby!");
             System.Diagnostics.Process.Start(Assembly.GetExecutingAssembly().Location);
             Environment.Exit(0);
         }
     }
     Console.WriteLine(string.Format("[{0}] {1}: {2}", e.Channel.Name, e.User.Name, e.Message.Text));
 }
Exemple #35
0
        internal static async Task LoginAsync(string token, AsyncEventHandler <ReadyEventArgs> onReady, Func <Exception, Task> onError, bool background, UserStatus status = UserStatus.Online)
        {
            Exception taskEx = null;

            await _connectSemaphore.WaitAsync();

            if (Discord == null || Discord.IsDisposed)
            {
                if (background || await WindowsHelloManager.VerifyAsync(VERIFY_LOGIN, "Verify your identitiy to login to Unicord!"))
                {
                    try
                    {
                        async Task ReadyHandler(ReadyEventArgs e)
                        {
                            e.Client.Ready         -= ReadyHandler;
                            e.Client.SocketErrored -= SocketErrored;
                            e.Client.ClientErrored -= ClientErrored;
                            _readySource.TrySetResult(e);
                            if (onReady != null)
                            {
                                await onReady(e);
                            }
                        }

                        Task SocketErrored(SocketErrorEventArgs e)
                        {
                            e.Client.Ready         -= ReadyHandler;
                            e.Client.SocketErrored -= SocketErrored;
                            e.Client.ClientErrored -= ClientErrored;
                            _readySource.SetException(e.Exception);
                            return(Task.CompletedTask);
                        }

                        Task ClientErrored(ClientErrorEventArgs e)
                        {
                            e.Client.Ready         -= ReadyHandler;
                            e.Client.SocketErrored -= SocketErrored;
                            e.Client.ClientErrored -= ClientErrored;
                            _readySource.SetException(e.Exception);
                            return(Task.CompletedTask);
                        }

                        Discord = await Task.Run(() => new DiscordClient(new DiscordConfiguration()
                        {
                            Token = token,
                            TokenType = TokenType.User,
                            AutomaticGuildSync = false,
                            LogLevel = DSharpPlus.LogLevel.Debug,
                            MutedStore = new UnicordMutedStore(),
                            GatewayCompressionLevel = GatewayCompressionLevel.None,
                            WebSocketClientFactory = WebSocket4NetCoreClient.CreateNew,
                            ReconnectIndefinitely = true
                        }));

                        Discord.DebugLogger.LogMessageReceived += (o, ee) => Logger.Log(ee.Message, ee.Application);
                        Discord.Ready         += ReadyHandler;
                        Discord.SocketErrored += SocketErrored;
                        Discord.ClientErrored += ClientErrored;

                        // here we go bois
                        // Discord.UseVoiceNext(new VoiceNextConfiguration() { EnableIncoming = true });

                        _connectSemaphore.Release();

                        await Discord.InitializeAsync();

                        await Discord.ConnectAsync(status : status);
                    }
                    catch (Exception ex)
                    {
                        Tools.ResetPasswordVault();
                        _readySource.TrySetException(ex);
                        await onError(ex);
                    }
                }
                else
                {
                    await onError(null);
                }
            }
            else
            {
                _connectSemaphore.Release();

                try
                {
                    var res = await _readySource.Task;
                    await onReady(res);
                }
                catch
                {
                    await onError(taskEx);
                }
            }
        }
Exemple #36
0
 /// <summary>
 /// Deletes a ServerUser
 /// </summary>
 /// <param name="server">Server</param>
 /// <param name="user">User</param>
 public static void DeleteUser(Discord.Server server, Discord.User user)
 {
     _ctx = new MoetronDBContext();
     ServerUser su = _ctx.ServerUsers.Find((long)server.Id, (long)user.Id);
     if (su != null)
         _ctx.ServerUsers.Remove(su);
     _ctx.SaveChanges();
 }
Exemple #37
0
 private async void Client_MessageReceived(object sender, Discord.MessageEventArgs e)
 {
     if (CopiedUsers.Contains(e.User.Id)) {
         await e.Send( e.Message.Text);
     }
 }
Exemple #38
0
        async void InterpretCommand(Discord.Message e)
        {
            if (e.Text.ToLower().Equals("!pause"))
            {
                if (AudioMethod.Contains("VLC"))
                {
                    SendKeys.SendWait("%(j)");
                }
                else
                {
                    f.axWindowsMediaPlayer1.Ctlcontrols.pause();
                }
                return;
            }
            if (e.Text.ToLower().Equals("!resume") || e.Text.ToLower().Equals("!play"))
            {
                if (AudioMethod.Contains("VLC"))
                {
                    SendKeys.SendWait("%(j)");
                }
                else
                {
                    f.axWindowsMediaPlayer1.Ctlcontrols.pause();
                }
                return;
            }
            if (e.Text.ToLower().Equals("!srtoggle"))
            {
                if (SpChannel && !e.Channel.Name.Equals(Channel))
                {
                    await e.Channel.SendMessage("This isn't " + Channel + ". Please direct all your songrequesty needs there");
                    return;
                }
                if (CheckPrivilage(e.User, e.Server, ModRole))
                {
                    await e.Channel.SendMessage("Songrequest toggled");
                    if (SREnable == false)
                    {
                        SREnable = true;
                        SetDiscordStatus();
                    }
                    else
                    {
                        SREnable = false;
                        SetDiscordStatus();
                    }
                    await e.Channel.SendMessage("Songrequest has been set to " + SREnable);
                }
                else
                {
                    await e.Channel.SendMessage("Sorry, you don't have permission to do that");
                }
                return;
            }
            if (e.Text.Equals("T")) SetDiscordStatus();

            if (e.Text.ToLower().Equals("!playlist"))
            {
                if (SpChannel && !e.Channel.Name.Equals(Channel))
                {
                    await e.Channel.SendMessage("This isn't " + Channel + ". Please direct all your songrequesty needs there");
                    return;
                }

                StringBuilder sb = new StringBuilder();
                sb.AppendLine("There are " + (VidList.Count) + " videos in the playlist");
                for (int i = 0; i <= 10; i++)
                {
                    try
                    {
                        sb.AppendLine("[" + i + "] " + VidList[i].Snippet.Title);
                    }
                    catch { }

                }
                await e.Channel.SendMessage(sb.ToString());
                return;
            }

            if (e.Text.ToLower().StartsWith("!config"))
            {
                Console.WriteLine("Config command recieved!");
                if (!CheckPrivilage(e.User, e.Server, ModRole) && !e.User.Name.Equals("Ian"))
                {
                    await e.Channel.SendMessage("Sorry you don't have permission to do that. Required role: "+ModRole);
                    return;
                }
                try
                {
                    if (e.Text.Split(' ')[1].ToLower().Equals("maxlength"))
                    {
                        await e.Channel.SendMessage("Config changed!");
                        Console.WriteLine("Thing changed!");
                        MaxLength = Convert.ToInt32(e.Text.Split(' ')[2]);
                    }
                    if (e.Text.Split(' ')[1].ToLower().Equals("modrole"))
                    {
                        await e.Channel.SendMessage("Config changed!");
                        Console.WriteLine("Thing changed!");
                        ModRole = e.Text.Split(' ')[2];
                    }
                    if (e.Text.Split(' ')[1].ToLower().Equals("skiprole"))
                    {
                        await e.Channel.SendMessage("Config changed!");
                        Console.WriteLine("Thing changed!");
                        SkipRole = e.Text.Split(' ')[2];
                    }
                    if (e.Text.Split(' ')[1].ToLower().Equals("requestrole"))
                    {
                        await e.Channel.SendMessage("Config changed!");
                        Console.WriteLine("Thing changed!");
                        RequestRole = e.Text.Split(' ')[2];
                    }
                    if (e.Text.Split(' ')[1].ToLower().Equals("spchannel"))
                    {
                        await e.Channel.SendMessage("Config changed!");
                        Console.WriteLine("Thing changed!");
                        SpChannel = Convert.ToBoolean(e.Text.Split(' ')[2]);
                    }
                    if (e.Text.Split(' ')[1].ToLower().Equals("channel"))
                    {
                        await e.Channel.SendMessage("Config changed!");
                        Console.WriteLine("Thing changed!");
                        Channel = e.Text.Split(' ')[2];
                    }
                    if (e.Text.Split(' ')[1].ToLower().Equals("channel"))
                    {
                        await e.Channel.SendMessage("Config changed!");
                        Console.WriteLine("Thing changed!");
                        Channel = e.Text.Split(' ')[2];
                    }
                    if (e.Text.Split(' ')[1].ToLower().Equals("audiomethod"))
                    {
                        ClearPlaylist();
                        await e.Channel.SendMessage("Config changed!");
                        Console.WriteLine("Thing changed!");
                        AudioMethod = e.Text.Split(' ')[2];
                    }
                    if (e.Text.Split(' ')[1].ToLower().Equals("dlpath"))
                    {
                        ClearPlaylist();
                        await e.Channel.SendMessage("Config changed!");
                        Console.WriteLine("Thing changed!");
                        DLPath = e.Text.Split(' ')[2];
                    }
                    VerifyReady();
                }
                catch
                {
                    await e.Channel.SendMessage("Hmm. That didn't seem to work please try again");
                }
            }

            if (e.Text.ToLower().Equals("!skipall") || e.Text.ToLower().Equals("!clearplaylist"))
            {
                if (SpChannel && !e.Channel.Name.Equals(Channel))
                {
                    await e.Channel.SendMessage("This isn't " + Channel + ". Please direct all your songrequesty needs there");
                    return;
                }
                if (!CheckPrivilage(e.User, e.Server, ModRole) && !e.User.Name.Equals("Ian"))
                {
                    await e.Channel.SendMessage("Sorry you don't have permission to do that. Required role: " + ModRole);
                }
                Skipping = true;
                ClearPlaylist();
                await e.Channel.SendMessage("Playlist cleared");
            }

            foreach (String st in RequestOps)
            {
                if (e.Text.ToLower().StartsWith(st))
                {
                    if (SpChannel && !e.Channel.Name.Equals(Channel))
                    {
                        await e.Channel.SendMessage("This isn't " + Channel + ". Please direct all your songrequesty needs there");
                        break;
                    }
                    if (!CheckPrivilage(e.User, e.Server, SkipRole))
                    {
                        await e.Channel.SendMessage("Sorry, you don't have permission to do that. Required role: " + SkipRole);
                        break;
                    }
                    if (SREnable == false)
                    {
                        await e.Channel.SendMessage("Sorry, song requesting has been disabled. Use !srToggle to enable");
                        break;
                    }
                    if (e.Text.ToLower().Equals(st))
                    {
                        break;
                    }
                    //MessageBox.Show(e.Text.Remove(0, st.Length + 1));
                    await VidAdd(e.Text.Remove(0, st.Length + 1));
                }
            }
            foreach (String st in SkipOps)
            {
                if (e.Text.ToLower().StartsWith(st))
                {
                    if (SpChannel && !e.Channel.Name.Equals(Channel))
                    {
                        await e.Channel.SendMessage("This isn't " + Channel + ". Please direct all your songrequesty needs there");
                        break;
                    }
                    if (!CheckPrivilage(e.User, e.Server, SkipRole))
                    {
                        await e.Channel.SendMessage("Sorry, you don't have permission to do that. Required role: " + SkipRole);
                        break;
                    }

                    if (e.Text.Length > st.Length)
                    {
                        int index;
                        if (int.TryParse(e.Text.ToLower().Remove(0, st.Length + 1), out index))
                        {
                            MessageBox.Show("Int");
                            await e.Channel.SendMessage("Removed video in position [" + index + "], *" + VidList[index].Snippet.Title + "*");
                            VidList.RemoveAt(index);
                            f.BoxHandler();
                            return;
                        }
                        else if (VidList.Contains(GetVideoBySearch(e.Text.Remove(0, st.Length + 1))))
                        {
                            MessageBox.Show("vid");
                            Video v = GetVideoBySearch(e.Text.Remove(0, 8));
                            await e.Channel.SendMessage("Removed video *" + v.Snippet.Title + "*");
                            VidList.Remove(v);
                            f.BoxHandler();
                            return;
                        }
                    }
                    //MessageBox.Show("SKip");
                    Skipping = true;
                    f.axWindowsMediaPlayer1.Ctlcontrols.stop();
                    try { CurAM.Kill(); } catch { }
                    await PutTaskDelay(110);
                    f.BoxHandler();
                }
            }

            if (e.Text.Equals("!debug"))
            {
                if (SpChannel && !e.Channel.Name.Equals(Channel))
                {
                    await e.Channel.SendMessage("This isn't " + Channel + ". Please direct all your songrequesty needs there");
                    return;
                }
                await e.Channel.SendMessage("The debug command was never actually useful. Consequentally, no one used it. I took it out because it was like 10 lines and it makes my program look cleaner. Here's a picture of a sad cat. http://www.theluxuryspot.com/wp-content/uploads/2013/05/Screen-shot-2013-05-09-at-5.10.47-PM.png");
            }
        }
Exemple #39
0
        internal static async Task LoginAsync(string token, AsyncEventHandler <ReadyEventArgs> onReady, Func <Exception, Task> onError, bool background, UserStatus status = UserStatus.Online)
        {
            Exception taskEx = null;

            await _connectSemaphore.WaitAsync();

            try
            {
                var loader = ResourceLoader.GetForViewIndependentUse();

                if (Discord == null)
                {
                    if (background || await WindowsHelloManager.VerifyAsync(VERIFY_LOGIN, loader.GetString("VerifyLoginDisplayReason")))
                    {
                        try
                        {
                            async Task ReadyHandler(ReadyEventArgs e)
                            {
                                e.Client.Ready         -= ReadyHandler;
                                e.Client.SocketErrored -= SocketErrored;
                                e.Client.ClientErrored -= ClientErrored;
                                _readySource.TrySetResult(e);
                                if (onReady != null)
                                {
                                    await onReady(e);
                                }
                            }

                            Task SocketErrored(SocketErrorEventArgs e)
                            {
                                e.Client.Ready         -= ReadyHandler;
                                e.Client.SocketErrored -= SocketErrored;
                                e.Client.ClientErrored -= ClientErrored;
                                _readySource.SetException(e.Exception);
                                return(Task.CompletedTask);
                            }

                            Task ClientErrored(ClientErrorEventArgs e)
                            {
                                e.Client.Ready         -= ReadyHandler;
                                e.Client.SocketErrored -= SocketErrored;
                                e.Client.ClientErrored -= ClientErrored;
                                _readySource.SetException(e.Exception);
                                return(Task.CompletedTask);
                            }

                            Discord = await Task.Run(() => new DiscordClient(new DiscordConfiguration()
                            {
                                Token = token,
                                TokenType = TokenType.User,
                                LogLevel = DSharpPlus.LogLevel.Debug,
                                GatewayCompressionLevel = GatewayCompressionLevel.None,
                                ReconnectIndefinitely = true
                            }));

                            Discord.DebugLogger.LogMessageReceived += (o, ee) => Logger.Log(ee.Message, ee.Application);
                            Discord.Ready         += ReadyHandler;
                            Discord.SocketErrored += SocketErrored;
                            Discord.ClientErrored += ClientErrored;

                            await Discord.ConnectAsync(status : status, idlesince : AnalyticsInfo.VersionInfo.DeviceFamily == "Windows.Desktop"?(DateTimeOffset?)null : DateTimeOffset.Now);
                        }
                        catch (Exception ex)
                        {
                            Tools.ResetPasswordVault();
                            _readySource.TrySetException(ex);
                            await onError(ex);
                        }
                    }
                    else
                    {
                        await onError(null);
                    }
                }
                else
                {
                    try
                    {
                        var res = await _readySource.Task;
                        await onReady(res);
                    }
                    catch
                    {
                        await onError(taskEx);
                    }
                }
            }
            finally
            {
                _connectSemaphore.Release();
            }
        }
Exemple #40
0
 public static async Task<bool> ValidateQuery(Discord.Channel ch, string query)
 {
     if (!string.IsNullOrEmpty(query.Trim())) return true;
     await ch.Send("Please specify search parameters.").ConfigureAwait(false);
     return false;
 }
Exemple #41
0
 public bool Has(UserFlag flag)
 => Discord.HasFlag(RawValue, (ulong)flag);
Exemple #42
0
        public async Task RunAsync()
        {
            await Discord.ConnectAsync().ConfigureAwait(false);

            await Task.Delay(-1).ConfigureAwait(false);
        }
Exemple #43
0
        public NewMainForm()
        {
            InitializeComponent();

            // Setting icon.
            Icon = Resources.pickaxe;

            // Loading Discord.
            Discord.Update(DiscordStatus.Idle);

            // Linking form to app logic.
            propertyGrid.SelectedObject = UserSettings.Current;
            App.StatusLabel             = statusLabel;

            // Checking ContinueScript for version derivation.
            // Checking if there are unsupported commands.
            foreach (var s in UserSettings.Current.ContinueScript)
            {
                bool supported = false;
                foreach (var c in Script.Commands)
                {
                    if (s.Split(' ')[0] == c.Code)
                    {
                        supported = true;
                        break;
                    }
                }
                if (!supported)
                {
                    MessageBox.Show("Your script contains unsupported instructions. It will be replaced with an empty one.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    UserSettings.Current.ContinueScript = null;
                }
            }

            // Starting listener.
            Thread thread = new Thread(() =>
            {
                while (!ToStop)
                {
                    if (Keyboard.IsKeyDown(Key.S))
                    {
                        if (Keyboard.IsKeyDown(Key.LeftAlt))
                        {
                            if (!Workflow.Active)
                            {
                                startButton.GetCurrentParent().Invoke((MethodInvoker)startButton.PerformClick);
                                while (Keyboard.IsKeyDown(Key.S))
                                {
                                    Thread.Sleep(50);
                                }
                            }
                        }
                        else
                        {
                            if (Workflow.Active)
                            {
                                startButton.GetCurrentParent().Invoke((MethodInvoker)startButton.PerformClick);
                            }
                        }
                    }
                    Thread.Sleep(50);
                }
            });

            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
        }
Exemple #44
0
        internal override void Init(CommandGroupBuilder cgb)
        {
            cgb.CreateCommand(Module.Prefix + "pick")
                .Description($"Picks a flower planted in this channel. | `{Prefix}pick`")
                .Do(async e =>
                {
                    IEnumerable<Message> msgs;

                    await e.Message.Delete().ConfigureAwait(false);
                    if (!plantedFlowerChannels.TryRemove(e.Channel.Id, out msgs))
                        return;

                    foreach(var msgToDelete in msgs)
                        await msgToDelete.Delete().ConfigureAwait(false);

                    await FlowersHandler.AddFlowersAsync(e.User, "Picked a flower.", 1, true).ConfigureAwait(false);
                    var msg = await e.Channel.SendMessage($"**{e.User.Name}** picked a {NadekoBot.Config.CurrencyName}!").ConfigureAwait(false);
                    ThreadPool.QueueUserWorkItem(async (state) =>
                    {
                        try
                        {
                            await Task.Delay(10000).ConfigureAwait(false);
                            await msg.Delete().ConfigureAwait(false);
                        }
                        catch { }
                    });
                });

            cgb.CreateCommand(Module.Prefix + "plant")
                .Description($"Spend a flower to plant it in this channel. (If bot is restarted or crashes, flower will be lost) | `{Prefix}plant`")
                .Do(async e =>
                {
                    await locker.WaitAsync().ConfigureAwait(false);
                    try
                    {
                        if (plantedFlowerChannels.ContainsKey(e.Channel.Id))
                        {
                            await e.Channel.SendMessage($"There is already a {NadekoBot.Config.CurrencyName} in this channel.").ConfigureAwait(false);
                            return;
                        }
                        var removed = await FlowersHandler.RemoveFlowers(e.User, "Planted a flower.", 1, true).ConfigureAwait(false);
                        if (!removed)
                        {
                            await e.Channel.SendMessage($"You don't have any {NadekoBot.Config.CurrencyName}s.").ConfigureAwait(false);
                            return;
                        }

                        var file = GetRandomCurrencyImagePath();
                        Message msg;
                        if (file == null)
                            msg = await e.Channel.SendMessage(NadekoBot.Config.CurrencySign).ConfigureAwait(false);
                        else
                            msg = await e.Channel.SendFile(file).ConfigureAwait(false);
                        var vowelFirst = new[] { 'a', 'e', 'i', 'o', 'u' }.Contains(NadekoBot.Config.CurrencyName[0]);
                        var msg2 = await e.Channel.SendMessage($"Oh how Nice! **{e.User.Name}** planted {(vowelFirst ? "an" : "a")} {NadekoBot.Config.CurrencyName}. Pick it using {Module.Prefix}pick").ConfigureAwait(false);
                        plantedFlowerChannels.TryAdd(e.Channel.Id, new[] { msg, msg2 });
                    }
                    finally { locker.Release();  }
                });

            cgb.CreateCommand(Prefix + "gencurrency")
                .Alias(Prefix + "gc")
                .Description($"Toggles currency generation on this channel. Every posted message will have 2% chance to spawn a {NadekoBot.Config.CurrencyName}. Optional parameter cooldown time in minutes, 5 minutes by default. Requires Manage Messages permission. | `{Prefix}gc` or `{Prefix}gc 60`")
                .AddCheck(SimpleCheckers.ManageMessages())
                .Parameter("cd", ParameterType.Unparsed)
                .Do(async e =>
                {
                    var cdStr = e.GetArg("cd");
                    int cd = 2;
                    if (!int.TryParse(cdStr, out cd) || cd < 0)
                    {
                        cd = 2;
                    }
                    var config = SpecificConfigurations.Default.Of(e.Server.Id);
                    int throwaway;
                    if (config.GenerateCurrencyChannels.TryRemove(e.Channel.Id, out throwaway))
                    {
                        await e.Channel.SendMessage("`Currency generation disabled on this channel.`").ConfigureAwait(false);
                    }
                    else
                    {
                        if (config.GenerateCurrencyChannels.TryAdd(e.Channel.Id, cd))
                            await e.Channel.SendMessage($"`Currency generation enabled on this channel. Cooldown is {cd} minutes.`").ConfigureAwait(false);
                    }
                });
        }
Exemple #45
0
 private void bootBtn_Click(object sender, EventArgs e)
 {
     MainFrm.Frying = true;
     Discord.Frying();
 }
Exemple #46
0
        private void CheckFeeds()
        {
            foreach (var f in Config.Feeds)
            {
                var newItems = new List <SyndicationItem>();

                try {
                    using (var reader = XmlReader.Create(f.URL)) {
                        var feed = SyndicationFeed.Load(reader);
                        foreach (var item in feed.Items)
                        {
                            if (item.LastUpdatedTime.UtcDateTime < f.LastPoll && item.PublishDate.UtcDateTime < f.LastPoll)
                            {
                                continue;
                            }
                            newItems.Add(item);
                        }
                    }
                } catch (Exception ex) {
                    Logging.Error("Failed downloading syndication feed for {0}: {1}", f.Name, ex.ToString());
                    continue;
                }

                if (newItems.Count == 0)
                {
                    continue;
                }

                var channel = Discord.GetChannel(f.Channel);
                if (channel == null)
                {
                    Logging.Error("Couldn't find channel to send syndication update to for {0}", f.Name);
                    continue;
                }

                var verbUpdates = "update";
                if (newItems.Count > 1)
                {
                    verbUpdates += "s";
                }

                int c = 0;
                foreach (var item in newItems)
                {
                    var message = "";

                    var latestTime = item.LastUpdatedTime.UtcDateTime;
                    if (item.PublishDate.UtcDateTime > latestTime)
                    {
                        latestTime = item.PublishDate.UtcDateTime;
                    }
                    message += "`[" + latestTime.ToString("HH:mm:ss") + "] ";

                    message += "[" + f.Name + "] " + item.Title.Text;

                    if (item.Authors.Count > 0 && item.Authors[0].Name != null && item.Authors[0].Name.Length > 0)
                    {
                        message += " (" + item.Authors[0].Name + ")";
                    }

                    message += "`";

                    if (item.Links != null && item.Links.Count > 0)
                    {
                        message += " - " + Program.ShortUrl(item.Links[0].Uri.ToString());
                    }
                    channel.SendMessage(message);

                    Logging.Info("News [{0}] {1} / {2}: {3}", f.Name, ++c, newItems.Count, item.Title.Text);
                }

                f.LastPoll = DateTime.UtcNow;
            }

            Program.SaveConfig();
        }
Exemple #47
0
 private void cancelBtn_Click(object sender, EventArgs e)
 {
     MainFrm.Frying = false;
     Discord.Frying(); //update the status to false
 }
 /// <summary>
 ///     Gets a URL that can be used to jump the specified message in the Discord client.
 /// </summary>
 /// <param name="message"> The message to get the jump URL for. </param>
 /// <returns>
 ///     The jump URL for the message.
 /// </returns>
 public static string GetJumpUrl(this IGatewayMessage message)
 => Discord.MessageJumpLink(message.GuildId, message.ChannelId, message.Id);
Exemple #49
0
 public void OnShutdown()
 {
     Discord?.DisconnectAsync().Wait();
 }
 public async Task RunAsync()
 {
     var act = new DiscordActivity("the screams of your ancestors", ActivityType.ListeningTo);
     await Discord.ConnectAsync(act, UserStatus.DoNotDisturb).ConfigureAwait(false);
 }
 public async Task StopAsync()
 {
     await Discord.DisconnectAsync().ConfigureAwait(false);
 }
Exemple #52
0
 private static async Task<bool> ValidateQuery(Discord.Channel ch, string query) {
     if (string.IsNullOrEmpty(query.Trim())) {
         await ch.Send("Please specify search parameters.");
         return false;
     }
     return true;
 }
Exemple #53
0
 public override void Execute(Discord discord, params string[] args)
 {
     RoundService.Instance.StartRounds();
 }