Ejemplo n.º 1
0
        public static async void HandleIncomingMessage(object client, MessageEventArgs e)
        {
            if (e != null && e.Message != null && !e.Message.IsAuthor)
            {
                string server = e.Message.Server == null ? "1-1" : e.Message.Server.Name;
                string user = e.Message.User == null ? "?" : e.Message.User.Name;
                string rawtext = e.Message.RawText ?? "";
                Console.WriteLine("[{0}][Message] {1}: {2}", server, user, rawtext);
                string reply = null;
                string[] words = rawtext.Split(' ');

                // Private message, check for invites
                if (e.Server == null)
                {
                    await SendReply(client, e.Message, e.Message.Channel.Id, e.Message.Id, $"You can add the bot via {Program.AuthUrl}");
                    return;
                }

                reply = await HandleCommands((DiscordClient) client, reply, words);

                if (reply == null)
                    reply = HandleEmotesAndConversions(reply, words);

                if (!string.IsNullOrWhiteSpace(reply))
                {
                    await SendReply(client, e.Message, e.Message.Channel.Id, e.Message.Id, reply);
                }
            }
        }
Ejemplo n.º 2
0
 private void DisplayObservedMessage(object sender, MessageEventArgs e)
 {
     Application.Current.Dispatcher.Invoke((() =>
     {
         MessageHistory.Add(string.Format("{0} {1} <{2}>: {3}", e.Message.Timestamp, e.Message.User.Name, e.Message.Channel.Name, e.Message.RawText));
     }));
 }
Ejemplo n.º 3
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 { }
 }
Ejemplo n.º 4
0
 private async void ball_MessageReceived(object sender, Discord.MessageEventArgs e)
 {
     if (e.Message.RawText.StartsWith(";8ball"))
     {
         int    Random8BallIndex = rand.Next(random8Ball.Length);
         string ballToPost       = random8Ball[Random8BallIndex];
         await e.Channel.SendMessage(ballToPost);
     }
 }
Ejemplo n.º 5
0
 public void messageReceived(object sender, MessageEventArgs e)
 {
     // Don't handle to our own messages, ever.
     if (e.Message.IsAuthor)
     {
         return;
     }
     Logger.Output(LogType.INFO, "Discord message: " + e.User.Name + ": " + e.Message.RawText);
     dIRCBot.DiscordMessage(e.Channel.Id, e.User.Name, e.Message.RawText);
 }
Ejemplo n.º 6
0
        public CommandArgs(MessageEventArgs e)
        {
            Message = e.Message;
            Channel = e.Channel;
            Server = e.Server;
            User = e.User;

            Args = e.Message.RawText.Split(new char[] { ' ' },
                StringSplitOptions.RemoveEmptyEntries).Skip(1);
        }
Ejemplo n.º 7
0
        private void Client_MessageReceived(object sender, MessageEventArgs e)
        {

            lastMessage = "[" + e.User.Name + "] on [" + e.Server.Name + "] server, channel: [" + e.Channel.Name + "]                                \n" + "Body: " + e.Message.Text + "                 ";
            
            if (e.Message.MentionedUsers.Where(u => u.Id == NadekoBot.OwnerID).Count() > 0)
            {
                lastMention = "You were last mentioned in '" + e.Server.Name + "' server, channel '" + e.Channel.Name + "', by " + e.User.Name;
            }
            
        }
Ejemplo n.º 8
0
 private async void TryJoin(MessageEventArgs e, string code) {
     try
     {
         await (await NadekoBot.client.GetInvite(code)).Accept();
         await e.Send(e.User.Mention + " I joined it, thanks :)");
         DEBUG_LOG("Successfuly joined server with code " + code);
         DEBUG_LOG("Here is a link for you: discord.gg/" + code);
     }
     catch (Exception ex) {
         DEBUG_LOG("Failed to join " + code);
         DEBUG_LOG("Reason: " + ex.ToString());
     }
 }
Ejemplo n.º 9
0
 private async void MsgDltd(object sender, MessageEventArgs e)
 {
     try
     {
         if (e.Server == null || e.Channel.IsPrivate || e.User.Id == NadekoBot.Client.CurrentUser.Id)
             return;
         Channel ch;
         if (!logs.TryGetValue(e.Server, out ch) || e.Channel == ch)
             return;
         await ch.SendMessage($"`Type:` **Message deleted** `Time:` **{DateTime.Now}** `Channel:` **{e.Channel.Name}**\n`{e.User}:` {e.Message.Text}");
     }
     catch { }
 }
Ejemplo n.º 10
0
 internal static async void Do(MessageEventArgs e)
 {
     if (chatbots.Count() == 0) return; // No bot sessions
     string msg = e.Message.Text;
     // It's lame we have to do this, but our User isn't exposed by Discord.Net, so we don't know our name
     string neko = e.Channel.IsPrivate ? "" : Program.client.GetUser(e.Server, Program.client.CurrentUserId).Name;
     if (chatbots.ContainsKey(e.Channel.Id) && (e.Channel.IsPrivate || msg.ToLower().IndexOf(neko.ToLower()) != -1))
     {
         if (!e.Channel.IsPrivate)
             msg = msg.Replace(neko, "");
         await Program.client.SendMessage(e.Channel, System.Net.WebUtility.HtmlDecode(chatbots[e.Channel.Id].Think(msg)));
     }
 }
