コード例 #1
0
        public async Task <Result> Execute(SocketUserMessage e)
        {
            List <Object> results = await MessageControl.CreateQuestionnaire(e.Author.Id, e.Channel,
                                                                             new MessageControl.QE("Give poll name.", typeof(string)),
                                                                             new MessageControl.QE("Give poll end date.", typeof(DateTime)),
                                                                             new MessageControl.QE("Give poll max votes per person.", typeof(int)),
                                                                             new MessageControl.QE("Give poll option #", typeof(string [])));

            object [] obj     = results [3] as object [];
            string [] options = new string [obj.Length];
            for (int i = 0; i < obj.Length; i++)
            {
                options [i] = obj [i] as string;
            }

            try {
                MessageControl.Poll poll    = new MessageControl.Poll((string)results [0], e.Channel.Id, 0, DateTime.Parse(results [1].ToString()), (int)results [2], null, options);
                IMessage            message = await MessageControl.CreatePoll(poll);

                await poll.AwaitEnd();

                return(new Result(poll.winner, poll.winner.name));
            } catch (Exception exc) {
                Logging.DebugLog(Logging.LogType.EXCEPTION, exc.Message + " - " + exc.StackTrace);
                return(new Result(null, ""));
            }
        }
コード例 #2
0
ファイル: CCreateBook.cs プロジェクト: Lomztein/Adminthulhu
        public async Task <Result> Execute(SocketUserMessage e)
        {
            List <object> results = await MessageControl.CreateQuestionnaire(e.Author.Id, e.Channel, new MessageControl.QE("Page #", typeof(string [])));

            if (results.Count > 0)
            {
                object [] obj = results [0] as object [];
                string [] str = new string [obj.Length];
                for (int i = 0; i < obj.Length; i++)
                {
                    str [i] = obj [i].ToString();
                }
                RestUserMessage message = await Program.messageControl.SendBookMessage(e.Channel, "", str, true);

                return(new Result(message, ""));
            }
            return(new Result(null, ""));
        }
コード例 #3
0
        private async void CountVotes()
        {
            try {
                status = WeeklyEventStatus.Waiting;

                highestGame = null;
                int         highestVote       = int.MinValue;
                List <Game> highestVotedGames = new List <Game> ();

                foreach (Game game in games)
                {
                    if (game.votes == highestVote)
                    {
                        highestVotedGames.Add(game);
                    }
                    if (game.votes > highestVote)
                    {
                        highestVote       = game.votes;
                        highestVotedGames = new List <Game> ();
                        highestVotedGames.Add(game);
                    }
                }

                if (highestVotedGames.Count == 1)
                {
                    highestGame = highestVotedGames.FirstOrDefault();
                }
                else
                {
                    SocketChannel announcementChannel = Utility.SearchChannel(announcementsChannelName);
                    string        pollWinner          = string.Empty;

                    MessageControl.Poll poll = new MessageControl.Poll("Tiebreaker Vote!", announcementChannel.Id, 0, DateTime.Now.AddDays(1), 1, delegate(MessageControl.Poll p) {
                        pollWinner = p.winner.name;
                    },
                                                                       highestVotedGames.Select(x => x.name).ToArray()
                                                                       );
                    // What even is formatting.

                    MessageControl.CreatePoll(poll);
                    await poll.AwaitEnd();

                    highestGame = allGames.Find(x => x.name == pollWinner);
                }

                DateTime now      = DateTime.Now;
                DateTime eventDay = new DateTime(now.Year, now.Month, now.Day, eventHour, 0, 0).AddDays(daysBetween);
                DiscordEvents.CreateEvent(EVENT_NAME, eventDay, new TimeSpan(4, 0, 0), Program.discordClient.CurrentUser.Id, highestGame.iconUrl, highestGame.name + " has been chosen by vote!", new TimeSpan(0));

                SocketGuildChannel mainChannel = Utility.GetMainChannel();
                RestUserMessage    joinMessage = await Program.messageControl.AsyncSend(mainChannel as SocketTextChannel, onEventChosenByVoteMessage.Replace("{VOTEDGAME}", highestGame.name), true);

                joinMessageID = joinMessage.Id;
                joinMessage.AddReactionAsync(new Emoji("🗓"));

                Dictionary <ulong, bool> didWin = new Dictionary <ulong, bool> ();

                foreach (Vote vote in votes)
                {
                    if (!didWin.ContainsKey(vote.voterID))
                    {
                        didWin.Add(vote.voterID, false);
                    }

                    if (!didWin [vote.voterID])
                    {
                        if (highestGame.name == games [vote.votedGameID].name)
                        {
                            didWin [vote.voterID] = true;
                        }
                    }
                }

                int count = didWin.Count();
                for (int i = 0; i < count; i++)
                {
                    KeyValuePair <ulong, bool> pair = didWin.ElementAt(i);
                    if (pair.Value)
                    {
                        DiscordEvents.JoinEvent(pair.Key, EVENT_NAME);
                    }
                }

                await UpdateVoteMessage(false);

                SaveData();
            } catch (Exception e) {
                Logging.DebugLog(Logging.LogType.EXCEPTION, e.Message + " - " + e.StackTrace);
            }
        }