Ejemplo n.º 11
0
 internal async static Task handleTiroCommands(MessageEventArgs e, DiscordClient client, Channel currentChannel)
 {
     switch(e.Message.Text)
     {
         case "-touhou":
             await client.SendMessage(currentChannel, "is THAT another TOUHOU map???");
             break;
         case "!r":
             await client.SendMessage(currentChannel, getTillerinoText(e.Message.User.Id));
             break;
         default:
             break;
     }
 }
Ejemplo n.º 12
0
 async System.Threading.Tasks.Task Do(MessageEventArgs e)
 {
     if (chatbots.Count() == 0) return; // No bot sessions
     string msg = e.Message.Text;
     if (chatbots.ContainsKey(e.Channel.Id) && (e.Channel.IsPrivate || HasNeko(ref msg, e.Server.CurrentUser)))
     {
         string chat;
         lock (chatbots[e.Channel.Id]) chat = chatbots[e.Channel.Id].Ask(msg); // Ask in order.
         chat = System.Net.WebUtility.HtmlDecode(chat);
         await e.Channel.SendIsTyping();
         for (int i = 10; i != 0; --i) try { await (e.Message.IsTTS ? e.Channel.SendTTSMessage(chat) : e.Channel.SendMessage(chat)); break; }
             catch (Discord.Net.HttpException ex) { if (i == 1) Log.Write(LogSeverity.Error, $"{ex.Message}\nCould not SendMessage to {(e.Channel.IsPrivate ? "private" : "public")} channel {e.Channel} in response to {e.User}'s message: {e.Message.Text}"); }
     }
 }
Ejemplo n.º 13
0
        private async void AnswerReceived(object sender, MessageEventArgs e) {
            if (e.Channel == null || e.Channel.Id != channel.Id) return;

            var guess = e.Message.RawText;

            var distance = currentSentence.LevenshteinDistance(guess);
            var decision = Judge(distance, guess.Length);
            if (decision && !finishedUserIds.Contains(e.User.Id)) {
                finishedUserIds.Add(e.User.Id);
                await channel.Send($"{e.User.Mention} finished in **{sw.Elapsed.Seconds}** seconds with { distance } errors, **{ currentSentence.Length / TypingGame.WORD_VALUE / sw.Elapsed.Seconds * 60 }** WPM!");
                if (finishedUserIds.Count % 2 == 0) {
                    await e.Send($":exclamation: `A lot of people finished, here is the text for those still typing:`\n\n:book:**{currentSentence}**:book:");
                }

            }
        }
Ejemplo n.º 14
0
        //code for the message to show up along with the username
        //being displayed next to the message
        private static void Bot_MessageReceived(object sender, MessageEventArgs e)
        {
            //"headquarters - liekabauws: !fuckingmemes"
            Console.WriteLine("[Server: {3}] {0} - {1}: {2}", e.Message.Channel, e.User.Name, e.Message.Text, e.Server);
            //checks if the command was sent by the bot to prevent a loop of triggering the commands
            if (e.Message.IsAuthor) return;
            //commands
            if(e.Message.Text == "!tigered")
            {
                e.Channel.SendMessage("Get TIGERED!"); e.Channel.SendFile("images/tigered.png");
            }

            if (e.Message.Text == "!customicon")
            {
                e.Channel.SendMessage(e.User.Mention + "Custom Discord Icon made by Liekabauws"); e.Channel.SendFile("images/app.png");
            }

            if (e.Message.Text == "!myid")
            {
                e.Channel.SendMessage(e.User.Mention + "Your id is: " + e.User.Id);
            }

            if (e.Message.Text == "!joindate")
            {
                e.Channel.SendMessage(e.User.Mention + "The date and time at which you joined the server is: "
                    + e.User.JoinedAt);
            }

            if (e.Message.Text == "!avalink")
            {
                e.Channel.SendMessage(e.User.Mention + "Your avatar link: " + e.User.AvatarUrl);
            }

            if (e.Message.Text == "!sowner")
            {
                e.Channel.SendMessage(e.User.Mention + "The server owner is: " + e.Server.Owner);
            }

            if (e.Message.Text == "!topic")
            {
                e.Channel.SendMessage(e.User.Mention + e.Channel.Topic); //e.Channel.Client.SessionId);
            }
        }
Ejemplo n.º 15
0
 static void bot_MessageReceived(object sender, Discord.MessageEventArgs e)
 {
     if (e.Message.RawText.Contains("i want to die") | e.Message.RawText.Contains("I WANT TO DIE") | e.Message.RawText.Contains("i wanna die"))
     {
         e.Channel.SendMessage("me too");
     }
     else if (e.Message.RawText.StartsWith(":v"))
     {
         e.Channel.SendMessage("wkwkwk i indo");
     }
     else if (e.Message.RawText.StartsWith("<@243084189556015104> ping"))
     {
         e.Channel.SendMessage(e.User.Mention + " i am here");
     }
     if (e.Message.RawText.StartsWith(";avatar"))
     {
         e.Channel.SendMessage(e.User.AvatarUrl);
     }
 }
Ejemplo n.º 16
0
        private void _client_MessageReceived(object sender, Discord.MessageEventArgs e)
        {
            Console.WriteLine(e.Message.RawText);
            if (!e.Message.IsAuthor)
            {
                SteamBotLite.User user = new SteamBotLite.User(e.User.Id, this);
                user.DisplayName = e.User.Name;
                user.ExtraData   = e.User;

                try
                {
                    if (e.User.ServerPermissions.Administrator | e.User.ServerPermissions.KickMembers)
                    {
                        user.Rank = ChatroomEntity.AdminStatus.True;
                    }
                    else
                    {
                        user.Rank = ChatroomEntity.AdminStatus.False;
                    }
                }
                catch
                {
                }

                MessageEventArgs Msg = new MessageEventArgs(this);
                Msg.ReceivedMessage = e.Message.RawText;
                Msg.Sender          = user;

                Msg.Chatroom = new Chatroom(e.Message.Channel, this);

                if (e.Message.Channel != null)
                {
                    ChatRoomMessageProcessEvent(Msg);
                }
                else
                {
                    PrivateMessageProcessEvent(Msg);
                }
            }
        }
Ejemplo n.º 17
0
        private void OnMessageCreated(object sender, MessageEventArgs e)
        {
            if (e.Message.IsAuthor)
                return;

            var command = CommandFactory.ParseCommand(e.Message.RawText);
            if (command != null)
            {
                command.Delegate.Invoke(e.Message);
                return;
            }
                
            var pendingPrompt = PendingPrompts.FirstOrDefault(p => p.UserId == e.Message.User.Id);
            if (pendingPrompt != null)
            {
                pendingPrompt.PromptResponse(e.Message);
                PendingPrompts.Remove(pendingPrompt);
                return;
            }

            React(e.Message);
        }
Ejemplo n.º 18
0
        private async void Vote(object sender, MessageEventArgs e)
        {
            try
            {
                if (!e.Channel.IsPrivate)
                    return;
                if (participants.ContainsKey(e.User))
                    return;

                int vote;
                if (!int.TryParse(e.Message.Text, out vote)) return;
                if (vote < 1 || vote > answers.Length)
                    return;
                if (participants.TryAdd(e.User, vote))
                {
                    await e.User.SendMessage($"Thanks for voting **{e.User.Name}**.").ConfigureAwait(false);
                }
            }
            catch { }
        }
Ejemplo n.º 19
0
 public static bool IsBlackListed(MessageEventArgs evArgs) => IsUserBlacklisted(evArgs.User.Id) ||
                                                               (!evArgs.Channel.IsPrivate &&
                                                                (IsChannelBlacklisted(evArgs.Channel.Id) || IsServerBlacklisted(evArgs.Server.Id)));