コード例 #4
0
 public async Task <IMessage> GetMessage()
 {
     return(await MessageControl.GetMessage(channelID, messageID));
 }
コード例 #5
0
ファイル: Program.cs プロジェクト: Lomztein/Adminthulhu
        public async Task Start(string [] args)
        {
            dataPath = AppContext.BaseDirectory + "/data/";
            dataPath = dataPath.Replace('\\', '/');

            InitializeDirectories();
            Logging.Log(Logging.LogType.BOT, "Initializing bot.. Datapath: " + dataPath);
            BotConfiguration.Initialize();
            Encryption.Initialize();

            BotConfiguration.AddConfigurable(this);
            LoadConfiguration();

            discordClient  = new DiscordSocketClient();
            messageControl = new MessageControl();
            karma          = new Karma();
            new StreamingMonitor();

            LegalJunk.Initialize();
            Logging.Log(Logging.LogType.BOT, "Loading data..");
            InitializeCommands();
            UserConfiguration.Initialize();
            InviteHandler.Initialize();
            CommandChain.Initialize();
            Permissions.Initialize();
            AutoCommands.Initialize();
            clock = new Clock();

            InitializeData();
            UserGameMonitor.Initialize();

            bootedTime = DateTime.Now.AddSeconds(BOOT_WAIT_TIME);

            Logging.Log(Logging.LogType.BOT, "Setting up events..");
            discordClient.MessageReceived += async(e) => {
                Logging.Log(Logging.LogType.CHAT, Utility.GetChannelName(e) + " says: " + e.Content);

                bool hideTrigger = false;
                if (e.Content.Length > 0 && ContainsCommandTrigger(e.Content, out hideTrigger))
                {
                    FindAndExecuteCommand(e, e.Content, commands, 0, true, true);
                }

                if (e.Author.Id != discordClient.CurrentUser.Id)
                {
                    FindPhraseAndRespond(e);
                    AutoCommands.RunEvent(AutoCommands.Event.MessageRecieved, e.Content, e.Channel.Id.ToString());
                }

                if (e.Content.Length > 0 && hideTrigger)
                {
                    e.DeleteAsync();
                    allowedDeletedMessages.Add(e.Content);
                }
            };

            discordClient.MessageUpdated += async(cache, message, channel) => {
                Logging.Log(Logging.LogType.CHAT, "Message edited: " + Utility.GetChannelName(message as SocketMessage) + " " + message.Content);
                AutoCommands.RunEvent(AutoCommands.Event.MessageDeleted, message.Content, message.Channel.Id.ToString());
            };

            discordClient.MessageDeleted += async(cache, channel) => {
                IMessage message = await cache.GetOrDownloadAsync();

                Logging.Log(Logging.LogType.CHAT, "Message deleted: " + Utility.GetChannelName(channel as SocketGuildChannel));
                AutoCommands.RunEvent(AutoCommands.Event.MessageDeleted, channel.Id.ToString());
            };

            discordClient.UserJoined += async(e) => {
                Younglings.OnUserJoined(e);
                RestInviteMetadata possibleInvite = await InviteHandler.FindInviter();

                Logging.Log(Logging.LogType.BOT, "User " + e.Username + " joined.");
                AutoCommands.RunEvent(AutoCommands.Event.UserJoined, e.Id.ToString());
                SocketGuildUser inviter;

                if (possibleInvite != null)
                {
                    inviter = Utility.GetServer().GetUser(possibleInvite.Inviter.Id);
                    string joinMessage = Utility.SelectRandom(onUserJoinFromInviteMessage);
                    messageControl.SendMessage(Utility.GetMainChannel() as SocketTextChannel, joinMessage.Replace("{USERNAME}", Utility.GetUserName(e)).Replace("{INVITERNAME}", Utility.GetUserName(inviter)), true);
                }
                else
                {
                    string joinMessage = Utility.SelectRandom(onUserJoinMessage);
                    messageControl.SendMessage(Utility.GetMainChannel() as SocketTextChannel, joinMessage.Replace("{USERNAME}", Utility.GetUserName(e)), true);
                }

                string [] welcomeMessage = SerializationIO.LoadTextFile(dataPath + "welcomemessage" + gitHubIgnoreType);
                string    combined       = "";
                for (int i = 0; i < welcomeMessage.Length; i++)
                {
                    combined += welcomeMessage [i] + "\n";
                }

                await messageControl.SendMessage(e, combined);
            };

            discordClient.UserLeft += (e) => {
                string leftMessage = Utility.SelectRandom(onUserLeaveMessage);
                Logging.Log(Logging.LogType.BOT, "User " + e.Username + " left.");
                AutoCommands.RunEvent(AutoCommands.Event.UserLeft, e.Id.ToString());
                if (automaticLeftReason.ContainsKey(e.Id))
                {
                    leftMessage = $"**{Utility.GetUserName (e)}** left - " + automaticLeftReason [e.Id];
                    automaticLeftReason.Remove(e.Id);
                }
                messageControl.SendMessage(Utility.GetMainChannel() as SocketTextChannel, leftMessage.Replace("{USERNAME}", Utility.GetUserName(e)), true);
                return(Task.CompletedTask);
            };

            discordClient.UserVoiceStateUpdated += async(user, before, after) => {
                Logging.Log(Logging.LogType.BOT, "User voice updated: " + user.Username);
                SocketGuild guild = (user as SocketGuildUser).Guild;

                if (after.VoiceChannel != null)
                {
                    Voice.allVoiceChannels [after.VoiceChannel.Id].OnUserJoined(user as SocketGuildUser);
                }

                if (before.VoiceChannel == null && after.VoiceChannel != null)
                {
                    AutoCommands.RunEvent(AutoCommands.Event.JoinedVoice, user.Id.ToString(), after.VoiceChannel.Id.ToString());
                }
                if (before.VoiceChannel != null && after.VoiceChannel == null)
                {
                    AutoCommands.RunEvent(AutoCommands.Event.LeftVoice, user.Id.ToString(), before.VoiceChannel.Id.ToString());
                }

                await Voice.OnUserUpdated(guild, before.VoiceChannel, after.VoiceChannel);

                return;
            };

            discordClient.GuildMemberUpdated += async(before, after) => {
                if ((before as SocketGuildUser).Nickname != (after as SocketGuildUser).Nickname)
                {
                    MentionNameChange(before, after);
                }
            };

            discordClient.UserUpdated += (before, after) => {
                if (before.Username != after.Username && (after as SocketGuildUser).Nickname == "")
                {
                    MentionNameChange(before as SocketGuildUser, after as SocketGuildUser);
                }

                return(Task.CompletedTask);
            };

            discordClient.UserBanned += (e, guild) => {
                SocketChannel channel = Utility.GetMainChannel();
                if (channel == null)
                {
                    return(Task.CompletedTask);
                }

                string banMessage = Utility.SelectRandom(onUserBannedMessage);
                messageControl.SendMessage(channel as SocketTextChannel, banMessage.Replace("{USERNAME}", Utility.GetUserName(e as SocketGuildUser)), true);

                return(Task.CompletedTask);
            };

            discordClient.UserUnbanned += (e, guild) => {
                SocketChannel channel = Utility.GetMainChannel();
                if (channel == null)
                {
                    return(Task.CompletedTask);
                }

                string unbannedMessage = Utility.SelectRandom(onUserUnbannedMessage);
                messageControl.SendMessage(channel as SocketTextChannel, unbannedMessage.Replace("{USERNAME}", Utility.GetUserName(e as SocketGuildUser)), true);

                return(Task.CompletedTask);
            };

            discordClient.Ready += () => {
                Logging.Log(Logging.LogType.BOT, "Bot is ready and running!");

                return(Task.CompletedTask);
            };

            string token = "";

            try {
                token = SerializationIO.LoadTextFile(dataPath + "bottoken" + gitHubIgnoreType)[0];
            }catch (Exception e) {
                Logging.Log(Logging.LogType.CRITICAL, "Bottoken not found, please create a file at <botroot>/data/bottoken.botproperty and insert bottoken there. " + e.Message);
            }

            Logging.Log(Logging.LogType.BOT, "Connecting to Discord..");
            await discordClient.LoginAsync(TokenType.Bot, token);

            await discordClient.StartAsync();

            BotConfiguration.PostInit();

            await Utility.AwaitFullBoot();

            try {
                if (args.Length > 0 && args [0] == "true" && onPatchedAnnounceChannel != 0)
                {
                    using (HttpClient client = new HttpClient()) {
                        string changelog = await client.GetStringAsync(AutoPatcher.url + "changelog.txt");

                        string version = await client.GetStringAsync(AutoPatcher.url + "version.txt");

                        string total = $"Succesfully installed new patch, changelog for {version}:\n{changelog}";

                        SocketGuildChannel patchNotesChannel = Utility.GetServer().GetChannel(onPatchedAnnounceChannel);
                        if (patchNotesChannel != null)
                        {
                            messageControl.SendMessage(patchNotesChannel as ISocketMessageChannel, total, true, "```");
                        }
                    }
                }
            } catch (Exception e) {
                Logging.Log(e);
            }

            BakeQuickCommands();

            await Task.Delay(-1);
        }