Ejemplo n.º 20
0
        // This code is executed every time a message is received.
         void bot_MessageReceived(object sender, MessageEventArgs e)
        {
             // If Crypto is the author of the Message, nothing happens, therefore the code returns.
            if (e.Message.IsAuthor) return;

             // Outputs a message which displays all Commands.
            if (e.Message.Text.ToLower().StartsWith("?help"))
            {
                e.Channel.SendMessage(e.User.Mention + " I've sent you a Private Message containing what you requested.");
                e.User.SendMessage(" ```\n\n?help \n\nPrivate messages you all commands available.\n\n?setgame STRING\n\n?id\n\nOutputs your User ID.\n\n~DevLocked~  Changes Crypto’s current game to a string.\n\n?encrypt STRING\n\nEncrypts any given string using an unique Cryptographic method. \n\n?decrypt STRING\n\nDecrypts any given string using an unique Cryptographic method..\n\nConsole.WriteLIne STRING\n\n~DevLocked~  Simple C# Echo function.\n\n?ping\n\nPong!\n\n?joke\n\nOutputs the biggest joke in the Universe.\n\n?cp\n\n8 Chan in Real Time\n\n?whois crypto\n\nOutputs a brief description about the Bot.\n\n?insulted\n\n~DevLocked~  Outputs an offensive defense for Rithari.\n\n?quit\n\n~DevLocked~  Kills Crypto\n\n?red/orange/purple/green/black/white/lime/lavender/salmon/cyan/yellow/pink/lightred/darkblue/darkpurple\n\n~DevLocked~  Changes Crypto’s name color.\n\n?uncolor\n\n~DevLocked~  Uncolors Crypto.```\n\n\n\n Crypto is a Discord Bot written in C# with DiscordNet, his current version is: V3.0. His main function comes from his name, he encrypts and decrypts any type of string. In order to decrypt you need the encryption password, which is currently default and cannot be specified by the user.");
            }
             // Changes what Crypto is currently playing.
            if (e.Message.Text.StartsWith("?setgame"))
            {
                if (e.Message.User.Id == 127504308156628992)
                {   
                        string game = e.Message.Text.Substring(9);
                        bot.SetGame(game);
                        e.Channel.SendMessage("Will do!");
                }
                else
                {
                    e.Channel.SendMessage("No.");
                }

            } 
             //String gets encrypted with a password which will be needed to decrypt the string.
             // Warning though, currently this code does the password part on its own, but it is planned to make the User Input an Encryption Password.
             if (e.Message.Text.StartsWith("?encrypt"))
             {
                 e.Channel.SendMessage(e.User.Mention + " Processing...");
                 string encryptthis = e.Message.Text.Substring(9);
                 string password = "******";
                 string encryptthiss = StringCipher.Encrypt(encryptthis, password);
                 e.Channel.SendMessage(encryptthiss);

             } 
             // String gets decrypted by using the same password used for encryption.
             // Warning though, currently this code does the password part on its own, but it is planned to make the User Input a Decryption Password.
             if (e.Message.Text.StartsWith("?decrypt"))
             {
                 //e.User.PrivateChannel.SendMessage("Please input the decryption password.");
                 string password = "******";
                  e.Channel.SendMessage(e.User.Mention + " Processing...");
                 string decryptthis = e.Message.Text.Substring(9);
                 string decryptthiss = StringCipher.Decrypt(decryptthis, password);
                 e.Channel.SendMessage(decryptthiss);
             }
             // Outputs your ID.
             if (e.Message.Text.StartsWith("?id"))
             {
                 string userid = e.User.Id.ToString();
                 e.Channel.SendMessage("Your ID is: " + userid + ".");
             }
             // Gives you all User's IDs. (EXPERIMENTAL)
             if (e.Message.Text.StartsWith("?listallids"))
             {
                 if (e.User.Id == 127504308156628992)
                 {
                     e.Channel.SendMessage(e.User.Mention + " I've sent the ID of everyone on all Servers I'm connected to.");
                     foreach (Discord.User u in e.Channel.Users.ToArray())
                     {
                         e.User.SendMessage(u.Name + " - " + u.Id.ToString());
                     }
                 }
                 else
                 {
                     e.Channel.SendMessage("You're not allowed to crash me just yet.");
                 }
             }
             if (e.Message.Text.StartsWith("?whois"))
             {

             }
             // C# WriteLine Function
            if (e.Message.Text.StartsWith("Console.WriteLine"))
            {
                if (e.Message.User.Id == 127504308156628992)
                {
                    e.Channel.SendMessage(e.Message.Text.Substring(18));
                }
                else
                {
                    e.Channel.SendMessage("Sorry, you're not allowed to use this command, " + e.User.Mention);
                }
            }
             // Pings Crypto
            if (e.Message.Text == "?ping")
            {
                e.Channel.SendMessage("Your exact Ping is: ** " +  Convert.ToString((DateTime.UtcNow - e.Message.Timestamp).TotalMilliseconds) + " ms**"); // Broken ?
            }
             // Outputs a joke.
            if (e.Message.Text == "?joke")
            {
                e.Channel.SendMessage("French People");
            }
             // Outputs CP - Not really though.
            if (e.Message.Text.ToLower().Contains("?cp"))
            {
                e.Channel.SendMessage("\n Processing...");
                e.Channel.SendFile("images/keep-calm-and-call-the-fbi-6.png");
                e.Channel.SendFile("shrek.jpg"); // Doesn't seem to work.
            }
             // Outputs information about the Bot.
            if (e.Message.Text.ToLower().Contains("who is crypto"))
            {
                if (e.Message.User.Id == 127504308156628992)
                {
                    e.Channel.SendMessage(e.User.Mention +" I'm your Bot you f*****g retard!");
                    return;

                }
                  e.Channel.SendMessage(e.User.Mention +" I am your Father! \n Just kidding, I'm a Bot, and I was created by Rithari.\n For more Info, type ?help :)!");

            }
             // Outputs an offensive defense for yourself.
            if (e.Message.Text == "?insulted")
            {
                if (e.Message.User.Id == 127504308156628992)
                {
                    e.Channel.SendMessage("You dirty nigerian astronaut quit insulting " + e.User.Mention + "!");
                }
                else
                {
                    e.Channel.SendMessage("I don't care fam.");
                }
            }
             // Quits the Bot.
            if (e.Message.Text == "?quit")
            {
                if (e.Message.User.Id == 127504308156628992)
                {
                    this.bot.Disconnect();
                }
                else
                {
                    e.Channel.SendMessage("Sorry, you're not allowed to use this command, " + e.User.Mention);
                }
            }
             // Change color to Red and in the other cases to other colors. Hardcoded like a real haxor. - Garry's Mod Developers Server Only.
             string color = e.Message.Text;
             if (e.Message.User.Id == 127504308156628992)
             {

                 switch (color)
                 {
                     case "?red":
                         e.Channel.SendMessage(".color red");
                         break;
                     case "?orange":
                         e.Channel.SendMessage(".color orange");
                         break;
                     case "?purple":
                         e.Channel.SendMessage(".color purple");
                         break;
                     case "?green":
                         e.Channel.SendMessage(".color green");
                         break;
                     case "?blue":
                         e.Channel.SendMessage(".color blue");
                         break;
                     case "?black":
                         e.Channel.SendMessage(".color black");
                         break;
                     case "?white":
                         e.Channel.SendMessage(".color white");
                         break;
                     case "?cyan":
                         e.Channel.SendMessage(".color cyan");
                         break;
                     case "?lime":
                         e.Channel.SendMessage(".color lime");
                         break;
                     case "?pink":
                         e.Channel.SendMessage(".color pink");
                         break;
                     case "?yellow":
                         e.Channel.SendMessage(".color yellow");
                         break;
                     case "?lightred":
                         e.Channel.SendMessage(".color lightred");
                         break;
                     case "?lavender":
                         e.Channel.SendMessage(".color lavender");
                         break;
                     case "?salmon":
                         e.Channel.SendMessage(".color salmon");
                         break;
                     case "?darkblue":
                         e.Channel.SendMessage(".color darkblue");
                         break;
                     case "?darkpurple":
                         e.Channel.SendMessage(".color darkpurple");
                         break;
                     case "?uncolor":
                         e.Channel.SendMessage(".uncolor");
                         break;
                 }
             }
            Console.WriteLine("{0} said: {1}", e.User.Name, e.Message.Text);
        }
Ejemplo n.º 21
0
        private static async void Client_MessageReceived(object sender, MessageEventArgs e) {
            if (e.Server != null || e.User.Id == client.CurrentUser.Id) return;
            if (PollCommand.ActivePolls.SelectMany(kvp => kvp.Key.Users.Select(u=>u.Id)).Contains(e.User.Id)) return;
            // just ban this trash AutoModerator
            // and cancer christmass spirit
            // and crappy shotaslave
            if (e.User.Id == 105309315895693312 ||
                e.User.Id == 119174277298782216 ||
                e.User.Id == 143515953525817344)
                return; // FU

            try {
                await (await client.GetInvite(e.Message.Text)).Accept();
                await e.Send("I got in!");
                return;
            } catch  {
                if (e.User.Id == 109338686889476096) { //carbonitex invite
                    await e.Send("Failed to join the server.");
                    return;
                }
            }

            if (ForwardMessages && OwnerPrivateChannel != null)
                await OwnerPrivateChannel.SendMessage(e.User + ": ```\n" + e.Message.Text + "\n```");

            if (!repliedRecently) {
                repliedRecently = true;
                await e.Send("**COMMANDS DO NOT WORK IN PERSONAL MESSAGES**\nYou can type `-h` or `-help` or `@MyName help` in any of the channels I am in and I will send you a message with my commands.\n Or you can find out what i do here: https://github.com/Kwoth/NadekoBot\nYou can also just send me an invite link to a server and I will join it.\nIf you don't want me on your server, you can simply ban me ;(\nBot Creator's server: https://discord.gg/0ehQwTK2RBhxEi0X");
                Timer t = new Timer();
                t.Interval = 2000;
                t.Start();
                t.Elapsed += (s, ev) => {
                    repliedRecently = false;
                    t.Stop();
                    t.Dispose();
                };
            }
        }
Ejemplo n.º 22
0
 private void Links(MessageEventArgs e)
 {
     string concat = "";
     foreach (string str in links)
     {
         concat = concat + str + "\n";
     }
     _bot.SendMessage(e.ChannelId, concat);
 }
Ejemplo n.º 23
0
        private void Quit(MessageEventArgs e)
        {
            if (e.Message.User.Name == admin)
            {
                _bot.SendMessage(e.ChannelId, "*beep boop* Shutting down...");
                scoreWriter = new StreamWriter("C:\\Scoreboard.txt");
                foreach (KeyValuePair<string, int> pair in scoreboard)
                {
                    scoreWriter.WriteLine(pair.Key + " " + pair.Value);
                }
                scoreWriter.Close();

                linksWriter = new StreamWriter("C:\\Links.txt");
                foreach (string str in links)
                {
                    linksWriter.WriteLine(str);
                }
                linksWriter.Close();
                _bot.Disconnect();
                System.Environment.Exit(1);
            }
        }
Ejemplo n.º 24
0
        private static async void Client_MessageReceived(object sender, MessageEventArgs e)
        {
            try
            {
                if (e.Server != null || e.User.Id == Client.CurrentUser.Id) return;
                if (PollCommand.ActivePolls.SelectMany(kvp => kvp.Key.Users.Select(u => u.Id)).Contains(e.User.Id)) return;
                if (ConfigHandler.IsBlackListed(e))
                    return;

                if (!NadekoBot.Config.DontJoinServers && !IsBot)
                {
                    try
                    {
                        await (await Client.GetInvite(e.Message.Text).ConfigureAwait(false)).Accept().ConfigureAwait(false);
                        await e.Channel.SendMessage("I got in!").ConfigureAwait(false);
                        return;
                    }
                    catch
                    {
                        if (e.User.Id == 109338686889476096)
                        { //carbonitex invite
                            await e.Channel.SendMessage("Failed to join the server.").ConfigureAwait(false);
                            return;
                        }
                    }
                }

                if (Config.ForwardMessages && !NadekoBot.Creds.OwnerIds.Contains(e.User.Id) && OwnerPrivateChannel != null)
                    await OwnerPrivateChannel.SendMessage(e.User + ": ```\n" + e.Message.Text + "\n```").ConfigureAwait(false);

                if (repliedRecently) return;

                repliedRecently = true;
                if (e.Message.RawText != "-h")
                    await e.Channel.SendMessage(HelpCommand.DMHelpString).ConfigureAwait(false);
                await Task.Delay(2000).ConfigureAwait(false);
                repliedRecently = false;
            }
            catch { }
        }
Ejemplo n.º 25
0
        private void Discord_MessageReceived(object sender, MessageEventArgs e)
        {
            string firstWord = Regex.Match(e.Message.Text, @"^\S+\b").Value.ToLower();
            UserCommand foundCommand = MainWindow.colBotCommands.FirstOrDefault(x =>
                x.Command == firstWord);

            if (foundCommand != null)
            {
                //foundCommand.ExecuteCommand(new IrcMessage(e.User.Name + "@Discord", e.Message.Text));
                foundCommand.ExecuteCommandDiscord(e.Message);
            }
            else
            {
                //BotCommands.RunBotCommand(firstWord, new IrcMessage(e.User.Name + "@Discord", e.Message.Text));
                BotCommands.RunBotCommandDiscord(firstWord, e.Message);
            }
            if (e.Channel.IsPrivate)
            {
                if(e.Message.Text.Split(' ')[0] == "confirm" && e.Message.Text.Split(' ').Length == 2)
                {
                    Discord.User confirm = e.User;
                    Models.Channel target = client.GetChannel(e.Message.Text.Split(' ')[1]);
                    string id = target.Game;
                    if(id == confirm.Id.ToString())
                    {
                        Viewer vwr = colDatabase.FirstOrDefault(x => x.UserName.ToLower() == target.Name.ToLower());
                        vwr.DiscordID = confirm.Id.ToString();
                        DatabaseUtils.UpdateViewer(vwr);
                    }
                }
            }
        }
Ejemplo n.º 26
0
        private static void OnMessageReceived(DiscordSocketClient client, Discord.MessageEventArgs args)
        {
            Stopwatch timer   = new Stopwatch();
            string    message = args.Message.Content.ToString();

            if (message.Contains("https://discord.gift/") || message.Contains("https://discord.com/gifts/"))
            {
                string status = redeemcode(message, timer);

                string time = "0." + timer.ElapsedMilliseconds.ToString();

                string channel = "";
                string server  = "";
                string user;
                if (client.GetChannel(args.Message.Channel.Id).Type == ChannelType.DM || client.GetChannel(args.Message.Channel.Id).Type == ChannelType.Group)
                {
                    if (client.GetChannel(args.Message.Channel.Id).Type == ChannelType.DM)
                    {
                        user = args.Message.Author.User.ToString();
                    }
                    else
                    {
                        channel = client.GetChannel(args.Message.Channel.Id).ToGroup().Name;
                        user    = args.Message.Author.User.ToString();
                    }
                }
                else
                {
                    channel = client.GetChannel(args.Message.Channel.Id).Name;
                    server  = client.GetGuild(args.Message.Guild.Id).Name;
                    user    = args.Message.Author.User.ToString();
                }

                StyleSheet styleSheet = new StyleSheet(Color.White);
                styleSheet.AddStyle("[\\[\\]]", Color.Cyan);
                styleSheet.AddStyle(time, Color.Yellow);
                styleSheet.AddStyle("Link: ", Color.Orange);
                styleSheet.AddStyle(message, Color.White);
                styleSheet.AddStyle("Server: ", Color.Orange);
                styleSheet.AddStyle("Channel: ", Color.Orange);
                styleSheet.AddStyle("User: "******"DM from user: "******"REDEEMED":
                    styleSheet.AddStyle(status, Color.Lime);
                    break;

                case "ALREADY REDEEMED":
                    styleSheet.AddStyle(status, Color.Red);
                    break;

                case "ERROR REDEEMING":
                    styleSheet.AddStyle(status, Color.Yellow);
                    break;

                case "UNKNOWN ERROR":
                    styleSheet.AddStyle(status, Color.Yellow);
                    break;
                }

                Console.WriteLineStyled("[" + time + "] " + "Link: " + message + " " + "[" + status + "]", styleSheet);

                if (client.GetChannel(args.Message.Channel.Id).Type == ChannelType.DM || client.GetChannel(args.Message.Channel.Id).Type == ChannelType.Group)
                {
                    Console.WriteLineStyled("DM from user: "******"Server: " + server + " Channel: " + channel + " User: " + user, styleSheet);
                    Console.WriteLine();
                }
            }
        }
Ejemplo n.º 27
0
 private void Client_MessageReceived(object sender, MessageEventArgs e)
 {
     if (e.Channel.Id == Options.DiscordOptions.DiscordServerID && !e.Message.IsAuthor)
     {
         SendMessageAfterDelay(Options.DiscordOptions.SteamChat, string.Format("{0} sent a message in Discord: {1}", e.Message.User.Name, e.Message.Text), true);
     }
 }
Ejemplo n.º 28
0
 private void Scores(MessageEventArgs e)
 {
     string txtScores = "";
     foreach (KeyValuePair<string, int> pair in scoreboard)
     {
         txtScores += (pair.Key + ": " + pair.Value + "\n");
     }
     try
     {
         _bot.DeleteMessage(e.Message);
     }
     catch
     {
         _bot.SendMessage(e.ChannelId, "Your command cannot be deleted in this channel.\n");
     }
     _bot.SendMessage(botChannel, txtScores);
 }
Ejemplo n.º 29
0
        private void RockPaperScissors(MessageEventArgs e, int playerChoice)
        {
            if (!scoreboard.ContainsKey(e.Message.User.Name))
            {
                scoreboard.Add(e.Message.User.Name, 0);
            }

            int num = rand.Next(0, 3); // 0 = rock; 1 = paper; 2 = scissors
            if (num == 0 && playerChoice == 0)
            {
                _bot.SendMessage(botChannel, "@" + e.Message.User.Name + ": " + "I chose rock and you chose rock. We tie!");
            }
            else if (num == 0 && playerChoice == 1)
            {
                _bot.SendMessage(botChannel, "@" + e.Message.User.Name + ": " + "I chose rock and you chose paper. You win!");
                IncreaseScore(e);
            }
            else if (num == 0 && playerChoice == 2)
            {
                _bot.SendMessage(botChannel, "@" + e.Message.User.Name + ": " + "I chose rock and you chose scissors. I win!");
                DeductScore(e);
            }
            else if (num == 1 && playerChoice == 0)
            {
                _bot.SendMessage(botChannel, "@" + e.Message.User.Name + ": " + "I chose paper and you chose rock. I win!");
                DeductScore(e);
            }
            else if (num == 1 && playerChoice == 1)
            {
                _bot.SendMessage(botChannel, "@" + e.Message.User.Name + ": " + "I chose paper and you chose paper. We tie!");
            }
            else if (num == 1 && playerChoice == 2)
            {
                _bot.SendMessage(botChannel, "@" + e.Message.User.Name + ": " + "I chose paper and you chose scissors. You win!");
                IncreaseScore(e);
            }
            else if (num == 2 && playerChoice == 0)
            {
                _bot.SendMessage(botChannel, "@" + e.Message.User.Name + ": " + "I chose scissors and you chose rock. You win!");
                IncreaseScore(e);
            }
            else if (num == 2 && playerChoice == 1)
            {
                _bot.SendMessage(botChannel, "@" + e.Message.User.Name + ": " + "I chose scissors and you chose paper. I win!");
                DeductScore(e);
            }
            else
            {
               _bot.SendMessage(botChannel, "@" + e.Message.User.Name + ": " + "I chose scissors and you chose scissors. We tie!");
            }
            try
            {
                _bot.DeleteMessage(e.Message);
            }
            catch
            {
                _bot.SendMessage(e.ChannelId, "Your command cannot be deleted in this channel.\n");
            }
        }
Ejemplo n.º 30
0
 private static async Task<bool> handleSimpleCommands(MessageEventArgs e, DiscordClient client, Channel currentChannel)
 {
     switch (e.Message.Text)
     {
         case "-waifu":
             await client.SendMessage(currentChannel, "KokoroBot is your waifu now.");
             break;
         case "-brainpower":
             await client.SendMessage(currentChannel, "Huehuehue.");
             await client.SendMessage(currentChannel, "You know...");
             await client.SendMessage(currentChannel, @">youtube https://www.youtube.com/watch?v=0bOV4ExHPZY");
             break;
         case "-praise":
             await client.SendMessage(currentChannel, "ALL PRAISE KARD (/O.o)/");
             break;
         case "-part":
             await client.SendMessage(currentChannel, "part is the baka who created this bot.");
             break;
         case "-amazing":
             await client.SendMessage(currentChannel, "Amazing \nAmazing \nAmazing \nAmazing \nAmazing");
             break;
         case "-??":
             await client.SendMessage(currentChannel, "??\n??\n??\n??\n??\n??\n??\n??\n??");
             break;
         case "-sayo":
             await client.SendMessage(currentChannel, sayoFacts());
             break;
         default:
             return false;
     }
     return true;
 }
Ejemplo n.º 31
0
        private async static void PlaySoundWav(MessageEventArgs e)
        {
            if (e.Message.Text.Length > "-play ".Length && voiceclient != null)
            {
                string file = e.Message.Text.Substring("-play ".Length);
                Console.WriteLine("Trying to play: " + file);
                try {
                    var ws = new NAudio.Wave.WaveFileReader(file);
                    byte[] buf;
                    if (ws.WaveFormat.Channels > 1)
                    {
                        var tomono = new NAudio.Wave.StereoToMonoProvider16(ws);
                        tomono.RightVolume = 0.5f;
                        tomono.LeftVolume = 0.5f;
                        buf = new byte[ws.Length];
                        while (ws.HasData(ws.WaveFormat.AverageBytesPerSecond))
                        {
                            tomono.Read(buf, 0, ws.WaveFormat.AverageBytesPerSecond);
                            voiceclient.SendVoicePCM(buf, buf.Length);
                        }
                    }
                    else
                    {
                        buf = new byte[ws.Length];
                        ws.Read(buf, 0, buf.Length);
                        voiceclient.SendVoicePCM(buf, buf.Length);
                    }
                    ws.Close();
                }
                catch(Exception)
                {
                    Console.WriteLine("File not found or incompatible.");
                }

            }
        }
Ejemplo n.º 32
0
        private async void PotentialGuess(object sender, MessageEventArgs e) {
            if (e.Channel.IsPrivate) return;
            if (e.Server != _server) return;

            bool guess = false;
            lock (_guessLock) {
                if (GameActive && CurrentQuestion.IsAnswerCorrect(e.Message.Text) && !triviaCancelSource.IsCancellationRequested) {
                    users.TryAdd(e.User, 0); //add if not exists
                    users[e.User]++; //add 1 point to the winner
                    guess = true;
                    triviaCancelSource.Cancel();
                }
            }
            if (guess) {
                await _channel.SendMessage($"☑️ {e.User.Mention} guessed it! The answer was: **{CurrentQuestion.Answer}**");
                if (users[e.User] == WinRequirement) {
                    ShouldStopGame = true;
                    await _channel.Send($":exclamation: We have a winner! Its {e.User.Mention}");
                }
            }
        }
Ejemplo n.º 33
0
        private static async void Client_MessageReceived(object sender, MessageEventArgs e)
        {
            try
            {
                if (e.Server != null || e.User.Id == Client.CurrentUser.Id) return;
                if (PollCommand.ActivePolls.SelectMany(kvp => kvp.Key.Users.Select(u => u.Id)).Contains(e.User.Id)) return;
                if (ConfigHandler.IsBlackListed(e))
                    return;

                if (Config.ForwardMessages && !NadekoBot.Creds.OwnerIds.Contains(e.User.Id) && OwnerPrivateChannels.Any())
                    await SendMessageToOwner(e.User + ": ```\n" + e.Message.Text + "\n```").ConfigureAwait(false);

                if (repliedRecently) return;

                repliedRecently = true;
                if (e.Message.RawText != NadekoBot.Config.CommandPrefixes.Help + "h")
                    await e.Channel.SendMessage(HelpCommand.DMHelpString).ConfigureAwait(false);
                await Task.Delay(2000).ConfigureAwait(false);
                repliedRecently = false;
            }
            catch { }
        }
Ejemplo n.º 34
0
        private static async void Bot_MessagedReceived(object sender, MessageEventArgs e)
        {
            if (e.Message.IsAuthor) return;

            //help cmd
            string[] cmds = {"!help", "!ping", "!yt <search term>", "!img <search term>", "!8ball <question>", "!roll", "!bass" };
            if (e.Message.Text.ToLower().Equals(prefix + "help"))
            {
                string cmdStringer = e.User.Mention + "\n__**Commands:**__";
                foreach (string s in cmds)
                {
                    cmdStringer += "\n\t- " + s;
                }
                await e.Channel.SendMessage(cmdStringer);
            }
            //ping cmd
            else if (e.Message.Text.ToLower().Equals(prefix + "ping"))
            {
                await e.Channel.SendMessage(e.User.Mention + " Pong");
            }
            //yt cmd
            else if (e.Message.Text.ToLower().Contains(prefix + "yt") && e.Message.Text.IndexOf(prefix) == 0)
            {
                ytSearch = e.Message.Text.Remove(0, 3);
                if (String.IsNullOrWhiteSpace(ytSearch))
                {
                    await e.Channel.SendMessage(e.User.Mention + " Your command must have a search term attached to it! Use \"!help\" for assistance.");
                }
                else
                {
                    new Program().YoutubeMethod().Wait();
                    await e.Channel.SendMessage(e.User.Mention + " " + ytResult);
                }
            }
            //image cmd
            else if (e.Message.Text.ToLower().Contains(prefix + "img") && e.Message.Text.IndexOf(prefix) == 0)
            {
                string searchTerm = e.Message.Text.Remove(0, 5);
                if (String.IsNullOrWhiteSpace(searchTerm))
                {
                    await e.Channel.SendMessage(e.User.Mention + " Your command must have a search term attached to it! Use \"!help\" for assistance.");
                }
                else
                {

                    var bing = new BingSearchContainer(
                        new Uri("https://api.datamarket.azure.com/Bing/Search/"))
                    { Credentials = new NetworkCredential(bingSearchKey, bingSearchKey) };

                    var query = bing.Image(searchTerm, "EnableHighlighting", "en-US", "Moderate", null, null, null);
                    var results = query.Execute();

                    ImageResult[] aResults = results.ToArray<ImageResult>();

                    int index = r.Next(0, aResults.Length);
                    ImageResult item = aResults[index];

                    await e.Channel.SendMessage(e.User.Mention + " " + item.MediaUrl);
                }
            }
            //8ball cmd
            else if (e.Message.Text.ToLower().Contains(prefix + "8ball") && e.Message.Text.IndexOf(prefix) == 0)
            {
                string question = e.Message.Text.Remove(0, 6);
                if (string.IsNullOrWhiteSpace(question))
                {
                    await e.Channel.SendMessage(e.User.Mention + " Your command must have a question attached to it! Use \"!help\" for assistance.");
                    return;
                }

                string[] responses = {"Not likely.", "More than likely"};
                int index = r.Next(0, responses.Length);
                await e.Channel.SendMessage(e.User.Mention + " " + responses[index]);
            }
            //roll cmd
            else if (e.Message.Text.ToLower().Equals(prefix + "roll"))
            {
                int face = r.Next(1, 7);
                await e.Channel.SendMessage(e.User.Mention + " Rolled a " + face);
                switch (face)
                {
                    case 1:
                        await e.Channel.SendFile("Assets/Dice/dice1.png");
                        break;
                    case 2:
                        await e.Channel.SendFile("Assets/Dice/dice2.png");
                        break;
                    case 3:
                        await e.Channel.SendFile("Assets/Dice/dice3.png");
                        break;
                    case 4:
                        await e.Channel.SendFile("Assets/Dice/dice4.png");
                        break;
                    case 5:
                        await e.Channel.SendFile("Assets/Dice/dice5.png");
                        break;
                    case 6:
                        await e.Channel.SendFile("Assets/Dice/dice6.png");
                        break;
                    default:
                        await e.Channel.SendFile("Assets/Dice/dice1.png");
                        break;
                }
            }
            //bass cmd
            else if (e.Message.Text.ToLower().Equals(prefix + "bass"))
            {
                if (e.User.VoiceChannel != null)
                {
                    //set up
                    bot.UsingAudio(x =>
                    {
                        x.Mode = AudioMode.Outgoing;
                    });

                    //joining a channel
                    var voiceChannel = bot.FindServers("Bot Testing Place").FirstOrDefault().VoiceChannels.FirstOrDefault();
                    _vClient = await bot.GetService<AudioService>().Join(voiceChannel);

                    SendAudio("Assets/Audio/bass.mp3");


                }
                else
                {
                    await e.Channel.SendMessage(e.User.Mention + " You must be in a voice room to do this. Use \"!help\" for assistance.");
                }
            }

        }
Ejemplo n.º 35
0
 private void IncreaseScore(MessageEventArgs e)
 {
     scoreboard[e.Message.User.Name] += 1;
 }